List of usage examples for java.io IOException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:photosharing.api.conx.UploadFileDefinition.java
/** * uploads a file to the IBM Connections Cloud using the Files Service * //from w ww . j a v a2 s .co m * @param bearer token * @param nonce * @param request * @param response */ public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) { // Extracts from the Request Parameters String visibility = request.getParameter("visibility"); String title = request.getParameter("title"); String share = request.getParameter("share"); String tagsUnsplit = request.getParameter("q"); // Check for the Required Parameters if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } else { /* * Builds the URL Parameters */ StringBuilder builder = new StringBuilder(); builder.append("visibility=" + visibility + "&"); builder.append("title=" + title + "&"); // The Share parameters for the URL if (share != null && !share.isEmpty()) { builder.append("shared=true&"); builder.append("shareWith=" + share + "&"); } if (visibility.compareTo("private") == 0 && share == null) { builder.append("shared=false&"); } // Splits the TagString into Indvidual Tags // - Technically this API is limited to 3 tags at most. String[] tags = tagsUnsplit.split(","); for (String tag : tags) { logger.info("Tag-> " + tag); builder.append("tag=" + tag + "&"); } // Build the apiURL String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString(); //API Url logger.info(apiUrl); // Add the Headers String length = request.getHeader("X-Content-Length"); String contentType = request.getHeader("Content-Type"); String fileext = contentType.split("/")[1].split(";")[0]; String slug = title + "." + fileext; Request post = Request.Post(apiUrl); post.addHeader("Authorization", "Bearer " + bearer); post.addHeader("X-Update-Nonce", nonce); post.addHeader("Slug", slug); post.addHeader("Content-Type", contentType); logger.info("Authorization: Bearer " + bearer); logger.info("X-Update-Nonce: " + nonce); logger.info("Slug: " + slug); logger.info("Content-Type: " + contentType); try { // InputStream in = request.getInputStream(); Base64InputStream bis = new Base64InputStream(in); long len = Long.parseLong(length); InputStreamEntity entity = new InputStreamEntity(bis, len); post.body(entity); post.removeHeaders("Cookie"); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(post); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); logger.info("code is " + code); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Duplicate Item else if (code == HttpStatus.SC_CONFLICT) { response.setStatus(HttpStatus.SC_CONFLICT); } // Checks if Created else if (code == HttpStatus.SC_CREATED) { response.setStatus(HttpStatus.SC_OK); /** * Do Extra Processing Here to process the body */ InputStream inRes = hr.getEntity().getContent(); // Converts XML to JSON String String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes); JSONObject obj = new JSONObject(jsonString); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.append(obj.toString()); writer.close(); } else { // Catch All response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); InputStream inRes = hr.getEntity().getContent(); String out = IOUtils.toString(inRes); logger.info("Content: " + out); logger.info("Content Type of Response: " + response.getContentType()); Collection<String> coll = response.getHeaderNames(); Iterator<String> iter = coll.iterator(); while (iter.hasNext()) { String header = iter.next(); logger.info(header + " " + response.getHeader(header)); } } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("SAXException " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("JSONException " + e.toString()); } } }
From source file:org.dataconservancy.ui.api.ProjectController.java
@ExceptionHandler(IOException.class) public void handleException(IOException e, HttpServletRequest req, HttpServletResponse resp) { log.debug("Handling exception [" + e.getClass() + "] [" + e.getMessage() + "]"); resp.setStatus(500);/* www . j a v a 2 s . c om*/ try { resp.getWriter().print(e.getMessage()); resp.getWriter().flush(); resp.getWriter().close(); } catch (Exception ee) { log.debug("Handling exception", e); } }
From source file:org.csploit.android.core.UpdateService.java
public static boolean isGemUpdateAvailable() { try {/*from w w w .jav a 2s. c om*/ synchronized (mGemUploadParser) { GemParser.RemoteGemInfo[] gemInfoArray = mGemUploadParser.parse(); ArrayList<GemParser.RemoteGemInfo> gemsToUpdate = new ArrayList<GemParser.RemoteGemInfo>(); if (gemInfoArray.length == 0) return false; String format = String.format("%s/lib/ruby/gems/1.9.1/specifications/%%s-%%s-arm-linux.gemspec", System.getRubyPath()); for (GemParser.RemoteGemInfo gemInfo : gemInfoArray) { File f = new File(String.format(format, gemInfo.name, gemInfo.version)); if (!f.exists() || f.lastModified() < gemInfo.uploaded.getTime()) { Logger.debug(String.format("'%s' %s", f.getAbsolutePath(), (f.exists() ? "is old" : "does not exists"))); gemsToUpdate.add(gemInfo); } } if (gemsToUpdate.size() == 0) return false; mGemUploadParser.setOldGems(gemsToUpdate.toArray(new GemParser.RemoteGemInfo[gemsToUpdate.size()])); return true; } } catch (IOException e) { Logger.warning(e.getClass() + ": " + e.getMessage()); } catch (Exception e) { System.errorLogging(e); } return false; }
From source file:info.magnolia.rendering.engine.RenderingFilter.java
/** * Get the requested resource and copy it to the ServletOutputStream, bit by bit. * @param request HttpServletRequest as given by the servlet container * @param response HttpServletResponse as given by the servlet container * @throws IOException standard servlet exception */// w w w . j a v a 2s .c om protected void handleResourceRequest(AggregationState aggregationState, HttpServletRequest request, HttpServletResponse response) throws IOException { final String resourceHandle = aggregationState.getHandle(); log.debug("handleResourceRequest, resourceHandle=\"{}\"", resourceHandle); if (StringUtils.isNotEmpty(resourceHandle)) { InputStream is = null; try { Session session = MgnlContext.getJCRSession(aggregationState.getRepository()); is = getNodedataAsStream(resourceHandle, session, response); if (null != is) { // don't reset any existing status code, see MAGNOLIA-2005 // response.setStatus(HttpServletResponse.SC_OK); sendUnCompressed(is, response); IOUtils.closeQuietly(is); return; } } catch (IOException e) { // don't log at error level since tomcat tipically throws a // org.apache.catalina.connector.ClientAbortException if the user stops loading the page log.debug("Exception while dispatching resource " + e.getClass().getName() + ": " + e.getMessage(), e); return; } catch (Exception e) { log.error("Exception while dispatching resource " + e.getClass().getName() + ": " + e.getMessage(), e); return; } finally { IOUtils.closeQuietly(is); } } log.debug("Resource not found, redirecting request for [{}] to 404 URI", request.getRequestURI()); if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { log.info("Unable to redirect to 404 page for {}, response is already committed", request.getRequestURI()); } }
From source file:com.android.idtt.http.RetryHandler.java
@Override public boolean retryRequest(IOException exception, int retriedTimes, HttpContext context) { boolean retry = true; Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT); boolean sent = (b != null && b.booleanValue()); if (retriedTimes > maxRetries) { // ?5// ww w . j a v a2s .co m retry = false; } else if (exceptionBlackList.contains(exception.getClass())) { // ?? retry = false; } else if (exceptionWhiteList.contains(exception.getClass())) { retry = true; } else if (!sent) { retry = true; } if (retry) { try { Object currRequest = context.getAttribute(ExecutionContext.HTTP_REQUEST); if (currRequest != null) { if (currRequest instanceof HttpRequestBase) { HttpRequestBase requestBase = (HttpRequestBase) currRequest; retry = requestBase != null && "GET".equals(requestBase.getMethod()); } else if (currRequest instanceof RequestWrapper) { RequestWrapper requestWrapper = (RequestWrapper) currRequest; retry = requestWrapper != null && "GET".equals(requestWrapper.getMethod()); } } else { LogUtils.e("retry error, curr request is null"); } } catch (Exception e) { retry = false; LogUtils.e("retry error", e); } } if (retry) { //1??? SystemClock.sleep(RETRY_SLEEP_INTERVAL); } else { LogUtils.e(exception.getMessage(), exception); } return retry; }
From source file:org.hyperic.hq.topn.TopNManagerImpl.java
public byte[] compressData(final byte[] data) { try {// ww w.j av a 2 s.c o m return Snappy.compress(data); } catch (final IOException e) { log.error("Unable to compress TopN data " + e.getClass().getSimpleName(), e); return data; } }
From source file:org.jwebsocket.sso.OAuth.java
/** * * @param aUsername// w ww .j av a 2 s . co m * @param aPassword * @param aTimeout * @return */ public String authDirect(String aUsername, String aPassword, long aTimeout) { String lPostBody; try { lPostBody = "client_id=ro_client" + "&grant_type=password" + "&username=" + URLEncoder.encode(aUsername, "UTF-8") + "&password=" + URLEncoder.encode(aPassword, "UTF-8"); Map lHeaders = new HashMap<String, String>(); lHeaders.put("Content-Type", "application/x-www-form-urlencoded"); String lJSONString = HTTPSupport.request(mOAuthHost, "POST", lHeaders, lPostBody, aTimeout); Map<String, Object> lJSON = parseJSON(lJSONString); mAccessToken = (String) lJSON.get("access_token"); mRefreshToken = (String) lJSON.get("refresh_token"); return lJSONString; } catch (IOException lEx) { mReturnCode = -1; mReturnMsg = lEx.getClass().getSimpleName() + " authenticating directly against OAuth host."; return "{\"code\":-1, \"msg\":\"" + lEx.getClass().getSimpleName() + "\"}"; } }
From source file:org.hyperic.hq.topn.TopNManagerImpl.java
public byte[] uncompressData(final byte[] data) { try {//from w w w .j a va2s .c om return Snappy.uncompress(data); } catch (final IOException e) { log.error("Unable to uncompress TopN data " + e.getClass().getSimpleName(), e); return data; } }
From source file:photosharing.api.conx.ProfileDefinition.java
/** * retrieves a profile based on the person's userid * /* w ww. j av a2 s . c o m*/ * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void run(HttpServletRequest request, HttpServletResponse response) { /** * check if query is empty, send SC_PRECONDITION_FAILED - 412 */ String query = request.getParameter("uid"); if (query == null || query.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } /** * get the users bearer token */ HttpSession session = request.getSession(false); Object oData = session.getAttribute(OAuth20Handler.CREDENTIALS); if (oData == null) { logger.warning("OAuth20Data is null"); } OAuth20Data data = (OAuth20Data) oData; String bearer = data.getAccessToken(); try { /** * Example URL: * http://localhost:9080/photoSharing/api/profile?uid=self maps to * https://apps.collabservnext.com/profiles/atom/profileService.do * * and results in an id for the self user, this data is ideally cached on the client. */ if (query.compareTo("self") == 0) { String apiUrl = getApiUrlForServiceDoc(); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired - 403 if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized // SC_UNAUTHORIZED (401) else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Content is returned // OK (200) else if (code == HttpStatus.SC_OK) { InputStream in = hr.getEntity().getContent(); // Converts the XML to JSON // Alternatively, one can parse the XML using XPATH String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); logger.info("json string is " + jsonString); JSONObject jsonObj = new JSONObject(jsonString); JSONObject workspace = jsonObj.getJSONObject("service").getJSONObject("workspace") .getJSONObject("collection"); String id = workspace.getString("userid"); query = id; } else { JSONObject obj = new JSONObject(); obj.put("error", "unexpected content"); } } /** * The query should be cleansed before passing it to the backend * cleansing can incorporate checking that the id is a number * * example URL * http://localhost:9080/photoSharing/api/profile?uid=20131674 maps * to https * ://apps.collabservnext.com/profiles/atom/profile.do?userid * =20131674 * * example response {"img": * "https:\/\/apps.collabservnext.com\/profiles\/photo.do?key=fef1b5f3-586f-4470-ab0a-a9d4251fe1ec&lastMod=1443607729019","name":"P * a u l Demo","email":"demo@us.ibm.com"} * */ String apiUrl = getApiUrl(query); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired // SC_FORBIDDEN (403) if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized // SC_UNAUTHORIZED (401) else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Content is returned OK (200) else if (code == HttpStatus.SC_OK) { InputStream in = hr.getEntity().getContent(); // Converts the XML to JSON // Alternatively, one can parse the XML using XPATH String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); logger.info("json string is " + jsonString); JSONObject jsonObj = new JSONObject(jsonString); JSONObject entry = jsonObj.getJSONObject("feed").getJSONObject("entry"); logger.info("entry" + entry); // Check if the Entry exists for the given id if (entry != null) { // Start Building the Response String name = ""; String image = ""; String email = ""; JSONObject contributor = entry.getJSONObject("contributor"); name = contributor.getString("name"); email = contributor.getString("email"); JSONArray links = entry.getJSONArray("link"); // Scans through the links and finds the profile image // XPath is much more efficient boolean found = false; int idx = 0; int len = links.length(); while (!found && idx < len) { JSONObject link = links.getJSONObject(idx); String type = link.getString("type"); if (type != null && !type.isEmpty() && type.compareTo("image") == 0) { found = true; image = link.getString("href"); } idx++; } // Build the json to send back JSONObject profile = new JSONObject(); profile.put("name", name); profile.put("email", email); profile.put("img", image); profile.put("userid", query); // Write output streams ServletOutputStream out = response.getOutputStream(); profile.write(out); } else { // There is no Entry for the user with the id. response.setStatus(HttpStatus.SC_NOT_FOUND); PrintWriter out = response.getWriter(); out.println("User does not exist"); } } // Unexpected status else { JSONObject obj = new JSONObject(); obj.put("error", "unexpected content"); //Should serialize result response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("JSONException " + e.toString()); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("SAXException " + e.toString()); } }
From source file:info.magnolia.rendering.engine.RenderingFilter.java
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { final AggregationState aggregationState = MgnlContext.getAggregationState(); String templateName = aggregationState.getTemplateName(); if (StringUtils.isNotEmpty(templateName)) { try {/*from w w w . java 2 s . co m*/ // don't reset any existing status code, see MAGNOLIA-2005 // response.setStatus(HttpServletResponse.SC_OK); if (response != MgnlContext.getWebContext().getResponse()) { log.warn("Context response not synced. This may lead to discrepancies in rendering."); } Node content = aggregationState.getMainContent().getJCRNode(); // if the content isn't visible output a 404 if (!isVisible(content, request, response, aggregationState)) { if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { log.info("Unable to redirect to 404 page for {}, response is already committed", request.getRequestURI()); } return; } render(content, templateName, response); try { response.flushBuffer(); } catch (IOException e) { // don't log at error level since tomcat typically throws a // org.apache.catalina.connector.ClientAbortException if the user stops loading the page log.debug("Exception flushing response " + e.getClass().getName() + ": " + e.getMessage(), e); } } catch (RenderException e) { // TODO better handling of rendering exception // TODO dlipp: why not move this section up to the actual call to render() -> that's the only place where a RenderException could occur... log.error(e.getMessage(), e); throw new ServletException(e); } catch (Exception e) { // TODO dlipp: there's no other checked exceptions thrown in the code above - is it correct to react like that??? log.error(e.getMessage(), e); if (!response.isCommitted()) { response.setContentType("text/html"); } throw new RuntimeException(e); } } else { // direct request handleResourceRequest(aggregationState, request, response); } // TODO don't make it a dead end // currently we can't process the chain because there is no content/nop servlet // chain.doFilter(request, response); }