Example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED

List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED

Introduction

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

Prototype

int HTTP_UNAUTHORIZED

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

Click Source Link

Document

HTTP Status-Code 401: Unauthorized.

Usage

From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

public void authenticate(IProgressMonitor monitor) throws CoreException {
    if (loggedIn || (!hasAuthenticationCredentials() && !hasHTTPAuthenticationCredentials())) {
        return;/*from  ww  w  .  j av  a  2  s  .  com*/
    }

    monitor = Policy.monitorFor(monitor);

    GzipPostMethod postMethod = null;

    try {
        hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);

        NameValuePair[] formData;

        String loginToken = getBugzillaLoginTokenIfExists(monitor);
        if (loginToken != null) {
            formData = new NameValuePair[3];
            formData[2] = new NameValuePair("Bugzilla_login_token", loginToken); //$NON-NLS-1$
        } else {
            formData = new NameValuePair[2];
        }

        AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
        AuthenticationCredentials httpAuthCredentials = location.getCredentials(AuthenticationType.HTTP);
        if (credentials == null && httpAuthCredentials == null) {
            loggedIn = false;
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "Authentication credentials from location missing.")); //$NON-NLS-1$
        }
        if (credentials != null) {
            String password = credentials.getPassword();
            if ("".equals(password) && !hasHTTPAuthenticationCredentials()) { //$NON-NLS-1$
                loggedIn = false;
                throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                        RepositoryStatus.ERROR_EMPTY_PASSWORD, repositoryUrl.toString(),
                        "Empty password not allowed for Authentication credentials.")); //$NON-NLS-1$
            }
            formData[0] = new NameValuePair(IBugzillaConstants.POST_INPUT_BUGZILLA_LOGIN,
                    credentials.getUserName());
            formData[1] = new NameValuePair(IBugzillaConstants.POST_INPUT_BUGZILLA_PASSWORD,
                    credentials.getPassword());
        }
        postMethod = new GzipPostMethod(
                WebUtil.getRequestPath(repositoryUrl.toString() + IBugzillaConstants.URL_POST_LOGIN), true);

        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" //$NON-NLS-1$ //$NON-NLS-2$
                + getCharacterEncoding());

        if (credentials != null) {
            postMethod.setRequestBody(formData);
        }
        postMethod.setDoAuthentication(true);
        postMethod.setFollowRedirects(false);

        if (httpAuthCredentials != null && httpAuthCredentials.getUserName() != null
                && httpAuthCredentials.getUserName().length() > 0) {
            httpClient.getParams().setAuthenticationPreemptive(true);
        }

        int code = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor);
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            loggedIn = false;
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "HTTP authentication failed.")); //$NON-NLS-1$

        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            loggedIn = false;
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "Proxy authentication required")); //$NON-NLS-1$

        } else if (code != HttpURLConnection.HTTP_OK) {
            loggedIn = false;
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$
        }
        if (httpAuthCredentials != null && httpAuthCredentials.getUserName() != null
                && httpAuthCredentials.getUserName().length() > 0) {
            // If httpAuthCredentials are used HttpURLConnection.HTTP_UNAUTHORIZED when the credentials are invalide so we
            // not need to test the cookies.
            // see bug 305267 or https://bugzilla.mozilla.org/show_bug.cgi?id=385606
            loggedIn = true;
            InputStream inputStream = getResponseStream(postMethod, monitor);
            try {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(inputStream, getCharacterEncoding()));

                try {
                    String errorMessage = extractErrorMessage(in);

                    if (errorMessage != null) {
                        loggedIn = false;
                        throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                                RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                                errorMessage));
                    }
                } finally {
                    inputStream.close();
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else if (hasAuthenticationCredentials()) {
            for (Cookie cookie : httpClient.getState().getCookies()) {
                if (cookie.getName().equals(COOKIE_BUGZILLA_LOGIN)) {
                    loggedIn = true;
                    break;
                }
            }

            if (!loggedIn) {
                InputStream input = getResponseStream(postMethod, monitor);
                try {
                    throw new CoreException(parseHtmlError(input));
                } finally {
                    input.close();
                }
            }
        } else {
            // anonymous login
            loggedIn = true;
        }
    } catch (IOException e) {
        throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e));
    } finally {
        if (postMethod != null) {
            WebUtil.releaseConnection(postMethod, monitor);
        }
        httpClient.getParams().setAuthenticationPreemptive(false);
    }
}

From source file:Java_BWS_Sample.SampleBwsClient.java

/*******************************************************************************************************************
 *
 * Call _bwsService.getSystemInfo() and display the returned properties.
 *
 * @return Returns true if getSystemInfo is successful, and false otherwise.
 *
 *******************************************************************************************************************
 *//* w  ww.j  a v a2s . co m*/
public static boolean getSystemInfo() {
    final String METHOD_NAME = "getSystemInfo()";
    final String BWS_API_NAME = "_bws.getSystemInfo()";

    logMessage("Entering %s", METHOD_NAME);
    boolean returnValue = false;

    GetSystemInfoRequest request = new GetSystemInfoRequest();

    /*
     * Setting the value of loadAuthenticatedUserProperties to true will cause the API to return additional
     * properties about the current user, like the Authenticated User Uid property. The Authenticated User Uid
     * property is often used to make calls to APIs like getUsersDetail(), assignSWConfigsToGroup() and
     * others.
     *
     * Valid for BlackBerry Enterprise Server 5.0.3 MR5 or later
     */
    request.setLoadAuthenticatedUserProperties(true);
    request.setMetadata(REQUEST_METADATA);

    GetSystemInfoResponse response = null;

    /*
     * The try catch block here is used to illustrate how to handle a specific type of exception.
     * For example, in this case we check to see if the error was caused by invalid credentials.
     */
    try {
        logRequest(BWS_API_NAME);
        response = _bws.getSystemInfo(request);
        logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata());
    } catch (WebServiceException e) {
        if (e.getCause() instanceof HTTPException) {
            HTTPException httpException = (HTTPException) e.getCause();
            // Handle authentication failure.
            if (httpException != null
                    && httpException.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                logMessage("Failed to authenticate with the BWS web service");
                logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
                return returnValue;
            }
        }

        // Log and re-throw exception.
        logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage());
        throw e;

    }

    if (response.getReturnStatus().getCode().equals("SUCCESS")) {
        if (response.getProperties() != null && !response.getProperties().isEmpty()) {
            logMessage("%s returned the following properties:", BWS_API_NAME);
            for (Property property : response.getProperties()) {
                displayResult("%s: %s", property.getName(), property.getValue());
            }

            returnValue = true;
        } else {
            logMessage("No properties in response");
        }
    } else {
        System.err.format("Error: Code: \"%s\", Message: \"%s\"%n", response.getReturnStatus().getCode(),
                response.getReturnStatus().getMessage());
    }

    logMessage("Exiting %s with value \"%s\"", METHOD_NAME, returnValue);
    return returnValue;
}

From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Get all application list separated into two categories. All apps registered for the member and other apps.
 * /*  ww w . j av a  2 s  . c o  m*/
 * 
 * @return HttpResponse with the returnString
 */
@GET
@Path("/list/separated")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "getSeparateApplicationInfo", notes = "Get all application list separated into two categories. All apps registered for the member and other apps.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "List of apps"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database error"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "JsonProcessingException") })
public HttpResponse getSeparateApplicationInfo() {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/applications/list/separated");

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

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    ObjectMapper objectMapper = new ObjectMapper();
    //Set pretty printing of json
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    try {
        conn = dbm.getConnection();
        List<List<ApplicationModel>> allApps = applicationAccess.getSeparateApplicationsWithMemberId(conn,
                name);

        try {
            String response = objectMapper.writeValueAsString(allApps);
            allApps.clear();
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_11, "" + name);

            return new HttpResponse(response, HttpURLConnection.HTTP_OK);

        } catch (JsonProcessingException e) {
            e.printStackTrace();

            allApps.clear();
            // return HTTP Response on error
            objResponse.put("message", "Cannot delete Application. JsonProcessingException." + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
    } catch (SQLException e) {

        e.printStackTrace();
        objResponse.put("message", "Database error");
        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.openrdf.http.client.HTTPClient.java

public void sendTransaction(final Iterable<? extends TransactionOperation> txn)
        throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();/*from w w w  .  j  a  v a2  s .  c  o m*/

    PostMethod method = new PostMethod(Protocol.getStatementsLocation(getRepositoryURL()));
    setDoAuthentication(method);

    // Create a RequestEntity for the transaction data
    method.setRequestEntity(new RequestEntity() {

        public long getContentLength() {
            return -1; // don't know
        }

        public String getContentType() {
            return Protocol.TXN_MIME_TYPE;
        }

        public boolean isRepeatable() {
            return true;
        }

        public void writeRequest(OutputStream out) throws IOException {
            TransactionWriter txnWriter = new TransactionWriter();
            txnWriter.serialize(txn, out);
        }
    });

    try {
        int httpCode = httpClient.executeMethod(method);

        if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthorizedException();
        } else if (!is2xx(httpCode)) {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new RepositoryException("Transaction failed: " + errInfo + " (" + httpCode + ")");
        }
    } finally {
        releaseConnection(method);
    }
}

From source file:org.apache.hadoop.mapred.TestWebUIAuthorization.java

/**
 * Make sure that multiple jobs get killed using jobtracker.jsp url when
 * user has modify access on only some of those jobs.
 * @param cluster/*from  w w w.  j  av a 2s .  com*/
 * @param conf
 * @param jtURL
 * @param user
 * @throws Exception
 */
private void validateKillMultipleJobs(MiniMRCluster cluster, JobConf conf, String jtURL) throws Exception {
    String jobTrackerJSP = jtURL + "/jobtracker.jsp?a=b";
    // jobTrackerJSP killJob url
    String url = jobTrackerJSP + "&killJobs=true";
    // view-job-acl doesn't matter for killJob from jobtracker jsp page
    conf.set(JobContext.JOB_ACL_VIEW_JOB, " ");

    // Let us start 4 jobs as 4 different users(none of these 4 users is
    // mrOwner and none of these users is a member of mrAdmin and none of
    // these 4 users is a queue admin for the default queue). So only
    // based on the config JobContext.JOB_ACL_MODIFY_JOB being set here and the
    // job-submitter, killJob on each of the jobs will be succeeded.

    // start 1st job.
    // Out of these 4 users, only jobSubmitter can do killJob on 1st job
    conf.set(JobContext.JOB_ACL_MODIFY_JOB, " ");
    RunningJob job1 = startSleepJobAsUser(jobSubmitter, conf, cluster);
    org.apache.hadoop.mapreduce.JobID jobid = job1.getID();
    url = url.concat("&jobCheckBox=" + jobid.toString());

    // start 2nd job.
    // Out of these 4 users, only jobSubmitter1 can do killJob on 2nd job
    RunningJob job2 = startSleepJobAsUser(jobSubmitter1, conf, cluster);
    jobid = job2.getID();
    url = url.concat("&jobCheckBox=" + jobid.toString());

    // start 3rd job.
    // Out of these 4 users, only jobSubmitter2 can do killJob on 3rd job
    RunningJob job3 = startSleepJobAsUser(jobSubmitter2, conf, cluster);
    jobid = job3.getID();
    url = url.concat("&jobCheckBox=" + jobid.toString());

    // start 4rd job.
    // Out of these 4 users, jobSubmitter1 and jobSubmitter3
    // can do killJob on 4th job
    conf.set(JobContext.JOB_ACL_MODIFY_JOB, jobSubmitter1);
    RunningJob job4 = startSleepJobAsUser(jobSubmitter3, conf, cluster);
    jobid = job4.getID();
    url = url.concat("&jobCheckBox=" + jobid.toString());

    try {
        // Try killing all the 4 jobs as user viewColleague who can kill only
        // 2nd and 4th jobs. Check if 1st and 3rd jobs are not killed and
        // 2nd and 4th jobs get killed
        assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(url, jobSubmitter1, "POST"));

        waitForKillJobToFinish(job2);
        assertTrue("killJob failed for a job for which user has " + "job-modify permission", job2.isComplete());
        waitForKillJobToFinish(job4);
        assertTrue("killJob failed for a job for which user has " + "job-modify permission", job4.isComplete());
        assertFalse("killJob succeeded for a job for which user doesnot " + " have job-modify permission",
                job1.isComplete());
        assertFalse("killJob succeeded for a job for which user doesnot " + " have job-modify permission",
                job3.isComplete());
    } finally {
        // Kill all 4 jobs as user mrOwner(even though some of them
        // were already killed)
        assertEquals(HttpURLConnection.HTTP_OK, getHttpStatusCode(url, mrOwner, "GET"));
    }
}

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

protected void openStreams() throws IncomingFileTransferException {

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

    int code = -1;

    try {/*from   ww  w.jav  a2  s  . c o  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.
        setRequestHeaderValues();

        Trace.trace(Activator.PLUGIN_ID, "retrieve=" + urlString); //$NON-NLS-1$
        // Set request header for possible gzip encoding, but only if
        // 1) The file range specification is null (we want the whole file)
        // 2) The target remote file does *not* end in .gz (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=280205)
        if (getFileRangeSpecification() == null && !targetHasGzSuffix(super.getRemoteFileName())) {
            Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding: gzip,deflate added to request header"); //$NON-NLS-1$

            // Add the interceptors to provide the gzip 
            httpClient.addRequestInterceptor(new RequestAcceptEncoding());
            httpClient.addResponseInterceptor(new ResponseContentEncoding());
        } else {
            Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding NOT added to header"); //$NON-NLS-1$
        }

        fireConnectStartEvent();
        if (checkAndHandleDone()) {
            return;
        }

        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;
        }

        code = responseCode;

        responseHeaders = getResponseHeaders();

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

        // Check for NTLM proxy in response headers 
        // This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002
        boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(httpContext);
        if (ntlmProxyFound && !hasForceNTLMProxyOption())
            throw new IncomingFileTransferException(
                    "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$
                    HttpClientOptions.NTLM_PROXY_RESPONSE_CODE);

        if (NTLMProxyDetector.detectSPNEGOProxy(httpContext))
            throw new BrowseFileTransferException(
                    "HttpClient Provider does not support the use of SPNEGO proxy authentication."); //$NON-NLS-1$

        if (code == HttpURLConnection.HTTP_PARTIAL || code == HttpURLConnection.HTTP_OK) {
            getResponseHeaderValues();
            setInputStream(httpResponse.getEntity().getContent());
            fireReceiveStartEvent();
        } 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$
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException("Forbidden", code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code);
        } else {
            Trace.trace(Activator.PLUGIN_ID, EntityUtils.toString(httpResponse.getEntity()));
            //            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code);
        }
    } catch (final Exception e) {
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "openStreams", //$NON-NLS-1$
                e);
        if (code == -1) {
            if (!isDone()) {
                setDoneException(e);
            }
            fireTransferReceiveDoneEvent();
        } else {
            IncomingFileTransferException ex = (IncomingFileTransferException) ((e instanceof IncomingFileTransferException)
                    ? e
                    : new IncomingFileTransferException(
                            NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT,
                                    urlString),
                            e, code));
            throw ex;
        }
    }
    Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(), "openStreams"); //$NON-NLS-1$
}

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

protected void upload(RequestEntity reqEntity, String baseURI, boolean overwrite, Resource... contexts)
        throws IOException, RDFParseException, RepositoryException, UnauthorizedException {
    OpenRDFUtil.verifyContextNotNull(contexts);

    checkRepositoryURL();/*from  w  w w .ja  v a  2 s .c o  m*/

    String uploadURL = Protocol.getStatementsLocation(getRepositoryURL());

    // Select appropriate HTTP method
    EntityEnclosingMethod method;
    if (overwrite) {
        method = new PutMethod(uploadURL);
    } else {
        method = new PostMethod(uploadURL);
    }

    setDoAuthentication(method);

    // Set relevant query parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>(5);
    for (String encodedContext : Protocol.encodeContexts(contexts)) {
        params.add(new NameValuePair(Protocol.CONTEXT_PARAM_NAME, encodedContext));
    }
    if (baseURI != null && baseURI.trim().length() != 0) {
        String encodedBaseURI = Protocol.encodeValue(new URIImpl(baseURI));
        params.add(new NameValuePair(Protocol.BASEURI_PARAM_NAME, encodedBaseURI));
    }
    method.setQueryString(params.toArray(new NameValuePair[params.size()]));

    // Set payload
    method.setRequestEntity(reqEntity);

    // Send request
    try {
        int httpCode = httpClient.executeMethod(method);

        if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthorizedException();
        } else if (httpCode == HttpURLConnection.HTTP_UNSUPPORTED_TYPE) {
            throw new UnsupportedRDFormatException(method.getResponseBodyAsString());
        } else if (!is2xx(httpCode)) {
            ErrorInfo errInfo = ErrorInfo.parse(method.getResponseBodyAsString());

            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 {
                throw new RepositoryException("Failed to upload data: " + errInfo);
            }
        }
    } finally {
        releaseConnection(method);
    }
}

From source file:com.google.wave.api.AbstractRobot.java

/**
 * Processes the incoming HTTP request to obtain the verification token.
 *
 * @param req the HTTP request./*from w ww  .  j  a  v  a  2s.c  om*/
 * @param resp the HTTP response.
 */
private void processVerifyToken(HttpServletRequest req, HttpServletResponse resp) {
    if (verificationToken == null || verificationToken.isEmpty()) {
        LOG.info("Please register a verification token by calling " + "AbstractRobot.setVerificationToken().");
        resp.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
        return;
    }

    String incomingSecurityToken = req.getParameter(SECURITY_TOKEN_PARAMETER_KEY);
    if (securityToken != null && !securityToken.equals(incomingSecurityToken)) {
        LOG.info("The incoming security token " + incomingSecurityToken + " does not match the "
                + "expected security token " + securityToken + ".");
        resp.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
        return;
    }

    resp.setContentType(TEXT_MIME_TYPE);
    resp.setCharacterEncoding(UTF_8);
    try {
        resp.getWriter().write(verificationToken);
    } catch (IOException e) {
        resp.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
        return;
    }
    resp.setStatus(HttpURLConnection.HTTP_OK);
}

From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java

/**
 * Get a list of actions from database//from w ww.java2  s.  c  o  m
 * @param appId applicationId
 * @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_OK, message = "Found a list of actions"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getActionList", notes = "Returns a list of actions", response = ActionModel.class, responseContainer = "List")
public HttpResponse getActionList(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Page number for retrieving data") @QueryParam("current") int currentPage,
        @ApiParam(value = "Number of data size") @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/actions/" + appId);

    List<ActionModel> achs = 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 Actions");

        try {
            if (!actionAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get actions. 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 get actions. 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);
        }
        int offset = (currentPage - 1) * windowSize;
        int totalNum = actionAccess.getNumberOfActions(conn, appId);

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

        achs = actionAccess.getActionsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase);

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

        String actionString = objectMapper.writeValueAsString(achs);
        JSONArray actionArray = (JSONArray) JSONValue.parse(actionString);
        logger.info(actionArray.toJSONString());
        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", actionArray);
        objResponse.put("total", totalNum);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_10,
                "Actions fetched" + " : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS,
                "Actions fetched" + " : " + appId + " : " + userAgent);
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        e.printStackTrace();

        // return HTTP Response on error
        objResponse.put("message", "Cannot get actions. Database error. " + 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 actions. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), 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

protected void openStreams() throws IncomingFileTransferException {

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

    int code = -1;

    try {//  ww w.j  av a  2s .  c om
        initHttpClientConnectionManager();
        setupAuthentication(urlString);

        CredentialsProvider credProvider = new ECFCredentialsProvider();
        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);
        setRequestHeaderValues();

        Trace.trace(Activator.PLUGIN_ID, "retrieve=" + urlString); //$NON-NLS-1$
        // Set request header for possible gzip encoding, but only if
        // 1) The file range specification is null (we want the whole file)
        // 2) The target remote file does *not* end in .gz (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=280205)
        if (getFileRangeSpecification() == null && !targetHasGzSuffix(super.getRemoteFileName())) {
            Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding: gzip added to request header"); //$NON-NLS-1$
            getMethod.setRequestHeader(GzipGetMethod.ACCEPT_ENCODING, GzipGetMethod.CONTENT_ENCODING_ACCEPTED);
        } else {
            Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding NOT added to header"); //$NON-NLS-1$
        }

        fireConnectStartEvent();
        if (checkAndHandleDone()) {
            return;
        }

        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;
        }

        code = responseCode;

        responseHeaders = getResponseHeaders();

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

        // Check for NTLM proxy in response headers 
        // This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002
        boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(getMethod);
        if (ntlmProxyFound && !hasForceNTLMProxyOption())
            throw new IncomingFileTransferException(
                    "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$
                    HttpClientOptions.NTLM_PROXY_RESPONSE_CODE);

        if (code == HttpURLConnection.HTTP_PARTIAL || code == HttpURLConnection.HTTP_OK) {
            getResponseHeaderValues();
            setInputStream(getMethod.getResponseBodyAsUnzippedStream());
            fireReceiveStartEvent();
        } else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(NLS.bind("File not found: {0}", urlString), code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException("Forbidden", code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code);
        } else {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code);
        }
    } catch (final Exception e) {
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "openStreams", //$NON-NLS-1$
                e);
        if (code == -1) {
            if (!isDone()) {
                setDoneException(e);
            }
            fireTransferReceiveDoneEvent();
        } else {
            IncomingFileTransferException ex = (IncomingFileTransferException) ((e instanceof IncomingFileTransferException)
                    ? e
                    : new IncomingFileTransferException(
                            NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT,
                                    urlString),
                            e, code));
            throw ex;
        }
    }
    Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(), "openStreams"); //$NON-NLS-1$
}