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:rapture.kernel.ScriptApiImpl.java

@Override
public RaptureScript putScript(CallingContext context, String scriptURI, RaptureScript script) {
    RaptureURI internalURI = new RaptureURI(scriptURI, Scheme.SCRIPT);
    if (internalURI.hasDocPath() && !internalURI.getDocPath().equals(script.getName())) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, String.format("Supplied URI "
                + scriptURI + " has a docPath which does not match the script name " + script.getName()));
    }/*from ww  w . ja  v a  2 s .co m*/
    script.setAuthority(internalURI.getAuthority());

    RaptureScript currentlyThere = RaptureScriptStorage.readByAddress(script.getAddressURI());
    if (currentlyThere != null && currentlyThere.getPurpose() == RaptureScriptPurpose.LINK) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, String
                .format("You cannot write directly to a link, use %s instead", currentlyThere.getScript()));
    }

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

From source file:rapture.kernel.BlobApiImpl.java

@Override
public void addBlobContent(CallingContext context, String blobUri, byte[] content) {
    RaptureURI interimUri = new RaptureURI(blobUri, BLOB);
    Preconditions.checkNotNull(interimUri);
    Map<String, String> newMeta = createMetaData(context);

    BlobRepo blobRepo = getRepoFromCache(interimUri.getAuthority());
    if (blobRepo == null)
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoSuchRepo", interimUri.toAuthString())); //$NON-NLS-1$

    blobRepo.storeBlob(context, interimUri, true, new ByteArrayInputStream(content));

    Map<String, String> meta = getBlobMetaData(context, blobUri);
    String size = meta.get(ContentEnvelope.CONTENT_SIZE);
    long originalSize = Long.valueOf(size);
    originalSize += content.length;/*w w  w.  ja v  a  2  s. co  m*/
    meta.put(ContentEnvelope.CONTENT_SIZE, "" + originalSize);
    meta.put(WRITE_TIME, newMeta.get(WRITE_TIME));
    meta.put(MODIFIED_TIMESTAMP, newMeta.get(MODIFIED_TIMESTAMP));
    meta.put(USER, newMeta.get(USER));
    putBlobMetaData(context, interimUri.toString(), meta);
}

From source file:eu.codeplumbers.cosi.services.CosiCallService.java

/**
 * Make remote request to get all calls stored in Cozy
 *///from  w w w  .j a v  a 2s .  c  o  m
public String getRemoteCalls() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                Call.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    EventBus.getDefault().post(new CallSyncEvent(SYNC_MESSAGE,
                            "Reading calls on Cozy " + i + "/" + jsonArray.length() + "..."));
                    JSONObject callJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Call call = Call.getByRemoteId(callJson.get("_id").toString());
                    if (call == null) {
                        call = new Call(callJson);
                    } else {
                        call.setRemoteId(callJson.getString("_id"));
                        call.setCallerId(callJson.getString("callerId"));
                        call.setCallerNumber(callJson.getString("callerNumber"));
                        call.setDuration(callJson.getLong("duration"));
                        call.setDateAndTime(callJson.getString("dateAndTime"));
                        call.setType(callJson.getInt("type"));
                    }

                    call.save();

                    allCalls.add(call);
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, errorMessage));
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new CallSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

private List<Sms> getRemoteMessages() {
    allSms.clear();/*from w  w  w.j  a  v  a  2s. c  om*/
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new SmsSyncEvent(SYNC_MESSAGE, "Your Cozy has no Text messages stored."));
                Sms.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mNotifyManager.notify(notification_id, mBuilder.build());
                    EventBus.getDefault()
                            .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_cozy)));

                    JSONObject smsJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Sms sms = Sms.getBySystemIdAddressAndBody(smsJson.get("systemId").toString(),
                            smsJson.getString("address"), smsJson.getString("body"));
                    if (sms == null) {
                        sms = new Sms(smsJson);
                    } else {
                        sms.setRemoteId(smsJson.getString("_id"));
                        sms.setSystemId(smsJson.getString("systemId"));
                        sms.setAddress(smsJson.getString("address"));
                        sms.setBody(smsJson.getString("body"));

                        if (smsJson.has("readState")) {
                            sms.setReadState(smsJson.getBoolean("readState"));
                        }

                        sms.setDateAndTime(smsJson.getString("dateAndTime"));
                        sms.setType(smsJson.getInt("type"));
                    }

                    sms.save();

                    allSms.add(sms);
                }
            }
        } else {
            errorMessage = "Failed to parse API response";
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }
    return allSms;
}

From source file:org.dcm4che3.tool.wadors.WadoRS.java

private static SimpleHTTPResponse sendRequest(final WadoRS main) throws IOException {
    URL newUrl = new URL(main.getUrl());

    LOG.info("WADO-RS URL: {}", newUrl);

    HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();

    connection.setDoOutput(true);//  ww w .  j a v  a2  s  .  c  o  m

    connection.setDoInput(true);

    connection.setInstanceFollowRedirects(false);

    connection.setRequestMethod("GET");

    connection.setRequestProperty("charset", "utf-8");

    String[] acceptHeaders = compileAcceptHeader(main.acceptTypes);

    LOG.info("Accept-Headers: {}", Arrays.toString(acceptHeaders));

    for (String acceptStr : acceptHeaders)
        connection.addRequestProperty("Accept", acceptStr);

    if (main.getRequestTimeOut() != null) {
        connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut()));
        connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut()));
    }

    connection.setUseCaches(false);

    int responseCode = connection.getResponseCode();
    String responseMessage = connection.getResponseMessage();

    boolean isErrorCase = responseCode >= HttpURLConnection.HTTP_BAD_REQUEST;
    if (!isErrorCase) {

        InputStream in = null;
        if (connection.getHeaderField("content-type").contains("application/json")
                || connection.getHeaderField("content-type").contains("application/zip")) {
            String headerPath;
            in = connection.getInputStream();
            if (main.dumpHeader)
                headerPath = writeHeader(connection.getHeaderFields(),
                        new File(main.outDir, "out.json" + "-head"));
            else {
                headerPath = connection.getHeaderField("content-location");
            }
            File f = new File(main.outDir,
                    connection.getHeaderField("content-type").contains("application/json") ? "out.json"
                            : "out.zip");
            Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
            main.retrievedInstances.put(headerPath, f.toPath().toAbsolutePath());
        } else {
            if (main.dumpHeader)
                dumpHeader(main, connection.getHeaderFields());
            in = connection.getInputStream();
            try {
                File spool = new File(main.outDir, "Spool");
                Files.copy(in, spool.toPath(), StandardCopyOption.REPLACE_EXISTING);
                String boundary;
                BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(spool)));
                boundary = (rdr.readLine());
                boundary = boundary.substring(2, boundary.length());
                rdr.close();
                FileInputStream fin = new FileInputStream(spool);
                new MultipartParser(boundary).parse(fin, new MultipartParser.Handler() {

                    @Override
                    public void bodyPart(int partNumber, MultipartInputStream partIn) throws IOException {

                        Map<String, List<String>> headerParams = partIn.readHeaderParams();
                        String mediaType;
                        String contentType = headerParams.get("content-type").get(0);

                        if (contentType.contains("transfer-syntax"))
                            mediaType = contentType.split(";")[0];
                        else
                            mediaType = contentType;

                        // choose writer
                        if (main.isMetadata) {
                            main.writerType = ResponseWriter.XML;

                        } else {
                            if (mediaType.equalsIgnoreCase("application/dicom")) {
                                main.writerType = ResponseWriter.DICOM;
                            } else if (isBulkMediaType(mediaType)) {
                                main.writerType = ResponseWriter.BULK;
                            } else {
                                throw new IllegalArgumentException("Unknown media type "
                                        + "returned by server, media type = " + mediaType);
                            }

                        }
                        try {
                            main.writerType.readBody(main, partIn, headerParams);
                        } catch (Exception e) {
                            System.out.println("Error parsing media type to determine extension" + e);
                        }
                    }

                    private boolean isBulkMediaType(String mediaType) {
                        if (mediaType.contains("octet-stream"))
                            return true;
                        for (Field field : MediaTypes.class.getFields()) {
                            try {
                                if (field.getType().equals(String.class)) {
                                    String tmp = (String) field.get(field);
                                    if (tmp.equalsIgnoreCase(mediaType))
                                        return true;
                                }
                            } catch (Exception e) {
                                System.out.println("Error deciding media type " + e);
                            }
                        }

                        return false;
                    }
                });
                fin.close();
                spool.delete();
            } catch (Exception e) {
                System.out.println("Error parsing Server response - " + e);
            }
        }

    } else {
        LOG.error("Server returned {} - {}", responseCode, responseMessage);
    }

    connection.disconnect();

    main.response = new WadoRSResponse(responseCode, responseMessage, main.retrievedInstances);
    return new SimpleHTTPResponse(responseCode, responseMessage);

}

From source file:com.google.enterprise.adaptor.experimental.Sim.java

private void processMultipartPost(HttpExchange ex) throws IOException {
    InputStream inStream = ex.getRequestBody();
    String encoding = ex.getRequestHeaders().getFirst("Content-encoding");
    if (null != encoding && "gzip".equals(encoding.toLowerCase())) {
        inStream = new GZIPInputStream(inStream);
    }//from   www .j av  a2 s .  c  om
    String lens = ex.getRequestHeaders().getFirst("Content-Length");
    long len = (null != lens) ? Long.parseLong(lens) : 0;
    String ct = ex.getRequestHeaders().getFirst("Content-Type");
    try {
        String xml = extractFeedFromMultipartPost(inStream, len, ct);
        processXml(xml);
        respond(ex, HttpURLConnection.HTTP_OK, "text/plain", "Success".getBytes(UTF8));
    } catch (NoXmlFound nox) {
        log.warning("failed to find xml");
        respond(ex, HttpURLConnection.HTTP_BAD_REQUEST, "text/plain", "xml beginning not found".getBytes(UTF8));
    } catch (SAXException saxe) {
        log.warning("sax error: " + saxe.getMessage());
        respond(ex, HttpURLConnection.HTTP_BAD_REQUEST, "text/plain", "sax not liking the xml".getBytes(UTF8));
    } catch (ParserConfigurationException confige) {
        log.warning("parser error: " + confige.getMessage());
        respond(ex, HttpURLConnection.HTTP_BAD_REQUEST, "text/plain", "parser error".getBytes(UTF8));
    } catch (BadFeed bad) {
        log.warning("error in feed: " + bad.getMessage());
        respond(ex, HttpURLConnection.HTTP_BAD_REQUEST, "text/plain", bad.getMessage().getBytes(UTF8));
    }
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

private TenantResult<JsonObject> getForCertificateAuthority(final X500Principal subjectDn) {

    if (subjectDn == null) {
        return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
    } else {//from   www.  ja v  a  2 s  .co m
        final TenantObject tenant = getByCa(subjectDn);

        if (tenant == null) {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_OK, JsonObject.mapFrom(tenant),
                    CacheDirective.maxAgeDirective(MAX_AGE_GET_TENANT));
        }
    }
}

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

/**
 * Get jobs for given filter criteria./*from  ww w. ja  v  a  2  s .c  o m*/
 *
 * @param id          id for job
 * @param name        name of job (can be a SQL-style pattern such as HIVE%)
 * @param userName    user who submitted job
 * @param statuses    statuses of jobs to find
 * @param tags        tags for the job
 * @param clusterName the name of the cluster
 * @param clusterId   the id of the cluster
 * @param commandName the name of the command run by the job
 * @param commandId   the id of the command run by the job
 * @param page        page number for job
 * @param limit       max number of jobs to return
 * @param descending  Whether the order of the results should be descending or ascending
 * @param orderBys    Fields to order the results by
 * @return successful response, or one with HTTP error code
 * @throws GenieException For any error
 */
@GET
@ApiOperation(value = "Find jobs", notes = "Find jobs by the submitted criteria.", response = Job.class, responseContainer = "List")
@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 List<Job> getJobs(@ApiParam(value = "Id of the job.") @QueryParam("id") final String id,
        @ApiParam(value = "Name of the job.") @QueryParam("name") final String name,
        @ApiParam(value = "Name of the user who submitted the job.") @QueryParam("userName") final String userName,
        @ApiParam(value = "Statuses of the jobs to fetch.", allowableValues = "INIT, RUNNING, SUCCEEDED, KILLED, FAILED") @QueryParam("status") final Set<String> statuses,
        @ApiParam(value = "Tags for the job.") @QueryParam("tag") final Set<String> tags,
        @ApiParam(value = "Name of the cluster on which the job ran.") @QueryParam("executionClusterName") final String clusterName,
        @ApiParam(value = "Id of the cluster on which the job ran.") @QueryParam("executionClusterId") final String clusterId,
        @ApiParam(value = "The page to start on.") @QueryParam("commandName") final String commandName,
        @ApiParam(value = "Id of the cluster on which the job ran.") @QueryParam("commandId") final String commandId,
        @ApiParam(value = "The page to start on.") @QueryParam("page") @DefaultValue("0") final int page,
        @ApiParam(value = "Max number of results per page.") @QueryParam("limit") @DefaultValue("1024") final int limit,
        @ApiParam(value = "Whether results should be sorted in descending or ascending order. Defaults to descending") @QueryParam("descending") @DefaultValue("true") final boolean descending,
        @ApiParam(value = "The fields to order the results by. Must not be collection fields. Default is updated.") @QueryParam("orderBy") final Set<String> orderBys)
        throws GenieException {
    LOG.info("Called with [id | jobName | userName | statuses | executionClusterName "
            + "| executionClusterId | page | limit | descending | orderBys]");
    LOG.info(id + " | " + name + " | " + userName + " | " + statuses + " | " + tags + " | " + clusterName
            + " | " + clusterId + " | " + commandName + " | " + commandId + " | " + page + " | " + limit + " | "
            + descending + " | " + orderBys);
    Set<JobStatus> enumStatuses = null;
    if (!statuses.isEmpty()) {
        enumStatuses = EnumSet.noneOf(JobStatus.class);
        for (final String status : statuses) {
            if (StringUtils.isNotBlank(status)) {
                enumStatuses.add(JobStatus.parse(status));
            }
        }
    }

    return this.jobService.getJobs(id, name, userName, enumStatuses, tags, clusterName, clusterId, commandName,
            commandId, page, limit, descending, orderBys);
}

From source file:rapture.kernel.AdminApiImpl.java

/**
 * Some type specific calls/*from   w w  w.  j  a  v  a2  s  .c  o m*/
 */
@Override
public void deleteUser(CallingContext context, String userName) {
    checkParameter("User", userName); //$NON-NLS-1$
    // Assuming the userName is not "you", mark the user as inactive
    if (userName.equals(context.getUser())) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                adminMessageCatalog.getMessage("NoDeleteYourself")); //$NON-NLS-1$
    }
    log.info(adminMessageCatalog.getMessage("RemovingUser", userName)); //$NON-NLS-1$
    RaptureUser usr = getUser(context, userName);
    if (!usr.getInactive()) {
        if (usr.getHasRoot()) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    adminMessageCatalog.getMessage("NoDeleteRoot")); //$NON-NLS-1$
        }
        usr.setInactive(true);
        RaptureUserStorage.add(usr, context.getUser(),
                adminMessageCatalog.getMessage("Inactive", userName).toString()); //$NON-NLS-1$ //$NON-NLS-2$
    }
}

From source file:org.apache.hadoop.fs.http.server.TestHttpFSServer.java

@Test
@TestDir/* ww  w. j  a  v  a2  s  . c  om*/
@TestJetty
@TestHdfs
public void instrumentation() throws Exception {
    createHttpFSServer(false);

    URL url = new URL(TestJettyHelper.getJettyURL(),
            MessageFormat.format("/webhdfs/v1?user.name={0}&op=instrumentation", "nobody"));
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_UNAUTHORIZED);

    url = new URL(TestJettyHelper.getJettyURL(), MessageFormat.format(
            "/webhdfs/v1?user.name={0}&op=instrumentation", HadoopUsersConfTestHelper.getHadoopUsers()[0]));
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_OK);
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = reader.readLine();
    reader.close();
    Assert.assertTrue(line.contains("\"counters\":{"));

    url = new URL(TestJettyHelper.getJettyURL(), MessageFormat.format(
            "/webhdfs/v1/foo?user.name={0}&op=instrumentation", HadoopUsersConfTestHelper.getHadoopUsers()[0]));
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(conn.getResponseCode(), HttpURLConnection.HTTP_BAD_REQUEST);
}