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.openrdf.http.client.HTTPClient.java

public void removeNamespacePrefix(String prefix)
        throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();//from  w  w  w. j a v  a 2 s  .c  o  m

    HttpMethod method = new DeleteMethod(Protocol.getNamespacePrefixLocation(repositoryURL, prefix));
    setDoAuthentication(method);

    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("Failed to remove namespace: " + errInfo + " (" + httpCode + ")");
        }
    } finally {
        releaseConnection(method);
    }
}

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

public void clearNamespaces() throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();/*from w  w  w .  jav a 2 s.  c  o m*/

    HttpMethod method = new DeleteMethod(Protocol.getNamespacesLocation(repositoryURL));
    setDoAuthentication(method);

    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("Failed to clear namespaces: " + errInfo + " (" + httpCode + ")");
        }
    } finally {
        releaseConnection(method);
    }
}

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

/**
 * Validate member and add to the database as the new member if he/she is not registered yet
 * @return HttpResponse status if validation success
 *///from  w ww .ja va2 s.  co m
@POST
@Path("/validation")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "memberLoginValidation", notes = "Simple function to validate a member login.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is registered"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "User data error to be retrieved"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "User data error to be retrieved. Not JSON object") })
public HttpResponse memberLoginValidation() {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/applications/validation");

    JSONObject objResponse = new JSONObject();

    MemberModel member;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    // take username as default name
    String name = userAgent.getLoginName();
    System.out.println("User name : " + name);
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    // try to fetch firstname/lastname from user data received from OpenID
    Serializable userData = userAgent.getUserData();

    if (userData != null) {
        Object jsonUserData = JSONValue.parse(userData.toString());
        if (jsonUserData instanceof JSONObject) {
            JSONObject obj = (JSONObject) jsonUserData;
            Object firstnameObj = obj.get("given_name");
            Object lastnameObj = obj.get("family_name");
            Object emailObj = obj.get("email");
            String firstname, lastname, email;
            if (firstnameObj != null) {
                firstname = ((String) firstnameObj);
            } else {
                firstname = "";
            }

            if (lastnameObj != null) {
                lastname = ((String) lastnameObj);
            } else {
                lastname = "";
            }

            if (emailObj != null) {
                email = ((String) emailObj);
            } else {
                email = "";
            }

            member = new MemberModel(name, firstname, lastname, email);
            //logger.info(member.getId()+" "+member.getFullName()+" "+member.getEmail());
            try {
                conn = dbm.getConnection();
                if (!applicationAccess.isMemberRegistered(conn, member.getId())) {
                    applicationAccess.registerMember(conn, member);
                    objResponse.put("message", "Welcome " + member.getId() + "!");
                    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_7, "" + member.getId());

                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message", "Cannot validate member login. Database Error. " + 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);
                }
            }
        } else {
            //logger.warning("Parsing user data failed! Got '" + jsonUserData.getClass().getName() + " instead of "+ JSONObject.class.getName() + " expected!");
            objResponse.put("message",
                    "Cannot validate member login. User data error to be retrieved. Not JSON object.");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        objResponse.put("message", "Member already registered");
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_8, "" + member.getId());

        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
    } else {
        objResponse.put("message", "Cannot validate member login. User data error to be retrieved.");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    }

}

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

public long size(Resource... contexts) throws IOException, RepositoryException, UnauthorizedException {
    checkRepositoryURL();/* w ww .ja  va  2s.  c  o  m*/

    String[] encodedContexts = Protocol.encodeContexts(contexts);

    NameValuePair[] contextParams = new NameValuePair[encodedContexts.length];
    for (int i = 0; i < encodedContexts.length; i++) {
        contextParams[i] = new NameValuePair(Protocol.CONTEXT_PARAM_NAME, encodedContexts[i]);
    }

    HttpMethod method = new GetMethod(Protocol.getSizeLocation(repositoryURL));
    setDoAuthentication(method);
    method.setQueryString(contextParams);

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

        if (httpCode == HttpURLConnection.HTTP_OK) {
            String response = method.getResponseBodyAsString();
            try {
                return Long.parseLong(response);
            } catch (NumberFormatException e) {
                throw new RepositoryException("Server responded with invalid size value: " + response);
            }
        } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthorizedException();
        } else {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new RepositoryException(errInfo.toString());
        }
    } finally {
        releaseConnection(method);
    }
}

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 {// w w  w  .  java2s. 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.
        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:org.openrdf.http.client.SparqlSession.java

protected HttpResponse execute(HttpUriRequest method) throws IOException, OpenRDFException {
    boolean consume = true;
    method.setParams(params);/*from   w w  w . j av a  2 s  .c  om*/
    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:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Get a list of badges from database/*from   w w  w  .  ja v  a2s .c o  m*/
 * @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 {//  www.  ja 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;
    }
}

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

protected void getTupleQueryResult(HttpMethod method, TupleQueryResultHandler handler)
        throws IOException, TupleQueryResultHandlerException, RepositoryException, MalformedQueryException,
        UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support using Accept headers
    Set<TupleQueryResultFormat> tqrFormats = TupleQueryResultParserRegistry.getInstance().getKeys();
    if (tqrFormats.isEmpty()) {
        throw new RepositoryException("No tuple query result parsers have been registered");
    }//from  w  w  w  .  j  a v a 2s  .c  om

    for (TupleQueryResultFormat format : tqrFormats) {
        // Determine a q-value that reflects the user specified preference
        int qValue = 10;

        if (preferredTQRFormat != null && !preferredTQRFormat.equals(format)) {
            // Prefer specified format over other formats
            qValue -= 2;
        }

        for (String mimeType : format.getMIMETypes()) {
            String acceptParam = mimeType;

            if (qValue < 10) {
                acceptParam += ";q=0." + qValue;
            }

            method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam);
        }
    }

    int httpCode = httpClient.executeMethod(method);

    if (httpCode == HttpURLConnection.HTTP_OK) {
        String mimeType = getResponseMIMEType(method);
        try {
            TupleQueryResultFormat format = TupleQueryResultFormat.matchMIMEType(mimeType, tqrFormats);
            TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory());
            parser.setTupleQueryResultHandler(handler);
            parser.parse(method.getResponseBodyAsStream());
        } catch (UnsupportedQueryResultFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (QueryResultParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        }
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new UnauthorizedException();
    } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        throw new QueryInterruptedException();
    } else {
        ErrorInfo errInfo = getErrorInfo(method);

        // Throw appropriate exception
        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());
        }
    }
}

From source file:org.betaconceptframework.astroboa.resourceapi.resource.ContentObjectResource.java

@DELETE
@Path("/{contentObjectIdOrName: " + CmsConstants.UUID_OR_SYSTEM_NAME_REG_EXP_FOR_RESTEASY + "}")
public Response deleteContentObjectByIdOrName(
        @PathParam("contentObjectIdOrName") String contentObjectIdOrName) {

    if (StringUtils.isBlank(contentObjectIdOrName)) {
        logger.warn("No id or system name was provided. Delete request cannot proceed");
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }/*from  ww w.  j a  v  a2  s .c  o m*/

    try {
        boolean objectDeleted = astroboaClient.getContentService().deleteContentObject(contentObjectIdOrName);

        return ContentApiUtils.createResponseForHTTPDelete(objectDeleted, contentObjectIdOrName);
    } catch (CmsUnauthorizedAccessException e) {
        throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED);
    } catch (Exception e) {
        logger.error("", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }
}