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.okj.im.core.service.QQHttpService.java

/**
 * ?//from   ww w  . j  a  va  2  s .  c  om
 * @param conn
 * @return
 */
protected boolean checkResponseCode(final HttpURLConnection conn) {
    boolean success = false;

    //?false;
    if (conn == null) {
        return false;
    }

    try {
        InputStream is = conn.getInputStream();
        if (is == null) {
            return false;
        }

        InputStream isrs = conn.getErrorStream();
        if (isrs != null) {
            return false;
        }

        int status = conn.getResponseCode();
        switch (status) {
        case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504
            LogUtils.warn(LOGGER, "! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_FORBIDDEN://403
            LogUtils.warn(LOGGER, "?! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500
            LogUtils.warn(LOGGER, "WebQQ?! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_NOT_FOUND://404
            LogUtils.warn(LOGGER, "??! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_OK:
            LogUtils.warn(LOGGER, "Connect OK! status{0}", status);
            success = true;
        }
    } catch (IOException ex) {
        LogUtils.error(LOGGER, "??", ex);
    }
    return success;
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Returns an INTERNAL_ERROR response with the specified message
 * @param message the message format/*  w  ww. j av a  2  s. com*/
 * @param args the message parameters
 */
protected Response internalError(String msg, Object... args) {
    return status(HttpURLConnection.HTTP_INTERNAL_ERROR, msg, args);
}

From source file:rapture.ftp.common.FTPConnection.java

@Override
public boolean connectAndLogin() {
    if (isLocal()) {
        log.info("In local mode - not connecting");
        return true;
    }//  w w  w . ja v a  2 s  . c  o m
    return FTPService.runWithRetry("Could not login to " + config.getAddress() + " as " + config.getLoginId(),
            this, false, new FTPAction<Boolean>() {
                @Override
                public Boolean run(int attemptNum) throws IOException {
                    FTPClient ftpClient = getFtpClient();
                    log.debug(String.format("Connecting to %s. Attempt %s of %s", config.getAddress(),
                            1 + attemptNum, config.getRetryCount()));
                    try {
                        ftpClient.connect(config.getAddress());
                    } catch (UnknownHostException e) {
                        log.info(ExceptionToString.summary(e));
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Unknown host " + config.getAddress());
                    }
                    int reply = ftpClient.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        log.debug("Got non-positive reply of " + reply);
                        logoffAndDisconnect();
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Could not connect to: " + config.getAddress());
                    }
                    log.debug("Logging in user: " + config.getLoginId());
                    if (!ftpClient.login(config.getLoginId(), config.getPassword())) {
                        log.info("Could not login to " + config.getAddress() + " as " + config.getLoginId());
                        ftpClient.logout();
                        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                                "Could not login to " + config.getAddress() + " as " + config.getLoginId());
                    }
                    isLoggedIn = true;
                    log.debug("Entering local passive mode");
                    ftpClient.enterLocalPassiveMode();
                    log.info("Connected and logged in to: " + config.getAddress());
                    ftpClient.setSoTimeout(1000 * config.getTimeout());
                    return true;
                }
            });
}

From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java

/**
 * /*from w w  w. j  a v a 2 s  .c  om*/
 * loadGraph
 * 
 * @param id a String
 * 
 * @return HttpResponse
 * 
 */
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "graphNotFound"),
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "graphLoaded"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError") })
@ApiOperation(value = "loadGraph", notes = "")
public HttpResponse loadGraph(@PathParam("id") String id) {
    String result = "";
    String columnName = "";
    String selectquery = "";
    int columnCount = 0;
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        // get connection from connection pool
        conn = dbm.getConnection();
        selectquery = "SELECT * FROM graphs WHERE graphId = " + id + " ;";

        // prepare statement
        stmnt = conn.prepareStatement(selectquery);

        // retrieve result set
        rs = stmnt.executeQuery();
        rsmd = (ResultSetMetaData) rs.getMetaData();
        columnCount = rsmd.getColumnCount();
        // process result set
        if (rs.next()) {
            JSONObject ro = new JSONObject();
            for (int i = 1; i <= columnCount; i++) {
                result = rs.getString(i);
                columnName = rsmd.getColumnName(i);
                // setup resulting JSON Object
                ro.put(columnName, result);
            }
            HttpResponse graphLoaded = new HttpResponse(ro.toJSONString(), HttpURLConnection.HTTP_OK);
            return graphLoaded;
        } else {
            // return HTTP Response on error
            String er = "No result for graph with id " + id;
            HttpResponse graphNotFound = new HttpResponse(er, HttpURLConnection.HTTP_NOT_FOUND);
            return graphNotFound;
        }

    } catch (Exception e) {
        String er = "Internal error: " + e.getMessage();
        HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
        return internalError;
    } finally {
        // free resources
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (stmnt != null) {
            try {
                stmnt.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
    }
}

From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java

/**
 * Communicates with redirect url and works as a transparent proxy
 * // w w w.  j a v a2s . c o  m
 * @param request
 *          the servlet request
 * @param response
 *          the servlet response
 * @throws IOException
 *           if an exception occurs
 */
private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException {

    HttpURLConnection httpCon = null;
    URL redirectURL = null;
    InputStream input = null;
    OutputStream output = null;
    InputStream proxyInput = null;
    OutputStream proxyOutput = null;

    try {

        input = request.getInputStream();
        output = response.getOutputStream();

        String sQueryStr = request.getQueryString();
        String sAuthorization = request.getHeader("Authorization");
        String requestBody = readInputCharacters(input);
        String requestMethod = request.getMethod();
        String contentType = request.getContentType();
        String encoding = request.getCharacterEncoding();

        LOGGER.finer(" Request method = " + requestMethod);
        LOGGER.finer(" Query string = " + sQueryStr);
        LOGGER.finer(" Authorization header =" + sAuthorization);
        LOGGER.finer(" Character Encoding = " + encoding);
        LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr);

        redirectURL = new URL(this._redirectURL + "?" + sQueryStr);

        httpCon = (HttpURLConnection) redirectURL.openConnection();

        httpCon.setDoInput(true);
        httpCon.setDoOutput(true);
        httpCon.setUseCaches(false);
        httpCon.setRequestMethod(requestMethod);
        httpCon.setRequestProperty("Content-type", contentType);

        if (sAuthorization != null) {
            httpCon.addRequestProperty("Authorization", sAuthorization);
        }

        proxyOutput = httpCon.getOutputStream();
        send(requestBody, proxyOutput);

        String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate");
        if (authenticateHdr != null) {
            LOGGER.finer(" WWW-Authenticate : " + authenticateHdr);
            response.setHeader("WWW-Authenticate",
                    StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr)));
        }
        LOGGER.finer(" Response Code : " + httpCon.getResponseCode());

        if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) {

            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            proxyInput = httpCon.getInputStream();
            send(proxyInput, output);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
        if (proxyInput != null) {
            proxyInput.close();
        }
        if (proxyOutput != null) {
            proxyOutput.close();
        }
        if (httpCon != null) {
            httpCon.disconnect();
        }
    }
}

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

private void createSymLink(String k, String filePath) {
    Path originalFile = Paths.get(filePath);
    File fromFile = FileRepoUtils.makeGenericFile(parentDir, convertKeyToPathWithExtension(k));
    Path fromFilePath = Paths.get(fromFile.getAbsolutePath());
    try {/*from   w  w  w  . ja  va2s.com*/
        Files.deleteIfExists(fromFilePath);
        FileUtils.forceMkdir(fromFilePath.getParent().toFile());
        Files.createSymbolicLink(fromFilePath, originalFile);
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Error creating sym link",
                e);
    }
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Returns an INTERNAL_ERROR response with the specified message and logs the given error
 * @param t the error to log//from  w ww  .  j  a v a  2 s. c om
 * @param message the message format
 * @param args the message parameters
 */
protected Response internalError(Throwable t, String msg, Object... args) {
    Logger.error(t, msg, args);
    return status(HttpURLConnection.HTTP_INTERNAL_ERROR, msg, args);
}

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

/**
 * Executes the state variable query 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 state variable response object containing the variable value
 * @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  .jav  a2 s  .  co  m*/
public StateVariableResponse service() throws IOException, UPNPResponseException {
    StateVariableResponse 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:QueryStateVariable xmlns:u=\"urn:schemas-upnp-org:control-1-0\">");
    body.append("<u:varName>").append(serviceStateVar.getName()).append("</u:varName>");
    body.append("</u:QueryStateVariable>");
    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("SOAPACTION", "\"urn:schemas-upnp-org:control-1-0#QueryStateVariable\"");
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    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);
        StateVariableResponseParser msgParser = new StateVariableResponseParser(serviceStateVar);
        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) {
                // ignoring
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getStateVariableResponse();
            } 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 RaptureQueryResult runNativeQuery(String repoType, List<String> queryParams) {
    if (repoType.toUpperCase().equals("FILE")) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Not yet implemented");
    } else {/*ww w . j a  v a  2s .  co  m*/
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "RepoType mismatch. Repo is of type FILE, asked for " + repoType);
    }
}

From source file:org.cellprofiler.subimager.ImageWriterHandler.java

public void handle(HttpExchange exchange) throws IOException {
    if (!exchange.getRequestMethod().equals("POST")) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_METHOD,
                "<html><body>writeimage only accepts HTTP post</body></html>");
        return;/*from   w  w  w.  j  ava 2  s  .c  o  m*/
    }
    final String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
    if (contentType == null) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>No Content-type request header</body></html>");
        return;
    }
    if (!contentType.startsWith(MULTIPART_FORM_DATA)) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>Content type must be " + MULTIPART_FORM_DATA + ".</body></html>");
        return;
    }
    int idx = contentType.indexOf(BOUNDARY_EQUALS, MULTIPART_FORM_DATA.length());
    if (idx == -1) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>Did not find boundary identifier in multipart/form-data content type.</body></html>");
        return;
    }
    final String contentEncoding = exchange.getRequestHeaders().getFirst("Content-Encoding");
    String contentLengthString = exchange.getRequestHeaders().getFirst("Content-Length");
    if (contentLengthString == null) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>No Content-Length request header</body></html>");
        return;
    }
    try {
        Integer.parseInt(contentLengthString);
    } catch (NumberFormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String
                .format("<html><body>Content length was not a number: %s</body></html>", contentLengthString));
        return;
    }
    final int contentLength = Integer.parseInt(contentLengthString);
    final InputStream requestBodyStream = exchange.getRequestBody();
    FileUpload upload = new FileUpload();
    FileItemIterator fileItemIterator;
    String omeXML = null;
    URI uri = null;
    int index = 0;
    NDImage ndimage = null;
    String compression = DEFAULT_COMPRESSION;
    try {
        fileItemIterator = upload.getItemIterator(new RequestContext() {

            public String getCharacterEncoding() {
                return contentEncoding;
            }

            public String getContentType() {
                return contentType;
            }

            public int getContentLength() {
                return contentLength;
            }

            public InputStream getInputStream() throws IOException {
                return requestBodyStream;
            }
        });
        while (fileItemIterator.hasNext()) {
            FileItemStream fis = fileItemIterator.next();
            String name = fis.getFieldName();

            if (name.equals(NAME_IMAGE)) {
                String imageContentType = fis.getContentType();
                if (imageContentType == null) {
                    reportError(exchange, HttpURLConnection.HTTP_UNSUPPORTED_TYPE,
                            "<html><body>Image form-data field must have a content type.</body></html>");
                    return;
                }
                try {
                    InputStream is = SubimagerUtils.getInputStream(exchange, fis);
                    if (is == null)
                        return;
                    ndimage = NDImage.decode(is);
                } catch (MalformedStreamException e) {
                    reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                            "<html><body>Failed to read body for part, " + name + ".</body></html>");
                } catch (IOException e) {
                    reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                            "<html><body>Failed to read multipart body data</body></html>");
                    return;
                } catch (org.cellprofiler.subimager.NDImage.FormatException e) {
                    reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                            "<html><body>Image data was not in correct format: " + e.getMessage()
                                    + "</body></html>");
                    return;
                }
            } else {
                String partDataString = SubimagerUtils.readFully(exchange, fis);
                if (partDataString == null)
                    return;
                if (name.equals(NAME_INDEX)) {
                    try {
                        index = Integer.parseInt(partDataString);
                    } catch (NumberFormatException e) {
                        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                                "<html><body>Index form-data field must be a number: " + partDataString
                                        + ".</body></html>");
                        return;
                    }
                } else if (name.equals(NAME_OMEXML)) {
                    omeXML = partDataString;
                } else if (name.equals(NAME_URL)) {
                    try {
                        uri = new URI(partDataString);
                    } catch (URISyntaxException e) {
                        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                                "<html><body>Improperly formatted URL: " + partDataString + ".</body></html>");
                        return;
                    }
                } else if (name.equals(NAME_COMPRESSION)) {
                    compression = partDataString;
                }
            }
        }
        if (ndimage == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have an image part</body></html>");
            return;
        }
        if (uri == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have a URL part</body></html>");
            return;
        }
        if (omeXML == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have an omexml part</body></html>");
            return;
        }
        writeImage(exchange, ndimage, uri, omeXML, index, compression);
    } catch (FileUploadException e) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String
                .format("<html><body>Parsing error in multipart message: %s</body></html>", e.getMessage()));
        return;
    }
}