Java Code Examples for java.net.URLEncoder

The following are top voted examples for showing how to use java.net.URLEncoder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: iswc2012metadata   File: ToolURI.java View source code 8 votes vote down vote up
/**
 * encode a string into canonical form (using UTF8 encoding as recommended by W3C), throw exception if not succeed.
 * 
 * http://www.w3.org/International/O-URL-code.html
 * 
 * @param szText
 * @return
 * @throws Sw4jException 
 */
public static String encodeURIString(String szUri) throws Sw4jException {
	ToolSafe.checkNonEmpty(szUri, ERROR_NON_EMPTY_URL_URI);

	// decode first
	String temp =null;
	do{
		if (null!=temp)
			szUri = temp;
		temp = decodeURIString(szUri);
	}while (!szUri.equals(temp));

	//encode
	try {
		String szEncoded = URLEncoder.encode(szUri, "UTF-8");
		szEncoded = szEncoded.replaceAll("\\+", "%2B");
		return szEncoded;
	} catch (UnsupportedEncodingException e) {
		throw new Sw4jException( Sw4jMessage.STATE_ERROR, e);
	}
}
 
Example 2
Project: aws-toolkit-eclipse   File: ElasticBeanstalkPublishingUtils.java View source code 7 votes vote down vote up
/**
 * Returns the key under which to store an uploaded application version.
 */
private String formVersionKey(String applicationName, String versionLabel) {
    try {
        return URLEncoder.encode(applicationName + "-" + versionLabel + ".war", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return applicationName + "-" + versionLabel + ".war";
    }
}
 
Example 3
Project: dlna   File: HttpServer.java View source code 6 votes vote down vote up
/**
 * URL-encodes everything between "/"-characters.
 * Encodes spaces as '%20' instead of '+'.
 */
private String encodeUri( String uri )
{
	String newUri = "";
	StringTokenizer st = new StringTokenizer( uri, "/ ", true );
	while ( st.hasMoreTokens())
	{
		String tok = st.nextToken();
		if ( tok.equals( "/" ))
			newUri += "/";
		else if ( tok.equals( " " ))
			newUri += "%20";
		else
		{
			newUri += URLEncoder.encode( tok );
			// For Java 1.4 you'll want to use this instead:
			// try { newUri += URLEncoder.encode( tok, "UTF-8" ); } catch ( java.io.UnsupportedEncodingException uee ) {}
		}
	}
	return newUri;
}
 
Example 4
Project: domeo   File: ElasticSearchWrapper.java View source code 6 votes vote down vote up
/**
 * Note: when using curl we need to use &scrollId=scrollvalue
 * 
 * @param scroll
 * @return
 */
String getAllDocumentsScroll(String scroll) {
	@SuppressWarnings("deprecation")
	String urlEncode = URLEncoder.encode(scroll);
	String url = esScrollUrl + urlEncode;
	@SuppressWarnings("unused")
	int resCode = doHttpOperation(url, HTTP_GET, null);
	return lastResponse;
}
 
Example 5
Project: jlibs   File: FormPayload.java View source code 6 votes vote down vote up
@Override
public void writeTo(OutputStream out) throws IOException{
    boolean first = true;
    for(Map.Entry<String, List<String>> entry: map.entrySet()){
        String key = URLEncoder.encode(entry.getKey(), IOUtil.UTF_8.name());
        for(String value: entry.getValue()){
            if(first){
                out.write('&');
                first = false;
            }
            write(out, key);
            out.write('=');
            write(out, URLEncoder.encode(value, IOUtil.UTF_8.name()));
        }
    }
}
 
Example 6
Project: BioWiki   File: UrlUtils.java View source code 6 votes vote down vote up
public static String urlEncode(final String text) {
    try {
        return URLEncoder.encode(text, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return text;
    }
}
 
Example 7
Project: OsmUi   File: EditorActions.java View source code 6 votes vote down vote up
/**
 * Saves XML+PNG format.
 */
protected void saveXmlPng(BasicGraphEditor editor, String filename,
		Color bg) throws IOException
{
	mxGraphComponent graphComponent = editor.getGraphComponent();
	mxGraph graph = graphComponent.getGraph();

	// Creates the image for the PNG file
	BufferedImage image = mxCellRenderer.createBufferedImage(graph,
			null, 1, bg, graphComponent.isAntiAlias(), null,
			graphComponent.getCanvas());

	// Creates the URL-encoded XML data
	mxCodec codec = new mxCodec();
	String xml = URLEncoder.encode(
			mxUtils.getXml(codec.encode(graph.getModel())), "UTF-8");
	mxPngEncodeParam param = mxPngEncodeParam
			.getDefaultEncodeParam(image);
	param.setCompressedText(new String[] { "mxGraphModel", xml });

	// Saves as a PNG file
	FileOutputStream outputStream = new FileOutputStream(new File(
			filename));
	try
	{
		mxPngImageEncoder encoder = new mxPngImageEncoder(outputStream,
				param);

		if (image != null)
		{
			encoder.encode(image);

			editor.setModified(false);
			editor.setCurrentFile(new File(filename));
		}
		else
		{
			JOptionPane.showMessageDialog(graphComponent,
					mxResources.get("noImageData"));
		}
	}
	finally
	{
		outputStream.close();
	}
}
 
Example 8
Project: jena   File: Convert.java View source code 6 votes vote down vote up
public static String encWWWForm(String s)
{ 
    try {
        return URLEncoder.encode(s, "UTF-8") ;
        // Can't fail - UTF-8 is required
    } catch (UnsupportedEncodingException ex) { return null ;}
}
 
Example 9
Project: sgithub   File: GitHubApiGateway.java View source code 6 votes vote down vote up
/**
* Encode url.
* 
* @param original
*            the original
* 
* @return the string
*/
  private static String encodeUrl(String original) {
  	if (original == null) {
  		return "";
  	} else {
      	try {
  			return URLEncoder.encode(original, ApplicationConstants.CONTENT_ENCODING);
  		} catch (UnsupportedEncodingException e) {
  			// should never be here..
  			return original;
  		}
  	}
  }
 
Example 10
Project: aipo   File: ProxyRewriter.java View source code 6 votes vote down vote up
public String generateNewUrl( String targetURL, HTML.Tag tag, HTML.Attribute attribute)
                            //  String  targetURL, 
                            // String     baseURL,
                            // String     proxyURL,
                            // boolean proxied)
{
    try {                

        URL full = new URL(new URL(proxyRoot), targetURL);
        String fullPath = full.toString();

        StringBuffer buffer = new StringBuffer(proxyRoot.toString());
        buffer.append("?");
         buffer.append(DEFAULT_PROXY_PARAM);
        buffer.append("=");
        buffer.append(URLEncoder.encode(fullPath));
        String proxiedPath = buffer.toString().replace('&', '@');
        return proxiedPath;

    } 
    catch (Throwable t)
    {
        //FIXME: transient print to debug...
        System.err.println( "HTMLRewriter: BASE=" + proxyRoot);
        System.err.println( "target=" + targetURL);
        return URLEncoder.encode(targetURL);    
    }

}
 
Example 11
Project: p2-bridge   File: P2AuthSession.java View source code 6 votes vote down vote up
private static String getNodeName( final URI location )
{
    // if URI is not opaque, just getting the host may be enough
    String host = location.getHost();
    if ( host == null )
    {
        final String scheme = location.getScheme();
        if ( URIUtil.isFileURI( location ) || scheme == null )
        {
            // If the URI references a file, a password could possibly be needed for the directory
            // (it could be a protected zip file representing a compressed directory) - in this
            // case the key is the path without the last segment.
            // Using "Path" this way may result in an empty string - which later will result in
            // an invalid key.
            host = new Path( location.toString() ).removeLastSegments( 1 ).toString();
        }
        else
        {
            // it is an opaque URI - details are unknown - can only use entire string.
            host = location.toString();
        }
    }
    String nodeKey;
    try
    {
        nodeKey = URLEncoder.encode( host, "UTF-8" ); //$NON-NLS-1$
    }
    catch ( final UnsupportedEncodingException e2 )
    {
        // fall back to default platform encoding
        try
        {
            // Uses getProperty "file.encoding" instead of using deprecated URLEncoder.encode(String location)
            // which does the same, but throws NPE on missing property.
            final String enc = System.getProperty( "file.encoding" );//$NON-NLS-1$
            if ( enc == null )
            {
                throw new UnsupportedEncodingException(
                    "No UTF-8 encoding and missing system property: file.encoding" ); //$NON-NLS-1$
            }
            nodeKey = URLEncoder.encode( host, enc );
        }
        catch ( final UnsupportedEncodingException e )
        {
            throw new RuntimeException( e );
        }
    }
    return IRepository.PREFERENCE_NODE + '/' + nodeKey;
}
 
Example 12
Project: wso2-synapse   File: XFormURLEncodedFormatter.java View source code 6 votes vote down vote up
public byte[] getBytes(MessageContext messageContext, OMOutputFormat format) throws AxisFault {

        OMElement omElement = messageContext.getEnvelope().getBody().getFirstElement();

        if (omElement != null) {
            Iterator it = omElement.getChildElements();
            String paraString = "";

            String encoding= format.getCharSetEncoding();
            if(encoding==null)    {
                encoding= "UTF-8";
            }
            while (it.hasNext()) {
                OMElement ele1 = (OMElement) it.next();

                String parameter;
                try {
                    parameter = ele1.getLocalName() + "=" + URLEncoder.encode(ele1.getText(),encoding).replace("+", "%20");
                } catch (UnsupportedEncodingException e) {
                    throw new IllegalArgumentException("UnsupportedEncoding for " + ele1.getText());
                }

                //    "2a" "_JsonReader_PD_2a" replace with ""
                //    "$a" "_JsonReader_PS_a" replace with $
                parameter = parameter.replace("_JsonReader_PD_","").replace("_JsonReader_PS_","$");
                paraString = "".equals(paraString) ? parameter : (paraString + "&" + parameter);
            }
            return paraString.getBytes();
        }

        return new byte[0];
    }
 
Example 13
Project: iot-server-appliances   File: DeviceManagementServiceProviderImpl.java View source code 5 votes vote down vote up
@Override
public void sendRegistrationEmail(EmailMessageProperties emailMessageProperties) throws DeviceManagementException {
    List<NotificationMessages> notificationMessages = DeviceConfigurationManager.getInstance()
            .getNotificationMessagesConfig().getNotificationMessagesList();

    String messageHeader = "";
    String messageBody = "";
    String messageFooter1 = "";
    String messageFooter2 = "";
    String messageFooter3 = "";
    String url = "";
    String subject = "";

    for (NotificationMessages notificationMessage : notificationMessages) {
        if (DeviceManagementConstants.EmailNotifications.USER_REGISTRATION_NOTIFICATION_TYPE.
                equals(notificationMessage.getType())) {
            messageHeader = notificationMessage.getHeader();
            messageBody = notificationMessage.getBody();
            messageFooter1 = notificationMessage.getFooterLine1();
            messageFooter2 = notificationMessage.getFooterLine2();
            messageFooter3 = notificationMessage.getFooterLine3();
            url = notificationMessage.getUrl();
            subject = notificationMessage.getSubject();
            break;
        }
    }

    StringBuilder messageBuilder = new StringBuilder();

    try {
        messageHeader = messageHeader.replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants.FIRST_NAME + "\\}",
                URLEncoder.encode(emailMessageProperties.getFirstName(),
                        EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME));

        messageBody = messageBody.trim().replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants
                        .USERNAME
                        + "\\}",
                URLEncoder.encode(emailMessageProperties.getUserName(), EmailConstants.EnrolmentEmailConstants
                        .ENCODED_SCHEME));

        messageBody = messageBody.replaceAll("\\{" + EmailConstants.EnrolmentEmailConstants.PASSWORD + "\\}",
                URLEncoder.encode(emailMessageProperties.getPassword(), EmailConstants.EnrolmentEmailConstants
                        .ENCODED_SCHEME));

        messageBody = messageBody + System.getProperty("line.separator") + url.replaceAll("\\{"
                        + EmailConstants.EnrolmentEmailConstants.DOWNLOAD_URL + "\\}",
                URLDecoder.decode(emailMessageProperties.getEnrolmentUrl(),
                        EmailConstants.EnrolmentEmailConstants.ENCODED_SCHEME));

        messageBuilder.append(messageHeader).append(System.getProperty("line.separator"));
        messageBuilder.append(messageBody).append(System.getProperty("line.separator")).append(messageFooter1.trim());
        messageBuilder.append(System.getProperty("line.separator")).append(messageFooter2.trim());
        messageBuilder.append(System.getProperty("line.separator")).append(messageFooter3.trim());

    } catch (IOException e) {
        log.error("IO error in processing enrol email message " + emailMessageProperties);
        throw new DeviceManagementException("Error replacing tags in email template '" +
                emailMessageProperties.getSubject() + "'", e);
    }
    emailMessageProperties.setMessageBody(messageBuilder.toString());
    emailMessageProperties.setSubject(subject);
    EmailServiceDataHolder.getInstance().getEmailServiceProvider().sendEmail(emailMessageProperties);
}