DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets

  • submit to reddit

Recent Snippets

                    package Examples;

import org.testng.annotations.Test;
import com.aspose.words.Document;
import com.aspose.words.NodeList;
import com.aspose.words.FieldStart;
import com.aspose.words.FieldType;
import com.aspose.words.NodeType;
import com.aspose.words.Run;
import com.aspose.words.Node;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Shows how to replace hyperlinks in a Word document.
 */
public class ExReplaceHyperlinks extends ExBase
{
    /**
   {{ Finds all hyperlinks in a Word document and changes their URL and display name.
   {{/
    public void replaceHyperlinks() throws Exception
    {
        // Specify your document name here.
        Document doc = new Document(getMyDir() + "ReplaceHyperlinks.doc");

        // Hyperlinks in a Word documents are fields, select all field start nodes so we can find the hyperlinks.
        NodeList fieldStarts = doc.selectNodes("//FieldStart");
        for (FieldStart fieldStart : (Iterable<FieldStart>) fieldStarts)
        {
            if (fieldStart.getFieldType() == FieldType.FIELD_HYPERLINK)
            {
                // The field is a hyperlink field, use the "facade" class to help to deal with the field.
                Hyperlink hyperlink = new Hyperlink(fieldStart);

                // Some hyperlinks can be local (links to bookmarks inside the document), ignore these.
                if (hyperlink.isLocal())
                    continue;

                // The Hyperlink class allows to set the target URL and the display name
                // of the link easily by setting the properties.
                hyperlink.setTarget(NEW_URL);
                hyperlink.setName(NEW_NAME);
            }
        }

        doc.save(getMyDir() + "ReplaceHyperlinks Out.doc");
    }

    private static final String NEW_URL = "http://www.aspose.com";
    private static final String NEW_NAME = "Aspose - The .NET & Java Component Publisher";
}


/**
 * This "facade" class makes it easier to work with a hyperlink field in a Word document.
 *
 * A hyperlink is represented by a HYPERLINK field in a Word document. A field in Aspose.Words
 * consists of several nodes and it might be difficult to work with all those nodes directly.
 * Note this is a simple implementation and will work only if the hyperlink code and name
 * each consist of one Run only.
 *
 * [FieldStart][Run - field code][FieldSeparator][Run - field result][FieldEnd]
 *
 * The field code contains a string in one of these formats:
 * HYPERLINK "url"
 * HYPERLINK \l "bookmark name"
 *
 * The field result contains text that is displayed to the user.
 */
class Hyperlink
{
    Hyperlink(FieldStart fieldStart) throws Exception
    {
        if (fieldStart == null)
            throw new IllegalArgumentException("fieldStart");
        if (fieldStart.getFieldType() != FieldType.FIELD_HYPERLINK)
            throw new IllegalArgumentException("Field start type must be FieldHyperlink.");

        mFieldStart = fieldStart;

        // Find the field separator node.
        mFieldSeparator = findNextSibling(mFieldStart, NodeType.FIELD_SEPARATOR);
        if (mFieldSeparator == null)
            throw new IllegalStateException("Cannot find field separator.");

        // Find the field end node. Normally field end will always be found, but in the example document
        // there happens to be a paragraph break included in the hyperlink and this puts the field end
        // in the next paragraph. It will be much more complicated to handle fields which span several
        // paragraphs correctly, but in this case allowing field end to be null is enough for our purposes.
        mFieldEnd = findNextSibling(mFieldSeparator, NodeType.FIELD_END);

        // Field code looks something like [ HYPERLINK "http:\\www.myurl.com" ], but it can consist of several runs.
        String fieldCode = getTextSameParent(mFieldStart.getNextSibling(), mFieldSeparator);
        Matcher matcher = G_REGEX.matcher(fieldCode.trim());
        matcher.find();
        mIsLocal = (matcher.group(1) != null) && (matcher.group(1).length() > 0);    //The link is local if \l is present in the field code.
        mTarget = matcher.group(2).toString();
    }

    /**
   {{ Gets or sets the display name of the hyperlink.
   {{/
    String getName() throws Exception
    {
        return getTextSameParent(mFieldSeparator, mFieldEnd);
    }
    void setName(String value) throws Exception
    {
        // Hyperlink display name is stored in the field result which is a Run
        // node between field separator and field end.
        Run fieldResult = (Run)mFieldSeparator.getNextSibling();
        fieldResult.setText(value);

        // But sometimes the field result can consist of more than one run, delete these runs.
        removeSameParent(fieldResult.getNextSibling(), mFieldEnd);
    }

    /**
   {{ Gets or sets the target url or bookmark name of the hyperlink.
   {{/
    String getTarget() throws Exception
    {
        return mTarget;
    }
    void setTarget(String value) throws Exception
    {
        mTarget = value;
        updateFieldCode();
    }

    /**
   {{ True if the hyperlink's target is a bookmark inside the document. False if the hyperlink is a url.
   {{/
    boolean isLocal() throws Exception
    {
        return mIsLocal;
    }
    void isLocal(boolean value) throws Exception
    {
        mIsLocal = value;
        updateFieldCode();
    }

    private void updateFieldCode() throws Exception
    {
        // Field code is stored in a Run node between field start and field separator.
        Run fieldCode = (Run)mFieldStart.getNextSibling();
        fieldCode.setText(java.text.MessageFormat.format("HYPERLINK {0}\"{1}\"", ((mIsLocal) ? "\\l " : ""), mTarget));

        // But sometimes the field code can consist of more than one run, delete these runs.
        removeSameParent(fieldCode.getNextSibling(), mFieldSeparator);
    }

    /**
   {{ Goes through siblings starting from the start node until it finds a node of the specified type or null.
   {{/
    private static Node findNextSibling(Node startNode, int nodeType) throws Exception
    {
        for (Node node = startNode; node != null; node = node.getNextSibling())
        {
            if (node.getNodeType() == nodeType)
                return node;
        }
        return null;
    }

    /**
   {{ Retrieves text from start up to but not including the end node.
   {{/
    private static String getTextSameParent(Node startNode, Node endNode) throws Exception
    {
        if ((endNode != null) && (startNode.getParentNode() != endNode.getParentNode()))
            throw new IllegalArgumentException("Start and end nodes are expected to have the same parent.");

        StringBuilder builder = new StringBuilder();
        for (Node child = startNode; !child.equals(endNode); child = child.getNextSibling())
            builder.append(child.getText());

        return builder.toString();
    }

    /**
   {{ Removes nodes from start up to but not including the end node.
   {{ Start and end are assumed to have the same parent.
   {{/
    private static void removeSameParent(Node startNode, Node endNode) throws Exception
    {
        if ((endNode != null) && (startNode.getParentNode() != endNode.getParentNode()))
            throw new IllegalArgumentException("Start and end nodes are expected to have the same parent.");

        Node curChild = startNode;
        while ((curChild != null) && (curChild != endNode))
        {
            Node nextChild = curChild.getNextSibling();
            curChild.remove();
            curChild = nextChild;
        }
    }

    private final Node mFieldStart;
    private final Node mFieldSeparator;
    private final Node mFieldEnd;
    private boolean mIsLocal;
    private String mTarget;

    /**
   {{ RK I am notoriously bad at regexes. It seems I don't understand their way of thinking.
   {{/
    private static final Pattern G_REGEX = Pattern.compile(
        "\\S+" +            // one or more non spaces HYPERLINK or other word in other languages
        "\\s+" +            // one or more spaces
        "(?:\"\"\\s+)?" +    // non capturing optional "" and one or more spaces, found in one of the customers files.
        "(\\\\l\\s+)?" +    // optional \l flag followed by one or more spaces
        "\"" +                // one apostrophe
        "([How to Replace or Modify Hyperlinks^\"]+)" +        // one or more chars except apostrophe (hyperlink target)
        "\""                // one closing apostrophe
        );
}
                
                    #!/usr/bin/env ruby
# Author : Emad Elsaid (https://github.com/blazeeboy)
require 'open-uri' # we'll need to download image with that
require 'ruby_reddit_api' # gem install ruby_reddit_api

# method will take imgur url and 
# filename to save image to it
def download_imgur( url, filename )
  image = open( "#{url}.jpg" ).read
  File.write("#{filename}.jpg", image)
end

# make me a reddit client please
r = Reddit::Api.new

# browse AWW subreddit
# and download images if their url
# is referencing an imgur link
posts = r.browse("aww")
posts.each.with_index(1) do |r, i|
  puts "Downloading #{i}/#{posts.size}"
  download_imgur r.url, r.id if r.url.include? 'imgur'
end
                
                    / / MuSQL
$Database = new PDO ("mysql: host = $ host; dbname = $Databasename", $username, $password); 
/ / PostgreSQL
$Database = new PDO ("pgsql: host = $ host; dbname = $Databasename", $username, $password);
/ / MS SQL
$Database = new PDO ("mssql: host = $ host; dbname = $Databasename", $username, $password); 
/ / SQLite
$Database = new PDO ("sqlite: my / database / path / database.db");
This is a small introduction to PDO extension for beginners Read the full article.
                
                    int fibonaci(int n){
    
    int i;float tmp;
    
    //x^2 - x - 1 =0
    float x1 = ( 1 + sqrt(5) ) / 2;
    float x2 = (1 - sqrt(5) ) / 2;  
    
    for(i=0;i<n;i++){
               
        tmp = (pow(x1,i) - pow(x2,i)) / sqrt(5);
        printf("%d ",(int)floor(tmp)); //pembulatan kebawah         
    }
    
    printf("\n");
}                
                    // Create an instance of BarCodeReader class and specify the image and symbology
BarCodeReader reader;
reader = new BarCodeReader("c:\\Code39Extended.png", BarCodeReadType.getCode39Extended());
int counter = 0;

// Read all the barcodes from the images
while (reader.read())
{     
     // Display the symbology type
     System.out.println("BarCode Type: " + reader.getReadType());
     // Display the codetext
     System.out.println("BarCode CodeText: " + reader.getCodeText());
     // Get the barcode region
     com.aspose.barcoderecognition.BarCodeRegion region = reader.getRegion();
     if (region != null)
     {         
         // Initialize an object of type BufferedImage to get the Graphics object
         BufferedImage bufferedImage = ImageIO.read(new File("c:\\Code30Extended.png"));
         // Initialize graphics object from the image
         Graphics g = bufferedImage.getGraphics();
         // Initialize paint object
         Paint p = new GradientPaint(0, 0, Color.red, 100, 100, Color.pink, true);
	 // Initialize stroke object	 
         Stroke stroke = new BasicStroke(4.0f);
         region.drawBarCodeEdges((Graphics2D)g, stroke, p);
         // Save the image
         ImageIO.write(bufferedImage, "png",new File("C:\\ab\\Image001.png"));
     }
}
reader.close();
                
                    1. Simple Logic

int fibonaci(int n){

    int i,next,a=0,b=1;
    for(i=0;i<n;++i){
    
        if(i<=1){
            next = i;
        }else{
            
            next = a + b;
            a = b;
            b= next;
        }
        
        printf("%d ",next);
    }
}

2. Mathematical Formula

int fibonaci(int n){
    
    int i;float tmp;
    
    //x^2 - x - 1 =0
    float x1 = ( 1 + sqrt(5) ) / 2;
    float x2 = (1 - sqrt(5) ) / 2;  
    
    for(i=0;i<n;i++){
               
        tmp = (pow(x1,i) - pow(x2,i)) / sqrt(5);
        printf("%d ",(int)floor(tmp)); //rounding down         
    }
    
    printf("\n");
}                
                    //Creating and Sending a Message with Voting Options

//The following code sample shows how to create a new message and then send it with voting options.

//[C#]

string address = "firstname.lastname@aspose.com";

using (IEWSClient client = EWSClient.GetEWSClient("https://exchange.aspose.com/ews/Exchange.asmx", "username", "password", "aspose.com"))
{
    MailMessage message = CreateTestMessage(address);

    FollowUpOptions options = new FollowUpOptions();
    options.VotingButtons = "Yes;No;Maybe;Exactly!";

    client.Send(message, options);
}
 
//[VB.NET]

Dim address As String = "firstname.lastname@aspose.com"

Using client As IEWSClient = EWSClient.GetEWSClient("https://exchange.aspose.com/ews/Exchange.asmx", "username", "password", "aspose.com")
	Dim message As MailMessage = CreateTestMessage(address)

	Dim options As New FollowUpOptions()
	options.VotingButtons = "Yes;No;Maybe;Exactly!"

	client.Send(message, options)
End Using

//Sample Methods Used in Examples

//[C#]

private static MailMessage CreateTestMessage(string address)
{
    MailMessage eml = new MailMessage(
        address,
        address,
        "Flagged message",
        "Make it nice and short, but descriptive. The description may appear in search engines' search results pages...");

    return eml;
}
 
//[VB.NET]

private static MailMessage CreateTestMessage(string address)
{
    MailMessage eml = new MailMessage(
        address,
        address,
        "Flagged message",
        "Make it nice and short, but descriptive. The description may appear in search engines' search results pages...");

    return eml;
}                
                    //Instantiate a new workbook with Excel file path
String sdCardPath = Environment.getExternalStorageDirectory().getPath()+ File.separator;
Workbook workbook = new Workbook(sdCardPath + "Book1.xls");
//Save the document in PDF format
workbook.save(sdCardPath + "MyPdfFile.pdf", FileFormatType.PDF);

//PDF/A Conversion

Aspose.Cells for Java also provides support for PDF/A compliance.
//Open an existing Excel file
String sdCardPath = Environment.getExternalStorageDirectory().getPath()+ File.separator;
Workbook workbook = new Workbook(sdCardPath + "Book1.xls");
//Define PdfSaveOptions
PdfSaveOptions saveOptions = new PdfSaveOptions();
//Set the compliance type
saveOptiions.setCompliance(PdfCompliance.PDF_A_1_B);
//Save the PDF file
workbook.save(sdCardPath + "out.pdf", saveOptions);

//Set Creation Time for Output PDF

//When using the PdfSaveOptions class, you can get or set the PDF creation time.

File sdDir = Environment.getExternalStorageDirectory();
String sdPath = sdDir.getCanonicalPath();
//Load an exiting workbook or create from scratch
Workbook book = new Workbook(sdPath + "/book2.xlsx");
//Create an instance of PdfSaveOptions and pass SaveFormat to the construnctor
PdfSaveOptions options = new PdfSaveOptions(SaveFormat.PDF);
//Set the CreatedTime for the PdfSaveOptions as per requirement
options.setCreatedTime(DateTime.getNow());
//Save the workbook to PDF format while passing the object of PdfSaveOptions
book.save(sdPath + "/output.pdf", SaveFormat.PDF);
                
                    //Programming Sample for reading embedded email attachments from an existing email message

public static void ReadEmbeddedAttachments()
{
    // Base folder to load and save files used in this demo
    private static String strBaseFolder = Environment.getExternalStorageDirectory().getPath();
    strBaseFolder = strBaseFolder + "/";

    try
    {
        System.out.print("Reading message with embedded messages....");

        MailMessage message = MailMessage.load(strBaseFolder + "/embedded.msg", MessageFormat.getMsg());
        ParseMessage(message);

        System.out.println("Success");
    }
    catch (Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}

private static void ParseMessage(MailMessage message)
{
    System.out.println("Subject: " + message.getSubject());
    System.out.println("Extracting attachments....");
    for (int i = 0; i < message.getAttachments().size(); i++)
    {
        Attachment att = (Attachment) message.getAttachments().get(i);
        System.out.println("Attachment Name: " + att.getName());

        // Get the name of attachment. If msg subject contains characters like :, /, \ etc., replace with space
        // because windows cannot save files with these characters
        // also save first 50 characters as file name to avoid long file names
        String attFileName = att.getName().replace(".eml", "").replace(":", " ").replace("\\", " ").replace("/", " ").replace("?", "");
        if (attFileName.length() > 50)
        {
            attFileName = attFileName.substring(0, 50);
        }
        String attExt = (att.getName().substring(att.getName().lastIndexOf("."), att.getName().lastIndexOf(".") + 4));

        // Save the attachment to disk
        att.save(strBaseFolder + attFileName + attExt);

        // Check if it is an orphaned text attachment file (ATT00001.txt....) and of type eml
        if ((attExt.equals(".eml")) || (att.getContentType().getMediaType().equals("text/plain") && att.getName().contains(".txt") == true && att.getName().contains("ATT") == true))
        {
            // Try to load this text file in MailMessage
            MailMessage attMsg = MailMessage.load(strBaseFolder + "/" + attFileName + attExt, MessageFormat.getEml());
            // Call the function recursively to parse this message and attachments
            ParseMessage(attMsg);
        }
    }
}
                
                    //The sample code below creates RE (Reply/Reply All) and FW (Forward) messages from a source message.

//[C# Code Sample]

public static IEWSClient GetEWSClient()
{
    const string mailboxUri = "https://exchange.domain.com/ews/Exchange.asmx";
    const string domain = @"";
    const string username = @"username";
    const string password = @"password";
    NetworkCredential credential = new NetworkCredential(username, password, domain);
    IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credential);
    return client;
}
public static void TestMailReFw()
{
    using (IEWSClient client = GetAsposeEWSClient2())
    {
        try
        {

            MailMessage message = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");

            client.Send(message);
            // Wait for a while

            ExchangeMessageInfoCollection messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri);
            if(messageInfoCol.Count == 1)
                Console.WriteLine("1 message in Inbox");
            else
                Console.WriteLine("Error! No message in Inbox");

            MailMessage message1 = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");

            client.Send(message1);
            // Wait for a while
            messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri);

            if(messageInfoCol.Count == 2)
                Console.WriteLine("2 messages in Inbox");
            else
                Console.WriteLine("Error! No new message in Inbox");


            MailMessage message2 = new MailMessage(
                "user@domain.com",
                "user@domain.com",
                "TestMailRefw - " + Guid.NewGuid().ToString(),
                "TestMailRefw Implement ability to create RE and FW messages from source MSG file");
            message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 1", "Attachment Name 1"));
            message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 2", "Attachment Name 2"));

            client.Reply(message2, messageInfoCol[0]);
            client.ReplyAll(message2, messageInfoCol[0]);
            client.Forward(message2, messageInfoCol[0]);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error in program");
        }
    }
}

//[VB.NET Code Sample]

Public Shared Function GetEWSClient() As IEWSClient
	Const  mailboxUri As String = "https://exchange.domain.com/ews/Exchange.asmx"
	Const  domain As String = ""
	Const  username As String = "username"
	Const  password As String = "password"
	Dim credential As New NetworkCredential(username, password, domain)
	Dim client As IEWSClient = EWSClient.GetEWSClient(mailboxUri, credential)
	Return client
End Function
Public Shared Sub TestMailReFw()
	Using client As IEWSClient = GetAsposeEWSClient2()
		Try

			Dim message As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")

			client.Send(message)
			' Wait for a while

			Dim messageInfoCol As ExchangeMessageInfoCollection = client.ListMessages(client.MailboxInfo.InboxUri)
			If messageInfoCol.Count = 1 Then
				Console.WriteLine("1 message in Inbox")
			Else
				Console.WriteLine("Error! No message in Inbox")
			End If

			Dim message1 As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")

			client.Send(message1)
			' Wait for a while
			messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri)

			If messageInfoCol.Count = 2 Then
				Console.WriteLine("2 messages in Inbox")
			Else
				Console.WriteLine("Error! No new message in Inbox")
			End If


			Dim message2 As New MailMessage("user@domain.com", "user@domain.com", "TestMailRefw - " & Guid.NewGuid().ToString(), "TestMailRefw Implement ability to create RE and FW messages from source MSG file")
			message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 1", "Attachment Name 1"))
			message2.Attachments.Add(Attachment.CreateAttachmentFromString("Test attachment 2", "Attachment Name 2"))

			client.Reply(message2, messageInfoCol(0))
			client.ReplyAll(message2, messageInfoCol(0))
			client.Forward(message2, messageInfoCol(0))
		Catch ex As Exception
			Console.WriteLine("Error in program")
		End Try
	End Using
End Sub