Example usage for java.net URISyntaxException getMessage

List of usage examples for java.net URISyntaxException getMessage

Introduction

In this page you can find the example usage for java.net URISyntaxException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns a string describing the parse error.

Usage

From source file:com.unboundid.scim2.common.GenericScimResource.java

/**
 * Gets a URI value from a generic SCIM resource.  If the path exists,
 * the JSON node at the path must be a URI.  If the path does not exist,
 * "{@code null}" will be returned./*from w w w  . j  a  v a2s . co  m*/
 *   <p>
 *
 * For example:
 *   In a GenericScimResource (gsr) representing the following resource:
 * <pre><code>
 *   {
 *     "path1":"http://localhost:8080/uri/One"
 *   }
 * </code></pre>
 *   <p>
 *
 *   getURIValue(Path.fromString("path1"))
 *   returns "http://localhost:8080/uri/One"
 *   <p>
 *
 *   getURIValue(Path.fromString("bogusPath"))
 *   returns null
 *
 * @param path the path to get the value from.
 * @return the value at the path, or null.
 * @throws ScimException thrown if an error occurs.
 */
public URI getURIValue(final Path path) throws ScimException {
    try {
        JsonNode jsonNode = getValue(path);
        return jsonNode.isNull() ? null : new URI(jsonNode.textValue());
    } catch (URISyntaxException ex) {
        throw new ServerErrorException(ex.getMessage());
    }
}

From source file:com.unboundid.scim2.common.GenericScimResource.java

/**
 * Gets a list of URI from a generic SCIM resource.  If the path exists,
 * the JSON node at the path must be a list of URI.  If the path
 * does not exist, an empty list will be returned.
 *   <p>/*from  w ww .  java2s. c  om*/
 *
 * For example:
 *   In a GenericScimResource (gsr) representing the following resource:
 * <pre><code>
 *   {
 *     "path1":
 *     [
 *         "http://localhost:8080/uri/One", "http://localhost:8080/uri/Two"
 *     ]
 *   }
 * </code></pre>
 *   <p>
 *
 *   getURIValueList(Path.fromString("path1"))
 *   returns a list containing
 *       "http://localhost:8080/uri/One", "http://localhost:8080/uri/Two"
 *   <p>
 *
 *   getURIValueList(Path.fromString("bogusPath"))
 *   returns an empty list
 *   <p>
 *
 * @param path the path to get the value from.
 * @return the value at the path, or an empty list.
 * @throws ScimException thrown if an error occurs.
 */
public List<URI> getURIValueList(final Path path) throws ScimException {
    try {
        JsonNode valueNode = getValue(path);
        List<URI> values = new ArrayList<URI>();

        Iterator<JsonNode> iterator = valueNode.iterator();
        while (iterator.hasNext()) {
            String uriString = iterator.next().textValue();
            values.add(new URI(uriString));
        }
        return values;
    } catch (URISyntaxException ex) {
        throw new ServerErrorException(ex.getMessage());
    }
}

From source file:co.adrianblan.noraoke.SongNowPlayingFragment.java

private void connectWebSocket() {
    URI uri;//  w ww . j av  a  2  s . c  o  m
    try {
        //URL to a DigitalOcean instance in Singapore, dedicated to Noraoke
        uri = new URI("ws://128.199.134.30:8000/");
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }

    System.out.println("Opening socket");

    mWebSocketClient = new WebSocketClient(uri) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");
            mWebSocketClient.send("HELLO");
        }

        @Override
        public void onMessage(String s) {
            final String message = s;

            //Thread?
            System.out.println(message);

            //If it's connection messages we quit
            if (message.contains("HELLO") || message.contains("connected")) {
                return;
            }

            //If the others pause, we pause too
            if (message.contains("STOP")) {
                mPlayer.pause();
                return;
            }

            //Otherwise we need to seek to their position

            //The strings are split into three parts by " - " as token
            String[] result = message.split("\\s-\\s");

            //The first part is IP, the second the time it was played and third where in the song it was played
            if (result.length != 3) {
                return;
            }

            //Get the time in milliseconds
            //long timeshift = (System.currentTimeMillis() - Long.parseLong(result[1]));
            long timeshift = 250;
            int seekTo = Integer.parseInt(result[2]) + (int) timeshift;

            System.out.println("timeshift: " + timeshift + " + " + Integer.parseInt(result[2]));

            //The seek must be fitting within the song
            if (seekTo >= 0 && seekTo < mPlayer.getDuration()) {
                mPlayer.seekTo(seekTo);

                //If it's not playing, start
                if (!mPlayer.isPlaying()) {

                    //Only play if activity is in foreground
                    if (MainActivity.isInForeground()) {
                        mPlayer.start();
                    }
                }
            }

        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };
    mWebSocketClient.connect();
}

From source file:com.algolia.search.saas.APIClient.java

private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json,
        HashMap<String, String> errors) throws AlgoliaException {
    req.reset();// www.j a va  2  s  .co  m

    // set URL
    try {
        req.setURI(new URI("https://" + host + url));
    } catch (URISyntaxException e) {
        // never reached
        throw new IllegalStateException(e);
    }

    // set auth headers
    req.setHeader("X-Algolia-Application-Id", this.applicationID);
    if (forwardAdminAPIKey == null) {
        req.setHeader("X-Algolia-API-Key", this.apiKey);
    } else {
        req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey);
        req.setHeader("X-Forwarded-For", this.forwardEndUserIP);
        req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey);
    }
    for (Entry<String, String> entry : headers.entrySet()) {
        req.setHeader(entry.getKey(), entry.getValue());
    }

    // set user agent
    req.setHeader("User-Agent", "Algolia for Java " + version);

    // set JSON entity
    if (json != null) {
        if (!(req instanceof HttpEntityEnclosingRequestBase)) {
            throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity");
        }
        req.setHeader("Content-type", "application/json");
        try {
            StringEntity se = new StringEntity(json, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            ((HttpEntityEnclosingRequestBase) req).setEntity(se);
        } catch (UnsupportedEncodingException e) {
            throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$
        }
    }

    RequestConfig config = RequestConfig.custom().setSocketTimeout(httpSocketTimeoutMS)
            .setConnectTimeout(httpConnectTimeoutMS).setConnectionRequestTimeout(httpConnectTimeoutMS).build();
    req.setConfig(config);

    HttpResponse response;
    try {
        response = httpClient.execute(req);
    } catch (IOException e) {
        // on error continue on the next host
        errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage()));
        return null;
    }
    try {
        int code = response.getStatusLine().getStatusCode();
        if (code / 100 == 4) {
            String message = "";
            try {
                message = EntityUtils.toString(response.getEntity());
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (code == 400) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request");
            } else if (code == 403) {
                throw new AlgoliaException(code,
                        message.length() > 0 ? message : "Invalid Application-ID or API-Key");
            } else if (code == 404) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist");
            } else {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Error");
            }
        }
        if (code / 100 != 2) {
            try {
                errors.put(host, EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                errors.put(host, String.valueOf(code));
            }
            // KO, continue
            return null;
        }
        try {
            InputStream istream = response.getEntity().getContent();
            InputStreamReader is = new InputStreamReader(istream, "UTF-8");
            JSONTokener tokener = new JSONTokener(is);
            JSONObject res = new JSONObject(tokener);
            is.close();
            return res;
        } catch (IOException e) {
            return null;
        } catch (JSONException e) {
            throw new AlgoliaException("JSON decode error:" + e.getMessage());
        }
    } finally {
        req.releaseConnection();
    }
}

From source file:org.dasein.cloud.cloudsigma.CloudSigmaMethod.java

public @Nullable String getString(@Nonnull String resource) throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + CloudSigma.class.getName() + ".getString(" + resource + ")");
    }//from   ww  w .j a v  a2s .  com

    try {
        String target = getEndpoint(resource);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [GET (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new CloudSigmaConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }
                HttpGet get = new HttpGet(target);
                String auth;

                try {
                    String userName = new String(ctx.getAccessPublic(), "utf-8");
                    String password = new String(ctx.getAccessPrivate(), "utf-8");

                    auth = new String(Base64.encodeBase64((userName + ":" + password).getBytes()));
                } catch (UnsupportedEncodingException e) {
                    throw new InternalException(e);
                }
                //dmayne 20130218: add JSON headers
                get.addHeader("Host", uri.getHost());
                get.addHeader("Content-Type", "application/json; charset=utf-8");
                get.addHeader("Accept", "application/json");
                get.addHeader("Authorization", "Basic " + auth);

                if (wire.isDebugEnabled()) {
                    wire.debug(get.getRequestLine().toString());
                    for (Header header : get.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    response = client.execute(get);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND) {
                    return null;
                }
                if (status.getStatusCode() != OK && status.getStatusCode() != NO_CONTENT) {
                    logger.error("Expected OK for GET request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();
                    String body;

                    if (entity == null) {
                        throw new CloudSigmaException(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudSigmaException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    if (status.getStatusCode() == BAD_REQUEST && body.contains("could not be found")) {
                        return null;
                    }
                    throw new CloudSigmaException(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), body);
                } else {
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        return "";
                    }
                    String body;

                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudSigmaException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    return body;
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [GET (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + CloudSigma.class.getName() + ".getString()");
        }
    }
}

From source file:org.dasein.cloud.skeleton.RESTMethod.java

public void delete(@Nonnull String resource, @Nonnull String id, @Nullable NameValuePair... parameters)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + RESTMethod.class.getName() + ".delete(" + resource + "," + id + ","
                + Arrays.toString(parameters) + ")");
    }/*ww w.  ja  v  a  2s.c  o  m*/
    try {
        String target = getEndpoint(resource, id, parameters);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [DELETE (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new ConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }
                HttpDelete delete = new HttpDelete(target);

                long timestamp = System.currentTimeMillis();

                String signature = getSignature(ctx.getAccessPublic(), ctx.getAccessPrivate(), "DELETE",
                        resource, id, timestamp);

                try {
                    delete.addHeader(ACCESS_KEY_HEADER, new String(ctx.getAccessPublic(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new InternalException(e);
                }
                delete.addHeader("Accept", "application/json");
                delete.addHeader(SIGNATURE_HEADER, signature);
                delete.addHeader(VERSION_HEADER, VERSION);

                if (wire.isDebugEnabled()) {
                    wire.debug(delete.getRequestLine().toString());
                    for (Header header : delete.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "DELETE " + resource);
                    response = client.execute(delete);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND) {
                    throw new CloudException("No such endpoint: " + target);
                }
                if (status.getStatusCode() != NO_CONTENT) {
                    logger.error("Expected NO CONTENT for DELETE request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudProviderException(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    String body;

                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudProviderException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    throw new CloudProviderException(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), body);
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [DELETE (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + RESTMethod.class.getName() + ".delete()");
        }
    }
}

From source file:org.dasein.cloud.skeleton.RESTMethod.java

private void get(@Nonnull APIResponse apiResponse, @Nullable String paginationId, final int page,
        final @Nonnull String resource, final @Nullable String id, final @Nullable NameValuePair... parameters)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + RESTMethod.class.getName() + ".get(" + paginationId + "," + page + ","
                + resource + "," + id + "," + Arrays.toString(parameters) + ")");
    }//www  .jav a  2 s .  c om
    try {
        NameValuePair[] params;

        if (parameters != null && paginationId != null) {
            if (parameters == null || parameters.length < 1) {
                params = new NameValuePair[] { new BasicNameValuePair("requestPaginationId", paginationId),
                        new BasicNameValuePair("requestPage", String.valueOf(page)) };
            } else {
                params = new NameValuePair[parameters.length + 2];

                int i = 0;

                for (; i < parameters.length; i++) {
                    params[i] = parameters[i];
                }
                params[i++] = new BasicNameValuePair("requestPaginationId", paginationId);
                params[i] = new BasicNameValuePair("requestPage", String.valueOf(page));
            }
        } else {
            params = parameters;
        }
        String target = getEndpoint(resource, id, params);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [GET (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new ConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }
                HttpGet get = new HttpGet(target);
                long timestamp = System.currentTimeMillis();

                String signature = getSignature(ctx.getAccessPublic(), ctx.getAccessPrivate(), "GET", resource,
                        id, timestamp);

                try {
                    get.addHeader(ACCESS_KEY_HEADER, new String(ctx.getAccessPublic(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new InternalException(e);
                }
                get.addHeader("Accept", "application/json");
                get.addHeader(SIGNATURE_HEADER, signature);
                get.addHeader(VERSION_HEADER, VERSION);

                if (wire.isDebugEnabled()) {
                    wire.debug(get.getRequestLine().toString());
                    for (Header header : get.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "GET " + resource);
                    response = client.execute(get);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND) {
                    apiResponse.receive();
                    return;
                }
                if (status.getStatusCode() != OK) {
                    logger.error("Expected OK for GET request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();
                    String body;

                    if (entity == null) {
                        throw new CloudProviderException(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudProviderException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    apiResponse.receive(new CloudProviderException(CloudErrorType.GENERAL,
                            status.getStatusCode(), status.getReasonPhrase(), body));
                } else {
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudException("No entity was returned from an HTTP GET");
                    }
                    boolean complete;

                    Header h = response.getFirstHeader("x-es-pagination");
                    final String pid;

                    if (h != null) {
                        pid = h.getValue();

                        if (pid != null) {
                            Header last = response.getFirstHeader("x-es-last-page");

                            complete = last != null && last.getValue().equalsIgnoreCase("true");
                        } else {
                            complete = true;
                        }
                    } else {
                        pid = null;
                        complete = true;
                    }
                    if (entity.getContentType() == null
                            || entity.getContentType().getValue().contains("json")) {
                        String body;

                        try {
                            body = EntityUtils.toString(entity);
                        } catch (IOException e) {
                            throw new CloudProviderException(e);
                        }
                        if (wire.isDebugEnabled()) {
                            wire.debug(body);
                        }
                        wire.debug("");

                        try {
                            apiResponse.receive(status.getStatusCode(), new JSONObject(body), complete);
                        } catch (JSONException e) {
                            throw new CloudException(e);
                        }
                    } else {
                        try {
                            apiResponse.receive(status.getStatusCode(), entity.getContent());
                        } catch (IOException e) {
                            throw new CloudException(e);
                        }
                    }
                    if (!complete) {
                        APIResponse r = new APIResponse();

                        apiResponse.setNext(r);
                        get(r, pid, page + 1, resource, id, parameters);
                    }
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [GET (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + RESTMethod.class.getName() + ".get()");
        }
    }
}

From source file:com.cloudant.sync.cordova.CloudantSyncPlugin.java

/**
 * Creates a new Replicator/*w  ww.j a  v a2 s . c om*/
 * @param documentStoreName - The name of the DocumentStore
 * @param remoteURI - The remote database URI
 * @param type - The type of replication to be performed
 * @param token - The unique token id of the Replicator
 * @param callbackContext - The javascript callback to execute when complete or errored
 */
private void createReplicator(final String documentStoreName, final String remoteURI, final String type,
        final Integer token, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override
        public void run() {
            try {
                DocumentStore ds = getDocumentStore(documentStoreName);

                if (remoteURI == null || type == null || token == null) {
                    throw new Exception("Replicator uri, type, and token must not be null");
                }

                URI uri;
                try {
                    uri = new URI(remoteURI);
                } catch (URISyntaxException e) {
                    throw new Exception("Invalid uri: " + remoteURI);
                }

                Replicator replicator;
                final SyncPluginInterceptor interceptor = new SyncPluginInterceptor(callbackContext);
                if (type.equals("push")) {
                    replicator = ReplicatorBuilder.push().to(uri).from(ds)
                            .addRequestInterceptors((HttpConnectionRequestInterceptor) interceptor)
                            .addResponseInterceptors((HttpConnectionResponseInterceptor) interceptor).build();
                } else if (type.equals("pull")) {
                    replicator = ReplicatorBuilder.pull().from(uri).to(ds)
                            .addRequestInterceptors((HttpConnectionRequestInterceptor) interceptor)
                            .addResponseInterceptors((HttpConnectionResponseInterceptor) interceptor).build();
                } else {
                    throw new Exception("Replicator 'type' must be either 'push' or 'pull'. Received: " + type);
                }

                if (replicator == null) {
                    throw new Exception("Failed to create " + type + " Replicator. Builder returned null");
                }

                replicator.getEventBus().register(new SyncPluginListener(callbackContext));

                replicators.put(token, replicator);
                interceptors.put(token, interceptor);

                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);

            } catch (Exception e) {
                callbackContext.error(e.getMessage());
            }
        }
    });
}

From source file:org.dasein.cloud.cloudsigma.CloudSigmaMethod.java

public @Nullable String deleteString(@Nonnull String resource, @Nonnull String body)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + CloudSigma.class.getName() + ".deleteString(" + resource + "," + body + ")");
    }/*from www .  j  a v a 2  s.  c om*/

    try {
        String target = getEndpoint(resource);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [DELETE (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new CloudSigmaConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }
                HttpDelete delete = new HttpDelete(target);
                String auth;

                try {
                    String userName = new String(ctx.getAccessPublic(), "utf-8");
                    String password = new String(ctx.getAccessPrivate(), "utf-8");

                    auth = new String(Base64.encodeBase64((userName + ":" + password).getBytes()));
                } catch (UnsupportedEncodingException e) {
                    throw new InternalException(e);
                }
                //dmayne 20130218: add new JSON headers
                delete.addHeader("Host", uri.getHost());
                delete.addHeader("Content-Type", "application/json; charset=utf-8");
                delete.addHeader("Accept", "application/json");
                delete.addHeader("Authorization", "Basic " + auth);

                if (wire.isDebugEnabled()) {
                    wire.debug(delete.getRequestLine().toString());
                    for (Header header : delete.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                    wire.debug(body);
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    response = client.execute(delete);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND) {
                    return null;
                }
                if (status.getStatusCode() != OK && status.getStatusCode() != NO_CONTENT) {
                    logger.error("Expected OK for DELETE request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudSigmaException(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudSigmaException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    throw new CloudSigmaException(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), body);
                } else {
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        return "";
                    }
                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new CloudSigmaException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    return body;
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [DELETE (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + CloudSigma.class.getName() + ".deleteString()");
        }
    }
}