List of usage examples for java.io IOException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.apache.hadoop.hdfs.TestAvatarVerification.java
@Test public void testVerificationRoll() throws Exception { LOG.info("------------------- test: testVerificationRoll START ----------------"); try {/* w ww . jav a 2 s . com*/ conf = new Configuration(); cluster = new MiniAvatarCluster(conf, 1, true, null, null); // wait to separate checkpoints DFSTestUtil.waitNMilliSecond(500); TestAvatarVerificationHandler h = new TestAvatarVerificationHandler(); InjectionHandler.set(h); try { h.doCheckpoint(); fail("Checkpoint should not succeed"); } catch (IOException e) { // exception during roll LOG.info("Expected exception", e); assertTrue("Should get remote exception here", e.getClass().equals(RemoteException.class)); } assertTrue(h.receivedEvents.contains(InjectionEvent.STANDBY_EXIT_CHECKPOINT_FAILED_ROLL)); } finally { if (cluster != null) { cluster.shutDown(); } } }
From source file:photosharing.api.conx.SearchPeopleDefinition.java
/** * searches for people//ww w . j a va2 s . co 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("q"); if (query == null || query.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } /** * get the users bearer token */ HttpSession session = request.getSession(false); OAuth20Data data = (OAuth20Data) session.getAttribute(OAuth20Handler.CREDENTIALS); String bearer = data.getAccessToken(); /** * The query should be cleansed before passing it to the backend * * Example API Url * http://localhost:9080/photoSharing/api/searchPeople?q=sub * maps to * https://apps.collabservnext.com/search/oauth/people/typeahead?query=sub * * Response Data * { * "totalResults": 1, * "startIndex": 1, * "numResultsInCurrentPage": 1, * "persons": [ * { * "id": "20000397", * "name": "John Doe2", * "userType": "EMPLOYEE", * "jobResponsibility": "Stooge", * "confidence": "medium", * "score": 10997.0 * } * ] * } * */ Request get = Request.Get(getApiUrl(query)); get.addHeader("Authorization", "Bearer " + bearer); try { Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); logger.info("Code is " + code + " " + getApiUrl(query)); // 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); } // Content is returned else if (code == HttpStatus.SC_OK) { response.setStatus(HttpStatus.SC_OK); ServletOutputStream out = response.getOutputStream(); InputStream in = hr.getEntity().getContent(); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } // Unexpected status else { JSONObject obj = new JSONObject(); obj.put("error", "unexpected content"); 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()); } }
From source file:com.sunchenbin.store.feilong.servlet.http.ResponseUtil.java
/** * Down load data./*from ww w .j a va 2 s . co m*/ * * @param saveFileName * the save file name * @param inputStream * the input stream * @param contentLength * the content length * @param request * the request * @param response * the response */ private static void downLoadData(String saveFileName, InputStream inputStream, Number contentLength, HttpServletRequest request, HttpServletResponse response) { Date beginDate = new Date(); if (LOGGER.isInfoEnabled()) { LOGGER.info("begin download~~,saveFileName:[{}],contentLength:[{}]", saveFileName, FileUtil.formatSize(contentLength.longValue())); } try { OutputStream outputStream = response.getOutputStream(); //? //inputStream.read(buffer); //outputStream = new BufferedOutputStream(response.getOutputStream()); //outputStream.write(buffer); IOWriteUtil.write(inputStream, outputStream); if (LOGGER.isInfoEnabled()) { Date endDate = new Date(); LOGGER.info("end download,saveFileName:[{}],contentLength:[{}],time use:[{}]", saveFileName, FileUtil.formatSize(contentLength.longValue()), DateExtensionUtil.getIntervalForView(beginDate, endDate)); } } catch (IOException e) { /* * ? ClientAbortException ????? * ?? ?? * ??????? * ? KILL? ?? ClientAbortException */ //ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error final String exceptionName = e.getClass().getName(); if (StringUtil.contains(exceptionName, "ClientAbortException") || StringUtil.contains(e.getMessage(), "ClientAbortException")) { LOGGER.warn( "[ClientAbortException],maybe user use Thunder soft or abort client soft download,exceptionName:[{}],exception message:[{}] ,request User-Agent:[{}]", exceptionName, e.getMessage(), RequestUtil.getHeaderUserAgent(request)); } else { LOGGER.error("[download exception],exception name: " + exceptionName, e); throw new UncheckedIOException(e); } } }
From source file:com.veterinaria.jsf.controllers.ClienteController.java
public String addCliente() { try {//from w ww. j av a2s. c o m clienteActual.setPassword(DigestUtils.sha1Hex(password)); clienteActual.setFechaCreacionCliente(new Date()); clienteActual.setEstado(true); getClienteFacade().create(clienteActual); addSuccesMessage("CLIENTE CREADO", "Cliente Creado Exitosamente."); recargarLista(); FacesContext.getCurrentInstance().getExternalContext().redirect("clientesList.xhtml"); return "/faces/clientes/clientesList"; } catch (IOException e) { addErrorMessage("Error closing resource " + e.getClass().getName(), "Message: " + e.getMessage()); return null; } }
From source file:httpfailover.FailoverHttpClient.java
private void logRetry(IOException ex) { if (this.log.isWarnEnabled()) { this.log.warn("I/O exception (" + ex.getClass().getName() + ") caught when processing request: " + ex.getMessage());/*w w w . j a v a2 s . c o m*/ } if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } this.log.info("Trying request on next target"); }
From source file:org.openhab.binding.tacmi.internal.TACmiBinding.java
/** * @throws UnknownHostException/* w ww. j a va 2s .c o m*/ * @{inheritDoc */ @Override protected void internalReceiveCommand(String itemName, Command command) { logger.debug("internalReceiveCommand({},{}) is called!", itemName, command); for (TACmiBindingProvider provider : providers) { int canNode = provider.getCanNode(itemName); String portType = provider.getPortType(itemName); int portNumber = provider.getPortNumber(itemName); logger.trace("Type: {}, portNumber: {}, command: {}", portType, portNumber, command.toString()); byte[] messageBytes; if (portType.equals("d") && portNumber == 1 && command instanceof OnOffType) { boolean state = OnOffType.ON.equals(command) ? true : false; DigitalMessage message = new DigitalMessage((byte) canNode, state); messageBytes = message.getRaw(); } else if (portType.equals("a") && (portNumber - 1) % 4 == 0 && command instanceof DecimalType) { TACmiMeasureType measureType = provider.getMeasureType(itemName); AnalogMessage message = new AnalogMessage((byte) canNode, 1, (DecimalType) command, measureType); messageBytes = message.getRaw(); } else { logger.info("Not sending command: portType: {}, portNumber: {}, command: {}", portType, portNumber, command.toString()); return; } DatagramPacket packet = new DatagramPacket(messageBytes, messageBytes.length, cmiAddress, TACmiBinding.cmiPort); try { clientSocket.send(packet); } catch (IOException e) { logger.warn("Error sending message: {}, {}", e.getClass().getName(), e.getMessage()); } } }
From source file:org.paxle.core.doc.impl.jaxb.JaxbFileAdapter.java
/** * Converts the {@link DataHandler} into a {@link File}. * The file is created via the {@link ITempFileManager}. *//*from w ww . ja v a 2 s . co m*/ @Override public File unmarshal(DataHandler dataHandler) throws Exception { if (dataHandler == null) return null; final DataSource dataSource = dataHandler.getDataSource(); if (dataSource != null) { String cid = null; // avoid deserializing a file twice for (Entry<String, DataHandler> attachment : attachments.entrySet()) { if (attachment.getValue().equals(dataHandler)) { cid = attachment.getKey(); break; } } if (cid != null && this.cidFileMap.containsKey(cid)) { return this.cidFileMap.get(cid); } File tempFile = null; InputStream input = null; OutputStream output = null; try { // getting the input stream input = dataSource.getInputStream(); // getting the output stream tempFile = this.tempFileManager.createTempFile(); output = new BufferedOutputStream(new FileOutputStream(tempFile)); // copy data long byteCount = IOUtils.copy(input, output); if (this.logger.isDebugEnabled()) { this.logger.debug(String.format("%d bytes copied from the data-source into the temp-file '%s'.", Long.valueOf(byteCount), tempFile.getName())); } if (cid != null) { this.cidFileMap.put(cid, tempFile); } return tempFile; } catch (IOException e) { this.logger.error(String.format("Unexpected '%s' while loading datasource '%s' (CID=%s).", e.getClass().getName(), dataSource.getName(), cid), e); // delete the temp file on errors if (tempFile != null && this.tempFileManager.isKnown(tempFile)) { this.tempFileManager.releaseTempFile(tempFile); } // re-throw exception throw e; } finally { // closing streams if (input != null) input.close(); if (output != null) output.close(); } } return null; }
From source file:fr.duminy.jbackup.core.task.BackupTaskTest.java
@Theory public void testCall_deleteArchiveOnError(TaskListener listener) throws Throwable { final IOException exception = new IOException("An unexpected error"); thrown.expect(exception.getClass()); thrown.expectMessage(exception.getMessage()); final ArchiveParameters archiveParameters = createArchiveParameters(); testCall(ZipArchiveFactory.INSTANCE, archiveParameters, listener, exception, null); verify(listener).taskStarted();// ww w.java 2 s .c om verify(listener).taskFinished(eq(exception)); verifyNoMoreInteractions(listener); }
From source file:org.jboss.tools.common.reporting.Submit.java
/** * Submit report to RedHat.//w w w . j a v a2 s . c om * @param reportText * @param cleanBuffer */ public void submit(final String reportText, final boolean cleanBuffer) { Job job = new Job(JOB_NAME) { @Override public IStatus run(IProgressMonitor monitor) { try { submitReport(reportText); } catch (IOException e) { String exceptionMessage = e.getMessage(); String message = ERROR_MESSAGE; if (exceptionMessage != null && exceptionMessage.trim().length() > 0) { message = message + ".\r\n" + e.getClass().getName() + ": " + exceptionMessage; //$NON-NLS-1$ //$NON-NLS-2$ } Status status = new Status(IStatus.WARNING, CommonCorePlugin.PLUGIN_ID, IStatus.WARNING, message, e); return status; } if (cleanBuffer) { ProblemReportingHelper.buffer.clean(); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); }
From source file:jflowmap.JFlowMapApplet.java
public String exportToPng() { String bytes = null;// ww w .j a v a 2 s. c o m VisualCanvas canvas = getCanvas(); if (canvas != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); canvas.paintToPng(out); bytes = new String(Base64.encodeBase64(out.toByteArray())); } catch (IOException e) { logger.error("PNG export failed", e); JMsgPane.showErrorDialog(this, "SVG export failed: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } } return bytes; }