Example usage for java.net HttpURLConnection HTTP_INTERNAL_ERROR

List of usage examples for java.net HttpURLConnection HTTP_INTERNAL_ERROR

Introduction

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

Prototype

int HTTP_INTERNAL_ERROR

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

Click Source Link

Document

HTTP Status-Code 500: Internal Server Error.

Usage

From source file:org.apache.hadoop.yarn.server.webproxy.TestWebAppProxyServlet.java

@Test(timeout = 5000)
public void testWebAppProxyServlet() throws Exception {

    Configuration configuration = new Configuration();
    configuration.set(YarnConfiguration.PROXY_ADDRESS, "localhost:9090");
    // overriding num of web server threads, see HttpServer.HTTP_MAXTHREADS 
    configuration.setInt("hadoop.http.max.threads", 5);
    WebAppProxyServerForTest proxy = new WebAppProxyServerForTest();
    proxy.init(configuration);// w  w w  .j  a  v  a 2  s .  co  m
    proxy.start();

    int proxyPort = proxy.proxy.proxyServer.getConnectorAddress(0).getPort();
    AppReportFetcherForTest appReportFetcher = proxy.proxy.appReportFetcher;

    // wrong url
    try {
        // wrong url. Set wrong app ID
        URL wrongUrl = new URL("http://localhost:" + proxyPort + "/proxy/app");
        HttpURLConnection proxyConn = (HttpURLConnection) wrongUrl.openConnection();

        proxyConn.connect();
        assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, proxyConn.getResponseCode());
        // set true Application ID in url
        URL url = new URL("http://localhost:" + proxyPort + "/proxy/application_00_0");
        proxyConn = (HttpURLConnection) url.openConnection();
        // set cookie
        proxyConn.setRequestProperty("Cookie", "checked_application_0_0000=true");
        proxyConn.connect();
        assertEquals(HttpURLConnection.HTTP_OK, proxyConn.getResponseCode());
        assertTrue(isResponseCookiePresent(proxyConn, "checked_application_0_0000", "true"));
        // cannot found application 1: null
        appReportFetcher.answer = 1;
        proxyConn = (HttpURLConnection) url.openConnection();
        proxyConn.setRequestProperty("Cookie", "checked_application_0_0000=true");
        proxyConn.connect();
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, proxyConn.getResponseCode());
        assertFalse(isResponseCookiePresent(proxyConn, "checked_application_0_0000", "true"));
        // cannot found application 2: ApplicationNotFoundException
        appReportFetcher.answer = 4;
        proxyConn = (HttpURLConnection) url.openConnection();
        proxyConn.setRequestProperty("Cookie", "checked_application_0_0000=true");
        proxyConn.connect();
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, proxyConn.getResponseCode());
        assertFalse(isResponseCookiePresent(proxyConn, "checked_application_0_0000", "true"));
        // wrong user
        appReportFetcher.answer = 2;
        proxyConn = (HttpURLConnection) url.openConnection();
        proxyConn.connect();
        assertEquals(HttpURLConnection.HTTP_OK, proxyConn.getResponseCode());
        String s = readInputStream(proxyConn.getInputStream());
        assertTrue(s.contains("to continue to an Application Master web interface owned by"));
        assertTrue(s.contains("WARNING: The following page may not be safe!"));
        //case if task has a not running status
        appReportFetcher.answer = 3;
        proxyConn = (HttpURLConnection) url.openConnection();
        proxyConn.setRequestProperty("Cookie", "checked_application_0_0000=true");
        proxyConn.connect();
        assertEquals(HttpURLConnection.HTTP_OK, proxyConn.getResponseCode());
    } finally {
        proxy.close();
    }
}

From source file:com.stackmob.example.SendGrid.java

@Override
public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) {
    int responseCode = 0;
    String responseBody = "";
    String username = "";
    String subject = "";
    String text = "";
    String from = "";
    String to = "";
    String toname = "";
    String body = "";
    String url = "";

    LoggerService logger = serviceProvider.getLoggerService(SendGrid.class);
    //Log the JSON object passed to the StackMob Logs
    logger.debug(request.getBody());/*  ww  w. j a  v a2 s .c om*/

    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(request.getBody());
        JSONObject jsonObject = (JSONObject) obj;

        //We use the username passed to query the StackMob datastore
        //and retrieve the user's name and email address
        username = (String) jsonObject.get("username");

        // The following values could be static or dynamic
        subject = (String) jsonObject.get("subject");
        text = (String) jsonObject.get("text");
        from = (String) jsonObject.get("from");
    } catch (ParseException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();
    }

    if (username == null || username.isEmpty()) {
        HashMap<String, String> errParams = new HashMap<String, String>();
        errParams.put("error", "the username passed was empty or null");
        return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request
    }

    // get the StackMob datastore service and assemble the query
    DataService dataService = serviceProvider.getDataService();

    // build a query
    List<SMCondition> query = new ArrayList<SMCondition>();
    query.add(new SMEquals("username", new SMString(username)));

    SMObject userObject;
    List<SMObject> result;
    try {
        // return results from user query
        result = dataService.readObjects("user", query);
        if (result != null && result.size() == 1) {
            userObject = result.get(0);
            to = userObject.getValue().get("email").toString();
            toname = userObject.getValue().get("name").toString();
        } else {
            HashMap<String, String> errMap = new HashMap<String, String>();
            errMap.put("error", "no user found");
            errMap.put("detail", "no matches for the username passed");
            return new ResponseToProcess(HttpURLConnection.HTTP_OK, errMap); // http 500 - internal server error
        }

    } catch (InvalidSchemaException e) {
        HashMap<String, String> errMap = new HashMap<String, String>();
        errMap.put("error", "invalid_schema");
        errMap.put("detail", e.toString());
        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
    } catch (DatastoreException e) {
        HashMap<String, String> errMap = new HashMap<String, String>();
        errMap.put("error", "datastore_exception");
        errMap.put("detail", e.toString());
        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
    } catch (Exception e) {
        HashMap<String, String> errMap = new HashMap<String, String>();
        errMap.put("error", "unknown");
        errMap.put("detail", e.toString());
        return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errMap); // http 500 - internal server error
    }

    if (subject == null || subject.equals("")) {
        logger.error("Subject is missing");
    }

    //Encode any parameters that need encoding (i.e. subject, toname, text)
    try {
        subject = URLEncoder.encode(subject, "UTF-8");
        text = URLEncoder.encode(text, "UTF-8");
        toname = URLEncoder.encode(toname, "UTF-8");

    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
    }

    String queryParams = "api_user=" + API_USER + "&api_key=" + API_KEY + "&to=" + to + "&toname=" + toname
            + "&subject=" + subject + "&text=" + text + "&from=" + from;

    url = "https://www.sendgrid.com/api/mail.send.json?" + queryParams;

    Header accept = new Header("Accept-Charset", "utf-8");
    Header content = new Header("Content-Type", "application/x-www-form-urlencoded");

    Set<Header> set = new HashSet();
    set.add(accept);
    set.add(content);

    try {
        HttpService http = serviceProvider.getHttpService();

        PostRequest req = new PostRequest(url, set, body);

        HttpResponse resp = http.post(req);
        responseCode = resp.getCode();
        responseBody = resp.getBody();

    } catch (TimeoutException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();

    } catch (AccessDeniedException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();

    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();

    } catch (ServiceNotActivatedException e) {
        logger.error(e.getMessage(), e);
        responseCode = -1;
        responseBody = e.getMessage();
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("response_body", responseBody);

    return new ResponseToProcess(responseCode, map);
}

From source file:com.nimbits.user.GoogleAuthentication.java

private Cookie getAuthCookie(final String gaeAppBaseUrl, final String gaeAppLoginUrl, final String authToken)
        throws NimbitsException {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    Cookie retObj = null;/*from  w w w.j  av  a2 s  .  com*/
    final String cookieUrl;
    try {
        cookieUrl = gaeAppLoginUrl + "?continue=" + URLEncoder.encode(gaeAppBaseUrl, Const.CONST_ENCODING)
                + "&auth=" + URLEncoder.encode(authToken, Const.CONST_ENCODING);

        //
        //      String cookieUrl = gaeAppLoginUrl + "?continue="
        //      + URLEncoder.encode(gaeAppBaseUrl,Const.CONST_ENCODING) + "&auth=" + authToken;
        //httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        final HttpGet httpget = new HttpGet(cookieUrl);
        final HttpResponse response = httpClient.execute(httpget);

        if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
                || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) {

            for (final Cookie cookie : httpClient.getCookieStore().getCookies()) {
                if (cookie.getName().equals(Parameters.acsid.getText())) {
                    retObj = cookie;
                    break;
                }

            }
        } else if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            throw new NimbitsException("invalid token");

        } else {
            throw new NimbitsException(
                    "Error getting cookie: status code:" + response.getStatusLine().getStatusCode());
        }

        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    } catch (UnsupportedEncodingException e) {
        throw new NimbitsException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new NimbitsException(e.getMessage());
    } catch (IOException e) {
        throw new NimbitsException(e.getMessage());
    }

    return retObj;

}

From source file:rapture.table.file.FileIndexHandler.java

private void persistFullIndex() {
    // Write to a separate file and then rename so we don't risk losing data
    // if we are interrupted in the middle of this process.
    try (FileOutputStream tmpFileStream = new FileOutputStream(tmpFile)) {
        // Write each entry as a separate line to facilitate buffered reading.
        for (Map.Entry<String, Map<String, Object>> entry : memoryView.entrySet()) {
            persistIndexEntry(entry.getKey(), entry.getValue(), tmpFileStream);
        }/*from  www. j a  va  2  s  .c  o  m*/

        FileUtils.copyFile(tmpFile, persistenceFile);
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "Error writing full index to index file", e);
    } finally {
        FileUtils.deleteQuietly(tmpFile);

        // Seems to work just fine on a Mac without reinitializing after the file has
        // been changed underneath it, but to be safer let's close and reopen.
        initUpdatesStream();
    }
}

From source file:nl.ru.cmbi.vase.web.rest.JobRestResource.java

@MethodMapping(value = "/custom", httpMethod = HttpMethod.POST, produces = RestMimeTypes.TEXT_PLAIN)
public String custom() {

    if (Config.isXmlOnly()) {
        log.warn("rest/custom was requested, but xml-only is set");

        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND);
    } else if (!Config.hsspPdbCacheEnabled()) {
        log.warn("rest/custom was requested, but pdb cache is not enabled");

        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND);
    }/*from w  ww.  j  a v a2s.co m*/

    // getPostParameters doesn't work for some reason
    IRequestParameters p = RequestCycle.get().getRequest().getRequestParameters();

    StringValue pdbContents = p.getParameterValue("pdbfile");
    if (pdbContents.toString() == null) {

        log.error("pdbfile parameter not set");

        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_BAD_REQUEST);
    }

    StringRepresentation entity = new StringRepresentation(pdbContents.toString(), MediaType.TEXT_PLAIN);
    Disposition disposition = new Disposition();
    disposition.setFilename("custom.pdb");
    entity.setDisposition(disposition);

    FormDataSet fds = new FormDataSet();
    fds.setMultipart(true);
    fds.getEntries().add(new FormData("file_", entity));

    String url = hsspRestURL + "/create/pdb_file/hssp_stockholm/";
    ClientResource resource = new ClientResource(url);

    Representation repResponse = null;
    try {
        repResponse = resource.post(fds);

        String content = repResponse.getText();

        JSONObject output = new JSONObject(content);
        String jobID = output.getString("id");

        File pdbFile = new File(Config.getHSSPCacheDir(), jobID + ".pdb.gz");

        OutputStream pdbOut = new GZIPOutputStream(new FileOutputStream(pdbFile));
        IOUtils.write(pdbContents.toString(), pdbOut);
        pdbOut.close();

        return jobID;
    } catch (Exception e) {

        log.error("io error: " + e.toString());
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:rapture.common.connection.ConnectionInfoConfigurer.java

protected ConnectionInfo getConnectionInfoFromLocal(String instanceName) {
    try {//from  ww w  .ja  va  2 s .  com
        String url = getConnectionUrl(instanceName);
        URI uri = new URI(url);
        String host = StringUtils.isBlank(uri.getHost()) ? "localhost" : uri.getHost();
        int port = uri.getPort() < 0 ? getDefaultPort() : uri.getPort();
        String username = "";
        String password = "";
        if (!StringUtils.isBlank(uri.getUserInfo())) {
            String[] userInfo = uri.getUserInfo().split(":");
            username = userInfo[0];
            password = userInfo[1];
        }
        String dbName = uri.getPath().substring(1);
        ConnectionInfo c = new ConnectionInfo(host, port, username, password, dbName, instanceName);
        c.setUrl(url);
        return c;
    } catch (URISyntaxException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Invalid URI", e);
    }
}

From source file:rapture.pipeline2.gcp.PubsubPipeline2Handler.java

public void deleteTopic(String topicId) {
    if (topicId == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "Illegal Argument: topic Id is null");
    }// w w w. j  a  v a2 s .c o m
    String topId = (topicId.toLowerCase().startsWith("rapture")) ? topicId : topicId + "rapture";
    Topic topic = topics.get(topId);
    if (topic != null) {
        try (TopicAdminClient topicAdminClient = topicAdminClientCreate()) {
            TopicName topicName = TopicName.create(projectId, topId);
            topicAdminClient.deleteTopic(topicName);
        } catch (Exception ioe) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                    "Cannot delete topic " + topicId, ioe);
        }
    }
    topics.remove(topicId);
}

From source file:com.netflix.genie.server.resources.JobResource.java

/**
 * Get job information for given job id.
 *
 * @param id id for job to look up/* w ww .  j a va2  s.  c om*/
 * @return the Job
 * @throws GenieException For any error
 */
@GET
@Path("/{id}")
@ApiOperation(value = "Find a job by id", notes = "Get the job by id if it exists", response = Job.class)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid id supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Job getJob(@ApiParam(value = "Id of the job to get.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("called for job with id: " + id);
    return this.jobService.getJob(id);
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl.java

@Override
public byte[] send(byte[] request) {
    HttpClientContext context = HttpClientContext.create();

    context.setTargetHost(host);//from  w w  w.ja v  a2  s  .c o m
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthSchemeRegistry(authRegistry);
    context.setAuthCache(authCache);

    ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM);

    // Create the client with the AuthSchemeRegistry and manager
    HttpPost post = new HttpPost(toURI(url));
    post.setEntity(entity);

    try (CloseableHttpResponse response = client.execute(post, context)) {
        final int statusCode = response.getStatusLine().getStatusCode();
        if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
            return EntityUtils.toByteArray(response.getEntity());
        }

        throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        LOG.debug("Failed to execute HTTP request", e);
        throw new RuntimeException(e);
    }
}

From source file:eionet.cr.web.action.PingActionBean.java

/**
 * The default handler of this API's calls.
 *
 * @return//from  w  w  w.  j av a 2s.c om
 */
@DefaultHandler
public Resolution defaultHandler() {

    // Get client host/IP, ensure that it's in the whitelist.
    HttpServletRequest request = getContext().getRequest();
    String ip = request.getRemoteAddr();
    String host = processClientHostName(request.getRemoteHost(), ip);
    if (!isTrustedRequester(host, ip)) {
        LOGGER.debug("Client denied: host = " + host + ", IP = " + ip);
        return new ErrorResolution(HttpURLConnection.HTTP_FORBIDDEN);
    }

    // The default result-message and error code that will be printed into XML response.
    int errorCode = 0;
    String message = "";
    try {
        // Ensure that the pinged URI is not blank, is legal URI, does not have a fragment part and is not broken.
        if (StringUtils.isBlank(uri)) {
            errorCode = ERR_BLANK_URI;
            message = "No URI given, no action taken.";
        } else if (!URLUtil.isURL(uri)) {
            if (create) {
                errorCode = ERR_INVALID_URL;
                message = "Not a valid URL, source cannot be created.";
            } else {
                message = "URL not in catalogue of sources, no action taken.";
            }
        } else if (create && new URL(uri).getRef() != null) {
            errorCode = ERR_FRAGMENT_URL;
            message = "URL with a fragment part not allowed, source cannot be created.";
        } else if (create && URLUtil.isNotExisting(uri)) {
            errorCode = ERR_BROKEN_URL;
            message = "Could not make a connection to this URL, source cannot be created.";
        } else {
            // Helper flag that will be raised if a harvest is indeed needed.
            boolean doHarvest = false;

            // Check if a graph by this URI exists.
            boolean exists = DAOFactory.get().getDao(HelperDAO.class).isGraphExists(uri);
            if (exists) {
                doHarvest = true;
            } else if (create) {

                // Graph does not exist, but must be created as indicated in request parameters
                HarvestSourceDTO source = new HarvestSourceDTO();
                source.setUrl(uri);
                source.setIntervalMinutes(
                        GeneralConfig.getIntProperty(GeneralConfig.HARVESTER_REFERRALS_INTERVAL, 60480));
                DAOFactory.get().getDao(HarvestSourceDAO.class).addSource(source);
                doHarvest = true;
            } else {
                message = "URL not in catalogue of sources, no action taken.";
            }

            if (doHarvest) {
                UrgentHarvestQueue.addPullHarvest(uri);
                message = "URL added to the urgent harvest queue: " + uri;
            }
        }
    } catch (Exception e) {
        LOGGER.error("PING request failed: " + e.toString(), e);
        return new ErrorResolution(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }

    LOGGER.debug(message);
    String response = RESPONSE_XML.replace("@message@", message);
    response = response.replace("@errorCode@", String.valueOf(errorCode));
    return new StreamingResolution("text/xml", response);
}