Example usage for java.io UnsupportedEncodingException toString

List of usage examples for java.io UnsupportedEncodingException toString

Introduction

In this page you can find the example usage for java.io UnsupportedEncodingException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:de.andreas_rueckert.trade.site.mtgox.client.MtGoxClient.java

/**
 * Create authentication entries for a HTTP post header.
 *
 * @param postData The data to post via HTTP.
 * @param userAccount The account of the user on the exchange. Null, if the default account should be used.
 *
 * @return The header entries as a map or null if an error occured.
 *//*ww w.  j  a v a  2s  . co  m*/
Map<String, String> getAuthenticationHeader(String postData, TradeSiteUserAccount userAccount) {
    HashMap<String, String> result = new HashMap<String, String>();
    Mac mac;
    String accountKey = null;
    String accountSecret = null;

    // Try to get user account and secret.
    if (userAccount != null) {

        accountKey = userAccount.getAPIkey();
        accountSecret = userAccount.getSecret();

    } else { // Use the default account from the API implementation.

        accountKey = _key;
        accountSecret = _secret;
    }

    // Check, if key and secret are available for the request.
    if (accountKey == null) {
        throw new MissingAccountDataException("Key not available for authenticated request to MtGox");
    }
    if (accountSecret == null) {
        throw new MissingAccountDataException("Secret not available for authenticated request to MtGox");
    }

    result.put("Rest-Key", accountKey);

    // Create a new secret key
    SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(accountSecret), "HmacSHA512");

    // Create a new mac
    try {

        mac = Mac.getInstance("HmacSHA512");

    } catch (NoSuchAlgorithmException nsae) {

        System.err.println("No such algorithm exception: " + nsae.toString());

        return null;
    }

    // Init mac with key.
    try {

        mac.init(key);

    } catch (InvalidKeyException ike) {

        System.err.println("Invalid key exception: " + ike.toString());

        return null;
    }

    // Encode the post data by the secret and encode the result as base64.
    try {

        result.put("Rest-Sign", Base64.encodeBase64String(mac.doFinal(postData.getBytes("UTF-8"))));

    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());

        return null;
    }

    return result;
}

From source file:de.andreas_rueckert.trade.site.cryptsy.client.CryptsyClient.java

/**
 * Execute a authenticated query on cryptsy.
 *
 * @param method      The method to execute.
 * @param arguments   The arguments to pass to the server.
 * @param userAccount The user account on the exchange, or null if the default account should be used.
 * @return The returned data as JSON or null, if the request failed.
 *//*from   ww w . j ava  2 s  .  c om*/
private final JSON authenticatedHTTPRequest(String method, Map<String, String> arguments,
        TradeSiteUserAccount userAccount) {

    HashMap<String, String> headerLines = new HashMap<String, String>(); // Create a new map for the header lines.
    Mac mac;
    SecretKeySpec key = null;
    String accountKey = null; // The used key of the account.
    String accountSecret = null; // The used secret of the account.

    // Try to get an account key and secret for the request.
    if (userAccount != null) {

        accountKey = userAccount.getAPIkey();
        accountSecret = userAccount.getSecret();

    } else if (_defaultUserAccount != null) { // Use the default values from the API implementation.

        accountKey = _defaultUserAccount.getAPIkey();
        accountSecret = _defaultUserAccount.getSecret();
    }

    // Check, if account key and account secret are available for the request.
    if (accountKey == null) {
        throw new MissingAccountDataException("Public key not available for authenticated request to " + _name);
    }
    if (accountSecret == null) {
        throw new MissingAccountDataException(
                "Private key not available for authenticated request to " + _name);
    }

    if (arguments == null) { // If the user provided no arguments, just create an empty argument array.
        arguments = new HashMap<String, String>();
    }

    arguments.put("method", method); // Add the method to the post data.
    arguments.put("nonce", "" + ++_nonce); // Add the dummy nonce.

    // Convert the arguments into a string to post them.
    String postData = "";

    for (Iterator argumentIterator = arguments.entrySet().iterator(); argumentIterator.hasNext();) {
        Map.Entry argument = (Map.Entry) argumentIterator.next();

        if (postData.length() > 0) {
            postData += "&";
        }
        postData += argument.getKey() + "=" + argument.getValue();
    }

    // Create a new secret key
    try {

        key = new SecretKeySpec(accountSecret.getBytes("UTF-8"), "HmacSHA512");

    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    // Create a new mac
    try {

        mac = Mac.getInstance("HmacSHA512");

    } catch (NoSuchAlgorithmException nsae) {

        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    // Init mac with key.
    try {
        mac.init(key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }

    // Add the key to the header lines.
    headerLines.put("Key", accountKey);

    // Encode the post data by the secret and encode the result as base64.
    try {

        headerLines.put("Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8"))));
    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    // Now do the actual request
    String requestResult = HttpUtils.httpPost(_url, headerLines, postData);

    if (requestResult != null) { // The request worked

        try {
            // Convert the HTTP request return value to JSON to parse further.
            JSONObject jsonResult = JSONObject.fromObject(requestResult);

            // Check, if the request was successful
            int success = jsonResult.getInt("success");

            if (success == 0) { // The request failed.
                String errorMessage = jsonResult.getString("error");

                LogUtils.getInstance().getLogger().error(_name + " trade API request failed: " + errorMessage);

                return null;

            } else { // Request succeeded!

                // Try to figure, what the return actually is: json object or json array?

                // Test, if the return value is an JSONArray.
                JSONArray arrayReturn = jsonResult.optJSONArray("return");

                if (arrayReturn != null) { // Converting the result into a JSON array worked, so return it.

                    return arrayReturn;
                }

                // Now test, if the return value is a JSONObject.
                JSONObject objectReturn = jsonResult.optJSONObject("return");

                if (objectReturn != null) { // Converting the result into a JSON object worked, so return it.

                    return objectReturn;
                }

                if (!jsonResult.has("return")) { // Has this object no return value?

                    LogUtils.getInstance().getLogger()
                            .error(_name + " trade API request '" + method + "' has no return value.");

                    return null; // No reasonable return value possible.

                } else { // There is a return value, but it's neither an array or a object, so we cannot convert it.

                    LogUtils.getInstance().getLogger().error(_name + " trade API request '" + method
                            + "' has a return value, that is neither a JSONObject or a JSONArray. Don't know, what to do with it.");

                    return null; // Not much we can do here...
                }
            }

        } catch (JSONException je) {
            System.err.println("Cannot parse json request result: " + je.toString());

            return null; // An error occured...
        }
    }

    return null; // The request failed.
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String getOauth2UserEmail() throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {/*from   w w w.j  a  v a2s. c  om*/
        // convert the auth code into an auth token
        URI nakedUri;
        try {
            nakedUri = new URI(tokenUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpPost httppost = new HttpPost(nakedUri);
        logger.info(httppost.getURI().toString());

        // THESE ARE POST BODY ARGS...    
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        qparams.add(new BasicNameValuePair("code", code));
        qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
        UrlEncodedFormEntity postentity;
        try {
            postentity = new UrlEncodedFormEntity(qparams, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            throw new IllegalArgumentException("Unexpected");
        }

        httppost.setEntity(postentity);

        HttpResponse response = null;
        try {
            response = client.execute(httppost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase()
                        + " status code: " + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    // stuff the map in the Context...
                    for (Map.Entry<String, Object> e : userData.entrySet()) {
                        ctxt.putContext(e.getKey(), e.getValue());
                    }
                } else {
                    logger.error("unexpected body");
                    return "Error with Oauth2 token request - missing body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    String email = null;
    {
        URI nakedUri;
        try {
            nakedUri = new URI(userInfoUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token")));
        URI uri;
        try {
            uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                    nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpGet httpget = new HttpGet(uri);
        logger.info(httpget.getURI().toString());

        HttpResponse response = null;
        try {
            response = client.execute(httpget, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error - reason: " + response.getStatusLine().getReasonPhrase() + " status code: "
                        + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);

                    email = (String) userData.get("email");
                } else {
                    logger.error("unexpected body");
                    return "Error - missing body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    return email;
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String obtainOauth2Data(String destinationUrl) throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {//from  ww  w  .j av  a2 s  . c o m
        // convert the auth code into an auth token
        URI nakedUri;
        try {
            nakedUri = new URI(tokenUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpPost httppost = new HttpPost(nakedUri);
        logger.info(httppost.getURI().toString());

        // THESE ARE POST BODY ARGS...    
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        qparams.add(new BasicNameValuePair("code", code));
        qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
        UrlEncodedFormEntity postentity;
        try {
            postentity = new UrlEncodedFormEntity(qparams, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            throw new IllegalArgumentException("Unexpected");
        }

        httppost.setEntity(postentity);

        HttpResponse response = null;
        try {
            response = client.execute(httppost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase()
                        + " status code: " + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    // stuff the map in the Context...
                    for (Map.Entry<String, Object> e : userData.entrySet()) {
                        ctxt.putContext(e.getKey(), e.getValue());
                    }
                } else {
                    logger.error("unexpected body");
                    return "Error with Oauth2 token request - unexpected body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    {
        URI nakedUri;
        try {
            nakedUri = new URI(destinationUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token")));
        URI uri;
        try {
            uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                    nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpGet httpget = new HttpGet(uri);
        logger.info(httpget.getURI().toString());

        HttpResponse response = null;
        try {
            response = client.execute(httpget, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error";
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    String contentType = entity.getContentType().getValue();
                    if (contentType.toLowerCase().contains("xml")) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                        StringBuilder b = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            b.append(line);
                        }
                        String value = b.toString();
                        return value;
                    } else {
                        logger.error("unexpected body");
                        return "Error";
                    }
                } else {
                    logger.error("unexpected missing body");
                    return "Error";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }
}

From source file:de.andreas_rueckert.trade.site.anx.client.ANXClient.java

/**
 * Create authentication entries for a HTTP post header.
 *
 * @param postData The data to post via HTTP.
 * @param userAccount The account of the user on the exchange. Null, if the default account should be used.
 *
 * @return The header entries as a map or null if an error occured.
 *///from   w  w  w . j a va2 s  .co m
Map<String, String> getAuthenticationHeader(String postData, TradeSiteUserAccount userAccount) {

    HashMap<String, String> result = new HashMap<String, String>();
    Mac mac;
    String accountKey = null;
    String accountSecret = null;

    // Try to get user account and secret.
    if (userAccount != null) {

        accountKey = userAccount.getAPIkey();
        accountSecret = userAccount.getSecret();

    } else { // Throw an error.

        throw new MissingAccountDataException("No user account given for " + _name + " request");
    }

    // Check, if key and secret are available for the request.
    if (accountKey == null) {
        throw new MissingAccountDataException("Key not available for authenticated request to " + _name);
    }
    if (accountSecret == null) {
        throw new MissingAccountDataException("Secret not available for authenticated request to " + _name);
    }

    result.put("Rest-Key", accountKey);

    // Create a new secret key
    SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(accountSecret), "HmacSHA512");

    // Create a new mac
    try {

        mac = Mac.getInstance("HmacSHA512");

    } catch (NoSuchAlgorithmException nsae) {

        System.err.println("No such algorithm exception: " + nsae.toString());

        return null;
    }

    // Init mac with key.
    try {

        mac.init(key);

    } catch (InvalidKeyException ike) {

        System.err.println("Invalid key exception: " + ike.toString());

        return null;
    }

    // Encode the post data by the secret and encode the result as base64.
    try {

        result.put("Rest-Sign", Base64.encodeBase64String(mac.doFinal(postData.getBytes("UTF-8"))));

    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());

        return null;
    }

    return result;
}

From source file:se.lu.nateko.edca.svc.GeoHelper.java

/**
 * Uploads the active layer's data to the geospatial server
 * and deletes the data from the device.
 * @return True if successful.//from  ww w  . j a  v a  2  s .c om
 */
private boolean upload() {
    Log.d(TAG, "upload() called.");
    /* Try to form an URI from the supplied ServerConnection info. */
    if (mService.getActiveServer() == null) // Cannot connect unless there is an active connection.
        return false;
    String uriString = mService.getActiveServer().getAddress() + "/wfs";
    Log.i(TAG, uriString);

    /* Post all geometry from the active layer to that layer on the geospatial server. */
    HttpResponse response;
    StringEntity se;
    boolean responseSuccessful = false;
    StringBuilder stringTotal = new StringBuilder();
    try {
        final HttpParams httpParameters = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT * 1000);
        HttpConnectionParams.setSoTimeout(httpParameters, TIME_OUT * 1000);

        se = new StringEntity(formTransactXML());
        se.setContentType("text/xml");
        HttpPost postRequest = new HttpPost(uriString);
        postRequest.setEntity(se);

        response = mHttpClient.execute(postRequest);
        InputStream xmlStream = response.getEntity().getContent();

        BufferedReader r = new BufferedReader(new InputStreamReader(xmlStream));
        String line;
        while ((line = r.readLine()) != null)
            stringTotal.append(line);

        InputStream is = new ByteArrayInputStream(stringTotal.toString().getBytes("UTF-8"));
        responseSuccessful = parseXMLResponse(is);

    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.toString());
        return false;
    } catch (ClientProtocolException e) {
        Log.e(TAG, e.toString());
        return false;
    } catch (IOException e) {
        Log.e(TAG, e.toString());
        return false;
    }
    Log.i(TAG, "Insert Response: " + stringTotal.toString());

    try { // Consume the HttpEntity.
        se.consumeContent();
    } catch (UnsupportedOperationException e) {
        Log.e(TAG, "Operation unsupported by streaming entity sub-class: " + e.toString());
    } catch (IOException e) {
        Log.e(TAG, "Entity consumed?: " + e.toString());
        e.printStackTrace();
    }

    if (responseSuccessful) {
        /* Remove all uploaded geometry from the active layer and the local storage. */
        mGeoLayer.clearGeometry(false);

        deleteGeographyLayer(mGeoLayer.getName());

        /* Update the layer table to reflect that the layer is no longer stored on the device. */
        Cursor layerCursor = mService.getSQLhelper()
                .fetchData(LocalSQLDBhelper.TABLE_LAYER, LocalSQLDBhelper.KEY_LAYER_COLUMNS,
                        LocalSQLDBhelper.ALL_RECORDS,
                        new String(LocalSQLDBhelper.KEY_LAYER_NAME + " = \""
                                + Utilities.dropColons(mGeoLayer.getName(), Utilities.RETURN_LAST) + "\""),
                        false);
        mService.getActiveActivity().startManagingCursor(layerCursor);
        if (layerCursor.moveToFirst()) {
            long layerid = layerCursor.getInt(0);
            int layerMode = layerCursor.getInt(2);
            if (layerMode % LocalSQLDBhelper.LAYER_MODE_STORE == 0) // If the layer is currently stored, remove that mode.
                mService.getSQLhelper().updateData(LocalSQLDBhelper.TABLE_LAYER, layerid,
                        LocalSQLDBhelper.KEY_LAYER_ID, new String[] { LocalSQLDBhelper.KEY_LAYER_USEMODE },
                        new String[] { String.valueOf(layerMode / LocalSQLDBhelper.LAYER_MODE_STORE) });
        }
        return true;
    } else
        return false;

}

From source file:eu.dasish.annotation.backend.dao.impl.DBDispatcherImlp.java

private List<Number> filterAnnotationIDsOnReference(List<Number> annotationIDs, String link,
        MatchMode matchMode) {/*  w  ww  . j a v  a  2 s  . com*/
    if (link != null) {
        if (!link.isEmpty()) {
            if (annotationIDs != null) {
                String partiallyEncoded = this.encodeURLNoSlashEncoded(link);
                String urlEncoded = null;
                try {
                    urlEncoded = URLEncoder.encode(link, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    logger.debug(e.toString());
                }

                List<Number> result = new ArrayList();
                for (Number annotationID : annotationIDs) {
                    List<Number> targets = targetDao.getTargetIDs(annotationID);
                    for (Number targetID : targets) {
                        if (!result.contains(annotationID)) {
                            String linkRunner = targetDao.getLink(targetID);
                            if (matchCriterium(linkRunner, link, matchMode)
                                    || matchCriterium(linkRunner, partiallyEncoded, matchMode)) {
                                result.add(annotationID);
                            } else {
                                if (urlEncoded != null) {
                                    if (matchCriterium(linkRunner, urlEncoded, matchMode)) {
                                        result.add(annotationID);
                                    }
                                }
                            }
                        }
                    }
                }
                return result;
            }
        }
    }
    return annotationIDs;
}

From source file:eu.dasish.annotation.backend.dao.impl.DBDispatcherImlp.java

private String encodeURLNoSlashEncoded(String string) {
    String[] split = string.split("/");
    StringBuilder result = new StringBuilder(split[0]);
    for (int i = 1; i < split.length; i++) {
        try {/* w  ww .  j a v  a2s  .c o m*/
            result.append("/").append(URLEncoder.encode(split[i], "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            result.append("/").append(split[i]);
            logger.debug(e.toString());
        }
    }
    return result.toString();
}

From source file:apimanager.ZohoSupportAPIManager.java

private JSONObject getThreadIds(String authtoken, String portal, String department, String caseID,
        boolean needDescription, String fileToWriteResponse, int index) {

    String baseURL = "";
    try {/*from w  ww . ja va2 s. c o m*/
        baseURL = "https://support.zoho.com/api/json/requests/getrequestthreads?authtoken=" + authtoken
                + "&portal=" + URLEncoder.encode(portal, ENCODETYPE) + "&department="
                + URLEncoder.encode(department, ENCODETYPE) + "&requestid=" + caseID + "&needdescription="
                + needDescription;
    } catch (UnsupportedEncodingException ex) {
        loggerObj.log(Level.SEVERE, "UnsupportedEncodingException in url " + baseURL + "Exception is :", ex);
        return null;
    }

    loggerObj.log(Level.INFO, "Going to connect " + portal + " portal with base URL " + baseURL);

    HttpsClient httpsClient = new HttpsClient();
    String result = httpsClient.OpenHTTPSConnection(baseURL);

    JSONObject json = null;
    if (!JSONOperations.isErrorJSON(result)) {
        JSONParser parser = new JSONParser();
        try {
            json = (JSONObject) parser.parse(result);
        } catch (ParseException ex) {
            loggerObj.log(Level.INFO,
                    "Problem in parsing the data from Zoho Support. Exception is " + ex.toString());
        }
    }

    if (json != null) {
        String FileToWrite = fileToWriteResponse + index + ".json";
        boolean isFileWriteSuccess = FileOperations.writeObjectToFile(json, FileToWrite);
        if (!isFileWriteSuccess) {
            loggerObj.log(Level.SEVERE,
                    "Problem in writing the data from Zoho Support to the file: " + FileToWrite);
        }
    }
    return json;

}