Example usage for java.net HttpURLConnection HTTP_BAD_REQUEST

List of usage examples for java.net HttpURLConnection HTTP_BAD_REQUEST

Introduction

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

Prototype

int HTTP_BAD_REQUEST

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

Click Source Link

Document

HTTP Status-Code 400: Bad Request.

Usage

From source file:org.eclipse.orion.server.tests.servlets.git.GitInitTest.java

@Test
public void testInitWithoutNameAndFilePath() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath initPath = new Path("workspace").append(getWorkspaceId(workspaceLocation)).makeAbsolute();

    WebRequest request = getPostGitInitRequest(initPath, null, null);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}

From source file:rapture.kernel.UserApiImpl.java

@Override
public RaptureUser updateMyDescription(CallingContext context, String description) {
    RaptureUser usr = Kernel.getAdmin().getTrusted().getUser(context, context.getUser());
    if (usr != null) {
        usr.setDescription(description);
        RaptureUserStorage.add(usr, context.getUser(), "Updated my description");
        return usr;
    } else {/*from  w  ww  .  j a  v  a 2  s  .c  o  m*/
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Could not find user record");
    }
}

From source file:rapture.kernel.ScriptApiImpl.java

@Override
public RaptureScript createScript(CallingContext context, String scriptURI, RaptureScriptLanguage language,
        RaptureScriptPurpose purpose, String script) {

    if (doesScriptExist(context, scriptURI)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                String.format("Script %s already exists", scriptURI));
    } else {/*from   ww w  .j a va  2  s.co m*/

        RaptureURI internalURI = new RaptureURI(scriptURI, Scheme.SCRIPT);

        RaptureScript s = new RaptureScript();
        s.setLanguage(language);
        s.setPurpose(purpose);
        s.setName(internalURI.getDocPath());
        s.setScript(script);
        s.setAuthority(internalURI.getAuthority());

        RaptureScriptStorage.add(internalURI, s, context.getUser(), Messages.getString("Script.createdScript")); //$NON-NLS-1$
        return s;
    }
}

From source file:rapture.kernel.StructuredApiImpl.java

@Override
public void deleteStructuredRepo(CallingContext context, String repoURI) {
    RaptureURI uri = new RaptureURI(repoURI, Scheme.STRUCTURED);
    if (uri.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", repoURI)); //$NON-NLS-1$
    }/*from w  w  w . j  ava 2 s  . co  m*/
    getRepoOrFail(uri.getAuthority()).drop();
    removeRepoFromCache(uri.getAuthority());
    StructuredRepoConfigStorage.deleteByAddress(uri, context.getUser(), "Delete structured repo");
}

From source file:com.cognifide.aet.rest.ConfigsServlet.java

/***
 * Returns JSON representation of Suite based on correlationId or suite name.
 * If suite name is provided, then newest version of JSON is returned.
 *
 * @param req/*from  www.  j  ava2 s .  c o m*/
 * @param resp
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    LOGGER.debug("GET, req: '{}'", req);
    PrintWriter responseWriter = retrieveResponseWriter(req, resp);
    if (responseWriter != null) {
        resp.setContentType("application/json");
        String configType = StringUtils.substringAfter(req.getRequestURI(), Helper.getConfigsPath())
                .replace(Helper.PATH_SEPARATOR, "");
        String reportDomain = reportConfigurationManager.getReportDomain();

        if (COMMUNICATION_SETTINGS_PARAM.equals(configType)) {
            JmsEndpointConfig jmsEndpointConfig = jmsConnection.getEndpointConfig();
            CommunicationSettings communicationSettings = new CommunicationSettings(jmsEndpointConfig,
                    reportDomain);
            responseWriter.write(new Gson().toJson(communicationSettings));
        } else if (LIST_PARAM.equals(configType)) {
            resp.setContentType("text/html; charset=utf-8");
            resp.setHeader("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36");
            responseWriter.write(new SuitesListProvider(metadataDAO, reportDomain).listSuites());
        } else if (LOCKS_PARAM.equals(configType)) {
            responseWriter.write(getLocks());
        } else {
            resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
            responseWriter.write("Unable to get given config.");
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    flushResponseBuffer(req, resp);
}

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

public void testRunningJob() {

    MiniMRCluster mrCluster = null;/*from  www .  j a v  a 2s.  c  o m*/
    JobConf conf = new JobConf();
    try {
        conf.setLong("mapred.job.tracker.retiredjobs.cache.size", 1);
        conf.setLong("mapred.jobtracker.retirejob.interval", 0);
        conf.setLong("mapred.jobtracker.retirejob.check", 0);
        conf.setLong("mapred.jobtracker.completeuserjobs.maximum", 0);
        conf.set("mapreduce.history.server.http.address", "localhost:0");

        mrCluster = new MiniMRCluster(1, conf.get("fs.default.name"), 1, null, null, conf);

        conf = mrCluster.createJobConf();
        createInputFile(conf, "/tmp/input");

        RunningJob job = submitJob(conf);
        LOG.info("Job details: " + job);

        String url = job.getTrackingURL().replaceAll("jobdetails.jsp", "gethistory.jsp");
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        try {
            int status = client.executeMethod(method);
            Assert.assertEquals(status, HttpURLConnection.HTTP_BAD_REQUEST);
        } finally {
            method.releaseConnection();
            job.killJob();
        }

    } catch (IOException e) {
        LOG.error("Failure running test", e);
        Assert.fail(e.getMessage());
    } finally {
        if (mrCluster != null)
            mrCluster.shutdown();
    }
}

From source file:rapture.kernel.SearchApiImpl.java

@Override
public void createSearchRepo(CallingContext context, String searchRepoUri, String config) {
    checkParameter("Repository URI", searchRepoUri);
    checkParameter("Config", config);

    RaptureURI interimUri = new RaptureURI(searchRepoUri, Scheme.SEARCH);
    String authority = interimUri.getAuthority();
    if ((authority == null) || authority.isEmpty()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoAuthority")); //$NON-NLS-1$
    }//from  w  w w  .j a  v  a  2  s .co  m
    if (interimUri.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", searchRepoUri)); //$NON-NLS-1$
    }
    if (searchRepoExists(context, searchRepoUri)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("Exists", searchRepoUri)); //$NON-NLS-1$
    }

    // store repo config
    SearchRepoConfig rbc = new SearchRepoConfig();
    rbc.setConfig(config);
    rbc.setAuthority(interimUri.getAuthority());
    SearchRepoConfigStorage.add(rbc, context.getUser(), "create repo");
    logger.info("Created search repository config for uri: " + searchRepoUri);
}

From source file:com.cognifide.aet.rest.XUnitServlet.java

private void generateXUnitAndRespondWithIt(DBKey dbKey, HttpServletResponse response, Suite suite)
        throws IOException {
    final MetadataToXUnitConverter converter = new MetadataToXUnitConverter(suite);

    try (InputStream result = generateXML(converter.convert())) {
        response.setContentType(MediaType.APPLICATION_XML_UTF_8.toString());
        response.getWriter().write(IOUtils.toString(result));
    } catch (IOException | JAXBException e) {
        LOGGER.error("Fatal exception while generating xUnit xml", e);
        response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        response.getWriter().write(responseAsJson("Unable to get xUnit for %s", dbKey.toString()));
    }//from  w  w w.  j  a  v  a  2  s .c o m
}

From source file:net.mceoin.cominghome.api.NestUtil.java

/**
 * Make HTTP/JSON call to Nest and set away status.
 *
 * @param access_token OAuth token to allow access to Nest
 * @param structure_id ID of structure with thermostat
 * @param away_status Either "home" or "away"
 * @return Equal to "Success" if successful, otherwise it contains a hint on the error.
 *///w  ww  . j a  v a2 s.  co m
public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) {

    String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth="
            + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("PUT");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);

        urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        String payload = "\"" + away_status + "\"";

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(payload);
        wr.flush();
        log.info(payload);

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            urlConnection.setRequestProperty("Accept", "application/json");

            //                System.out.println("Redirect to URL : " + newUrl);

            wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(payload);
            wr.flush();

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;
        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    if (error) {
        return "Error: " + errorResult;
    } else {
        return "Success";
    }
}

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  w w  .  ja v a2  s  .c om*/

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