DevOps Zone is brought to you in partnership with:
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
  • submit to reddit
Ashwin Jiwane06/19/14
4016 views
0 replies

Test Your Third-Party Providers to Stay Reliable

Most businesses depend on third parties to reliably deliver products or services to their customers. E-commerce sites rely on delivery services. Broadcasters rely on cable and satellite providers. And web platforms rely on cloud infrastructure to keep their systems accessible.

Erich Styger06/19/14
2834 views
0 replies

Updated Freedom Board Logic Analyzer with DMA

Question: How to build a low-cost logic open source logic analyzer for less than $15? Answer: combine the Freedom KL25Z board with OLS!

David Winterbottom06/19/14
4884 views
0 replies

Continuously rebuild your project

New developers joining a project will often find that the project won't build cleanly on their machine, and hours of time will be sunk into setting up the project so work can start. Counter this by using continuous integration to build your project from scratch.

Mike Bushong06/19/14
3910 views
0 replies

How networking's "per port" discussion will change over the next 3 years

When people talk about pricing and switch sizes today, answers are usually framed up in some derivative of the per-port discussion

Anh Tuan Nguyen06/19/14
1166 views
0 replies

How to Increase Productivity

Unlocking productivity is one of the bigger concerns for any person taking a management role. However, people rarely agree on the best approaches to improve performance.

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
        );
}
Chris Odell06/18/14
6224 views
8 replies

Agile Decompiled: Pair Programming

Like many agile practices my personal opinion is that pair programming should be seen as another tool in your coding toolbox. When a hammer is the appropriate tool to use, use it.

Andres Navarro06/18/14
2518 views
0 replies

TCP/IP Sockets to monitor daemon processes.

I remember back in late 1990s when I discovered Socket communication and how that can help back-end processes to provide information to the outside world.

Mike Cottmeyer06/18/14
2180 views
0 replies

Gluten-Free Agile

Like gluten free, everyone tosses around the word “Agile”so readily from the boardroom to the server room.

Derek Weeks06/18/14
2971 views
0 replies

Walking in the Open Source Component Garden

The good news is that open source projects release newer versions of their components that address newly found vulnerabilities. Bug-free alternatives are available. But making use of these newer more secure versions, relies on ensuring your organization has a process to identify these defects easily and early.

Luis Aguilar06/18/14
4453 views
0 replies

How to Declare Modules in Node.js

One of those aspects of Node.js that took me a while to fully understand initially is how to properly declare modules.

Johanna Rothman06/18/14
1127 views
0 replies

Tips for Improving Your Geographically Distributed Agile Team

At the Better Software/Agile Development conference a couple of weeks ago, I gave a talk entitled At Least Five Tips for Improving Your Geographically Distributed Agile Team.

Allen Coin06/18/14
726 views
0 replies

Cisco to Acquire SDN Startup Tail-f for $175M

Yesterday, Cisco announced its intent to acquire Stockholm-based SDN developer Tail-f Systems for $175 million in cash and incentives.

Moshe Kaplan06/17/14
4647 views
0 replies

Auto Scaling your Workers based on Queue Length

Having an image or video processing engine? Having a web crawling solution? Doing OCR on media? If so, this post is probably for you.

John Sonmez06/17/14
3132 views
3 replies

Stop Taking Yourself So Seriously

If you are reading this blog post, you are probably a software developer. Now, it might be that you are working on a very important piece of a software system that will save lives or completely change the world but chances are, you are not.

Mike Bushong06/17/14
3494 views
0 replies

IT resellers: Disruptive or Disrupted?

When good enough becomes better than enough, the key purchasing criteria shift from performance and features to price and convenience. This is a huge part of why there is so much energy around merchant silicon and white box.

Mike Bushong06/17/14
1152 views
0 replies

It Infrastructure: -able vs. -ed

The point here is that the balance for your organization ought to reflect your actual practices. Whether you consider past practices or anticipated practices is an interesting thought exercise, but you should be considering something.

Dennis Doomen06/16/14
1092 views
0 replies

The Staring Game AKA The Art of Social Intelligence

So here I am in New York, all alone and looking for something fun to do during a rainy day preceding QCon New York. The Empire State Building was covered in clouds so what can you do?

#!/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
Andy Hawthorne06/16/14
3894 views
0 replies

Coding Can Make You Fat

Writing code for a living can make you fat. That’s because coders work long hours behind a computer and don’t have much time for exercise. Here’s what you can do about it.