Example usage for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN

List of usage examples for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN.

Prototype

int SC_FORBIDDEN

To view the source code for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN.

Click Source Link

Document

<tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

private void testKey() throws WebStoreAttachmentKeyException {
    if (testKeyURLStr == null)
        return; // skip test if there is not test url.

    GetMethod method = new GetMethod(testKeyURLStr);
    String r = "" + (new Random()).nextInt();
    method.setQueryString(new NameValuePair[] { new NameValuePair("random", r),
            new NameValuePair("token", generateToken(r)) });

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    try {/*from  w  ww . j  a  v a 2  s.c  om*/
        int status = client.executeMethod(method);
        updateServerTimeDelta(method);
        if (status == HttpStatus.SC_OK) {
            return;
        } else if (status == HttpStatus.SC_FORBIDDEN) {
            throw new WebStoreAttachmentKeyException("Attachment key is invalid.");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
    throw new WebStoreAttachmentKeyException("Problem verifying attachment key.");
}

From source file:com.rallydev.integration.build.rest.RallyRestServiceTest.java

public void testRallyRestServiceIOFailure() throws Exception {
    String xml = readFile(BUILD_SUCCESS_FILE);
    httpClientMockControl.expectAndReturn(httpClientMock.executeMethod(postMethodMock),
            HttpStatus.SC_FORBIDDEN);
    postMethodMockControl.expectAndReturn(postMethodMock.getStatusLine(), statusLineMock);
    postMethodMock.releaseConnection();// w w w .j  a va  2  s  .  c o  m
    httpClientMockControl.replay();
    postMethodMockControl.replay();

    try {
        rallyRestService.doCreate(xml, httpClientMock, postMethodMock);
        fail();
    } catch (IOException e) {
    }

    verify();
}

From source file:com.kodokux.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;/*from w  ww .j a v a  2  s  . com*/
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        String message = getErrorMessage(method);
        if (message.contains("API rate limit exceeded")) {
            throw new GithubRateLimitExceededException(message);
        }
        throw new GithubAuthenticationException("Request response: " + message);
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:com.google.collide.server.fe.WebFE.java

/**
 * Writes cookies for the session ID that is posted to it.
 *//*w w w.  ja  v  a2s  . c o  m*/
private void writeSessionCookie(final HttpServerRequest req) {
    if (!"POST".equals(req.method)) {
        sendStatusCode(req, HttpStatus.SC_METHOD_NOT_ALLOWED);
        return;
    }

    // Extract the post data.
    req.bodyHandler(new Handler<Buffer>() {
        @Override
        public void handle(Buffer buff) {
            String contentType = req.headers().get("Content-Type");
            if ("application/x-www-form-urlencoded".equals(contentType)) {
                QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
                Map<String, List<String>> params = qsd.getParameters();

                List<String> loginSessionIdList = params.get(JsonFieldConstants.SESSION_USER_ID);
                List<String> usernameList = params.get(JsonFieldConstants.SESSION_USERNAME);
                if (loginSessionIdList == null || loginSessionIdList.size() == 0 || usernameList == null
                        || usernameList.size() == 0) {
                    sendStatusCode(req, 400);
                    return;
                }

                final String sessionId = loginSessionIdList.get(0);
                final String username = usernameList.get(0);
                vertx.eventBus().send("participants.authorise",
                        new JsonObject().putString("sessionID", sessionId).putString("username", username),
                        new Handler<Message<JsonObject>>() {
                            @Override
                            public void handle(Message<JsonObject> event) {
                                if ("ok".equals(event.body.getString("status"))) {
                                    req.response.headers().put("Set-Cookie", AUTH_COOKIE_NAME + "=" + sessionId
                                            + "__" + username + "; HttpOnly");
                                    sendStatusCode(req, HttpStatus.SC_OK);
                                } else {
                                    sendStatusCode(req, HttpStatus.SC_FORBIDDEN);
                                }
                            }
                        });
            } else {
                sendRedirect(req, "/static/login.html");
            }
        }
    });
}

From source file:com.ikanow.infinit.e.harvest.enrichment.legacy.opencalais.ExtractorOpenCalais.java

/**
 * Takes a feed with some of the information stored in it
 * such as title, desc, etc, and needs to parse the full
 * text and add entities, events, and other metadata.
 * /*from   ww w  .j a  v a 2s.  c  o m*/
 * @param partialDoc The feedpojo before extraction with fulltext field to extract on
 * @return The feedpojo after extraction with entities, events, and full metadata
 * @throws ExtractorDocumentLevelException 
 */
@Override
public void extractEntities(DocumentPojo partialDoc) throws ExtractorDocumentLevelException {
    if (null == partialDoc) {
        return;
    }
    configure(partialDoc.getTempSource());

    num_extraction_requests.incrementAndGet();
    try {
        if (null == partialDoc.getFullText()) {
            return;
        }
        if (partialDoc.getFullText().length() < 32) { // Else don't waste Extractor call/error logging
            return;
        }

        PostMethod method = createPostMethod(partialDoc.getFullText());
        int responseCode = client.executeMethod(method);

        if (responseCode == HttpStatus.SC_FORBIDDEN) //INF-1101 forbidden gets thrown when too many concurrent requests occur, try 14 more times
        {
            int count = 1;
            while (count < 15 && responseCode == HttpStatus.SC_FORBIDDEN) {
                try {
                    Thread.sleep(1800);
                } catch (Exception e) {
                } // carry on...

                responseCode = client.executeMethod(method); //attempt call again
                count++;
            }
            num_extraction_collisions.addAndGet(count);
        }

        if (responseCode == HttpStatus.SC_OK) {
            byte[] responseBytes = method.getResponseBody();
            String response = new String(responseBytes, "UTF-8");
            List<EntityPojo> entities = new ArrayList<EntityPojo>();
            List<AssociationPojo> events = new ArrayList<AssociationPojo>();
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readValue(response, JsonNode.class);
            Iterator<JsonNode> iter = root.getElements();
            Iterator<String> iterNames = root.getFieldNames();
            List<JsonNode> eventNodes = new ArrayList<JsonNode>();
            BasicDBList rawEventObjects = null;
            while (iter.hasNext()) {
                String currNodeName = iterNames.next();
                JsonNode currNode = iter.next();
                if (!currNodeName.equals("doc")) //we can assume these are the entities/topics
                {
                    String typeGroup = currNode.get("_typeGroup").getTextValue();
                    //check typegroup to see if it is an entity
                    if (typeGroup.equals("entities")) {
                        try {
                            EntityPojo ep = new EntityPojo();
                            //get what fields we can               
                            ep.setType(currNode.get("_type").getTextValue());
                            try {
                                ep.setDimension(DimensionUtility.getDimensionByType(ep.getType()));
                            } catch (java.lang.IllegalArgumentException e) {
                                ep.setDimension(EntityPojo.Dimension.What);
                            }
                            String name = "";
                            JsonNode nameNode = null;
                            try {
                                nameNode = currNode.get("name");
                                name = nameNode.getTextValue();
                            } catch (Exception ex) {
                                logger.debug("Error parsing name node: " + currNode.toString());
                                continue;
                            }
                            ep.setActual_name(name);
                            ep.setRelevance(Double.parseDouble(currNode.get("relevance").getValueAsText()));
                            ep.setFrequency((long) currNode.get("instances").size());
                            //attempt to get resolutions if they exist
                            JsonNode resolutionNode = currNode.get("resolutions");
                            if (null != resolutionNode) {
                                //resolution nodes are arrays
                                JsonNode resolutionFirst = resolutionNode.get(0);
                                ep.setSemanticLinks(new ArrayList<String>());
                                ep.getSemanticLinks().add(resolutionFirst.get("id").getTextValue()); //this is a link to an alchemy page
                                ep.setDisambiguatedName(resolutionFirst.get("name").getTextValue());
                                //check if we need to create a geo object
                                if (null != resolutionFirst.get("latitude")) {
                                    GeoPojo gp = new GeoPojo();
                                    String lat = resolutionFirst.get("latitude").getValueAsText();
                                    String lon = resolutionFirst.get("longitude").getValueAsText();
                                    gp.lat = Double.parseDouble(lat);
                                    gp.lon = Double.parseDouble(lon);
                                    ep.setGeotag(gp);
                                }
                            } else {
                                ep.setDisambiguatedName(name); // use actual name)                           
                            }
                            entityNameMap.put(currNodeName.toLowerCase(), ep);
                            entities.add(ep);
                        } catch (Exception ex) {
                            logger.error("Error creating event pojo from OpenCalaisNode: " + ex.getMessage(),
                                    ex);
                        }
                    } else if (typeGroup.equals("relations")) {
                        eventNodes.add(currNode);
                    }
                }
            }
            //handle events
            if (bAddRawEventsToMetadata) {
                // For now just re-process these into DB objects since we know that works...
                rawEventObjects = new BasicDBList();
            }
            for (JsonNode eventNode : eventNodes) {
                AssociationPojo event = parseEvent(eventNode);
                //remove useless events (an event is useless if it only has a verb (guessing currently)
                if (null != event) {
                    event = removeUselessEvents(event);
                    if (null != event) {
                        events.add(event);
                    }
                }
                if (bAddRawEventsToMetadata) {
                    BasicDBObject eventDbo = (BasicDBObject) com.mongodb.util.JSON.parse(eventNode.toString());
                    if (null != eventDbo) {
                        BasicDBObject transformObj = new BasicDBObject();
                        for (Map.Entry<String, Object> entries : eventDbo.entrySet()) {
                            if (entries.getValue() instanceof String) {
                                String val = (String) entries.getValue();
                                EntityPojo transformVal = findMappedEntityName(val);
                                if (null != transformVal) {
                                    transformObj.put(entries.getKey(), transformVal.getIndex());
                                    transformObj.put(entries.getKey() + "__hash", val);
                                } else {
                                    transformObj.put(entries.getKey(), val);
                                }
                            } else {
                                transformObj.put(entries.getKey(), entries.getValue());
                            }
                        }

                        // (add to another list, which will get written to metadata)
                        rawEventObjects.add(transformObj);
                    }
                }
            }
            if (bAddRawEventsToMetadata) {
                partialDoc.addToMetadata("OpenCalaisEvents", rawEventObjects.toArray());
            }
            if (null != partialDoc.getEntities()) {
                partialDoc.getEntities().addAll(entities);
                partialDoc.setEntities(partialDoc.getEntities());
            } else if (null != entities) {
                partialDoc.setEntities(entities);
            }
            if (null != partialDoc.getAssociations()) {
                partialDoc.getAssociations().addAll(events);
                partialDoc.setAssociations(partialDoc.getAssociations());
            } else if (null != events) {
                partialDoc.setAssociations(events);
            }
        } else // Error back from OC, presumably the input doc is malformed/too long
        {
            throw new InfiniteEnums.ExtractorDocumentLevelException(
                    "OpenCalais HTTP error code: " + Integer.toString(responseCode));
        }
    } catch (Exception e) {
        //DEBUG
        //e.printStackTrace();
        logger.debug("OpenCalais", e);
        //there was an error, so we return null instead
        throw new InfiniteEnums.ExtractorDocumentLevelException(e.getMessage());
    }
}

From source file:domderrien.wrapper.UrlFetch.UrlFetchHttpConnection.java

@Override
public String readLine(String charset) throws IOException, IllegalStateException {
    if (waitForHttpStatus) {
        // Dom Derrien: called only once to get the HTTP status, other information being read from the response output stream
        int responseCode = getResponse().getResponseCode();
        String line = "HTTP/1.1 " + responseCode;
        switch (responseCode) {
        case HttpStatus.SC_OK:
            line += " OK";
            break;
        case HttpStatus.SC_BAD_REQUEST:
            line += " BAD REQUEST";
            break;
        case HttpStatus.SC_UNAUTHORIZED:
            line += " UNAUTHORIZED";
            break;
        case HttpStatus.SC_FORBIDDEN:
            line += " FORBIDDEN";
            break;
        case HttpStatus.SC_NOT_FOUND:
            line += " NOT FOUND";
            break;
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            line += " INTERNAL SERVER ERROR";
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            line += " SERVICE UNAVAILABLE";
            break;
        default://  ww w .  j  av  a  2 s. c o m
            line = "HTTP/1.1 " + HttpStatus.SC_BAD_REQUEST + " BAD REQUEST";
        }
        waitForHttpStatus = false;
        return line;
    }
    throw new RuntimeException("readLine(String)");
}

From source file:edu.unc.lib.dl.ui.service.FedoraContentService.java

private void streamData(String simplepid, Datastream datastream, String slug, HttpServletResponse response,
        boolean asAttachment, int retryServerError) throws FedoraException, IOException {
    OutputStream outStream = response.getOutputStream();

    String dataUrl = fedoraUtil.getFedoraUrl() + "/objects/" + simplepid + "/datastreams/"
            + datastream.getName() + "/content";

    HttpClient client = HttpClientUtil.getAuthenticatedClient(dataUrl, accessClient.getUsername(),
            accessClient.getPassword());
    client.getParams().setAuthenticationPreemptive(true);
    GetMethod method = new GetMethod(dataUrl);
    method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());

    try {//from  w  w  w. j  a v a 2 s .  com
        client.executeMethod(method);

        if (method.getStatusCode() == HttpStatus.SC_OK) {
            if (response != null) {
                PID pid = new PID(simplepid);

                // Adjusting content related headers

                // Use the content length from Fedora it is not provided or negative, in which case use solr's
                long contentLength;
                try {
                    String contentLengthString = method.getResponseHeader("content-length").getValue();
                    contentLength = Long.parseLong(contentLengthString);
                } catch (Exception e) {
                    // If the content length wasn't provided or wasn't a number, set it to -1
                    contentLength = -1L;
                }
                if (contentLength < 0L) {
                    contentLength = datastream.getFilesize();
                }
                response.setHeader("Content-Length", Long.toString(contentLength));

                // Use Fedora's content type unless it is unset or octet-stream
                String mimeType;
                try {
                    mimeType = method.getResponseHeader("content-type").getValue();
                    if (mimeType == null || "application/octet-stream".equals(mimeType)) {
                        if ("mp3".equals(datastream.getExtension())) {
                            mimeType = "audio/mpeg";
                        } else {
                            mimeType = datastream.getMimetype();
                        }
                    }
                } catch (Exception e) {
                    mimeType = datastream.getMimetype();
                }
                response.setHeader("Content-Type", mimeType);

                // Setting the filename header for the response
                if (slug == null) {
                    slug = pid.getPid();
                }
                // For metadata types files, append the datastream name
                if (datastream.getDatastreamCategory().equals(DatastreamCategory.METADATA)
                        || datastream.getDatastreamCategory().equals(DatastreamCategory.ADMINISTRATIVE)) {
                    slug += "_" + datastream.getName();
                }
                // Add the file extension unless its already in there.
                if (datastream.getExtension() != null && datastream.getExtension().length() > 0
                        && !slug.toLowerCase().endsWith("." + datastream.getExtension())
                        && !"unknown".equals(datastream.getExtension())) {
                    slug += "." + datastream.getExtension();
                }
                if (asAttachment) {
                    response.setHeader("content-disposition", "attachment; filename=\"" + slug + "\"");
                } else {
                    response.setHeader("content-disposition", "inline; filename=\"" + slug + "\"");
                }
            }

            // Stream the content
            FileIOUtil.stream(outStream, method);
        } else if (method.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            throw new AuthorizationException(
                    "User does not have sufficient permissions to retrieve the specified object");
        } else {
            // Retry server errors
            if (method.getStatusCode() == 500 && retryServerError > 0) {
                LOG.warn("Failed to retrieve " + dataUrl + ", retrying.");
                this.streamData(simplepid, datastream, slug, response, asAttachment, retryServerError - 1);
            } else {
                throw new ResourceNotFoundException("Failure to stream fedora content due to response of: "
                        + method.getStatusLine().toString() + "\nPath was: " + dataUrl);
            }
        }
    } catch (ClientAbortException e) {
        if (LOG.isDebugEnabled())
            LOG.debug("User client aborted request to stream Fedora content for " + simplepid, e);
    } catch (HttpException e) {
        LOG.error("Error while attempting to stream Fedora content for " + simplepid, e);
    } catch (IOException e) {
        LOG.warn("Problem retrieving " + dataUrl + " for " + simplepid, e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Client call to upload the run back to the originating server.
 * This method does nothing if the run is local.
 * @param runId The id of the run// ww  w .  j a  v a2s .c o  m
 * @throws IOException If the upload fails
 */
public static void uploadIfOrigin(String runId) throws IOException {

    // 1. Check origin
    File originFile = new File(
            Config.OUT_DIR + File.separator + runId + File.separator + "META-INF" + File.separator + "origin");

    if (!originFile.isFile())
        return; // Is local run, do nothing.

    String originSpec = readStringFromFile(originFile);
    int idx = originSpec.lastIndexOf('.');
    if (idx == -1) { // This is wrong, we do not accept this.
        logger.severe("Bad origin spec.");
        return;
    }
    idx = originSpec.lastIndexOf('.', idx - 1);
    if (idx == -1) {
        logger.severe("Bad origin spec.");
        return;
    }

    String host = originSpec.substring(0, idx);
    String key = null;
    URL target = null;
    String proxyHost = null;
    int proxyPort = -1;

    // Search the poll hosts for this origin.
    for (int i = 0; i < Config.pollHosts.length; i++) {
        Config.HostInfo pollHost = Config.pollHosts[i];
        if (host.equals(pollHost.name)) {
            key = pollHost.key;
            target = new URL(pollHost.url, "upload");
            proxyHost = pollHost.proxyHost;
            proxyPort = pollHost.proxyPort;
            break;
        }
    }

    if (key == null) {
        logger.severe("Origin host/url/key not found!");
        return;
    }

    // 2. Jar up the run
    String[] files = new File(Config.OUT_DIR, runId).list();
    File jarFile = new File(Config.TMP_DIR, runId + ".jar");
    jar(Config.OUT_DIR + runId, files, jarFile.getAbsolutePath());

    // 3. Upload the run
    ArrayList<Part> params = new ArrayList<Part>();
    //MultipartPostMethod post = new MultipartPostMethod(target.toString());
    params.add(new StringPart("host", Config.FABAN_HOST));
    params.add(new StringPart("key", key));
    params.add(new StringPart("origin", "true"));
    params.add(new FilePart("jarfile", jarFile));
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);
    PostMethod post = new PostMethod(target.toString());
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    HttpClient client = new HttpClient();
    if (proxyHost != null)
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(post);
    if (status == HttpStatus.SC_FORBIDDEN)
        logger.severe("Server " + host + " denied permission to upload run " + runId + '!');
    else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
        logger.severe("Run " + runId + " origin error!");
    else if (status != HttpStatus.SC_CREATED)
        logger.severe(
                "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
    jarFile.delete();
}

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

@Override
public synchronized void login() {
    // exclude the NTLM authentication scheme (requires NTCredentials we don't supply)
    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.DIGEST);/*from  ww w.  j av  a2s.  c o m*/
    authPrefs.add(AuthPolicy.BASIC);
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    // first try Apollo style login
    String authPoint = pathJoin("/", location, "/authentication-point/alm-authenticate");
    String authXml = createAuthXml();
    PostMethod post = initPostMethod(authPoint, authXml);
    ResultInfo resultInfo = ResultInfo.create(null);
    executeAndWriteResponse(post, resultInfo, Collections.<Integer>emptySet());

    if (resultInfo.getHttpStatus() == HttpStatus.SC_NOT_FOUND) {
        // try Maya style login
        Credentials cred = new UsernamePasswordCredentials(userName, password);
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
        httpClient.getParams().setParameter(HttpMethodParams.CREDENTIAL_CHARSET, "UTF-8");
        httpClient.getState().setCredentials(scope, cred);

        authPoint = pathJoin("/", location, "/authentication-point/authenticate");
        GetMethod get = new GetMethod(authPoint);
        resultInfo = ResultInfo.create(null);
        executeAndWriteResponse(get, resultInfo, Collections.<Integer>emptySet());
    }
    HttpStatusBasedException.throwForError(resultInfo);
    if (resultInfo.getHttpStatus() != 200) {
        // during login we only accept 200 status (to avoid redirects and such as seemingly correct login)
        throw new AuthenticationFailureException(resultInfo);
    }

    Cookie[] cookies = httpClient.getState().getCookies();
    Cookie ssoCookie = getSessionCookieByName(cookies, COOKIE_SSO_NAME);
    addTenantCookie(ssoCookie);

    //Since ALM 12.00 it is required explicitly ask for QCSession calling "/rest/site-session"
    //For all the rest of HP ALM / AGM versions it is optional
    String siteSessionPoint = pathJoin("/", location, "/rest/site-session");
    String sessionParamXml = createRestSessionXml();
    post = initPostMethod(siteSessionPoint, sessionParamXml);
    resultInfo = ResultInfo.create(null);
    executeAndWriteResponse(post, resultInfo, Collections.<Integer>emptySet());
    //AGM throws 403
    if (resultInfo.getHttpStatus() != HttpStatus.SC_FORBIDDEN) {
        HttpStatusBasedException.throwForError(resultInfo);
    }

    cookies = httpClient.getState().getCookies();
    Cookie qcCookie = getSessionCookieByName(cookies, COOKIE_SESSION_NAME);
    sessionContext = new SessionContext(location, ssoCookie, qcCookie);
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public TransactionResult doTransaction(TransactionRequest transaction) {
    PostMethod method = new PostMethod(baseUrl + DO_TRANSACTION);

    log.info("Do Transaction, POST to: " + baseUrl + DO_TRANSACTION);
    try {/*from w  w w  .ja  va  2  s.  co  m*/
        String data = serialize(transaction);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, TransactionResult.class);

        }
        if (statusCode == HttpStatus.SC_FORBIDDEN) {
            throw new NegativeBalanceException(-1L);

        } else {
            throw new RuntimeException("Failed to do transaction, RESPONSE CODE: " + statusCode);
        }
    } catch (NegativeBalanceException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}