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:com.netflix.genie.server.resources.CommandConfigResource.java

/**
 * Update command configuration./*from  w w w .ja  v  a 2s. c  o  m*/
 *
 * @param id            unique id for the configuration to update.
 * @param updateCommand the information to update the command with
 * @return The updated command
 * @throws GenieException For any error
 */
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update a command", notes = "Update a command from the supplied information.", response = Command.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Command to update not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Command updateCommand(
        @ApiParam(value = "Id of the command to update.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The command information to update.", required = true) final Command updateCommand)
        throws GenieException {
    LOG.info("Called to create/update comamnd config");
    return this.commandConfigService.updateCommand(id, updateCommand);
}

From source file:net.sbbi.upnp.messages.ActionMessage.java

/**
 * Executes the message and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a response object containing the UPNP parsed response
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 *///from   w  ww  .ja va2  s .  c  o  m
public ActionResponse service() throws IOException, UPNPResponseException {
    ActionResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:").append(serviceAction.getName()).append(" xmlns:u=\"").append(service.getServiceType())
            .append("\">");

    if (serviceAction.getInputActionArguments() != null) {
        // this action requires params so we just set them...
        for (Iterator itr = inputParameters.iterator(); itr.hasNext();) {
            InputParamContainer container = (InputParamContainer) itr.next();
            body.append("<").append(container.name).append(">").append(container.value);
            body.append("</").append(container.name).append(">");
        }
    }
    body.append("</u:").append(serviceAction.getName()).append(">");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    conn.setRequestProperty("SOAPACTION",
            "\"" + service.getServiceType() + "#" + serviceAction.getName() + "\"");
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    out.close();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        ActionMessageResponseParser msgParser = new ActionMessageResponseParser(serviceAction);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getActionResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:rapture.repo.file.FileDataStore.java

@Override
public void visitKeys(String prefix, StoreKeyVisitor iStoreKeyVisitor) {
    File dir = FileRepoUtils.makeGenericFile(parentDir, convertKeyToPath(prefix));
    if (!dir.exists()) {
        try {//w  w  w  . j a v  a 2 s.  c om
            File file = FileRepoUtils.makeGenericFile(parentDir, convertKeyToPath(prefix) + EXTENSION);
            if (file.exists()) {
                iStoreKeyVisitor.visit(prefix + removeExtension(file.getName()),
                        FileUtils.readFileToString(file));
            }
        } catch (IOException e) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Could not read keys",
                    e);
        }
        return;
    }
    Iterator<File> fIterator = FileUtils.iterateFiles(dir, null, true);
    while (fIterator.hasNext()) {
        File f = fIterator.next();
        if (f.isFile()) {
            try {
                if (!iStoreKeyVisitor.visit(prefix + removeExtension(f.getName()),
                        FileUtils.readFileToString(f)))
                    break;
            } catch (IOException e) {
                throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                        "Could not read keys", e);
            }
        }
    }
}

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

/**
 * Update application./*from  w w  w.j a  va2 s.  c  om*/
 *
 * @param id        unique id for configuration to update
 * @param updateApp contains the application information to update
 * @return successful response, or one with an HTTP error code
 * @throws GenieException For any error
 */
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update an application", notes = "Update an application from the supplied information.", response = Application.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Application to update 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 Application updateApplication(
        @ApiParam(value = "Id of the application to update.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The application information to update.", required = true) final Application updateApp)
        throws GenieException {
    LOG.info("called to update application config with info " + updateApp.toString());
    return this.applicationConfigService.updateApplication(id, updateApp);
}

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

/**
 * Update a cluster configuration.//from  w  ww . ja  v  a2  s . com
 *
 * @param id            unique if for cluster to update
 * @param updateCluster contains the cluster information to update
 * @return the updated cluster
 * @throws GenieException For any error
 */
@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update a cluster", notes = "Update a cluster from the supplied information.", response = Cluster.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Cluster to update not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Cluster updateCluster(
        @ApiParam(value = "Id of the cluster to update.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The cluster information to update with.", required = true) final Cluster updateCluster)
        throws GenieException {
    LOG.info("Called to update cluster with id " + id + " update fields " + updateCluster);
    return this.clusterConfigService.updateCluster(id, updateCluster);
}

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

@Override
public void subscribe(String queueIdentifier, final QueueSubscriber qsubscriber) {
    if (StringUtils.stripToNull(queueIdentifier) == null) {
        throw new RuntimeException("Null topic");
    }// w ww . java  2s. c om

    SubscriptionName subscriptionName = SubscriptionName.create(projectId, qsubscriber.getSubscriberId());
    Topic topic = getTopic(queueIdentifier);
    Subscription subscription = subscriptions.get(subscriptionName);
    if (subscription == null) {
        try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
            try {
                subscription = subscriptionAdminClient.getSubscription(subscriptionName);
            } catch (Exception e) {
                if (subscription == null) {
                    subscription = subscriptionAdminClient.createSubscription(subscriptionName,
                            topic.getNameAsTopicName(), PushConfig.getDefaultInstance(), 0);
                    subscriptions.put(subscriptionName, subscription);
                }
            }
        } catch (Exception ioe) {
            System.err.println(ExceptionToString.format(ioe));
        }
    }
    try {
        MessageReceiver receiver = new MessageReceiver() {
            @Override
            public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
                System.out.println("Received " + message.getData().toStringUtf8());
                if (qsubscriber.handleEvent(message.getData().toByteArray()))
                    consumer.ack();
            }
        };

        Subscriber.Builder builder = Subscriber.defaultBuilder(subscriptionName, receiver);
        // The default executor provider creates an insane number of threads.
        if (executor != null)
            builder.setExecutorProvider(executor);
        Subscriber subscriber = builder.build();

        subscriber.addListener(new Subscriber.Listener() {
            @Override
            public void failed(Subscriber.State from, Throwable failure) {
                // Subscriber encountered a fatal error and is shutting down.
                System.err.println(failure);
            }
        }, MoreExecutors.directExecutor());
        subscriber.startAsync().awaitRunning();
        subscribers.put(qsubscriber, subscriber);
    } catch (Exception e) {
        String error = String.format("Cannot subscribe to topic %s:\n%s", topic.getName(),
                ExceptionToString.format(e));
        logger.error(error);
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, error, e);
    }
    logger.debug("Subscribed to " + queueIdentifier + " as " + qsubscriber.getSubscriberId());

}

From source file:rapture.plugin.install.PluginSandbox.java

public void save(ScriptingApi client) throws IOException {
    if (!rootDir.exists()) {
        if (!rootDir.mkdirs()) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                    "Could not create directory" + rootDir.getPath());
        }/*from w w  w .ja va 2s .  com*/
    }
    writeConfig();
    for (PluginSandboxItem item : uri2item.values()) {
        if (item.isFileCurrent()) {
            continue;
        }
        if (!item.isRemoteCurrent()) {
            item.download(client, true);
        }
        item.storeFile();
    }
    for (Map<RaptureURI, PluginSandboxItem> map : variant2map.values()) {
        for (PluginSandboxItem item : map.values()) {
            if (!item.isRemoteCurrent()) {
                item.download(client, true);
            }
            item.storeFile();
        }
    }
}

From source file:org.openmrs.web.filter.initialization.TestInstallUtil.java

/**
 * @param urlString//from w w  w .j a va 2s  .c  o  m
 * @param openmrsUsername
 * @param openmrsPassword
 * @return input stream
 * @throws MalformedURLException
 * @throws IOException
 */
protected static InputStream getResourceInputStream(String urlString, String openmrsUsername,
        String openmrsPassword) throws MalformedURLException, IOException, APIException {

    HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setConnectTimeout(15000);
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);

    String requestParams = "username=" + Base64.encode(openmrsUsername.getBytes(Charset.forName("UTF-8")))
            + "&password=" + Base64.encode(openmrsPassword.getBytes(Charset.forName("UTF-8")));

    OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
    out.write(requestParams);
    out.flush();
    out.close();

    if (log.isInfoEnabled()) {
        log.info("Http response message:" + urlConnection.getResponseMessage() + ", Code:"
                + urlConnection.getResponseCode());
    }

    if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new APIAuthenticationException("Invalid username or password");
    } else if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
        throw new APIException("error.occurred.on.remote.server", (Object[]) null);
    }

    return urlConnection.getInputStream();
}

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

@MethodMapping(value = "/structure/{id}", httpMethod = HttpMethod.GET, produces = RestMimeTypes.TEXT_PLAIN)
public String structure(String id) {
    try {/*w  w  w.j  av a  2  s  .co  m*/
        Matcher mpdb = StockholmParser.pPDBAC.matcher(id);
        if (mpdb.matches()) {

            URL url = Utils.getRcsbURL(mpdb.group(1));

            StringWriter pdbWriter = new StringWriter();
            IOUtils.copy(url.openStream(), pdbWriter, "UTF-8");
            pdbWriter.close();

            return pdbWriter.toString();
        }

        File xmlFile = new File(Config.getCacheDir(), id + ".xml.gz");
        if (xmlFile.isFile()) {

            VASEDataObject data = VASEXMLParser.parse(new GZIPInputStream(new FileInputStream(xmlFile)));

            return Utils.getPdbContents(data.getPdbID());
        }
        if (Config.hsspPdbCacheEnabled()) {

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

            if (pdbFile.isFile()) {

                StringWriter pdbWriter = new StringWriter();
                IOUtils.copy(new GZIPInputStream(new FileInputStream(pdbFile)), pdbWriter, "UTF-8");
                pdbWriter.close();

                return pdbWriter.toString();
            }
        }

        log.error("no structure file for " + id);
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND);

    } catch (Exception e) {

        log.error("structure " + id + ": " + e.getMessage(), e);

        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:rapture.server.web.servlet.BaseReflexScriptPageServlet.java

private void sendVerboseError(HttpServletResponse resp, ErrorWrapper ew) throws IOException {
    Map<String, Object> map = JacksonUtil.getHashFromObject(ew);
    map.put("error", ew.getMessage());
    String r = JacksonUtil.jsonFromObject(map);
    resp.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
    resp.setCharacterEncoding("UTF-8");
    resp.getWriter().append(r);//from   www  .jav  a2  s .  c o m
    resp.setContentType("text/plain");
}