Example usage for java.security KeyManagementException getMessage

List of usage examples for java.security KeyManagementException getMessage

Introduction

In this page you can find the example usage for java.security KeyManagementException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.prasanna.android.http.SecureHttpHelper.java

protected HttpClient createSecureHttpClient() {
    try {//from   w  w  w  .  ja va2s  .c  o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SSLSocketFactoryX509(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme(SCHEME_HTTPS, sf, HTTPS_PORT));
        schemeRegistry.register(new Scheme(SCHEME_HTTP, PlainSocketFactory.getSocketFactory(), HTTP_PORT));

        return new DefaultHttpClient(new SingleClientConnManager(params, schemeRegistry), params);
    } catch (KeyManagementException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (KeyStoreException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (CertificateException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (IOException e) {
        LogWrapper.e(TAG, e.getMessage());
    }

    throw new ClientException(ClientErrorCode.HTTP_REQ_ERROR);
}

From source file:edu.indiana.d2i.htrc.corpus.retrieve.RetrieveRawCorpusMapper.java

@Override
protected void setup(Context context) throws IOException, InterruptedException {
    Configuration conf = context.getConfiguration();

    boolean success = false;
    try {//from   www  .  j  a  v a 2s .  com
        dataAPIAgent = new DataAPIWrapper(conf.get(Constants.DATA_API_EPR),
                conf.get(Constants.DATA_API_PAGE_PREFIX), conf.get(Constants.DATA_API_VOL_PREFIX),
                conf.get(Constants.DATA_API_DELIMITER),
                Boolean.parseBoolean(conf.get(Constants.DATA_API_CONCAT)), conf.get(Constants.OAUTH2_EPR),
                conf.get(Constants.OAUTH2_USER_NAME), conf.get(Constants.OAUTH2_USER_PASSWORD),
                Boolean.parseBoolean(conf.get(Constants.DATA_API_SELFSIGN)));

        success = true;
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error("KeyManagementException : " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error("NoSuchAlgorithmException : " + e.getMessage());
    } catch (OAuthSystemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error("OAuthSystemException : " + e.getMessage());
    } catch (OAuthProblemException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error("OAuthProblemException : " + e.getMessage());
    }

    if (!success) {
        System.err.println("Failed to instantiate dataAPI agent");
        logger.error("Failed to instantiate dataAPI agent");
        System.exit(-1);
    }

    // # of volumes per request
    numVolsPerReq = Integer
            .parseInt(conf.get(Constants.DATA_API_REQ_SIZE, Constants.DATA_API_DEFAULT_REQ_SIZE));
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Calls a http node of JEM to get group anme of Hazelcast cluster,
 * necessary to client to connect to JEM.
 * //  w  w  w .  ja va  2 s  .c  om
 * @param url http URL to call
 * @return group name of Hazelcast cluster
 * @throws SubmitException if errors occur
 */
public static String getGroupName(String url) throws SubmitException {
    // creates a HTTP client
    CloseableHttpClient httpclient = null;
    try {
        httpclient = createHttpClient(url);
        // concats URL with query string
        String completeUrl = url + HttpUtil.NAME_QUERY_STRING;
        // prepares GET request and basic response handler
        HttpGet httpget = new HttpGet(completeUrl);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // executes and no parsing
        // result must be only a string
        String responseBody = httpclient.execute(httpget, responseHandler);
        return responseBody.trim();
    } catch (KeyManagementException e) {
        throw new SubmitException(SubmitMessage.JEMW002E, e);
    } catch (UnrecoverableKeyException e) {
        throw new SubmitException(SubmitMessage.JEMW002E, e);
    } catch (NoSuchAlgorithmException e) {
        throw new SubmitException(SubmitMessage.JEMW002E, e);
    } catch (KeyStoreException e) {
        throw new SubmitException(SubmitMessage.JEMW002E, e);
    } catch (URISyntaxException e) {
        throw new SubmitException(SubmitMessage.JEMW002E, e);
    } catch (ClientProtocolException e) {
        throw new SubmitException(SubmitMessage.JEMW002E, e);
    } catch (IOException e) {
        throw new SubmitException(SubmitMessage.JEMW002E, e);
    } finally {
        // close http client
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}

From source file:org.openmrs.module.rheapocadapter.handler.RequestHandler.java

/**
 * gets method, message body and parameters and call the connection, send
 * and call the response handler//w w  w .j ava  2s. c  o m
 * 
 * @param method
 *            Method to use for sending, the first element is either get or
 *            post, the second is used while creating the URL to know what
 *            action to be done. e.g: GetClinicalData is different to
 *            GetClients, both are gets but has different URLs.
 * @param body
 *            message to be sent, it can be null.
 * @param parameter
 *            used to create URL
 */
public Transaction sendRequest(String[] method, String body, TreeMap<String, String> parameter) {
    ResponseHandler response = new ResponseHandler();
    String url = null;
    User creator = Context.getUserService().getUserByUsername(Context.getAuthenticatedUser().getUsername());
    int sender = creator.getUserId();
    try {
        ConnectionHandler conn = new ConnectionHandler();
        // create url according to method to be used and transaction
        // performed
        url = conn.createUrl(method[1], parameter);
        if ((url == null) || (url == "")) {
            throw new SocketTimeoutException();
        }
        log.info("URL= " + url);
        // if the method is GET or POST, send accordingly.
        if (method[0].equalsIgnoreCase("GET")) {
            Date sendDateTime = new Date();
            String[] result = conn.callGet(url);
            Date receiveDateTime = new Date();
            log.info("After callGet " + result[0] + " = " + result[1]);
            Transaction transaction = generateTransaction(sendDateTime, result[1], url, sender);
            Transaction item = response.generateMessage(transaction, Integer.parseInt(result[0]), method[0],
                    receiveDateTime);
            return item;

        } else if (method[0].equalsIgnoreCase("POST") || method[0].equalsIgnoreCase("PUT")) {

            Date sendDateTime = new Date();
            String[] result = conn.callPostAndPut(url, body, method[0]);
            Date receiveDateTime = new Date();

            Transaction transaction = generateTransaction(sendDateTime, result[1], url, sender);
            Transaction item = response.generateMessage(transaction, Integer.parseInt(result[0]), method[0],
                    receiveDateTime);
            return item;

        }
    } catch (KeyManagementException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method[0], receiveDateTime);
        log.error("KeyManagementException generated" + e.getMessage());
        return item;
    } catch (KeyStoreException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method[0], receiveDateTime);
        log.error("KeyStoreException generated" + e.getMessage());
        return item;
    } catch (NoSuchAlgorithmException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method[0], receiveDateTime);
        log.error("NoSuchAlgorithmException generated" + e.getMessage());
        return item;
    } catch (CertificateException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method[0], receiveDateTime);
        log.error("CertificateException generated" + e.getMessage());
        return item;
    } catch (TransformerFactoryConfigurationError e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method[0], receiveDateTime);
        log.error("TransformerFactoryConfigurationError generated" + e.getMessage());
        return item;
    } catch (SocketTimeoutException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 600, method[0], receiveDateTime);
        log.error("SocketTimeoutException generated " + e.getMessage());
        return item;
    } catch (IOException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 600, method[0], receiveDateTime);
        log.error("IOException generated " + e.getMessage());
        e.printStackTrace();
        return item;
    }
    log.info("Gonna return null");
    return null;
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Returns the job by its ID. If is not in output queue, normal <code>Object</code> is returned.
 * @param user user to authenticate/* w  ww.  j  a  va 2  s .  c  o m*/
 * @param password password to authenticate
 * @param url http URL to call
 * @param jobId jobId
 * @return Object Job instance of a normal <code>Object</code> is not ended
 * @throws SubmitException if errors occur
 */
public static Object getEndedJobByID(String user, String password, String url, String jobId)
        throws SubmitException {
    // creates a HTTP client
    CloseableHttpClient httpclient = null;
    boolean loggedIn = false;
    try {
        httpclient = createHttpClient(url);
        // prepares the entity to send via HTTP
        XStream streamer = new XStream();

        login(user, password, url, httpclient);
        loggedIn = true;
        // concats URL with query string
        String completeUrl = url + HttpUtil.ENDE_JOBID_QUERY_STRING + "?jobId=" + jobId;
        // prepares POST request and basic response handler
        HttpGet httpget = new HttpGet(completeUrl);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // executes and no parsing
        // result must be only a string
        String responseBody = httpclient.execute(httpget, responseHandler);
        return streamer.fromXML(responseBody.trim());
    } catch (KeyManagementException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (UnrecoverableKeyException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (NoSuchAlgorithmException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (KeyStoreException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (URISyntaxException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (ClientProtocolException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (IOException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } finally {
        if (loggedIn) {
            try {
                logout(url, httpclient);
            } catch (Exception e) {
                // debug
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
        }
        // close http client
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}

From source file:org.openmrs.module.rheapocadapter.handler.RequestHandler.java

/**
 * this works with the sheduled task//from  w w w.j  a  v  a2  s  .c om
 * 
 * @param method
 *            to use while sending the body
 * @param body
 *            Message to send
 * @param url
 *            URL to send to
 */

public Transaction sendRequest(String method, String body, String url) {

    ResponseHandler response = new ResponseHandler();
    User creator = Context.getUserService().getUserByUsername(TransactionUtil.getCreator().getUsername());
    int sender = creator.getUserId();
    try {
        ConnectionHandler conn = new ConnectionHandler();

        log.info("url to use: " + url);

        if (method.equalsIgnoreCase("GET")) {
            Date sendDateTime = new Date();
            String[] result = conn.callGet(url);
            Date receiveDateTime = new Date();
            Transaction transaction = generateTransaction(sendDateTime, result[1], url, sender);
            Transaction item = response.generateMessage(transaction, Integer.parseInt(result[0]), method,
                    receiveDateTime);
            return item;

        } else if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {

            Date sendDateTime = new Date();
            String[] result = conn.callPostAndPut(url, body, method);
            Date receiveDateTime = new Date();
            Transaction transaction = generateTransaction(sendDateTime, result[1], url, sender);
            Transaction item = response.generateMessage(transaction, Integer.parseInt(result[0]), method,
                    receiveDateTime);
            return item;

        }
    } catch (KeyManagementException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method, receiveDateTime);
        log.error("KeyManagementException generated" + e.getMessage());
        return item;
    } catch (KeyStoreException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method, receiveDateTime);
        log.error("KeyStoreException generated" + e.getMessage());
        return item;
    } catch (NoSuchAlgorithmException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method, receiveDateTime);
        log.error("NoSuchAlgorithmException generated" + e.getMessage());
        return item;
    } catch (CertificateException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method, receiveDateTime);
        log.error("CertificateException generated" + e.getMessage());
        return item;
    } catch (TransformerFactoryConfigurationError e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method, receiveDateTime);
        log.error("TransformerFactoryConfigurationError generated" + e.getMessage());
        return item;
    } catch (SocketTimeoutException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 600, method, receiveDateTime);
        log.error("SocketTimeoutException generated " + e.getMessage());
        return item;
    } catch (IOException e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 600, method, receiveDateTime);
        log.error("IOException generated " + e.getMessage());
        e.printStackTrace();
        return item;
    } catch (Exception e) {
        Date sendDateTime = new Date();
        Date receiveDateTime = new Date();
        Transaction transaction = generateTransaction(sendDateTime, e.getMessage(), url, sender);
        Transaction item = response.generateMessage(transaction, 400, method, receiveDateTime);
        log.error("IOException generated " + e.getMessage());
        e.printStackTrace();
        return item;
    }
    return null;

}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Calls a http node of JEM to submit a job.
 * //w  ww.j  a v  a 2  s. co m
 * @param user user to authenticate
 * @param password password to authenticate
 * @param url http URL to call
 * @param prejob job instance to submit
 * @return job id
 * @throws SubmitException if errors occur
 */
public static String submit(String user, String password, String url, PreJob prejob) throws SubmitException {
    // creates a HTTP client
    CloseableHttpClient httpclient = null;
    boolean loggedIn = false;
    try {
        httpclient = createHttpClient(url);
        // prepares the entity to send via HTTP
        XStream streamer = new XStream();
        String content = streamer.toXML(prejob);

        login(user, password, url, httpclient);
        loggedIn = true;
        // concats URL with query string
        String completeUrl = url + HttpUtil.SUBMIT_QUERY_STRING;
        StringEntity entity = new StringEntity(content,
                ContentType.create("text/xml", CharSet.DEFAULT_CHARSET_NAME));

        // prepares POST request and basic response handler
        HttpPost httppost = new HttpPost(completeUrl);
        httppost.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // executes and no parsing
        // result must be only a string
        String responseBody = httpclient.execute(httppost, responseHandler);
        return responseBody.trim();
    } catch (KeyManagementException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (UnrecoverableKeyException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (NoSuchAlgorithmException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (KeyStoreException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (URISyntaxException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (ClientProtocolException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } catch (IOException e) {
        throw new SubmitException(SubmitMessage.JEMW003E, e);
    } finally {
        if (loggedIn) {
            try {
                logout(url, httpclient);
            } catch (Exception e) {
                // debug
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
        }
        // close http client
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Calls a http node of JEM to get all members of group, necessary to client
 * to connect to JEM./*  w w  w. j  a v  a  2s .  c o  m*/
 * 
 * @param url http URL to call
 * @return Arrays with all members of Hazelcast cluster
 * @throws SubmitException if errors occur
 */
public static String[] getMembers(String url) throws SubmitException {
    // creates a HTTP client
    CloseableHttpClient httpclient = null;
    try {
        httpclient = createHttpClient(url);
        // concats URL with query string
        String completeUrl = url + HttpUtil.MEMBERS_QUERY_STRING;
        // prepares GET request and basic response handler
        HttpGet httpget = new HttpGet(completeUrl);
        CloseableHttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            long len = entity.getContentLength();
            if (len != -1 && len < 2048) {
                // executes and parse the results
                // result must be
                // [ipaddress:port],[ipaddress:port],[ipaddress:port],....[ipaddress:port]
                return EntityUtils.toString(entity).trim().split(",");
            } else {
                throw new IOException("HTTP Entity content length wrong: " + len);
            }
        }
        throw new IOException("HTTP Entity is null");
    } catch (KeyManagementException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (UnrecoverableKeyException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (NoSuchAlgorithmException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (KeyStoreException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (URISyntaxException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (ClientProtocolException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } catch (IOException e) {
        throw new SubmitException(SubmitMessage.JEMW001E, e);
    } finally {
        // close http client
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();

    final String ids_string = getMediaIds(pics, twitter);

    if (ids_string == null) {
        return false;
    }/*  w  ww. ja  v a2  s.c  o m*/

    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                        twitter_endpoint_path);

                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);

                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message",
                        "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {

    }
    return true;
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public String getMediaIds(File[] pics, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    String ids = "";

    for (int i = 0; i < pics.length; i++) {
        File file = pics[i];//from  w  w  w  .jav a2s .com
        try {
            AccessToken token = twitter.getOAuthAccessToken();
            String oauth_token = token.getToken();
            String oauth_token_secret = token.getTokenSecret();

            // generate authorization header
            String get_or_post = "POST";
            String oauth_signature_method = "HMAC-SHA1";

            String uuid_string = UUID.randomUUID().toString();
            uuid_string = uuid_string.replaceAll("-", "");
            String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

            // get the timestamp
            Calendar tempcal = Calendar.getInstance();
            long ts = tempcal.getTimeInMillis();// get current time in milliseconds
            String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

            // the parameter string must be in alphabetical order, "text" parameter added at end
            String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                    + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                    + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
            System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

            String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json";
            String twitter_endpoint_host = "upload.twitter.com";
            String twitter_endpoint_path = "/1.1/media/upload.json";
            String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                    + encode(parameter_string);
            String oauth_signature = computeSignature(signature_base_string,
                    AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

            String authorization_header_string = "OAuth oauth_consumer_key=\""
                    + AppSettings.TWITTER_CONSUMER_KEY
                    + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                    + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
            HttpProtocolParams.setUseExpectContinue(params, false);
            HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                    // Required protocol interceptors
                    new RequestContent(), new RequestTargetHost(),
                    // Recommended protocol interceptors
                    new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
            HttpContext context = new BasicHttpContext(null);
            HttpHost host = new HttpHost(twitter_endpoint_host, 443);
            DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

            try {
                try {
                    SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory ssf = sslcontext.getSocketFactory();
                    Socket socket = ssf.createSocket();
                    socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                    conn.bind(socket, params);

                    BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                            twitter_endpoint_path);

                    // need to add status parameter to this POST
                    MultipartEntity reqEntity = new MultipartEntity();

                    FileBody sb_image = new FileBody(file);
                    reqEntity.addPart("media", sb_image);

                    request2.setEntity(reqEntity);
                    request2.setParams(params);

                    request2.addHeader("Authorization", authorization_header_string);
                    System.out.println(
                            "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                    System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
                    response2.setParams(params);
                    httpexecutor.postProcess(response2, httpproc, context);
                    String responseBody = EntityUtils.toString(response2.getEntity());
                    System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
                    // error checking here. Otherwise, status should be updated.
                    jsonresponse = new JSONObject(responseBody);
                    if (jsonresponse.has("errors")) {
                        JSONObject temp_jo = new JSONObject();
                        temp_jo.put("response_status", "error");
                        temp_jo.put("message",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
                        temp_jo.put("twitter_code",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
                        jsonresponse = temp_jo;
                    }

                    // add it to the media_ids string
                    ids += jsonresponse.getString("media_id_string");
                    if (i != pics.length - 1) {
                        ids += ",";
                    }

                    conn.close();
                } catch (HttpException he) {
                    System.out.println(he.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia HttpException message=" + he.getMessage());
                    return null;
                } catch (NoSuchAlgorithmException nsae) {
                    System.out.println(nsae.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
                    return null;
                } catch (KeyManagementException kme) {
                    System.out.println(kme.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
                    return null;
                } finally {
                    conn.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
                return null;
            }
        } catch (Exception e) {
            return null;
        }

    }
    return ids;
}