List of usage examples for java.net HttpURLConnection HTTP_NOT_FOUND
int HTTP_NOT_FOUND
To view the source code for java.net HttpURLConnection HTTP_NOT_FOUND.
Click Source Link
From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java
/** * // w w w .j a va2 s .c o m * getGraphList * * * @return HttpResponse * */ @GET @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError"), @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "graphListAsJsonArray"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "noGraphExists") }) @ApiOperation(value = "getGraphList", notes = "") public HttpResponse getGraphList() { String result = ""; String columnName = ""; String selectquery = ""; int columnCount = 0; Connection conn = null; PreparedStatement stmnt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; JSONObject ro = null; JSONArray graphList = new JSONArray(); try { // get connection from connection pool conn = dbm.getConnection(); selectquery = "SELECT graphId, description FROM graphs;"; // prepare statement stmnt = conn.prepareStatement(selectquery); // retrieve result set rs = stmnt.executeQuery(); rsmd = (ResultSetMetaData) rs.getMetaData(); columnCount = rsmd.getColumnCount(); // process result set while (rs.next()) { 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); } graphList.add(ro); } if (graphList.isEmpty()) { String er = "No results"; HttpResponse noGraphExists = new HttpResponse(er, HttpURLConnection.HTTP_NOT_FOUND); return noGraphExists; } else { // return HTTP Response on success HttpResponse graphListAsJsonArray = new HttpResponse(graphList.toJSONString(), HttpURLConnection.HTTP_OK); return graphListAsJsonArray; } } 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:org.jboss.as.test.integration.web.customerrors.CustomErrorsUnitTestCase.java
/** * Test that the custom 404 error page is seen * * @throws Exception/* w w w .j a v a 2s . c o m*/ */ @Test @OperateOnDeployment("error-producer.war") public void test404Error(@ArquillianResource(ErrorGeneratorServlet.class) URL baseURL) throws Exception { int errorCode = HttpURLConnection.HTTP_NOT_FOUND; URL url = new URL(baseURL + "/ErrorGeneratorServlet?errorCode=" + errorCode); testURL(url, errorCode, "404.jsp", null); }
From source file:org.cytoscape.app.internal.net.server.CyHttpdImplTest.java
@Test public void testHttpd() throws Exception { final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2608)); final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl(); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/testA$"); }//from w ww. ja va 2 s.c o m public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "testA response ok", "text/html"); } }); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/testB$"); } public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "testB response ok", "text/html"); } }); httpd.addBeforeResponse(new CyHttpBeforeResponse() { public CyHttpResponse intercept(CyHttpRequest request) { if (request.getMethod().equals("OPTIONS")) return responseFactory.createHttpResponse(HttpStatus.SC_OK, "options intercepted", "text/html"); else return null; } }); httpd.addAfterResponse(new CyHttpAfterResponse() { public CyHttpResponse intercept(CyHttpRequest request, CyHttpResponse response) { response.getHeaders().put("SomeRandomHeader", "WowInterceptWorks"); return response; } }); assertFalse(httpd.isRunning()); httpd.start(); assertTrue(httpd.isRunning()); final String url = "http://localhost:2608/"; // test if normal response works HttpURLConnection connection = connectToURL(url + "testA", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "testA response ok"); connection = connectToURL(url + "testB", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "testB response ok"); // test if 404 response works connection = connectToURL(url + "testX", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND); // test if before intercept works connection = connectToURL(url + "testA", "OPTIONS"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(readConnection(connection), "options intercepted"); // test if after intercept works connection = connectToURL(url + "testA", "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(connection.getHeaderField("SomeRandomHeader"), "WowInterceptWorks"); httpd.stop(); assertFalse(httpd.isRunning()); }
From source file:com.adaptris.http.RequestDispatcher.java
public void run() { RequestProcessor rp = null;//from w w w .j a v a 2s.co m HttpSession session = null; LinkedBlockingQueue queue = null; String oldName = Thread.currentThread().getName(); Thread.currentThread().setName(threadName); do { try { if (logR.isTraceEnabled()) { logR.trace("Reading HTTP Request"); } session = new ServerSession(); session.setSocket(socket); // String uri = session.getRequestLine().getURI(); String file = session.getRequestLine().getFile(); queue = (LinkedBlockingQueue) requestProcessors.get(file); if (queue == null) { // Get a default one, if any queue = (LinkedBlockingQueue) requestProcessors.get("*"); if (queue == null) { doResponse(session, HttpURLConnection.HTTP_NOT_FOUND); break; } } rp = waitForRequestProcessor(queue); if (!parent.isAlive()) { doResponse(session, HttpURLConnection.HTTP_INTERNAL_ERROR); break; } rp.processRequest(session); session.commit(); } catch (Exception e) { // if an exception occurs, then it's pretty much a fatal error for // this session // we ignore any output that it might have setup, and use our own try { logR.error(e.getMessage(), e); if (session != null) { doResponse(session, HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (Exception e2) { ; } } } while (false); try { if (rp != null && queue != null) { queue.put(rp); logR.trace(rp + " put back on to queue"); } } catch (Exception e) { ; } session = null; queue = null; rp = null; Thread.currentThread().setName(oldName); return; }
From source file:com.s3auth.rest.TkApp.java
/** * Authenticated.//from w w w. j av a 2s . c o m * @param takes Take * @return Authenticated takes */ private static Take fallback(final Take takes) { return new TkFallback(takes, new FbChain(new FbStatus(HttpURLConnection.HTTP_NOT_FOUND, new TkNotFound()), // @checkstyle AnonInnerLengthCheck (50 lines) new Fallback() { @Override public Iterator<Response> route(final RqFallback req) throws IOException { final String err = ExceptionUtils.getStackTrace(req.throwable()); return Collections.<Response>singleton(new RsWithStatus(new RsWithType( new RsVelocity(this.getClass().getResource("exception.html.vm"), new RsVelocity.Pair("err", err), new RsVelocity.Pair("rev", TkApp.REV)), "text/html"), HttpURLConnection.HTTP_INTERNAL_ERROR)).iterator(); } })); }
From source file:com.hotmart.dragonfly.profile.ui.ResetPasswordActivity.java
@OnClick(R.id.redefinirSalvar) public void salvarNovaSenha(View view) { ResetPasswordRequestVO resetPasswordRequestVO = new ResetPasswordRequestVO(); final String code = codeEditText.getText().toString(); resetPasswordRequestVO.setPassword(passwordEditText.getText().toString()); resetPasswordRequestVO.setRepeatPassword(repeatPasswordEditText.getText().toString()); mUserService.resetPassword(resetPasswordRequestVO, code).enqueue(new Callback<Void>() { @Override/* ww w .ja va 2 s .com*/ public void onResponse(Call<Void> call, Response<Void> response) { switch (response.code()) { case HttpURLConnection.HTTP_OK: Intent intent = new Intent(); setResult(RESULT_OK, intent); Intent homeIntent = new Intent(thisActivity, AuthenticatorActivity.class); thisActivity.startActivity(homeIntent); finish(); break; case HttpURLConnection.HTTP_BAD_REQUEST: Snackbar.make(codeEditText, response.message(), Snackbar.LENGTH_LONG).show(); case HttpURLConnection.HTTP_NOT_FOUND: Snackbar.make(codeEditText, response.message(), Snackbar.LENGTH_LONG).show(); default: Snackbar.make(codeEditText, response.message(), Snackbar.LENGTH_LONG).show(); } } @Override public void onFailure(Call<Void> call, Throwable t) { Snackbar.make(codeEditText, R.string.status_500, Snackbar.LENGTH_LONG).show(); Log.e("dragonfly", t.getMessage(), t); } }); }
From source file:org.eclipse.orion.server.tests.prefs.PreferenceTest.java
@Test public void testGetSingle() throws IOException, JSONException { List<String> locations = getTestPreferenceNodes(); for (String location : locations) { //unknown key should return 404 WebRequest request = new GetMethodWebRequest(location + "?key=Name"); setAuthentication(request);/* w w w . j ava 2 s .com*/ WebResponse response = webConversation.getResource(request); assertEquals("1." + location, HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode()); //put a value request = createSetPreferenceRequest(location, "Name", "Frodo"); setAuthentication(request); response = webConversation.getResource(request); assertEquals("2." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); //now doing a get should succeed request = new GetMethodWebRequest(location + "?key=Name"); setAuthentication(request); response = webConversation.getResource(request); assertEquals("3." + location, HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject result = new JSONObject(response.getText()); assertEquals("4." + location, "Frodo", result.optString("Name")); //getting another key on the same resource should still 404 request = new GetMethodWebRequest(location + "?key=Address"); setAuthentication(request); response = webConversation.getResource(request); assertEquals("5." + location, HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode()); } }
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 ww . ja va 2s. com*/ // 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); } }
From source file:org.mskcc.cbio.portal.util.SessionServiceUtil.java
/** * Returns an ServletRequest parameter map for a given sessionId. * Returns null if the session was not found. * * @param sessionId//from w w w. j a v a2 s.c om * @return an ServletRequest parameter map * @throws HttpException if session service API returns with a response code that is not 404 or 200 * @throws MalformedURLException * @throws IOException * @see ServletRequest#getParameterMap */ public static Map<String, String[]> getSession(String sessionId) throws HttpException, MalformedURLException, IOException { LOG.debug("SessionServiceUtil.getSession()"); Map<String, String[]> parameterMap = null; HttpURLConnection conn = null; try { URL url = new URL(GlobalProperties.getSessionServiceUrl() + "main_session/" + sessionId); LOG.debug("SessionServiceUtil.getSession(): url = '" + url + "'"); conn = (HttpURLConnection) url.openConnection(); // Use basic authentication if provided (https://stackoverflow.com/questions/496651) if (isBasicAuthEnabled()) { conn.setRequestProperty("Authorization", getBasicAuthString()); } if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { StringWriter stringWriter = new StringWriter(); IOUtils.copy(conn.getInputStream(), stringWriter, Charset.forName("UTF-8")); String contentString = stringWriter.toString(); LOG.debug("SessionServiceUtil.getSession(): response = '" + contentString + "'"); JsonNode json = new ObjectMapper().readTree(contentString); LOG.debug( "SessionServiceUtil.getSession(): response.data = '" + json.get("data").textValue() + "'"); parameterMap = new ObjectMapper().readValue(json.get("data").toString(), new TypeReference<Map<String, String[]>>() { }); } else { LOG.warn("SessionServiceUtil.getSession(): conn.getResponseCode() = '" + conn.getResponseCode() + "'"); if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { return null; } else if (conn.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) { throw new HttpException("Internal server error"); } else { throw new HttpException("Unexpected error, response code '" + conn.getResponseCode() + "'"); } } } catch (MalformedURLException mfue) { LOG.warn("SessionServiceUtil.getSession(): MalformedURLException = '" + mfue.getMessage() + "'"); throw mfue; } catch (IOException ioe) { LOG.warn("SessionServiceUtil.getSession(): IOException = '" + ioe.getMessage() + "'"); throw ioe; } finally { if (conn != null) { conn.disconnect(); } } return parameterMap; }
From source file:org.codehaus.mojo.mrm.servlet.FileSystemServlet.java
/** * {@inheritDoc}// www . j a v a 2s.co m */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { boolean doesRequestJson = req.getHeader("Accept").contains("application/json"); String path = req.getPathInfo(); String context; if (path == null) { path = req.getServletPath(); context = req.getContextPath(); } else { context = req.getContextPath() + req.getServletPath(); } Entry entry = fileSystem.get(path); if (entry instanceof FileEntry) { FileEntry fileEntry = (FileEntry) entry; serverFileRaw(resp, fileEntry); return; } else if (entry instanceof DirectoryEntry) { if (!path.endsWith("/")) { resp.sendRedirect(entry.getName() + "/"); return; } DirectoryEntry dirEntry = (DirectoryEntry) entry; Entry[] entries = fileSystem.listEntries(dirEntry); if (doesRequestJson) serverDirectoryAsJSON(req, resp, path, context, dirEntry, entries); else serveDirectoryAsHTML(resp, path, context, dirEntry, entries); return; } resp.sendError(HttpURLConnection.HTTP_NOT_FOUND); }