List of usage examples for java.io IOException toString
public String toString()
From source file:eu.digitisation.idiomaident.utils.ExtractTestSamples.java
private static String nextSample(File inFolder) { File[] langFolders = inFolder.listFiles(); Date now = new Date(); Random rand = new Random(now.getTime()); //get a ramdom language int numLangs = langFolders.length; int chosenLang = rand.nextInt(numLangs); String lang = langFolders[chosenLang].getName(); //get a ramdom file from the folder File[] langFiles = langFolders[chosenLang].listFiles(); int numFiles = langFiles.length; int chosenFile = rand.nextInt(numFiles); File langFile = langFiles[chosenFile]; //open and read the file try {//from ww w . ja v a 2s . com String text = FileUtils.readFileToString(langFile, Charset.forName("UTF-8")); text = StringNormalize.stringNormalize(text); text = text.replaceAll("[\\n.,:;]", " "); text = text.trim(); if (text.replaceAll("[\\p{Space}]+", "").length() < 20) { return null; } //split the text in words String[] words = text.split("[\\p{Space}]+"); boolean correct = false; StringBuilder sampleBuild = null; while (!correct) { //chosen the initial position to read the words int actualWord = rand.nextInt(words.length); correct = true; sampleBuild = new StringBuilder(); while (sampleBuild.length() < 20) { if (actualWord < words.length) { sampleBuild.append(words[actualWord]); sampleBuild.append(" "); } else { correct = false; break; } actualWord++; } } //complete the sample sampleBuild.deleteCharAt(sampleBuild.length() - 1); sampleBuild.append(";").append(lang).append("\n"); return sampleBuild.toString(); } catch (IOException ex) { System.out.println(ex.toString()); } return null; }
From source file:com.dfki.av.sudplan.Configuration.java
/** * Initialize the {@link #SUDPLAN_3D_IMAGE}. * * @return the {@link Image} to return or null. *///from w ww. ja v a 2 s. c o m private static Image initImage() { log.info("Init suplan3D icon..."); Image image = null; try { ClassLoader loader = Configuration.class.getClassLoader(); URL iconURL = loader.getResource("icons/sudplan3D.png"); image = ImageIO.read(iconURL); } catch (IOException ex) { log.error(ex.toString()); } return image; }
From source file:gov.nist.appvet.tool.sigverifier.util.ReportUtil.java
/** * This method returns report information to the AppVet ToolAdapter as ASCII * text and cannot attach a file to the response. *//*from w w w. j a v a2 s.c o m*/ public static boolean sendInHttpResponse(HttpServletResponse response, String reportText, ToolStatus reportStatus) { try { response.setStatus(HttpServletResponse.SC_OK); // HTTP 200 response.setContentType("text/html"); response.setHeader("toolrisk", reportStatus.name()); PrintWriter out = response.getWriter(); out.println(reportText); out.flush(); out.close(); log.debug("Returned report"); return true; } catch (IOException e) { log.error(e.toString()); return false; } }
From source file:gov.nist.appvet.tool.sigverifier.util.FileUtil.java
public static boolean copyFile(String sourceFilePath, String destFilePath) { if (sourceFilePath == null || destFilePath == null) { return false; }//from ww w . j av a 2s .co m File sourceFile = new File(sourceFilePath); if (!sourceFile.exists()) { return false; } File destFile = new File(destFilePath); try { Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (final IOException e) { log.error(e.toString()); return false; } finally { sourceFile = null; destFile = null; } return true; }
From source file:org.openmrs.module.webservices.rest.ITBase.java
@BeforeClass public static void waitForServerToStart() { synchronized (serverStartupLock) { if (!serverStarted) { final long time = System.currentTimeMillis(); final int timeout = 300000; final int retryAfter = 10000; final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(retryAfter) .setConnectTimeout(retryAfter).build(); final String startupUri = TEST_URL.getScheme() + "://" + TEST_URL.getHost() + ":" + TEST_URL.getPort() + TEST_URL.getPath(); System.out.println(// w ww .j a v a 2 s. c o m "Waiting for server at " + startupUri + " for " + timeout / 1000 + " more seconds..."); while (System.currentTimeMillis() - time < timeout) { try { final HttpClient client = HttpClientBuilder.create().disableAutomaticRetries().build(); final HttpGet sessionGet = new HttpGet(startupUri); sessionGet.setConfig(requestConfig); final HttpClientContext context = HttpClientContext.create(); final HttpResponse response = client.execute(sessionGet, context); int status = response.getStatusLine().getStatusCode(); if (status >= 400) { throw new RuntimeException(status + " " + response.getStatusLine().getReasonPhrase()); } URI finalUri = sessionGet.getURI(); List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { finalUri = redirectLocations.get(redirectLocations.size() - 1); } String finalUriString = finalUri.toString(); if (!finalUriString.contains("initialsetup")) { serverStarted = true; return; } } catch (IOException e) { System.out.println(e.toString()); } try { System.out.println("Waiting for " + (timeout - (System.currentTimeMillis() - time)) / 1000 + " more seconds..."); Thread.sleep(retryAfter); } catch (InterruptedException e) { throw new RuntimeException(e); } } throw new RuntimeException("Server startup took longer than 5 minutes!"); } } }
From source file:gemlite.core.internal.support.system.WorkPathHelper.java
private static boolean lock(File directory) { String name = "node.lock"; File lockfile = new File(directory, name); lockfile.deleteOnExit();//from w w w. j a va 2 s . c o m try { FileChannel fc = (FileChannel) Channels.newChannel(new FileOutputStream(lockfile)); lock = fc.tryLock(); if (lock != null) { return true; } } catch (IOException x) { System.err.println(x.toString()); } catch (OverlappingFileLockException e) { System.err.println(e.toString()); } return false; }
From source file:ntpgraphic.LineChart.java
public static void NTPClient(String[] servers, int i) { Properties defaultProps = System.getProperties(); //obtiene las "properties" del sistema defaultProps.put("java.net.preferIPv6Addresses", "true");//mapea el valor true en la variable java.net.preferIPv6Addresses if (servers.length == 0) { System.err.println("Usage: NTPClient <hostname-or-address-list>"); System.exit(1);/* ww w . j a va 2 s . c o m*/ } Promedio = 0; Cant = 0; NTPUDPClient client = new NTPUDPClient(); // We want to timeout if a response takes longer than 10 seconds client.setDefaultTimeout(10000); try { client.open(); for (String arg : servers) { System.out.println(); try { InetAddress hostAddr = InetAddress.getByName(arg); System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress()); TimeInfo info = client.getTime(hostAddr); processResponse(info, i); } catch (IOException ioe) { System.err.println(ioe.toString()); } } } catch (SocketException e) { System.err.println(e.toString()); } client.close(); //System.out.println("\n Pomedio "+(Promedio/Cant)); }
From source file:com.mellanox.hadoop.mapred.UdaPluginTT.java
static IndexRecordBridge getPathIndex(String jobId, String mapId, int reduce) { String userName = null;/*from w ww.j a v a 2s . c o m*/ String runAsUserName = null; IndexRecordBridge data = null; try { JobConf jobConf = udaShuffleProvider.getJobConfFromSuperClass(JobID.forName(jobId)); userName = jobConf.getUser(); runAsUserName = taskTracker.getTaskController().getRunAsUser(jobConf); String intermediateOutputDir = UdaShuffleProviderPlugin.getIntermediateOutputDirFromSuperClass(userName, jobId, mapId); String indexKey = intermediateOutputDir + "/file.out.index"; Path indexFileName = fileIndexCache.get(indexKey); if (indexFileName == null) { indexFileName = localDirAllocator.getLocalPathToRead(indexKey, mjobConf); fileIndexCache.put(indexKey, indexFileName); } // Map-output file String fileKey = intermediateOutputDir + "/file.out"; Path mapOutputFileName = fileCache.get(fileKey); if (mapOutputFileName == null) { mapOutputFileName = localDirAllocator.getLocalPathToRead(fileKey, mjobConf); fileCache.put(fileKey, mapOutputFileName); } // Read the index file to get the information about where // the map-output for the given reducer is available. data = indexCache.getIndexInformationBridge(mapId, reduce, indexFileName, runAsUserName); data.pathMOF = mapOutputFileName.toString(); } catch (IOException e) { LOG.error("exception caught" + e.toString()); //to check how C behaves in case there is an exception } return data; }
From source file:de.uzk.hki.da.at.ATRetrieval.java
@BeforeClass public static void setUp() { removeTMPFiles();//from ww w .j av a2 s .c o m try { ath.putAIPToLongTermStorage(identifier, originalName, new Date(), 100); } catch (IOException e) { e.printStackTrace(); fail(e.toString()); } }
From source file:Main.java
/** * Utility method that creates a <code>UIDefaults.LazyValue</code> that * creates an <code>ImageIcon</code> <code>UIResource</code> for the * specified image file name. The image is loaded using * <code>getResourceAsStream</code>, starting with a call to that method * on the base class parameter. If it cannot be found, searching will * continue through the base class' inheritance hierarchy, up to and * including <code>rootClass</code>. * * @param baseClass the first class to use in searching for the resource * @param rootClass an ancestor of <code>baseClass</code> to finish the * search at/* w w w . jav a 2s .c o m*/ * @param imageFile the name of the file to be found * @return a lazy value that creates the <code>ImageIcon</code> * <code>UIResource</code> for the image, * or null if it cannot be found */ public static Object makeIcon(final Class<?> baseClass, final Class<?> rootClass, final String imageFile) { return new UIDefaults.LazyValue() { public Object createValue(UIDefaults table) { /* Copy resource into a byte array. This is * necessary because several browsers consider * Class.getResource a security risk because it * can be used to load additional classes. * Class.getResourceAsStream just returns raw * bytes, which we can convert to an image. */ byte[] buffer = java.security.AccessController .doPrivileged(new java.security.PrivilegedAction<byte[]>() { public byte[] run() { try { InputStream resource = null; Class<?> srchClass = baseClass; while (srchClass != null) { resource = srchClass.getResourceAsStream(imageFile); if (resource != null || srchClass == rootClass) { break; } srchClass = srchClass.getSuperclass(); } if (resource == null) { return null; } BufferedInputStream in = new BufferedInputStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int n; while ((n = in.read(buffer)) > 0) { out.write(buffer, 0, n); } in.close(); out.flush(); return out.toByteArray(); } catch (IOException ioe) { System.err.println(ioe.toString()); } return null; } }); if (buffer == null) { return null; } if (buffer.length == 0) { System.err.println("warning: " + imageFile + " is zero-length"); return null; } return new ImageIconUIResource(buffer); } }; }