Example usage for java.net HttpURLConnection HTTP_NOT_FOUND

List of usage examples for java.net HttpURLConnection HTTP_NOT_FOUND

Introduction

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

Prototype

int HTTP_NOT_FOUND

To view the source code for java.net HttpURLConnection HTTP_NOT_FOUND.

Click Source Link

Document

HTTP Status-Code 404: Not Found.

Usage

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Delete a badge data with specified ID
 * @param appId application id//from w  ww.ja  va2 s . c om
 * @param badgeId badge id
 * @return HttpResponse returned as JSON object
 */
@DELETE
@Path("/{appId}/{badgeId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Badge Delete Success"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Badges not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"), })
@ApiOperation(value = "", notes = "delete a badge")
public HttpResponse deleteBadge(@PathParam("appId") String appId, @PathParam("badgeId") String badgeId) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "DELETE " + "gamification/badges/" + appId + "/" + badgeId);
    long randomLong = new Random().nextLong(); //To be able to match 

    JSONObject objResponse = new JSONObject();
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_20, "" + randomLong);

        try {
            if (!badgeAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot delete badge. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot delete badge. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        if (!badgeAccess.isBadgeIdExist(conn, appId, badgeId)) {
            logger.info("Badge not found >> ");
            objResponse.put("message", "Cannot delete badge. Badge not found");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        badgeAccess.deleteBadge(conn, appId, badgeId);
        if (!LocalFileManager.deleteFile(LocalFileManager.getBasedir() + "/" + appId + "/" + badgeId)) {

            logger.info("Delete File Failed >> ");
            objResponse.put("message", "Cannot delete badge. Delete File Failed");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

        }
        objResponse.put("message", "File Deleted");
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_21, "" + randomLong);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_30, "" + name);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_31, "" + appId);
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {

        e.printStackTrace();
        objResponse.put("message", "Cannot delete badge. Cannot delete file. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
    }

}

From source file:org.wso2.carbon.registry.app.RemoteRegistry.java

public void createVersion(String path) throws RegistryException {
    AbderaClient abderaClient = new AbderaClient(abdera);
    ByteArrayInputStream is = new ByteArrayInputStream("createVersion".getBytes());
    ClientResponse clientResponse = abderaClient.post(
            baseURI + APPConstants.ATOM/*  ww w.ja v  a2s. c  om*/
                    + encodeURL(path + RegistryConstants.URL_SEPARATOR + APPConstants.CHECKPOINT),
            is, getAuthorization().setContentType(TEXT_PLAIN_MEDIA_TYPE));
    final int status = clientResponse.getStatus();
    if (status < 200 || status > 299) {
        RegistryException e;
        if (status == HttpURLConnection.HTTP_NOT_FOUND) {
            e = new ResourceNotFoundException(path);
        } else {
            e = new RegistryException("Response Status: " + clientResponse.getStatusText());
        }
        abderaClient.teardown();
        throw e;
    }
    abderaClient.teardown();
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitLogTest.java

@Test
public void testGetNonExistingCommit() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String projectName = getMethodName();
    JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());
    JSONObject testTxt = getChild(project, "test.txt");

    // get log for file
    JSONObject log = logObject(testTxt.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_HEAD));
    JSONArray commitsArray = log.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, commitsArray.length());

    JSONObject commit = commitsArray.getJSONObject(0);
    assertEquals("Initial commit", commit.getString(GitConstants.KEY_COMMIT_MESSAGE));
    String commitName = commit.getString(ProtocolConstants.KEY_NAME);
    String dummyName = "dummyName";
    assertFalse(dummyName.equals(commitName));
    String commitLocation = commit.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // prepare the dummy commit location
    commitLocation = commitLocation.replace(commitName, dummyName).replace("?parts=body", "?page=1&pageSize=1");

    WebRequest request = getGetRequest(commitLocation);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient4.HttpClientRetrieveFileTransfer.java

private boolean openStreamsForResume() {

    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "openStreamsForResume"); //$NON-NLS-1$
    final String urlString = getRemoteFileURL().toString();
    this.doneFired = false;

    int code = -1;

    try {/*from  w w  w.  j  av  a2s. co m*/
        httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, getSocketReadTimeout());
        int connectTimeout = getConnectTimeout();
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);

        setupAuthentication(urlString);

        getMethod = new HttpGet(urlString);
        // Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod)
        // Seems to be another way to select the credentials.
        setResumeRequestHeaderValues();

        Trace.trace(Activator.PLUGIN_ID, "resume=" + urlString); //$NON-NLS-1$

        // Gzip encoding is not an option for resume
        fireConnectStartEvent();
        if (checkAndHandleDone()) {
            return false;
        }

        connectingSockets.clear();
        // Actually execute get and get response code (since redirect is set to true, then
        // redirect response code handled internally
        if (connectJob == null) {
            performConnect(new NullProgressMonitor());
        } else {
            connectJob.schedule();
            connectJob.join();
            connectJob = null;
        }
        if (checkAndHandleDone()) {
            return false;
        }

        code = responseCode;

        responseHeaders = getResponseHeaders();

        Trace.trace(Activator.PLUGIN_ID, "retrieve resp=" + code); //$NON-NLS-1$

        if (code == HttpURLConnection.HTTP_PARTIAL || code == HttpURLConnection.HTTP_OK) {
            getResumeResponseHeaderValues();
            setInputStream(httpResponse.getEntity().getContent());
            this.paused = false;
            fireReceiveResumedEvent();
        } else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(NLS.bind("File not found: {0}", urlString), code, //$NON-NLS-1$
                    responseHeaders);
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code,
                    responseHeaders);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException("Forbidden", code, responseHeaders); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code, responseHeaders);
        } else {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code, responseHeaders);
        }
        Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(),
                "openStreamsForResume", Boolean.TRUE); //$NON-NLS-1$
        return true;
    } catch (final Exception e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, this.getClass(),
                "openStreamsForResume", e); //$NON-NLS-1$
        if (code == -1) {
            if (!isDone()) {
                setDoneException(e);
            }
        } else {
            setDoneException((e instanceof IncomingFileTransferException) ? e
                    : new IncomingFileTransferException(
                            NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT,
                                    urlString),
                            e, code, responseHeaders));
        }
        fireTransferReceiveDoneEvent();
        Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(),
                "openStreamsForResume", Boolean.FALSE); //$NON-NLS-1$
        return false;
    }
}

From source file:net.myrrix.client.ClientRecommender.java

/**
 * Like {@link #similarityToItem(long, long[])}, but allows caller to specify the user for which the request
 * is being made. This information does not directly affect the computation, but affects <em>routing</em>
 * of the request in a distributed context. This is always recommended when there is a user in whose context
 * the request is being made, as it will ensure that the request can take into account all the latest information
 * from the user, including very new items that may be in {@code itemIDs}.
 *///from  ww w . ja  v a2 s  . c o m
public float[] similarityToItem(long toItemID, long[] itemIDs, Long contextUserID) throws TasteException {
    StringBuilder urlPath = new StringBuilder(32);
    urlPath.append("/similarityToItem/");
    urlPath.append(toItemID);
    for (long itemID : itemIDs) {
        urlPath.append('/').append(itemID);
    }

    // Requests are typically partitioned by user, but this request does not directly depend on a user.
    // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other
    // requests related to that user. Otherwise just partition on (first0 item ID, which is at least
    // deterministic.
    long idToPartitionOn = contextUserID == null ? itemIDs[0] : contextUserID;

    TasteException savedException = null;
    for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) {
        HttpURLConnection connection = null;
        try {
            connection = buildConnectionToReplica(replica, urlPath.toString(), "GET");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                BufferedReader reader = IOUtils.bufferStream(connection.getInputStream());
                try {
                    float[] result = new float[itemIDs.length];
                    for (int i = 0; i < itemIDs.length; i++) {
                        result[i] = LangUtils.parseFloat(reader.readLine());
                    }
                    return result;
                } finally {
                    reader.close();
                }
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new NoSuchItemException(connection.getResponseMessage());
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new NotReadyException();
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitCloneTest.java

@Test
public void testGetOthersClones() throws Exception {
    // my clone//from w w w.  j  av a2 s.  co  m
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = getWorkspaceId(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    clone(workspaceId, project);

    JSONArray clonesArray = listClones(workspaceId, null);
    assertEquals(1, clonesArray.length());

    createUser("bob", "bob");
    // URI bobWorkspaceLocation = createWorkspace(getMethodName() + "bob");
    String workspaceName = getClass().getName() + "#" + getMethodName() + "bob";
    WebRequest request = new PostMethodWebRequest(SERVER_LOCATION + "/workspace");
    request.setHeaderField(ProtocolConstants.HEADER_SLUG, workspaceName);
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    URI bobWorkspaceLocation = SERVER_URI.resolve(response.getHeaderField(ProtocolConstants.HEADER_LOCATION));
    String bobWorkspaceId = workspaceIdFromLocation(bobWorkspaceLocation);

    // String bobWorkspaceId = getWorkspaceId(bobWorkspaceLocation);
    request = new GetMethodWebRequest(bobWorkspaceLocation.toString());
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);

    // JSONObject bobProject = createProjectOrLink(bobWorkspaceLocation, getMethodName() + "bob", null);
    JSONObject body = new JSONObject();
    request = new PostMethodWebRequest(bobWorkspaceLocation.toString(),
            IOUtilities.toInputStream(body.toString()), "UTF-8");
    request.setHeaderField(ProtocolConstants.HEADER_SLUG, getMethodName() + "bob");
    request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    JSONObject bobProject = new JSONObject(response.getText());
    assertEquals(getMethodName() + "bob", bobProject.getString(ProtocolConstants.KEY_NAME));
    String bobProjectId = bobProject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(bobProjectId);

    IPath bobClonePath = getClonePath(bobWorkspaceId, bobProject);

    // bob's clone
    URIish uri = new URIish(gitDir.toURI().toURL());
    request = getPostGitCloneRequest(uri, null, bobClonePath, null, null, null);
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    ServerStatus status = waitForTask(response, "bob", "bob");
    String cloneLocation = status.getJsonData().getString(ProtocolConstants.KEY_LOCATION);
    assertNotNull(cloneLocation);

    // validate the clone metadata
    request = getGetRequest(cloneLocation);
    setAuthentication(request, "bob", "bob");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // list my clones again
    clonesArray = listClones(workspaceId, null);
    assertEquals(1, clonesArray.length()); // nothing has been added

    // try to get Bob's clone
    request = getGetRequest(cloneLocation);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
}

From source file:org.openrdf.http.client.SparqlSession.java

protected HttpResponse execute(HttpUriRequest method) throws IOException, OpenRDFException {
    boolean consume = true;
    method.setParams(params);//  w w w  .  j ava  2  s  . co  m
    HttpResponse response = httpClient.execute(method, httpContext);

    try {
        int httpCode = response.getStatusLine().getStatusCode();
        if (httpCode >= 200 && httpCode < 300 || httpCode == HttpURLConnection.HTTP_NOT_FOUND) {
            consume = false;
            return response; // everything OK, control flow can continue
        } else {
            switch (httpCode) {
            case HttpURLConnection.HTTP_UNAUTHORIZED: // 401
                throw new UnauthorizedException();
            case HttpURLConnection.HTTP_UNAVAILABLE: // 503
                throw new QueryInterruptedException();
            default:
                ErrorInfo errInfo = getErrorInfo(response);
                // Throw appropriate exception
                if (errInfo.getErrorType() == ErrorType.MALFORMED_DATA) {
                    throw new RDFParseException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_FILE_FORMAT) {
                    throw new UnsupportedRDFormatException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
                    throw new MalformedQueryException(errInfo.getErrorMessage());
                } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
                    throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
                } else {
                    throw new RepositoryException(errInfo.toString());
                }
            }
        }
    } finally {
        if (consume) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

@Override
public boolean deleteVServerData(String tenant_id, String vserver_id, String cloudOwner, String cloudRegionId,
        String resourceVersion) throws AAIServiceException {
    boolean response = false;
    InputStream inputStream = null;

    try {/*from   w  w  w  . ja va 2  s . c om*/
        String local_network_complexes_path = network_vserver_path.replace("{tenant-id}",
                encodeQuery(tenant_id));
        local_network_complexes_path = local_network_complexes_path.replace("{vserver-id}",
                encodeQuery(vserver_id));
        local_network_complexes_path = local_network_complexes_path.replace("{cloud-owner}",
                encodeQuery(cloudOwner));
        local_network_complexes_path = local_network_complexes_path.replace("{cloud-region-id}",
                encodeQuery(cloudRegionId));

        String request_url = target_uri + local_network_complexes_path;
        if (resourceVersion != null) {
            request_url = request_url + "?resource-version=" + resourceVersion;
        }
        URL http_req_url = new URL(request_url);

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.DELETE);

        LOGwriteFirstTrace(HttpMethod.DELETE, http_req_url.toString());
        LOGwriteDateTrace("tenant_id", tenant_id);
        LOGwriteDateTrace("vserver_id", vserver_id);
        LOGwriteDateTrace("cloud-owner", cloudOwner);
        LOGwriteDateTrace("cloud-region-id", cloudRegionId);

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        LOG.debug("HttpURLConnection result:" + responseCode);
        if (inputStream == null)
            inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;

        ObjectMapper mapper = getObjectMapper();

        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            LOGwriteEndingTrace(responseCode, "SUCCESS", stringBuilder.toString());
            response = true;
        } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
            LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
            response = false;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
            throw new AAIServiceException(responseCode, errorresponse);
        }

    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn("deleteVServerData", exc);
        throw new AAIServiceException(exc);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception exc) {

            }
        }
    }
    return response;
}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Get a list of badges from database/*from   w ww .  j a va  2s  .  c om*/
 * @param appId application id
 * @param currentPage current cursor page
 * @param windowSize size of fetched data
 * @param searchPhrase search word
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Badge not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Find badges for specific App ID", notes = "Returns a list of badges", response = BadgeModel.class, responseContainer = "List", authorizations = @Authorization(value = "api_key"))
public HttpResponse getBadgeList(
        @ApiParam(value = "Application ID that contains badges", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Page number cursor for retrieving data") @QueryParam("current") int currentPage,
        @ApiParam(value = "Number of data size per fetch") @QueryParam("rowCount") int windowSize,
        @ApiParam(value = "Search phrase parameter") @QueryParam("searchPhrase") String searchPhrase) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/badges/" + appId);

    List<BadgeModel> badges = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(this, Event.AGENT_GET_STARTED, "Get Badges");

        try {
            if (!badgeAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get badges. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            logger.info(
                    "Cannot check whether application ID exist or not. Database error. >> " + e1.getMessage());
            objResponse.put("message",
                    "Cannot get badges. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        // Check app id exist or not

        int offset = (currentPage - 1) * windowSize;

        int totalNum = badgeAccess.getNumberOfBadges(conn, appId);

        if (windowSize == -1) {
            offset = 0;
            windowSize = totalNum;
        }

        badges = badgeAccess.getBadgesWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase);

        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String badgeString = objectMapper.writeValueAsString(badges);
        JSONArray badgeArray = (JSONArray) JSONValue.parse(badgeString);

        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", badgeArray);
        objResponse.put("total", totalNum);
        logger.info(objResponse.toJSONString());
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24,
                "Badges fetched" + " : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS, "Badges fetched" + " : " + appId + " : " + userAgent);

        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot get badges. Internal Error. Database connection failed. " + e.getMessage());

        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get badges. Cannot connect to database. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer.java

private boolean openStreamsForResume() {

    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "openStreamsForResume"); //$NON-NLS-1$
    final String urlString = getRemoteFileURL().toString();
    this.doneFired = false;

    int code = -1;

    try {/*from   w  w w . j  a v a 2  s.c o m*/
        initHttpClientConnectionManager();

        CredentialsProvider credProvider = new ECFCredentialsProvider();
        setupAuthentication(urlString);

        setupHostAndPort(credProvider, urlString);

        getMethod = new GzipGetMethod(hostConfigHelper.getTargetRelativePath());
        getMethod.addRequestHeader("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$
        getMethod.setFollowRedirects(true);
        // Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod)
        // Seems to be another way to select the credentials.
        getMethod.getParams().setParameter(CredentialsProvider.PROVIDER, credProvider);
        setResumeRequestHeaderValues();

        Trace.trace(Activator.PLUGIN_ID, "resume=" + urlString); //$NON-NLS-1$

        // Gzip encoding is not an option for resume
        fireConnectStartEvent();
        if (checkAndHandleDone()) {
            return false;
        }

        connectingSockets.clear();
        // Actually execute get and get response code (since redirect is set to true, then
        // redirect response code handled internally
        if (connectJob == null) {
            performConnect(new NullProgressMonitor());
        } else {
            connectJob.schedule();
            connectJob.join();
            connectJob = null;
        }
        if (checkAndHandleDone()) {
            return false;
        }

        code = responseCode;

        responseHeaders = getResponseHeaders();

        Trace.trace(Activator.PLUGIN_ID, "retrieve resp=" + code); //$NON-NLS-1$

        if (code == HttpURLConnection.HTTP_PARTIAL || code == HttpURLConnection.HTTP_OK) {
            getResumeResponseHeaderValues();
            setInputStream(getMethod.getResponseBodyAsUnzippedStream());
            this.paused = false;
            fireReceiveResumedEvent();
        } else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(NLS.bind("File not found: {0}", urlString), code, //$NON-NLS-1$
                    responseHeaders);
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code,
                    responseHeaders);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException("Forbidden", code, responseHeaders); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code, responseHeaders);
        } else {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code, responseHeaders);
        }
        Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(),
                "openStreamsForResume", Boolean.TRUE); //$NON-NLS-1$
        return true;
    } catch (final Exception e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, this.getClass(),
                "openStreamsForResume", e); //$NON-NLS-1$
        if (code == -1) {
            if (!isDone()) {
                setDoneException(e);
            }
        } else {
            setDoneException((e instanceof IncomingFileTransferException) ? e
                    : new IncomingFileTransferException(
                            NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT,
                                    urlString),
                            e, code, responseHeaders));
        }
        fireTransferReceiveDoneEvent();
        Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(),
                "openStreamsForResume", Boolean.FALSE); //$NON-NLS-1$
        return false;
    }
}