Example usage for org.apache.commons.codec.net URLCodec URLCodec

List of usage examples for org.apache.commons.codec.net URLCodec URLCodec

Introduction

In this page you can find the example usage for org.apache.commons.codec.net URLCodec URLCodec.

Prototype

public URLCodec() 

Source Link

Document

Default constructor.

Usage

From source file:org.eclipse.mylyn.internal.web.tasks.WebRepositoryConnector.java

private static String encode(String value) {
    try {/*  w  w  w . j a  v  a2 s  . c  o m*/
        return new URLCodec().encode(value);
    } catch (EncoderException ex) {
        return value;
    }
}

From source file:org.jenkinsci.plugins.elasticsearchquery.ElasticsearchQueryBuilder.java

@Override
public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener)
        throws AbortException {
    //print our arguments
    listener.getLogger().println("Query: " + query);
    listener.getLogger().println("Fail when: " + aboveOrBelow);
    listener.getLogger().println("Threshold: " + threshold);
    listener.getLogger().println("Since: " + since);
    listener.getLogger().println("Time units: " + units);
    //get/*  w w  w .j av  a  2 s.  c o m*/
    final String user = getDescriptor().getUser();
    //get
    final String password = getDescriptor().getPassword();
    //validate global user and password config
    if (isEmpty(user) != isEmpty(password)) {
        throw new AbortException(
                "user and password must both be provided or empty! Please set value of user and password in Jenkins > Manage Jenkins > Configure System > Elasticsearch Query Builder");
    }

    final String creds = isEmpty(user) ? "" : user + ":" + password + "@";

    //get
    final String host = getDescriptor().getHost();
    //print
    listener.getLogger().println("host: " + host);
    //validate global host config
    if (isEmpty(host)) {
        throw new AbortException(
                "Host cannot be empty! Please set value of host in Jenkins > Manage Jenkins > Configure System > ElasticSearch Query Builder");
    }

    //Calculate time in past for search and indexes
    Long past = currentTimeMillis() - MILLISECONDS.convert(since, TimeUnit.valueOf(units));

    //create the date clause to be added the query to restrict by relative time
    final String dateClause = " AND @timestamp:>=" + past;
    //use past to calculate specific indexes to search similar to kibana 3
    //ie if we are looking back to yesterday we dont need to search every index 
    //only today and yesterday
    final String queryIndexes = isNotBlank(getDescriptor().getIndexes()) ? getDescriptor().getIndexes()
            : buildLogstashIndexes(past);
    listener.getLogger().println("queryIndexes: " + queryIndexes);

    //we have all the parts now build the query URL
    String url = null;
    try {
        url = "http" + (getDescriptor().getUseSSL() ? "s" : "") + "://" + creds + getDescriptor().getHost()
                + "/" + queryIndexes + "/_count?pretty=true&q=" + new URLCodec().encode(query + dateClause);
    } catch (EncoderException ee) {
        throw new RuntimeException(ee);
    }
    listener.getLogger().println("query url: " + url);

    HttpClient httpClient = new DefaultHttpClient();
    final HttpGet httpget = new HttpGet(url);
    final Integer queryRequestTimeout = getDescriptor().getQueryRequestTimeout();
    setSoTimeout(httpClient.getParams(),
            queryRequestTimeout == null || queryRequestTimeout < 1
                    ? getDescriptor().defaultQueryRequestTimeout()
                    : queryRequestTimeout);
    HttpResponse response = null;

    try {
        response = httpClient.execute(httpget);
        listener.getLogger().println("response: " + response);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        String content = null;
        Long count = null;
        InputStream instream = null;
        try {

            instream = entity.getContent();

            // do something useful with the response
            content = IOUtils.toString(instream);
            listener.getLogger().println("content: " + content);
            Map<String, Object> map = new Gson().fromJson(content, new TypeToken<Map<String, Object>>() {
            }.getType());
            listener.getLogger().println("count: " + map.get("count"));
            count = Math.round((Double) map.get("count"));

        } catch (Exception ex) {

            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            httpget.abort();
            throw new RuntimeException(ex);

        } finally {

            // Closing the input stream will trigger connection release
            closeQuietly(instream);

        }

        listener.getLogger().println("search url: " + replace(url, "_count", "_search"));

        final String abortMessage = threshold + ". Failing build!\n" + "URL: " + url + "\n"
                + "response content: " + content;
        if (aboveOrBelow.equals("gte")) {
            if (count >= threshold) {
                throw new AbortException("Count: " + count + " is >= " + abortMessage);
            }
        } else {
            if (count <= threshold) {
                throw new AbortException("Count: " + count + " is <= " + abortMessage);
            }
        }
    }
}

From source file:org.jgap.util.StringKit.java

/**
 * Encodes a string.// ww  w .j  a v a  2 s.co m
 *
 * @param a_string the string to encode
 * @return encoded string
 *
 * @author Klaus Meffert
 * @since 3.2
 */
public static String encode(String a_string) {
    try {
        return new URLCodec().encode(a_string, "UTF-8");
    } catch (UnsupportedEncodingException uex) {
        throw new Error("UTF-8 encoding should always be supported!");
    }
}

From source file:org.jgap.util.StringKit.java

/**
 * Decodes an encoded string./*from   ww w . ja v a2 s .  c o  m*/
 *
 * @param a_string the encoded string to decode
 * @return decoded string
 *
 * @author Klaus Meffert
 * @since 3.2
 */
public static String decode(String a_string) {
    try {
        return new URLCodec().decode(a_string, "UTF-8");
    } catch (UnsupportedEncodingException uex) {
        throw new Error("UTF-8 encoding should always be supported!", uex);
    } catch (DecoderException dex) {
        throw new Error("UTF-8 encoding should always be supported!", dex);
    }
}

From source file:org.jwebsocket.sso.OAuth.java

/**
 *
 * @param aSessionId/*from w w  w .  j  ava2s  . co m*/
 * @param aTimeout
 * @return
 */
@Override
public String authSession(String aSessionId, long aTimeout) {
    if (mLog.isDebugEnabled()) {
        mLog.debug("Authenticating session '" + aSessionId + "'" + "', timeout: " + aTimeout + "ms...");
    }
    String lPostBody;
    String lJSONString;
    try {
        URLCodec lCodec = new URLCodec();
        lPostBody = "grant_type=password&" + SSO_SESSION_COOKIE_NAME + "=" + lCodec.encode(aSessionId, "UTF-8");
        Map lHeaders = new HashMap<String, String>();
        lHeaders.put("Content-Type", "application/x-www-form-urlencoded");
        String lAuthStr = Base64
                .encodeBase64String((getOAuthAppId() + ":" + getOAuthAppSecret()).getBytes("UTF-8"));
        lHeaders.put("Authorization", "Basic " + lAuthStr);
        lJSONString = HTTPSupport.request(mOAuthHost + OAUTH_AUTHSESSION_URL, "POST", lHeaders, lPostBody,
                aTimeout);
        Map<String, Object> lJSON = parseJSON(lJSONString);
        mAccessToken = (String) lJSON.get("access_token");
        mRefreshToken = (String) lJSON.get("refresh_token");
        if (mLog.isDebugEnabled()) {
            mLog.debug("Session authenticated, response: '"
                    + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        }
        return lJSONString;
    } catch (IOException lEx) {
        mReturnCode = -1;
        mReturnMsg = lEx.getClass().getSimpleName() + " authenticating session against OAuth host.";
        lJSONString = "{\"code\":-1, \"msg\":\"" + lEx.getClass().getSimpleName() + ": " + lEx.getMessage()
                + "\"}";
        mLog.error("Session could not be authenticated, response: '"
                + lJSONString.replace("\n", "\\n").replace("\r", "\\r") + "'");
        return lJSONString;
    }
}

From source file:org.opendatakit.aggregate.server.SubmissionServiceImpl.java

@Override
public String getSubmissionAuditCSV(String keyString) throws RequestFailureException {
    HttpServletRequest req = this.getThreadLocalRequest();
    CallingContext cc = ContextFactory.getCallingContext(this, req);

    URLCodec urlCodec = new URLCodec();
    String decode = null;/*from  w w w .j a  va2s  . c  o m*/
    try {
        decode = urlCodec.decode(keyString);
    } catch (DecoderException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    SubmissionKey key = new SubmissionKey(decode);

    List<SubmissionKeyPart> parts = key.splitSubmissionKey();
    if (parts.get(0).getElementName().equals(PersistentResults.FORM_ID_PERSISTENT_RESULT))
        return new String(getBytes(cc, key));

    Submission sub = getSubmission(cc, parts);
    BlobSubmissionType b = getBlobSubmissionType(parts, sub);
    return new String(getBytes(cc, parts, b));
}

From source file:org.openengsb.persistence.rulebase.filebackend.RuleBaseElementPersistenceBackendService.java

public void init() throws PersistenceException {
    encoder = new URLCodec();
    if (!storageFolder.exists()) {
        try {//from   w ww  . java 2 s  .  c  o m
            FileUtils.forceMkdir(storageFolder);
        } catch (IOException e) {
            throw new PersistenceException(e);
        }
    }
}

From source file:org.openengsb.persistence.rulebase.filebackend.RuleBaseElementPersistenceBackendServiceTest.java

@Before
public void setUp() throws Exception {
    encoder = new URLCodec();
    service = new RuleBaseElementPersistenceBackendService();
    storageFolder = temporaryFolder.newFolder("rules");
    service.setStorageFolderPath(storageFolder.getPath());
    service.init();/*from w w w.  jav a  2  s .co m*/
}

From source file:org.openengsb.persistence.rulebase.filebackend.RuleBaseFileNameFilter.java

public RuleBaseFileNameFilter(Map<String, String> metaData) {
    type = metaData.get(RuleBaseElement.META_RULE_TYPE);
    name = metaData.get(RuleBaseElement.META_RULE_NAME);
    pack = metaData.get(RuleBaseElement.META_RULE_PACKAGE);
    decoder = new URLCodec();
}

From source file:org.openestate.is24.restapi.AbstractClient.java

/**
 * Encode a string value for use in an URL according to
 * <a href="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>.
 *
 * @param value//  ww w  .  j av  a2  s.c  o  m
 * the value to encode
 *
 * @return
 * the encoded value
 */
public static String getUrlEncodedValue(String value) {
    try {
        return StringUtils.replace(new URLCodec().encode(StringUtils.trimToNull(value), getEncoding()), "+",
                "%20");
    } catch (UnsupportedEncodingException ex) {
        LOGGER.error("Unsupported encoding!", ex);
        return null;
    }
}