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.mongodb.MongoDBFactory.java

private Mongo getMongoFromSysConfig(String instanceName) {
    Map<String, ConnectionInfo> map = Kernel.getSys().getConnectionInfo(ContextFactory.getKernelUser(),
            ConnectionType.MONGODB.toString());
    if (!map.containsKey(instanceName)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                mongoMsgCatalog.getMessage("NoInstance", instanceName));
    }/*from www . j a va  2  s.  c om*/
    ConnectionInfo info = map.get(instanceName);
    log.info("Connection info = " + info);
    try {
        MongoClient mongo = new MongoClient(new MongoClientURI(info.getUrl()));
        mongoDBs.put(instanceName, mongo.getDB(info.getDbName()));
        mongoDatabases.put(instanceName, mongo.getDatabase(info.getDbName()));
        mongoInstances.put(instanceName, mongo);
        return mongo;
    } catch (MongoException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, new ExceptionToString(e));
    }
}

From source file:com.example.android.wearable.wcldemo.pages.StockFragment.java

private void handleHttpRequest(final String url, final String method, final String query, final String charset,
        final String nodeId, final String requestId) {
    new Thread(new Runnable() {
        @Override//from  w w  w. ja  v a  2  s  .  c  o  m
        public void run() {
            try {
                makeHttpCall(url, method, query, charset, nodeId, requestId);
            } catch (IOException e) {
                Log.e(TAG, "Failed to make the http call", e);
                WearManager.getInstance().sendHttpResponse("", HttpURLConnection.HTTP_BAD_REQUEST, nodeId,
                        requestId, mResultCallback);
            }
        }
    }).start();

}

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

/**
 * Make remote request to get all loyalty cards stored in Cozy
 */// w  ww  . jav a2s  . com
public String getRemoteLoyaltyCards() {
    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 LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                LoyaltyCard.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE,
                                "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        LoyaltyCard loyaltyCard = LoyaltyCard
                                .getByRemoteId(loyaltyCardJson.get("_id").toString());
                        if (loyaltyCard == null) {
                            loyaltyCard = new LoyaltyCard(loyaltyCardJson);
                        } else {
                            loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id"));
                            loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue"));
                            loyaltyCard.setCode(loyaltyCardJson.getInt("code"));
                            loyaltyCard.setLabel(loyaltyCardJson.getString("label"));
                            loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate"));
                        }

                        loyaltyCard.save();
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

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

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

From source file:rapture.kernel.StructuredApiImpl.java

@Override
public StructuredRepoConfig getStructuredRepoConfig(CallingContext ctx, String uriStr) {
    RaptureURI uri = new RaptureURI(uriStr, Scheme.STRUCTURED);
    if (uri.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "Structured repository URI " + uriStr + " can't have a doc path: '" + uri.getDocPath() + "'");
    }/*  w  w  w. ja va2 s.c  o  m*/
    return StructuredRepoConfigStorage.readByAddress(uri);
}

From source file:rapture.kernel.DocApiImpl.java

@Override
public void createDocRepo(CallingContext context, String docRepoUri, String config) {
    checkParameter("Repository URI", docRepoUri);
    checkParameter("Config", config); //$NON-NLS-1$

    RaptureURI internalUri = new RaptureURI(docRepoUri, Scheme.DOCUMENT);
    String authority = internalUri.getAuthority();

    if ((authority == null) || authority.isEmpty()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoAuthority")); //$NON-NLS-1$
    }//  w  ww  .  j  a v  a 2 s .c om
    if (internalUri.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", docRepoUri)); //$NON-NLS-1$
    }
    if (docRepoExists(context, docRepoUri)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("Exists", internalUri.toShortString())); //$NON-NLS-1$
    }

    // save repo config
    RaptureDocConfig dc = new RaptureDocConfig();
    dc.setConfig(config);
    dc.setAuthority(authority);

    DocumentRepoConfig documentRepo = new DocumentRepoConfig();
    documentRepo.setAuthority(authority);
    documentRepo.setDocumentRepo(dc);
    DocumentRepoConfigStorage.add(documentRepo, context.getUser(), apiMessageCatalog
            .getMessage("CreatedType", new String[] { internalUri.getDocPath(), authority }).format()); //$NON-NLS-1$

    // The repo will be created as needed in the cache when accessed the first time
    log.info("Creating Repository " + docRepoUri + " with config " + config);
}

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

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *//*w ww  .  java  2  s . c  o  m*/
public String getRemoteExpenses() {
    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 ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored."));
                Expense.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE,
                                "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString());
                        if (expense == null) {
                            expense = new Expense(expenseJson);
                        } else {
                            expense.setRemoteId(expenseJson.getString("_id"));
                            expense.setAmount(expenseJson.getDouble("amount"));
                            expense.setCategory(expenseJson.getString("category"));
                            expense.setDate(expenseJson.getString("date"));

                            if (expenseJson.has("deviceId")) {
                                expense.setDeviceId(expenseJson.getString("deviceId"));
                            } else {
                                expense.setDeviceId(Device.registeredDevice().getLogin());
                            }
                        }
                        expense.save();

                        if (expenseJson.has("receipts")) {
                            JSONArray receiptsArray = expenseJson.getJSONArray("receipts");

                            for (int j = 0; j < receiptsArray.length(); j++) {
                                JSONObject recJsonObject = receiptsArray.getJSONObject(i);
                                Receipt receipt = new Receipt();
                                receipt.setBase64(recJsonObject.getString("base64"));
                                receipt.setExpense(expense);
                                receipt.setName("");
                                receipt.save();
                            }
                        }
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

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

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

From source file:rapture.kernel.SeriesApiImpl.java

@Override
public Boolean seriesRepoExists(CallingContext context, String seriesURI) {
    RaptureURI uri = new RaptureURI(seriesURI, Scheme.SERIES);
    if (uri.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", seriesURI)); //$NON-NLS-1$
        // $NON-NLS-1$
    }//from w  w w  .  j  a v  a2  s.  c  o  m
    SeriesRepo series = getRepoFromCache(uri.getAuthority());
    return series != null;
}

From source file:rapture.repo.google.IdGenGoogleDatastore.java

@Override
public void resetIdGen(Long number) {
    Key entityKey = datastore.newKeyFactory().setKind(kind).newKey(kind);
    Entity entity = datastore.get(entityKey);
    try {//from  w  ww.  j a  va  2 s  .c  o  m
        Entity.Builder builder = Entity.newBuilder(entityKey);
        builder.set(kind, new LongValue(number));
        entity = builder.build();
        datastore.put(entity);
    } catch (Exception e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                googleMsgCatalog.getMessage("CannotReset"), e);
    }
}

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

public void testRetrieveInvalidJob() {

    MiniMRCluster mrCluster = null;//from  w w w . j a v  a2  s.  c  om
    JobConf conf = new JobConf();
    try {
        conf.set("mapreduce.history.server.http.address", "localhost:0");
        mrCluster = new MiniMRCluster(1, conf.get("fs.default.name"), 1, null, null, conf);
        JobConf jobConf = mrCluster.createJobConf();

        String url = "http://" + jobConf.get("mapred.job.tracker.http.address")
                + "/gethistory.jsp?jobid=job_20100714163314505_9991";
        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();
        }

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

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

private void getAllRemoteFiles() {
    URL urlO = null;/*from  www  .j av  a 2 s.co  m*/
    try {
        urlO = new URL(fileUrl);
        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) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

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

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