List of usage examples for java.io IOException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:info.magnolia.cms.servlets.EntryServlet.java
/** * Redirect based on the mapping in config/server/.node.xml * @param request HttpServletRequest//from w ww. j a v a 2 s . c o m * @param response HttpServletResponse * @return <code>true</code> if request has been redirected, <code>false</code> otherwise */ private boolean redirect(HttpServletRequest request, HttpServletResponse response) { String uri = this.getURIMap(request); if (StringUtils.isNotEmpty(uri)) { if (!response.isCommitted()) { if (uri.startsWith("redirect:")) { try { response.sendRedirect( request.getContextPath() + StringUtils.substringAfter(uri, "redirect:")); } catch (IOException e) { log.error("Failed to redirect to {}:{}", //$NON-NLS-1$ new Object[] { uri, e.getMessage() }); } } else { try { request.getRequestDispatcher(uri).forward(request, response); } catch (Exception e) { log.error("Failed to forward to {} - {}:{}", //$NON-NLS-1$ new Object[] { uri, ClassUtils.getShortClassName(e.getClass()), e.getMessage() }); } } } else { log.warn("Response is already committed, cannot forward to {} (original URI was {})", //$NON-NLS-1$ uri, request.getRequestURI()); } return true; } return false; }
From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java
@Test public void testCachingFailover() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); final CountDownLatch serverLatch = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();/*from w ww. j a v a 2 s.co m*/ while (!done.get()) { Socket socket = server.accept(); while (!socket.isClosed()) { try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String request = (String) ois.readObject(); logger.debug("Read " + request); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject("bar"); logger.debug("Replied to " + request); serverLatch.countDown(); } catch (IOException e) { logger.debug("error on write " + e.getClass().getSimpleName()); socket.close(); } } } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); // Failover AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class); TcpConnectionSupport mockConn1 = makeMockConnection(); when(factory1.getConnection()).thenReturn(mockConn1); doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class)); AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port); factory2.setSerializer(new DefaultSerializer()); factory2.setDeserializer(new DefaultDeserializer()); factory2.setSoTimeout(10000); factory2.setSingleUse(false); List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(factory1); factories.add(factory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); failoverFactory.start(); // Cache CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(cachingFactory); PollableChannel outputChannel = new QueueChannel(); gateway.setOutputChannel(outputChannel); gateway.afterPropertiesSet(); gateway.start(); GenericMessage<String> message = new GenericMessage<String>("foo"); gateway.handleMessage(message); Message<?> reply = outputChannel.receive(0); assertNotNull(reply); assertEquals("bar", reply.getPayload()); done.set(true); gateway.stop(); verify(mockConn1).send(Mockito.any(Message.class)); }
From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java
@Test public void testFailoverCached() throws Exception { final int port = SocketUtils.findAvailableServerSocket(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); final CountDownLatch serverLatch = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown();// w ww. j a v a2s. com while (!done.get()) { Socket socket = server.accept(); while (!socket.isClosed()) { try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String request = (String) ois.readObject(); logger.debug("Read " + request); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject("bar"); logger.debug("Replied to " + request); serverLatch.countDown(); } catch (IOException e) { logger.debug("error on write " + e.getClass().getSimpleName()); socket.close(); } } } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); // Cache AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class); TcpConnectionSupport mockConn1 = makeMockConnection(); when(factory1.getConnection()).thenReturn(mockConn1); doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class)); CachingClientConnectionFactory cachingFactory1 = new CachingClientConnectionFactory(factory1, 1); AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port); factory2.setSerializer(new DefaultSerializer()); factory2.setDeserializer(new DefaultDeserializer()); factory2.setSoTimeout(10000); factory2.setSingleUse(false); CachingClientConnectionFactory cachingFactory2 = new CachingClientConnectionFactory(factory2, 1); // Failover List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(cachingFactory1); factories.add(cachingFactory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); failoverFactory.start(); TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(failoverFactory); PollableChannel outputChannel = new QueueChannel(); gateway.setOutputChannel(outputChannel); gateway.afterPropertiesSet(); gateway.start(); GenericMessage<String> message = new GenericMessage<String>("foo"); gateway.handleMessage(message); Message<?> reply = outputChannel.receive(0); assertNotNull(reply); assertEquals("bar", reply.getPayload()); done.set(true); gateway.stop(); verify(mockConn1).send(Mockito.any(Message.class)); }
From source file:registry.ExtensionRegistryController.java
/** * A method that parses a url expecting a json object. * @param url the url to be parsed.//from www . ja v a2 s . c om * @return the json object if everything went well or a json object with an error msg if it * didn't. */ private Result parseUrl(final String url) { return async(new Callable<Result>() { @Override public Result call() throws Exception { try { URL u = new URL(url); String j = IOUtils.toString(u); JsonNode node = json.parse(j); node = createExt((ObjectNode) node, url); return ok(node); } catch (IOException e) { // Cannot read the URL logger().error("File not found or is unable to be read " + e); return ok(json.newObject().put("error", "An error has occurred:").put("reason", "File not found or unable to be read.")); } catch (Exception e) { logger().error(" A problem has occurred please check that your file is " + "valid JSON. " + " - " + e.getMessage() + " (" + e.getClass().getName() + ")", e); return ok(json.newObject().put("error", "An error has occurred:").put("reason", "Please check that your file is " + "valid JSON. ")); } } }); }
From source file:com.searchcode.app.jobs.repository.IndexBaseRepoJob.java
/** * Method to remove from the index files that are no longer required *//*from w ww .ja v a2 s .com*/ public void cleanMissingPathFiles(CodeSearcher codeSearcher, String repoName, Map<String, String> fileLocations) { int page = 0; boolean doClean = true; while (doClean) { List<String> indexLocations = codeSearcher.getRepoDocuments(repoName, page); Singleton.getLogger().info("cleanMissingPathFiles doClean " + page + " " + indexLocations.size()); if (indexLocations.isEmpty()) { doClean = false; } for (String file : indexLocations) { if (!fileLocations.containsKey(file)) { Singleton.getLogger().info("Missing from disk, removing from index " + file); try { Singleton.getCodeIndexer().deleteByCodeId(DigestUtils.sha1Hex(file)); } catch (IOException ex) { Singleton.getLogger() .warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " indexDocsByPath deleteByFileLocationFilename for " + repoName + " " + file + "\n with message: " + ex.getMessage()); } } } page++; } }
From source file:org.openflexo.localization.LocalizedDelegateImpl.java
private void saveDictionary(Language language, Properties dict) { File dictFile = getDictionaryFileForLanguage(language); try {/*from w w w. ja v a 2s . c om*/ final FileOutputStream fos = new FileOutputStream(dictFile); try { if (!dictFile.exists()) { dictFile.createNewFile(); } dict.store(new JavaPropertiesOutputStream(fos), language.getName()); logger.info("Saved " + dictFile.getAbsolutePath()); } catch (IOException e) { if (logger.isLoggable(Level.WARNING)) { logger.warning( "Unable to save file " + dictFile.getAbsolutePath() + " " + e.getClass().getName()); // e.printStackTrace(); } } finally { IOUtils.closeQuietly(fos); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java
public void execute(JobExecutionContext context) throws JobExecutionException { if (this.ENABLED == false) { return;//from ww w .j a v a 2 s . c o m } Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while (CodeIndexer.shouldPauseAdding()) { Singleton.getLogger().info("Pausing parser."); return; } // Pull the next repo to index from the queue UniqueRepoQueue repoQueue = Singleton.getUniqueSvnRepoQueue(); RepoResult repoResult = repoQueue.poll(); AbstractMap<String, Integer> runningIndexRepoJobs = Singleton.getRunningIndexRepoJobs(); if (repoResult != null && !runningIndexRepoJobs.containsKey(repoResult.getName())) { Singleton.getLogger().info("Indexing " + repoResult.getName()); try { runningIndexRepoJobs.put(repoResult.getName(), (int) (System.currentTimeMillis() / 1000)); JobDataMap data = context.getJobDetail().getJobDataMap(); String repoName = repoResult.getName(); String repoRemoteLocation = repoResult.getUrl(); String repoUserName = repoResult.getUsername(); String repoPassword = repoResult.getPassword(); String repoLocations = data.get("REPOLOCATIONS").toString(); this.LOWMEMORY = Boolean.parseBoolean(data.get("LOWMEMORY").toString()); // Check if sucessfully cloned, and if not delete and restart boolean cloneSucess = checkCloneUpdateSucess(repoLocations + repoName); if (cloneSucess == false) { // Delete the folder try { FileUtils.deleteDirectory(new File(repoLocations + repoName + "/")); CodeIndexer.deleteByReponame(repoName); } catch (IOException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); return; } } deleteCloneUpdateSuccess(repoLocations + repoName); String repoGitLocation = repoLocations + repoName + "/.svn/"; File f = new File(repoGitLocation); boolean existingRepo = f.exists(); boolean useCredentials = repoUserName != null && !repoUserName.isEmpty(); RepositoryChanged repositoryChanged; if (existingRepo) { repositoryChanged = this.updateSvnRepository(repoName, repoRemoteLocation, repoUserName, repoPassword, repoLocations, useCredentials); } else { repositoryChanged = this.checkoutSvnRepository(repoName, repoRemoteLocation, repoUserName, repoPassword, repoLocations, useCredentials); } // Write file indicating we have sucessfully cloned createCloneUpdateSuccess(repoLocations + repoName); if (repositoryChanged.isChanged()) { Singleton.getLogger().info("Update found indexing " + repoRemoteLocation); this.updateIndex(repoName, repoLocations, repoRemoteLocation, existingRepo, repositoryChanged); } } finally { // Clean up the job runningIndexRepoJobs.remove(repoResult.getName()); } } }
From source file:info.magnolia.cms.util.RequestDispatchUtil.java
/** * Returns true if processing took place, even if it fails. *//* w w w .j a v a2 s . c o m*/ public static boolean dispatch(String targetUri, HttpServletRequest request, HttpServletResponse response) { if (targetUri == null) { return false; } if (targetUri.startsWith(REDIRECT_PREFIX)) { String redirectUrl = StringUtils.substringAfter(targetUri, REDIRECT_PREFIX); try { if (isInternal(redirectUrl)) { redirectUrl = request.getContextPath() + redirectUrl; } response.sendRedirect(response.encodeRedirectURL(redirectUrl)); } catch (IOException e) { log.error("Failed to redirect to {}:{}", targetUri, e.getMessage()); } return true; } if (targetUri.startsWith(PERMANENT_PREFIX)) { String permanentUrl = StringUtils.substringAfter(targetUri, PERMANENT_PREFIX); try { if (isInternal(permanentUrl)) { if (isUsingStandardPort(request)) { permanentUrl = new URL(request.getScheme(), request.getServerName(), request.getContextPath() + permanentUrl).toExternalForm(); } else { permanentUrl = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath() + permanentUrl).toExternalForm(); } } response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", permanentUrl); } catch (MalformedURLException e) { log.error("Failed to create permanent url to redirect to {}:{}", targetUri, e.getMessage()); } return true; } if (targetUri.startsWith(FORWARD_PREFIX)) { String forwardUrl = StringUtils.substringAfter(targetUri, FORWARD_PREFIX); try { request.getRequestDispatcher(forwardUrl).forward(request, response); } catch (Exception e) { log.error("Failed to forward to {} - {}:{}", new Object[] { forwardUrl, ClassUtils.getShortClassName(e.getClass()), e.getMessage() }); } return true; } return false; }
From source file:com.maverick.ssl.SSLHandshakeProtocol.java
private void sendMessage(int type, byte[] data) throws SSLException { ByteArrayOutputStream msg = new ByteArrayOutputStream(); try {// w w w. j a v a2 s . co m msg.write(type); msg.write((data.length >> 16) & 0xFF); msg.write((data.length >> 8) & 0xFF); msg.write(data.length); msg.write(data); } catch (IOException ex) { throw new SSLException(SSLException.INTERNAL_ERROR, ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage()); } byte[] m = msg.toByteArray(); // Update the handshake hashes if its anything but the FINISHED_MSG if (type != FINISHED_MSG) { updateHandshakeHashes(m); } socket.sendMessage(HANDSHAKE_PROTOCOL_MSG, m); }
From source file:org.springframework.integration.ip.tcp.TcpOutboundGatewayTests.java
/** * Sends 2 concurrent messages on a shared connection. The GW single threads * these requests. The first will timeout; the second should receive its * own response, not that for the first. * @throws Exception// w w w . j av a2 s . co m */ private void testGoodNetGWTimeoutGuts(final int port, AbstractConnectionFactory ccf) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); /* * The payload of the last message received by the remote side; * used to verify the correct response is received. */ final AtomicReference<String> lastReceived = new AtomicReference<String>(); final CountDownLatch serverLatch = new CountDownLatch(2); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port); latch.countDown(); int i = 0; while (!done.get()) { Socket socket = server.accept(); i++; while (!socket.isClosed()) { try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String request = (String) ois.readObject(); logger.debug("Read " + request); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); if (i < 2) { Thread.sleep(1000); } oos.writeObject(request.replace("Test", "Reply")); logger.debug("Replied to " + request); lastReceived.set(request); serverLatch.countDown(); } catch (IOException e) { logger.debug("error on write " + e.getClass().getSimpleName()); socket.close(); } } } } catch (Exception e) { if (!done.get()) { e.printStackTrace(); } } } }); assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); final TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(ccf); gateway.setRequestTimeout(Integer.MAX_VALUE); QueueChannel replyChannel = new QueueChannel(); gateway.setRequiresReply(true); gateway.setOutputChannel(replyChannel); gateway.setRemoteTimeout(500); @SuppressWarnings("unchecked") Future<Integer>[] results = new Future[2]; for (int i = 0; i < 2; i++) { final int j = i; results[j] = (Executors.newSingleThreadExecutor().submit(new Callable<Integer>() { public Integer call() throws Exception { // increase the timeout after the first send if (j > 0) { gateway.setRemoteTimeout(5000); } gateway.handleMessage(MessageBuilder.withPayload("Test" + j).build()); return j; } })); Thread.sleep(50); } // wait until the server side has processed both requests assertTrue(serverLatch.await(10, TimeUnit.SECONDS)); List<String> replies = new ArrayList<String>(); int timeouts = 0; for (int i = 0; i < 2; i++) { try { int result = results[i].get(); String reply = (String) replyChannel.receive(1000).getPayload(); logger.debug(i + " got " + result + " " + reply); replies.add(reply); } catch (ExecutionException e) { if (timeouts >= 2) { fail("Unexpected " + e.getMessage()); } else { assertNotNull(e.getCause()); assertTrue(e.getCause() instanceof MessageTimeoutException); } timeouts++; continue; } } assertEquals("Expected exactly one ExecutionException", 1, timeouts); assertEquals(1, replies.size()); assertEquals(lastReceived.get().replace("Test", "Reply"), replies.get(0)); done.set(true); assertEquals(0, TestUtils.getPropertyValue(gateway, "pendingReplies", Map.class).size()); gateway.stop(); }