Example usage for java.net SocketTimeoutException SocketTimeoutException

List of usage examples for java.net SocketTimeoutException SocketTimeoutException

Introduction

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

Prototype

public SocketTimeoutException() 

Source Link

Document

Construct a new SocketTimeoutException with no detailed message.

Usage

From source file:com.google.code.jerseyclients.asynchttpclient.AsyncHttpClientJerseyClientHandler.java

/**
 * @see com.sun.jersey.api.client.ClientHandler#handle(com.sun.jersey.api.client.ClientRequest)
 */// w  w  w. ja  va  2  s  .c  om
public ClientResponse handle(final ClientRequest clientRequest) throws ClientHandlerException {

    final BoundRequestBuilder boundRequestBuilder = getBoundRequestBuilder(clientRequest);

    PerRequestConfig perRequestConfig = new PerRequestConfig();
    perRequestConfig.setRequestTimeoutInMs(this.jerseyHttpClientConfig.getReadTimeOut());

    if (this.jerseyHttpClientConfig.getProxyInformation() != null) {
        ProxyServer proxyServer = new ProxyServer(jerseyHttpClientConfig.getProxyInformation().getProxyHost(),
                jerseyHttpClientConfig.getProxyInformation().getProxyPort());
        perRequestConfig = new PerRequestConfig(proxyServer, this.jerseyHttpClientConfig.getReadTimeOut());
    }

    boundRequestBuilder.setPerRequestConfig(perRequestConfig);

    if (this.jerseyHttpClientConfig.getApplicationCode() != null) {
        boundRequestBuilder.addHeader(this.jerseyHttpClientConfig.getApplicationCodeHeader(),
                this.jerseyHttpClientConfig.getApplicationCode());
    }
    if (this.jerseyHttpClientConfig.getOptionnalHeaders() != null) {
        for (Entry<String, String> entry : this.jerseyHttpClientConfig.getOptionnalHeaders().entrySet()) {
            boundRequestBuilder.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (StringUtils.equalsIgnoreCase("POST", clientRequest.getMethod())) {

        if (clientRequest.getEntity() != null) {
            final RequestEntityWriter re = getRequestEntityWriter(clientRequest);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                re.writeRequestEntity(new CommittingOutputStream(baos) {
                    @Override
                    protected void commit() throws IOException {
                        writeOutBoundHeaders(clientRequest.getHeaders(), boundRequestBuilder);
                    }
                });
            } catch (IOException ex) {
                throw new ClientHandlerException(ex);
            }

            boundRequestBuilder.setBody(new ByteArrayInputStream(baos.toByteArray()));

        }
    } else {
        writeOutBoundHeaders(clientRequest.getHeaders(), boundRequestBuilder);
    }
    try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.reset();
        stopWatch.start();
        Future<Response> futureResponse = boundRequestBuilder.execute();
        Response response = futureResponse.get();
        int httpReturnCode = response.getStatusCode();
        stopWatch.stop();
        log.info("time to call rest url " + clientRequest.getURI() + ", " + stopWatch.getTime() + " ms");
        // in case of empty content returned we returned an empty stream
        // to return a null object
        if (httpReturnCode == Status.NO_CONTENT.getStatusCode()) {
            new ClientResponse(httpReturnCode, getInBoundHeaders(response), IOUtils.toInputStream(""),
                    getMessageBodyWorkers());
        }
        return new ClientResponse(httpReturnCode, getInBoundHeaders(response),
                response.getResponseBodyAsStream() == null ? IOUtils.toInputStream("")
                        : response.getResponseBodyAsStream(),
                getMessageBodyWorkers());
    } catch (Exception e) {
        if (e.getCause() != null && (e.getCause() instanceof TimeoutException)) {
            throw new ClientHandlerException(new SocketTimeoutException());
        }
        throw new ClientHandlerException(e);
    }
}

From source file:gov.nasa.ensemble.common.io.RemotableFile.java

/**
 * Get the concrete file from this locator. If the file is available
 * remotely but not present locally, it will be downloaded before this
 * method returns. Callers should be prepared for this method to block for
 * some time./*from w ww  .  ja va  2s .co  m*/
 * 
 * Note that the file returned from this method may not exist - this happens
 * if there was no remote counterpart, or the counterpart could not be
 * retrieved, AND the file is not already present on the local disk.
 * 
 * @param useCache
 *            by default this method is chained from getFile(), which uses
 *            the cache everywhere in an Ensemble application. Things like
 *            servlets need to call this method directly with useCache =
 *            false to workaround using the cache, since they do not cache
 *            data, and using the RCP extension registry is problematic.
 *            This is also appropriate when the file should not be
 *            downloaded regardless of whether the file exists or not.
 * @return the requested file, if it exists.
 * @throws IOException 
 */
public File getFile(boolean useCache, int socketTimeout) throws SocketTimeoutException {
    if (!useCache || override_mode == REMOTE_FILE_MODES.LOCAL_ONLY) {
        return localFile;
    }
    if (!localFile.exists())
        try {
            downloadRemoteFile(socketTimeout);
        } catch (HttpException hre) {
            // HACK HACK HACK
            if (hre.getMessage().contains("SocketTimeoutException"))
                throw new SocketTimeoutException();
            trace.warn("Error obtaining " + remoteFile, hre);
        } catch (Exception e) {
            trace.warn("Error obtaining " + remoteFile, e);
        }
    else {
        cacheAccessed();
    }
    return localFile;
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * Write upload POST request with file generated randomly.
 *//*from  w  ww.j  av a 2s.com*/
public void writeUpload(final String hostname, final int port, final String uri, final int fileSizeOctet) {

    mSpeedTestMode = SpeedTestMode.UPLOAD;

    this.mHostname = hostname;
    this.mPort = port;
    mUploadFileSize = new BigDecimal(fileSizeOctet);
    mForceCloseSocket = false;
    mErrorDispatched = false;
    mUploadTempFileSize = 0;
    mTimeStart = System.currentTimeMillis();

    connectAndExecuteTask(new Runnable() {
        @Override
        public void run() {
            if (mSocket != null && !mSocket.isClosed()) {

                RandomAccessFile uploadFile = null;
                final RandomGen randomGen = new RandomGen();

                try {

                    byte[] body = new byte[] {};

                    if (mSocketInterface.getUploadStorageType() == UploadStorageType.RAM_STORAGE) {
                        /* generate a file with size of fileSizeOctet octet */
                        body = randomGen.generateRandomArray(fileSizeOctet);
                    } else {
                        uploadFile = randomGen.generateRandomFile(fileSizeOctet);
                        uploadFile.seek(0);
                    }

                    final String head = "POST " + uri + " HTTP/1.1\r\n" + "Host: " + hostname + "\r\nAccept: "
                            + "*/*\r\nContent-Length: " + fileSizeOctet + "\r\n\r\n";

                    mUploadTempFileSize = 0;

                    final int uploadChunkSize = mSocketInterface.getUploadChunkSize();

                    final int step = fileSizeOctet / uploadChunkSize;
                    final int remain = fileSizeOctet % uploadChunkSize;

                    if (mSocket.getOutputStream() != null) {

                        if (writeFlushSocket(head.getBytes()) != 0) {
                            throw new SocketTimeoutException();
                        }

                        mTimeStart = System.currentTimeMillis();
                        mTimeEnd = 0;

                        if (mRepeatWrapper.isFirstUpload()) {
                            mRepeatWrapper.setFirstUploadRepeat(false);
                            mRepeatWrapper.setStartDate(mTimeStart);
                        }

                        if (mRepeatWrapper.isRepeatUpload()) {
                            mRepeatWrapper.updatePacketSize(mUploadFileSize);
                        }

                        for (int i = 0; i < step; i++) {

                            final byte[] chunk = SpeedTestUtils.readUploadData(
                                    mSocketInterface.getUploadStorageType(), body, uploadFile,
                                    mUploadTempFileSize, uploadChunkSize);

                            if (writeFlushSocket(chunk) != 0) {
                                throw new SocketTimeoutException();
                            }

                            mUploadTempFileSize += uploadChunkSize;

                            if (mRepeatWrapper.isRepeatUpload()) {
                                mRepeatWrapper.updateTempPacketSize(uploadChunkSize);
                            }

                            if (!mReportInterval) {
                                final SpeedTestReport report = mSocketInterface.getLiveUploadReport();

                                for (int j = 0; j < mListenerList.size(); j++) {
                                    mListenerList.get(j).onUploadProgress(report.getProgressPercent(), report);
                                }
                            }
                        }

                        final byte[] chunk = SpeedTestUtils.readUploadData(
                                mSocketInterface.getUploadStorageType(), body, uploadFile, mUploadTempFileSize,
                                remain);

                        if (remain != 0 && writeFlushSocket(chunk) != 0) {
                            throw new SocketTimeoutException();
                        } else {
                            mUploadTempFileSize += remain;

                            if (mRepeatWrapper.isRepeatUpload()) {
                                mRepeatWrapper.updateTempPacketSize(remain);
                            }
                        }

                        if (!mReportInterval) {
                            final SpeedTestReport report = mSocketInterface.getLiveUploadReport();

                            for (int j = 0; j < mListenerList.size(); j++) {
                                mListenerList.get(j).onUploadProgress(SpeedTestConst.PERCENT_MAX.floatValue(),
                                        report);

                            }
                        }
                    }
                } catch (SocketTimeoutException e) {
                    mReportInterval = false;
                    mErrorDispatched = true;
                    closeSocket();
                    closeExecutors();
                    if (!mForceCloseSocket) {
                        SpeedTestUtils.dispatchSocketTimeout(mForceCloseSocket, mListenerList, false,
                                SpeedTestConst.SOCKET_WRITE_ERROR);
                    } else {
                        SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage());
                    }
                } catch (IOException e) {
                    mReportInterval = false;
                    mErrorDispatched = true;
                    closeExecutors();
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, false, e.getMessage());
                } finally {
                    if (uploadFile != null) {
                        try {
                            uploadFile.close();
                            randomGen.deleteFile();
                        } catch (IOException e) {
                            //e.printStackTrace();
                        }
                    }
                }
            }
        }
    }, false);
}

From source file:gov.nasa.ensemble.common.io.RemotableFile.java

private File getConsistentFile(long modified, REMOTE_FILE_MODES myMode, int socketTimeout)
        throws SocketTimeoutException {
    Date modifiedDate = new Date(modified);
    DateFormat df = new SimpleDateFormat(DATE_FORMAT_STR);
    String formatedModifiedDate = df.format(modifiedDate);
    if (remoteFile == null) {
        return localFile;
    }/*  ww w  .j a  va2 s . co  m*/
    HttpConnectionParams.setSoTimeout(client.getParams(), socketTimeout);

    // tell the client to use the credential we got as parameter
    // if we have an authenticator
    Authenticator auth = AuthenticationUtil.getAuthenticator();
    if (auth != null) {
        if (client instanceof AbstractHttpClient) {
            ((AbstractHttpClient) client).getCredentialsProvider().setCredentials(
                    new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME), auth.getCredentials());
        }
        //         state.setAuthenticationPreemptive(true);
    }

    HttpResponse response = null;
    HttpGet get = new HttpGet(remoteFile.toString());
    HttpClientParams.setRedirecting(get.getParams(), false);
    HttpClientParams.setAuthenticating(get.getParams(), true);
    try {
        get.setHeader(HttpHeaders.IF_MODIFIED_SINCE, formatedModifiedDate);
        response = client.execute(get);
        if (HttpStatus.SC_NOT_MODIFIED == response.getStatusLine().getStatusCode()) {
            return localFile;
        } else if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            InputStream is = response.getEntity().getContent();
            getRemoteFileFromStream(is);
            if (REMOTE_FILE_MODES.CHECK_CUSTOM_TIMESTAMP == myMode) {
                localFile.setLastModified(customTimeStamp);
            } else {
                setModifiedTime(get);
            }
            return localFile;
        } else if (HttpStatus.SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
            remoteFileNotFound();
        }
    } catch (SocketTimeoutException e1) {
        throw e1;
    } catch (IOException e1) {
        // HACK HACK HACK HACK
        if (e1.getMessage().contains("SocketTimeoutException"))
            throw new SocketTimeoutException();
        else
            trace.warn("Error connecting to server when " + "checking the file modified time ", e1);
    } finally {
        try {
            HttpUtils.consume(get, response);
        } catch (IOException e) {
            trace.error(e);
        }
    }
    return localFile;

}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryWithExceptions(String dms_endpoint, String body, String method)
        throws SocketTimeoutException, ConnectException, IOException, InterruptedException {
    Cookie ck;/* w  ww  . j  ava 2s  .c om*/
    //String internalToken;
    CloseableHttpClient httpclient;
    HttpRequestBase httpaction;
    //boolean wasEmpty;
    //int code;

    httpclient = HttpClients.createDefault();

    URI uri = null;
    try {
        // Prepare to forward the request to the proxy
        uri = new URI(dms_URL + "/" + dms_endpoint);
    } catch (URISyntaxException e1) {
        java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
    }

    if (method.equals("GET")) {
        httpaction = new HttpGet(uri);
    } else {
        httpaction = new HttpPost(uri);
    }

    // Get token or authenticate if null or invalid
    //internalToken = client.getToken();
    ck = new Cookie("vitalAccessToken", cookie.substring(17));

    httpaction.setHeader("Cookie", ck.toString());
    httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)
            .setSocketTimeout(5000).build());
    httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON);

    StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8);

    if (method.equals("POST")) {
        ((HttpPost) httpaction).setEntity(strEntity);
    }

    // Execute and get the response.
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpaction);
    } catch (ClientProtocolException e) {
        throw new ClientProtocolException();
    } catch (IOException e) {
        try {
            // Try again with a higher timeout
            try {
                Thread.sleep(1000); // do not retry immediately
            } catch (InterruptedException e1) {
                throw new InterruptedException();
                // e1.printStackTrace();
            }
            httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000)
                    .setConnectTimeout(7000).setSocketTimeout(7000).build());
            response = httpclient.execute(httpaction);
        } catch (ClientProtocolException ea) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, ea);
            throw new ClientProtocolException();
        } catch (IOException ea) {
            try {
                // Try again with a higher timeout
                try {
                    Thread.sleep(1000); // do not retry immediately
                } catch (InterruptedException e1) {
                    java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
                    throw new InterruptedException();
                }
                httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000)
                        .setConnectTimeout(12000).setSocketTimeout(12000).build());
                response = httpclient.execute(httpaction);
            } catch (ClientProtocolException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ClientProtocolException();
            } catch (SocketTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new SocketTimeoutException();
            } catch (ConnectException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ConnectException();
            } catch (ConnectTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ConnectTimeoutException();
            }
        }
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
        if (statusCode == 503) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 503");
            throw new ServiceUnavailableException();
        } else if (statusCode == 502) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 502");
            throw new ServerErrorException(502);
        } else if (statusCode == 401) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "could't Athorize the DMS");
            throw new NotAuthorizedException("could't Athorize the DMS");
        } else {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 500");
            throw new ServiceUnavailableException();
        }
    }

    HttpEntity entity;
    entity = response.getEntity();
    String respString = "";

    if (entity != null) {
        try {
            respString = EntityUtils.toString(entity);
            response.close();
        } catch (ParseException | IOException e) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return respString;

}

From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuatorTest.java

public void recordsMetrics() throws IOException {
    final HttpClient client = prepareMockedClient(SC_PARTIAL_CONTENT, STUB_ETAG, STUB_CONTENT_RANGE,
            (long) STUB_CONTENT.length, STUB_RESPONSE_ENTITY);
    final MetricRegistry registry = new MetricRegistry();

    final InputStreamContinuator continuator = new ApacheHttpGetResponseEntityContentContinuator(client,
            new HttpGet(), STUB_MARKER, INFINITE_CONTINUATIONS, registry);

    final Optional<Histogram> maybeHistogram = registry
            .getHistograms((name, metric) -> name.equals(METRIC_NAME_CONTINUATIONS_PER_REQUEST)).values()
            .stream().findFirst();/*from   w  w  w .ja v a  2  s . c  o m*/

    assertTrue(maybeHistogram.isPresent());

    final Histogram histogram = maybeHistogram.get();
    assertEquals(histogram.getCount(), 0);

    continuator.buildContinuation(new SocketTimeoutException(), 0);

    final String expectedMetricName = METRIC_NAME_RECOVERED_EXCEPTION_PREFIX
            + SocketTimeoutException.class.getSimpleName();
    final Optional<Counter> maybeSocketTimeoutExceptionCounter = registry
            .getCounters((name, meter) -> name.equals(expectedMetricName)).values().stream().findFirst();

    assertTrue(maybeSocketTimeoutExceptionCounter.isPresent());

    final Counter socketTimeoutExceptionCounter = maybeSocketTimeoutExceptionCounter.get();

    assertEquals(socketTimeoutExceptionCounter.getCount(), 1);

    continuator.close();

    assertEquals(histogram.getCount(), 1);
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * Write download request to server host.
 *
 * @param data HTTP request to send to initiate download process
 *///from  w  w w  .  j  a  v  a 2  s . c  o m
private void writeDownload(final byte[] data) {

    connectAndExecuteTask(new Runnable() {
        @Override
        public void run() {

            if (mSocket != null && !mSocket.isClosed()) {

                try {
                    if ((mSocket.getOutputStream() != null) && (writeFlushSocket(data) != 0)) {
                        throw new SocketTimeoutException();
                    }
                } catch (SocketTimeoutException e) {
                    SpeedTestUtils.dispatchSocketTimeout(mForceCloseSocket, mListenerList, true,
                            SpeedTestConst.SOCKET_WRITE_ERROR);
                    closeSocket();
                    closeExecutors();
                } catch (IOException e) {
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, true, e.getMessage());
                    closeExecutors();
                }
            }
        }
    }, true);
}

From source file:org.apache.nifi.cluster.coordination.http.replication.TestThreadPoolRequestReplicator.java

@Test(timeout = 15000)
public void testLongWaitForResponse() {
    withReplicator(replicator -> {//w  w w .  j  a v  a 2s  . c  om
        final Set<NodeIdentifier> nodeIds = new HashSet<>();
        final NodeIdentifier nodeId = new NodeIdentifier("1", "localhost", 8000, "localhost", 8001, "localhost",
                8002, 8003, false);
        nodeIds.add(nodeId);
        final URI uri = new URI("http://localhost:8080/processors/1");
        final Entity entity = new ProcessorEntity();

        // set the user
        final Authentication authentication = new NiFiAuthenticationToken(
                new NiFiUserDetails(StandardNiFiUser.ANONYMOUS));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        final AsyncClusterResponse response = replicator.replicate(nodeIds, HttpMethod.GET, uri, entity,
                new HashMap<>(), true, true);

        // We should get back the same response object
        assertTrue(response == replicator.getClusterResponse(response.getRequestIdentifier()));

        final NodeResponse completedNodeResponse = response.awaitMergedResponse(2, TimeUnit.SECONDS);
        assertNotNull(completedNodeResponse);
        assertNotNull(completedNodeResponse.getThrowable());
        assertEquals(500, completedNodeResponse.getStatus());

        assertTrue(response.isComplete());
        assertNotNull(response.getMergedResponse());
        assertNull(replicator.getClusterResponse(response.getRequestIdentifier()));
    }, Status.OK, 1000, new ClientHandlerException(new SocketTimeoutException()));
}

From source file:org.openhab.binding.ihc.ws.IhcResourceInteractionService.java

/**
 * Wait runtime value notifications./*w w w  .j  a va  2 s .  c  o  m*/
 * 
 * Runtime value notification should firstly be activated by
 * enableRuntimeValueNotifications function.
 * 
 * @param timeoutInSeconds
 *            How many seconds to wait notifications.
 * @return List of received runtime value notifications.
 * @throws SocketTimeoutException 
 */
public List<? extends WSResourceValue> waitResourceValueNotifications(int timeoutInSeconds)
        throws IhcExecption, SocketTimeoutException {

    final String soapQuery = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:utcs=\"utcs\">"
            + "<soapenv:Header/>" + "<soapenv:Body>"
            + " <utcs:waitForResourceValueChanges1>%s</utcs:waitForResourceValueChanges1>" + "</soapenv:Body>"
            + "</soapenv:Envelope>";

    String query = String.format(soapQuery, timeoutInSeconds);
    openConnection(url);
    String response = sendQuery(query, timeout + timeoutInSeconds * 1000);
    closeConnection();

    List<WSResourceValue> resourceValueList = new ArrayList<WSResourceValue>();

    NodeList nodeList;
    try {
        nodeList = parseList(response,
                "/SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:waitForResourceValueChanges2/ns1:arrayItem");

        if (nodeList.getLength() == 1) {
            String resourceId = getValue(nodeList.item(0), "ns1:resourceID");
            if (resourceId == null || resourceId == "") {
                throw new SocketTimeoutException();
            }
        }

        for (int i = 0; i < nodeList.getLength(); i++) {

            int index = i + 2;

            WSResourceValue newVal = parseResourceValue(nodeList.item(i), index);
            resourceValueList.add(newVal);
        }

        return resourceValueList;

    } catch (XPathExpressionException e) {
        throw new IhcExecption(e);
    } catch (UnsupportedEncodingException e) {
        throw new IhcExecption(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//from www.  java  2 s. 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;
}