label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public List<SuspectFileProcessingStatus> retrieve() throws Exception { BufferedOutputStream bos = null; try { String listFilePath = GeneralUtils.generateAbsolutePath(getDownloadDirectoryPath(), getListName(), "/"); listFilePath = listFilePath.concat(".xml"); if (!new File(getDownloadDirectoryPath()).exists()) { FileUtils.forceMkdir(new File(getDownloadDirectoryPath())); } FileOutputStream listFileOutputStream = new FileOutputStream(listFilePath); bos = new BufferedOutputStream(listFileOutputStream); InputStream is = null; if (getUseProxy()) { is = URLUtils.getResponse(getUrl(), getUserName(), getPassword(), URLUtils.HTTP_GET_METHOD, getProxyHost(), getProxyPort()); IOUtils.copyLarge(is, bos); } else { URLUtils.getResponse(getUrl(), getUserName(), getPassword(), bos, null); } bos.flush(); bos.close(); File listFile = new File(listFilePath); if (!listFile.exists()) { throw new IllegalStateException("The list file did not get created"); } if (isLoggingInfo()) { logInfo("Downloaded list file : " + listFile); } List<SuspectFileProcessingStatus> sfpsList = new ArrayList<SuspectFileProcessingStatus>(); String loadType = GeneralConstants.LOAD_TYPE_FULL; String feedType = GeneralConstants.EMPTY_TOKEN; String listName = getListName(); String errorCode = ""; String description = ""; SuspectFileProcessingStatus sfps = getSuspectsLoaderService().storeFileIntoListIncomingDir(listFile, loadType, feedType, listName, errorCode, description); sfpsList.add(sfps); if (isLoggingInfo()) { logInfo("Retrieved list file with SuspectFileProcessingStatus: " + sfps); } return sfpsList; } finally { if (null != bos) { bos.close(); } } } Code Sample 2: public void invoke(InputStream is) throws AgentException { try { addHeader("Content-Type", "application/zip"); addHeader("Content-Length", String.valueOf(is.available())); connection.setDoOutput(true); connection.connect(); OutputStream os = connection.getOutputStream(); boolean success = false; try { IOUtils.copy(is, os); success = true; } finally { try { os.flush(); os.close(); } catch (IOException x) { if (success) throw x; } } connection.disconnect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new AgentException("Failed to execute REST call at " + connection.getURL() + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (ConnectException e) { throw new AgentException("Failed to connect to beehive at " + connection.getURL()); } catch (IOException e) { throw new AgentException("Failed to connect to beehive", e); } }
00
Code Sample 1: public String getSource(String urlAdd) throws Exception { HttpURLConnection urlConnection = null; URL url = new URL(urlAdd); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(timeout); if (!urlConnection.getContentType().contains("text/html")) { throw new Exception(); } if (urlConnection.getResponseCode() != 200) { throw new Exception(); } encoding = getPageEncoding(urlConnection); if (encoding == null) { encoding = defaultEncoding; } InputStream in = url.openStream(); byte[] buffer = new byte[12288]; StringBuffer sb = new StringBuffer(); int bytesRead = 0; while ((bytesRead = in.read(buffer)) != -1) { String reads = new String(buffer, 0, bytesRead, encoding); sb.append(reads); } in.close(); return sb.toString(); } Code Sample 2: public ClientDTO changePassword(String pMail, String pMdp) { Client vClientBean = null; ClientDTO vClientDTO = null; vClientBean = mClientDao.getClient(pMail); if (vClientBean != null) { MessageDigest vMd5Instance; try { vMd5Instance = MessageDigest.getInstance("MD5"); vMd5Instance.reset(); vMd5Instance.update(pMdp.getBytes()); byte[] vDigest = vMd5Instance.digest(); BigInteger vBigInt = new BigInteger(1, vDigest); String vHashPassword = vBigInt.toString(16); vClientBean.setMdp(vHashPassword); vClientDTO = BeanToDTO.getInstance().createClientDTO(vClientBean); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return vClientDTO; }
11
Code Sample 1: public static String generateHash(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest digest; digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(message.getBytes("iso-8859-1"), 0, message.length()); byte[] output = new byte[20]; digest.digest(output, 0, output.length); return convertToHex(output); } Code Sample 2: public String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
00
Code Sample 1: public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { PrintUtil.prt((char) buff.get()); } } Code Sample 2: public static String[] listFilesInJar(String resourcesLstName, String dirPath, String ext) { try { dirPath = Tools.subString(dirPath, "\\", "/"); if (!dirPath.endsWith("/")) { dirPath = dirPath + "/"; } if (dirPath.startsWith("/")) { dirPath = dirPath.substring(1, dirPath.length()); } URL url = ResourceLookup.getClassResourceUrl(Tools.class, resourcesLstName); if (url == null) { String msg = "File not found " + resourcesLstName; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } InputStream is = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String name = in.readLine(); HashSet<String> list = new HashSet<String>(10); while (name != null) { name = in.readLine(); if (name == null) { continue; } if (ext != null && !name.endsWith(ext)) { continue; } if (name.indexOf('.') == -1 && !name.endsWith("/")) { name = name + "/"; } int index = name.indexOf(dirPath); if (index < 0) { continue; } index += dirPath.length(); if (index >= name.length() - 1) { continue; } index = name.indexOf("/", index); if (ext != null && (name.endsWith("/") || index >= 0)) { continue; } else if (ext == null && (index < 0 || index < name.length() - 1)) { continue; } list.add("/" + name); } is.close(); String[] toReturn = {}; return list.toArray(toReturn); } catch (IOException ioe) { String msg = "Error reading file " + resourcesLstName + " caused by " + ioe; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } }
11
Code Sample 1: private void convertClasses(File source, File destination) throws PostProcessingException, CodeCheckException, IOException { Stack sourceStack = new Stack(); Stack destinationStack = new Stack(); sourceStack.push(source); destinationStack.push(destination); while (!sourceStack.isEmpty()) { source = (File) sourceStack.pop(); destination = (File) destinationStack.pop(); if (!destination.exists()) destination.mkdirs(); File[] files = source.listFiles(); for (int i = 0; i < files.length; i++) { File current = (File) files[i]; if (current.isDirectory()) { sourceStack.push(current); destinationStack.push(new File(destination, current.getName())); } else if (current.getName().endsWith(".class")) { ClassWriter writer = new ClassWriter(); InputStream is = new BufferedInputStream(new FileInputStream(current)); writer.readClass(is); is.close(); if ((getStatusFlags(writer.getClassName(writer.getCurrentClassIndex())) & PP_PROCESSED) != 0) { ClassWriter[] auxWriter = new ClassWriter[1]; transformClass(writer, auxWriter); File output = new File(destination, current.getName()); OutputStream os = new BufferedOutputStream(new FileOutputStream(output)); writer.writeClass(os); os.close(); if (auxWriter[0] != null) { String className = auxWriter[0].getClassName(auxWriter[0].getCurrentClassIndex()); className = className.substring(className.lastIndexOf('.') + 1, className.length()); output = new File(destination, className + ".class"); os = new BufferedOutputStream(new FileOutputStream(output)); auxWriter[0].writeClass(os); os.close(); } } } } } } Code Sample 2: public static File unGzip(File infile, boolean deleteGzipfileOnSuccess) throws IOException { GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile)); File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", "")); FileOutputStream fos = new FileOutputStream(outFile); byte[] buf = new byte[100000]; int len; while ((len = gin.read(buf)) > 0) fos.write(buf, 0, len); gin.close(); fos.close(); if (deleteGzipfileOnSuccess) infile.delete(); return outFile; }
00
Code Sample 1: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + StringUtils.byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } } Code Sample 2: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
11
Code Sample 1: public static void copyFile(File oldFile, File newFile) throws Exception { newFile.getParentFile().mkdirs(); newFile.createNewFile(); FileChannel srcChannel = new FileInputStream(oldFile).getChannel(); FileChannel dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: private boolean write(File file) { String filename = file.getPath(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteArrayOutputStream); try { StringBuffer xml = null; if (MainFrame.getInstance().getAnimation() != null) { MainFrame.getInstance().getAnimation().xml(out, "\t"); } else { xml = MainFrame.getInstance().getModel().xml("\t"); } if (file.exists()) { BufferedReader reader = new BufferedReader(new FileReader(filename)); BufferedWriter writer = new BufferedWriter(new FileWriter(filename + "~")); char[] buffer = new char[65536]; int charsRead = 0; while ((charsRead = reader.read(buffer)) > 0) writer.write(buffer, 0, charsRead); reader.close(); writer.close(); } BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<jpatch version=\"" + VersionInfo.ver + "\">\n"); if (xml != null) writer.write(xml.toString()); else writer.write(byteArrayOutputStream.toString()); writer.write("</jpatch>\n"); writer.close(); MainFrame.getInstance().getUndoManager().setChange(false); if (MainFrame.getInstance().getAnimation() != null) MainFrame.getInstance().getAnimation().setFile(file); else MainFrame.getInstance().getModel().setFile(file); MainFrame.getInstance().setFilename(file.getName()); return true; } catch (IOException ioException) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Unable to save file \"" + filename + "\"\n" + ioException, "Error", JOptionPane.ERROR_MESSAGE); return false; } }
00
Code Sample 1: public boolean add(String url) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("POST"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.setRequestProperty(GameRecord.GAME_MESSAGE_HEADER, message); request.setRequestProperty(GameRecord.GAME_LATITUDE_HEADER, df.format(lat)); request.setRequestProperty(GameRecord.GAME_LONGITUDE_HEADER, df.format(lon)); request.setRequestProperty("Content-Length", "0"); request.connect(); if (request.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected response: " + request.getResponseCode() + " " + request.getResponseMessage()); } return true; } catch (IOException e) { e.printStackTrace(); } return false; } Code Sample 2: private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
00
Code Sample 1: private InputStream getInputStream(final String pUrlStr) throws IOException { URL url; int responseCode; String encoding; url = new URL(pUrlStr); myActiveConnection = (HttpURLConnection) url.openConnection(); myActiveConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); responseCode = myActiveConnection.getResponseCode(); if (responseCode != RESPONSECODE_OK) { String message; String apiErrorMessage; apiErrorMessage = myActiveConnection.getHeaderField("Error"); if (apiErrorMessage != null) { message = "Received API HTTP response code " + responseCode + " with message \"" + apiErrorMessage + "\" for URL \"" + pUrlStr + "\"."; } else { message = "Received API HTTP response code " + responseCode + " for URL \"" + pUrlStr + "\"."; } throw new OsmosisRuntimeException(message); } myActiveConnection.setConnectTimeout(TIMEOUT); encoding = myActiveConnection.getContentEncoding(); responseStream = myActiveConnection.getInputStream(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { responseStream = new GZIPInputStream(responseStream); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { responseStream = new InflaterInputStream(responseStream, new Inflater(true)); } return responseStream; } Code Sample 2: public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void main(String[] args) throws Exception { System.out.println("Opening destination cbrout.jizz"); OutputStream out = new BufferedOutputStream(new FileOutputStream("cbrout.jizz")); System.out.println("Opening source output.jizz"); InputStream in = new CbrLiveStream(new BufferedInputStream(new FileInputStream("output.jizz")), System.currentTimeMillis() + 10000, 128); System.out.println("Starting read/write loop"); boolean started = false; int len; byte[] buf = new byte[4 * 1024]; while ((len = in.read(buf)) > -1) { if (!started) { System.out.println("Starting at " + new Date()); started = true; } out.write(buf, 0, len); } System.out.println("Finished at " + new Date()); out.close(); in.close(); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); }
00
Code Sample 1: public static String compute(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException nax) { RuntimeException rx = new IllegalStateException(); rx.initCause(rx); throw rx; } catch (UnsupportedEncodingException uex) { RuntimeException rx = new IllegalStateException(); rx.initCause(uex); throw rx; } } Code Sample 2: protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException { List<Datastream> tDatastreams = new ArrayList<Datastream>(); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); tDatastreams.add(tDatastream); tDatastreams.addAll(_zipFile.getFiles(tZipTempFileName)); return tDatastreams; }
11
Code Sample 1: public void testSystemPropertyConnector() throws Exception { final String rootFolderPath = "test/ConnectorTest/fs/".toLowerCase(); final Connector connector = new SystemPropertyConnector(); final ContentResolver contentResolver = new UnionContentResolver(); final FSContentResolver fsContentResolver = new FSContentResolver(); fsContentResolver.setRootFolderPath(rootFolderPath); contentResolver.addContentResolver(fsContentResolver); contentResolver.addContentResolver(new ClasspathContentResolver()); connector.setContentResolver(contentResolver); String resultString; byte[] resultContent; Object resultObject; resultString = connector.getString("helloWorldPath"); assertNull(resultString); resultContent = connector.getContent("helloWorldPath"); assertNull(resultContent); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "file:org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("file:org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNull(resultObject); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "classpath:org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("classpath:org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); final InputStream helloWorldIS = new ByteArrayInputStream("Hello World 2 - Test".getBytes("UTF-8")); FileUtils.forceMkdir(new File(rootFolderPath + "/org/settings4j/connector")); final String helloWorldPath = rootFolderPath + "/org/settings4j/connector/HelloWorld2.txt"; final FileOutputStream fileOutputStream = new FileOutputStream(new File(helloWorldPath)); IOUtils.copy(helloWorldIS, fileOutputStream); IOUtils.closeQuietly(helloWorldIS); IOUtils.closeQuietly(fileOutputStream); LOG.info("helloWorld2Path: " + helloWorldPath); System.setProperty("helloWorldPath", "file:org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("file:org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2 - Test", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2 - Test", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); System.setProperty("helloWorldPath", "classpath:org/settings4j/connector/HelloWorld2.txt"); resultString = connector.getString("helloWorldPath"); assertNotNull(resultString); assertEquals("classpath:org/settings4j/connector/HelloWorld2.txt", resultString); resultContent = connector.getContent("helloWorldPath"); assertNotNull(resultContent); assertEquals("Hello World 2", new String(resultContent, "UTF-8")); resultObject = connector.getObject("helloWorldPath"); assertNull(resultObject); } Code Sample 2: public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; this.logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; this.logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; this.logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { this.logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { this.logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
00
Code Sample 1: private static void upload(String login, String password, String file) throws ApiException { System.out.println("Trying to login to 4shared........"); File f = new File(file); if (!f.exists() || !f.canRead() || f.isDirectory()) { System.out.println("File does not exist, unreadable or not a file"); return; } DesktopAppJax2 da = new DesktopAppJax2Service().getDesktopAppJax2Port(); String loginRes = da.login(login, password); if (!loginRes.isEmpty()) { System.out.println("Login failed: " + loginRes); return; } if (!da.hasRightUpload()) { System.out.println("Uploading is temporarily disabled"); return; } System.out.println("4shared Login successful :)"); long newFileId = da.uploadStartFile(login, password, -1, f.getName(), f.length()); System.out.println("File id : " + newFileId); String sessionKey = da.createUploadSessionKey(login, password, -1); long dcId = da.getNewFileDataCenter(login, password); String url = da.getUploadFormUrl((int) dcId, sessionKey); try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); MultipartEntity me = new MultipartEntity(); StringBody rfid = new StringBody("" + newFileId); StringBody rfb = new StringBody("" + 0); InputStreamBody isb = new InputStreamBody(new BufferedInputStream(new FileInputStream(f)), "FilePart"); me.addPart("resumableFileId", rfid); me.addPart("resumableFirstByte", rfb); me.addPart("FilePart", isb); post.setEntity(me); HttpResponse resp = client.execute(post); HttpEntity resEnt = resp.getEntity(); String res = da.uploadFinishFile(login, password, newFileId, DigestUtils.md5Hex(new FileInputStream(f))); if (res.isEmpty()) { System.out.println("File uploaded."); downloadlink = da.getFileDownloadLink(login, password, newFileId); System.out.println("Download link : " + downloadlink); } else { System.out.println("Upload failed: " + res); } } catch (Exception ex) { System.out.println("Upload failed: " + ex.getMessage()); } } Code Sample 2: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getproducts"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); HttpGet request1 = new HttpGet(SERVICE_URI + "/json/getroutes/3165"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient1 = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringID = new String(); String tempStringName = new String(); String tempStringPrice = new String(); String tempStringSymbol = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetPerson_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray; nameArray = json.getJSONArray("getProductsResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringID = nameArray.getJSONObject(i).getString("ID"); tempStringName = nameArray.getJSONObject(i).getString("Name"); tempStringPrice = nameArray.getJSONObject(i).getString("Price"); tempStringSymbol = nameArray.getJSONObject(i).getString("Symbol"); this.dm.insertIntoProducts(tempStringID, tempStringName, tempStringPrice, tempStringSymbol); tempString = nameArray.getJSONObject(i).getString("Name") + "\n" + nameArray.getJSONObject(i).getString("Price") + "\n" + nameArray.getJSONObject(i).getString("Symbol"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); } catch (Exception e) { e.printStackTrace(); } try { HttpResponse response1 = httpClient1.execute(request1); HttpEntity response1Entity = response1.getEntity(); InputStream stream1 = response1Entity.getContent(); BufferedReader reader1 = new BufferedReader(new InputStreamReader(stream1)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString1 = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder1 = new StringBuilder(); String line1; while ((line1 = reader1.readLine()) != null) { builder1.append(line1); } stream1.close(); theString = builder1.toString(); JSONObject json1 = new JSONObject(theString); Log.i("_GetPerson_", "<jsonobject>\n" + json1.toString() + "\n</jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray1; nameArray1 = json1.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray1.length(); i++) { tempStringAgent = nameArray1.getJSONObject(i).getString("Agent"); tempStringClient = nameArray1.getJSONObject(i).getString("Client"); tempStringRoute = nameArray1.getJSONObject(i).getString("Route"); tempStringZone = nameArray1.getJSONObject(i).getString("Zone"); this.dm.insertIntoClients(tempStringAgent, tempStringClient, tempStringRoute, tempStringZone); tempString1 = nameArray1.getJSONObject(i).getString("Client") + "\n" + nameArray1.getJSONObject(i).getString("Route") + "\n" + nameArray1.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString1)); } int orderCount1 = vectorOfStrings.size(); String[] orderTimeStamps1 = new String[orderCount1]; vectorOfStrings.copyInto(orderTimeStamps1); } catch (Exception a) { a.printStackTrace(); } }
11
Code Sample 1: public static final void main(String[] args) throws FileNotFoundException, IOException { ArrayList<String[]> result = new ArrayList<String[]>(); IStream is = new StreamImpl(); IOUtils.copy(new FileInputStream("H:\\7-项目预算表.xlsx"), is.getOutputStream()); int count = loadExcel(result, is, 0, 0, -1, 16, 1); System.out.println(count); for (String[] rs : result) { for (String r : rs) { System.out.print(r + "\t"); } System.out.println(); } } Code Sample 2: public static void copy(String sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
11
Code Sample 1: private String[] verifyConnection(Socket clientConnection) throws Exception { List<String> requestLines = new ArrayList<String>(); InputStream is = clientConnection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringTokenizer st = new StringTokenizer(in.readLine()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no method token in this connection"); } String method = st.nextToken(); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no URI token in this connection"); } String uri = decodePercent(st.nextToken()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no version token in this connection"); } String version = st.nextToken(); Properties parms = new Properties(); int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } String params = ""; if (parms.size() > 0) { params = "?"; for (Object key : parms.keySet()) { params = params + key + "=" + parms.getProperty(((String) key)) + "&"; } params = params.substring(0, params.length() - 1).replace(" ", "%20"); } logger.debug("HTTP Request: " + method + " " + uri + params + " " + version); requestLines.add(method + " " + uri + params + " " + version); Properties headerVars = new Properties(); String line; String currentBoundary = null; Stack<String> boundaryStack = new Stack<String>(); boolean readingBoundary = false; String additionalData = ""; while (in.ready() && (line = in.readLine()) != null) { if (line.equals("") && (headerVars.get("Content-Type") == null || headerVars.get("Content-Length") == null)) { break; } logger.debug("HTTP Request Header: " + line); if (line.contains(": ")) { String vals[] = line.split(": "); headerVars.put(vals[0].trim(), vals[1].trim()); } if (!readingBoundary && line.contains(": ")) { if (line.contains("boundary=")) { currentBoundary = line.split("boundary=")[1].trim(); boundaryStack.push("--" + currentBoundary); } continue; } else if (line.equals("") && boundaryStack.isEmpty()) { int val = Integer.parseInt((String) headerVars.get("Content-Length")); if (headerVars.getProperty("Content-Type").contains("x-www-form-urlencoded")) { char buf[] = new char[val]; int read = in.read(buf); line = String.valueOf(buf, 0, read); additionalData = line; logger.debug("HTTP Request Header Form Parameters: " + line); } } else if (line.equals(boundaryStack.peek()) && !readingBoundary) { readingBoundary = true; } else if (line.equals(boundaryStack.peek()) && readingBoundary) { readingBoundary = false; } else if (line.contains(": ") && readingBoundary) { if (method.equalsIgnoreCase("PUT")) { if (line.contains("form-data; ")) { String formValues = line.split("form-data; ")[1]; for (String varValue : formValues.replace("\"", "").split("; ")) { String[] vV = varValue.split("="); vV[0] = decodePercent(vV[0]); vV[1] = decodePercent(vV[1]); headerVars.put(vV[0], vV[1]); } } } } else if (line.contains("") && readingBoundary && !boundaryStack.isEmpty() && headerVars.get("filename") != null) { int length = Integer.parseInt(headerVars.getProperty("Content-Length")); if (headerVars.getProperty("Content-Transfer-Encoding").contains("binary")) { File uploadFilePath = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory")); if (!uploadFilePath.exists()) { logger.error("Temporaty dir does not exist: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.isDirectory()) { logger.error("Temporary dir is not a directory: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.canWrite()) { logger.error("VOctopus Webserver doesn't have permissions to write on temporary dir: " + uploadFilePath.getCanonicalPath()); } FileOutputStream out = null; try { String putUploadPath = uploadFilePath.getAbsolutePath() + "/" + headerVars.getProperty("filename"); out = new FileOutputStream(putUploadPath); OutputStream outf = new BufferedOutputStream(out); int c; while (in.ready() && (c = in.read()) != -1 && length-- > 0) { outf.write(c); } } finally { if (out != null) { out.close(); } } File copied = new File(VOctopusConfigurationManager.getInstance().getDocumentRootPath() + uri + headerVars.get("filename")); File tempFile = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory") + "/" + headerVars.get("filename")); FileChannel ic = new FileInputStream(tempFile.getAbsolutePath()).getChannel(); FileChannel oc = new FileOutputStream(copied.getAbsolutePath()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } } } for (Object var : headerVars.keySet()) { requestLines.add(var + ": " + headerVars.get(var)); } if (!additionalData.equals("")) { requestLines.add("ADDITIONAL" + additionalData); } return requestLines.toArray(new String[requestLines.size()]); } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: private void runUpdateAppListing() { DataStorage.clearListedAppListing(); GenericUrl url = new GoogleUrl(EnterpriseMarketplaceUrl.generateAppListingUrl() + DataStorage.getVendorProfile().vendorId); AppListing appListingBody = buildAppListing(appsMarketplaceProject); JsonHttpContent content = new JsonHttpContent(); content.jsonFactory = jsonFactory; if (appListingBody != null) { content.data = appListingBody; } AppListing appListing; try { HttpRequest request = requestFactory.buildPutRequest(url, content); request.addParser(jsonHttpParser); request.readTimeout = readTimeout; HttpResponse response = request.execute(); appListing = response.parseAs(AppListing.class); operationStatus = validateAppListing(appListing, appListingBody); if (operationStatus) { DataStorage.setListedAppListing(appListing); } response.getContent().close(); } catch (IOException e) { AppsMarketplacePluginLog.logError(e); } } Code Sample 2: public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); }
00
Code Sample 1: private ParserFileReader createParserFileReader(final FromNetRecord record) throws IOException { final String strUrl = record.getStrUrl(); ParserFileReader parserFileReader; try { parserFileReader = parserFileReaderFactory.create(strUrl); } catch (Exception exception) { _log.error("can not create reader for \"" + strUrl + "\"", exception); parserFileReader = null; } url = parserFileReaderFactory.getUrl(); if (parserFileReader != null) { parserFileReader.mark(); final String outFileName = urlToFile("runtime/tests", url, ""); final File outFile = new File(outFileName); outFile.getParentFile().mkdirs(); final Writer writer = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"); int readed; while ((readed = parserFileReader.read()) != -1) { writer.write(readed); } writer.close(); parserFileReader.reset(); } return parserFileReader; } Code Sample 2: public Reader getReader() throws Exception { if (url_base == null) { return new FileReader(file); } else { URL url = new URL(url_base + file.getName()); return new InputStreamReader(url.openConnection().getInputStream()); } }
00
Code Sample 1: public static byte[] hash(String identifier) { if (function.equals("SHA-1")) { try { MessageDigest md = MessageDigest.getInstance(function); md.reset(); byte[] code = md.digest(identifier.getBytes()); byte[] value = new byte[KEY_LENGTH / 8]; int shrink = code.length / value.length; int bitCount = 1; for (int j = 0; j < code.length * 8; j++) { int currBit = ((code[j / 8] & (1 << (j % 8))) >> j % 8); if (currBit == 1) bitCount++; if (((j + 1) % shrink) == 0) { int shrinkBit = (bitCount % 2 == 0) ? 0 : 1; value[j / shrink / 8] |= (shrinkBit << ((j / shrink) % 8)); bitCount = 1; } } return value; } catch (Exception e) { e.printStackTrace(); } } if (function.equals("CRC32")) { CRC32 crc32 = new CRC32(); crc32.reset(); crc32.update(identifier.getBytes()); long code = crc32.getValue(); code &= (0xffffffffffffffffL >>> (64 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } if (function.equals("Java")) { int code = identifier.hashCode(); code &= (0xffffffff >>> (32 - KEY_LENGTH)); byte[] value = new byte[KEY_LENGTH / 8]; for (int i = 0; i < value.length; i++) { value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff); } return value; } return null; } Code Sample 2: public static void copy(File _from, File _to) throws IOException { if (_from == null || !_from.exists()) return; FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(_to); in = new FileInputStream(_from); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: protected void readInput(String filename, List<String> list) throws IOException { URL url = GeneratorBase.class.getResource(filename); if (url == null) { throw new FileNotFoundException("specified file not available - " + filename); } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { list.add(line.trim()); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } Code Sample 2: public String buscaCDE() { URL url; Properties prop = new CargaProperties().Carga(); BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("CDE")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("lastSuccessfulBuild/artifact/server/plugin/dist/pentaho-cdf-dd-TRUNK")) { miLinea = inputLine; miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/server/plugin/dist/pentaho-cdf-dd-TRUNK")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build CDE: " + miLinea); return miLinea; }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public String getInternetData() throws Exception { BufferedReader in = null; String data = null; try { HttpClient client = new DefaultHttpClient(); URI website = new URI("http://code.google.com/p/gadi-works"); HttpGet request = new HttpGet(); request.setURI(website); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String l = ""; String nl = System.getProperty("line.separator"); while ((l = in.readLine()) != null) { sb.append(l + nl); } in.close(); data = sb.toString(); return data; } finally { if (in != null) { try { in.close(); return data; } catch (Exception e) { e.printStackTrace(); } } } }
00
Code Sample 1: public LocalizationSolver(String name, String serverIP, int portNum, String workDir) { this.info = new HashMap<String, Object>(); this.workDir = workDir; try { Socket solverSocket = new Socket(serverIP, portNum); this.fromServer = new Scanner(solverSocket.getInputStream()); this.toServer = new PrintWriter(solverSocket.getOutputStream(), true); this.toServer.println("login client abc"); this.toServer.println("solver " + name); System.out.println(this.fromServer.nextLine()); } catch (IOException e) { System.err.println(e); e.printStackTrace(); System.exit(1); } System.out.println("Localization Solver started with name: " + name); } Code Sample 2: public static String createHash(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); return toHexString(digest); } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); } return ""; }
11
Code Sample 1: private void copy(File fromFile, File toFile) throws IOException { String fromFileName = fromFile.getName(); File tmpFile = new File(fromFileName); String toFileName = toFile.getName(); if (!tmpFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!tmpFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!tmpFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(tmpFile); File toF = new File(toFile.getCanonicalPath()); if (!toF.exists()) ; toF.createNewFile(); if (!SBCMain.DEBUG_MODE) to = new FileOutputStream(toFile); else to = new FileOutputStream(toF); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static void main(String[] args) throws IOException { long readfilelen = 0; BufferedRandomAccessFile brafReadFile, brafWriteFile; brafReadFile = new BufferedRandomAccessFile("C:\\WINNT\\Fonts\\STKAITI.TTF"); readfilelen = brafReadFile.initfilelen; brafWriteFile = new BufferedRandomAccessFile(".\\STKAITI.001", "rw", 10); byte buf[] = new byte[1024]; int readcount; long start = System.currentTimeMillis(); while ((readcount = brafReadFile.read(buf)) != -1) { brafWriteFile.write(buf, 0, readcount); } brafWriteFile.close(); brafReadFile.close(); System.out.println("BufferedRandomAccessFile Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); java.io.FileInputStream fdin = new java.io.FileInputStream("C:\\WINNT\\Fonts\\STKAITI.TTF"); java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fdin, 1024); java.io.DataInputStream dis = new java.io.DataInputStream(bis); java.io.FileOutputStream fdout = new java.io.FileOutputStream(".\\STKAITI.002"); java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(fdout, 1024); java.io.DataOutputStream dos = new java.io.DataOutputStream(bos); start = System.currentTimeMillis(); for (int i = 0; i < readfilelen; i++) { dos.write(dis.readByte()); } dos.close(); dis.close(); System.out.println("DataBufferedios Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); }
00
Code Sample 1: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } } Code Sample 2: protected static boolean isLatestVersion(double myVersion, String referenceAddress) { Scanner scanner = null; try { URL url = new URL(referenceAddress); InputStream iS = url.openStream(); scanner = new Scanner(iS); String firstLine = scanner.nextLine(); double latestVersion = Double.valueOf(firstLine.trim()); return myVersion >= latestVersion; } catch (Exception e) { displaySimpleAlert(null, "Cannot check latest version...check internet connection?"); return false; } }
00
Code Sample 1: public static void BubbleSortFloat1(float[] num) { boolean flag = true; // set flag to true to begin first pass float temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } } Code Sample 2: public static String httpGet(URL url) throws Exception { URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); }
11
Code Sample 1: public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); } Code Sample 2: public static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); }
00
Code Sample 1: protected BufferedReader getBufferedReader(InputSource input) throws IOException, SAXException { BufferedReader br = null; if (input.getCharacterStream() != null) { br = new BufferedReader(input.getCharacterStream()); } else if (input.getByteStream() != null) { br = new BufferedReader(new InputStreamReader(input.getByteStream())); } else if (input.getSystemId() != null) { URL url = new URL(input.getSystemId()); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { throw new SAXException("Invalid InputSource!"); } return br; } Code Sample 2: public void encryptPassword() { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.out.print(e); } try { digest.update(passwordIn.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.out.println("cannot find char set for getBytes"); } byte digestBytes[] = digest.digest(); passwordHash = (new BASE64Encoder()).encode(digestBytes); }
00
Code Sample 1: public void appendFetch(IProgress progress, PrintWriter pw, String list, int from, int to) throws IOException { progress.start(); try { File storage = new File(cacheDirectory.getValue(), "mboxes"); storage.mkdirs(); File mbox = new File(storage, list + "-" + from + "-" + to + ".mbox"); if (mbox.exists()) { BufferedReader in = new BufferedReader(new InputStreamReader(new ProgressInputStream(new FileInputStream(mbox), progress, 10000))); String line; while ((line = in.readLine()) != null) { pw.write(line); pw.write('\n'); } in.close(); return; } progress.setScale(100); IProgress subProgress1 = progress.getSub(75); URL url = getGmaneURL(list, from, to); BufferedReader in = new BufferedReader(new InputStreamReader(new ProgressInputStream(url.openStream(), subProgress1, 10000))); PrintWriter writeToMbox = new PrintWriter(mbox); int lines = 0; String line; while ((line = in.readLine()) != null) { lines++; if (line.matches("^From .*$") && !line.matches("^From .*? .*[0-9][0-9]:[0-9][0-9]:[0-9][0-9].*$")) { line = ">" + line; } writeToMbox.write(line); writeToMbox.write('\n'); } in.close(); writeToMbox.close(); appendFetch(progress.getSub(25), pw, list, from, to); } finally { progress.done(); } } Code Sample 2: public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
00
Code Sample 1: protected static File UrlGzipToAFile(File dir, String urlSt, String fileName) throws CaughtException { try { URL url = new URL(urlSt); InputStream zipped = url.openStream(); InputStream unzipped = new GZIPInputStream(zipped); File tempFile = new File(dir, fileName); copyFile(tempFile, unzipped); return tempFile; } catch (IOException e) { throw new CaughtException(e, logger); } } Code Sample 2: public static boolean copyFile(final String src, final String dest) { if (fileExists(src)) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); return true; } catch (IOException e) { Logger.getAnonymousLogger().severe(e.getLocalizedMessage()); } } return false; }
11
Code Sample 1: public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test1.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.encrypt(reader, writer, key, mode); } Code Sample 2: public File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; }
11
Code Sample 1: private void copyFile(String from, String to) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } File outScriptFile = new File(to); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } } Code Sample 2: public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: public synchronized String encrypt(String plaintext) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new PasswordException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new PasswordException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new Base64Encoder()).encode(raw); return hash; } Code Sample 2: private void outputSignedOpenDocument(byte[] signatureData) throws IOException { LOG.debug("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream(); if (null == signedOdfOutputStream) { throw new NullPointerException("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
11
Code Sample 1: public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public byte[] getXQueryForWorkflow(String workflowURI, Log4JLogger log) throws MalformedURLException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (workflowURI == null) { throw new XQGeneratorException("Null workflow URI"); } URL url = new URL(workflowURI); URLConnection urlconn = url.openConnection(); urlconn.setAllowUserInteraction(false); urlconn.setDoInput(true); urlconn.setDoOutput(false); urlconn.setUseCaches(true); urlconn.connect(); InputStream is = urlconn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); TavXQueryGenerator generator = (TavXQueryGenerator) Class.forName(generatorClass).newInstance(); generator.setLogger(log); generator.setInputStream(is); generator.setOutputStream(baos); generator.generateXQuery(); is.close(); return baos.toByteArray(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static String hashString(String pwd) { StringBuffer hex = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pwd.getBytes()); byte[] d = md.digest(); String plaintxt; for (int i = 0; i < d.length; i++) { plaintxt = Integer.toHexString(0xFF & d[i]); if (plaintxt.length() < 2) { plaintxt = "0" + plaintxt; } hex.append(plaintxt); } } catch (NoSuchAlgorithmException nsae) { } return hex.toString(); } Code Sample 2: public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; }
00
Code Sample 1: public void testIntegrityViolation() throws Exception { if (getDialect() instanceof MySQLMyISAMDialect) { reportSkip("MySQL (ISAM) does not support FK violation checking", "exception conversion"); return; } SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter(); Session session = openSession(); session.beginTransaction(); Connection connection = session.connection(); PreparedStatement ps = null; try { ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"); ps.setLong(1, 52134241); ps.setLong(2, 5342); ps.executeUpdate(); fail("INSERT should have failed"); } catch (SQLException sqle) { JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!"); JDBCException jdbcException = converter.convert(sqle, null, null); assertEquals("Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class, jdbcException.getClass()); ConstraintViolationException ex = (ConstraintViolationException) jdbcException; System.out.println("Violated constraint name: " + ex.getConstraintName()); } finally { if (ps != null) { try { ps.close(); } catch (Throwable ignore) { } } } session.getTransaction().rollback(); session.close(); } Code Sample 2: protected void discoverRegistryEntries() { DataSourceRegistry registry = this; try { ClassLoader loader = DataSetURI.class.getClassLoader(); Enumeration<URL> urls; if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFactory.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerExtension(ss[0], ss[i], null); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerMimeType(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFormat.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerFormatter(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerEditor(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerFormatEditor(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void actionPerformed(ActionEvent evt) { try { File tempFile = new File("/tmp/controler.xml"); File f = new File("/tmp/controler-temp.xml"); BufferedInputStream copySource = new BufferedInputStream(new FileInputStream(tempFile)); BufferedOutputStream copyDestination = new BufferedOutputStream(new FileOutputStream(f)); int read = 0; while (read != -1) { read = copySource.read(buffer, 0, BUFFER_SIZE); if (read != -1) { copyDestination.write(buffer, 0, read); } } copyDestination.write(new String("</log>\n").getBytes()); copySource.close(); copyDestination.close(); XMLParser parser = new XMLParser("Controler"); parser.parse(f); f.delete(); } catch (IOException ex) { System.out.println("An error occured during the file copy!"); } } Code Sample 2: private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; }
00
Code Sample 1: private long getLastModified(Set resourcePaths, Map jarPaths) throws Exception { long lastModified = 0; Iterator paths = resourcePaths.iterator(); while (paths.hasNext()) { String path = (String) paths.next(); URL url = context.getServletContext().getResource(path); if (url == null) { log.debug("Null url " + path); break; } long lastM = url.openConnection().getLastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + path + " " + lastM); } } if (jarPaths != null) { paths = jarPaths.values().iterator(); while (paths.hasNext()) { File jarFile = (File) paths.next(); long lastM = jarFile.lastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + jarFile.getAbsolutePath() + " " + lastM); } } } return lastModified; } Code Sample 2: @Override public void start() throws Exception { initMetaData(); Map<String, Set<ONDEXConcept>> accessions = new HashMap<String, Set<ONDEXConcept>>(); for (ONDEXConcept c : graph.getConcepts()) { for (ConceptAccession ca : c.getConceptAccessions()) { if (ca.getElementOf().equals(dsCHEMBL) && !accessions.containsKey(ca.getAccession())) accessions.put(ca.getAccession(), new HashSet<ONDEXConcept>()); accessions.get(ca.getAccession()).add(c); } } System.out.println(accessions); int count = 0; for (String accession : accessions.keySet()) { URL url = new URL("https://www.ebi.ac.uk/chemblws/compounds/" + accession + "/bioactivities"); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); int code = uc.getResponseCode(); if (code != 200) { String response = uc.getResponseMessage(); fireEventOccurred(new ParsingErrorEvent("HTTP/1.x " + code + " " + response, getCurrentMethodName())); } else { InputStream in = new BufferedInputStream(uc.getInputStream()); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(in); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("bioactivity"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; ONDEXConcept activity = graph.getFactory().createConcept(getTagValue("assay__chemblid", eElement), getTagValue("assay__description", eElement), dsCHEMBL, ccActivity, evidencetype); activity.createConceptAccession(getTagValue("assay__chemblid", eElement), dsASSAY, false); activity.createAttribute(anRef, getTagValue("reference", eElement), true); activity.createAttribute(anOrg, getTagValue("organism", eElement), true); String type = getTagValue("bioactivity__type", eElement); type = type.replace(" ", "_"); if (!anTypes.containsKey(type)) { AttributeName an = graph.getMetaData().getFactory().createAttributeName(type, Double.class); String units = getTagValue("units", eElement); if (graph.getMetaData().getUnit(units) == null) graph.getMetaData().getFactory().createUnit(units); an.setUnit(graph.getMetaData().getUnit(units)); anTypes.put(type, an); } String value = getTagValue("value", eElement); try { Double d = Double.valueOf(value); activity.createAttribute(anTypes.get(type), d, false); } catch (NumberFormatException nfe) { } String comment = getTagValue("activity__comment", eElement); if (comment != null && comment.trim().length() > 0) { if (mapping.containsKey(comment)) comment = mapping.get(comment); activity.createAttribute(anComment, comment, true); } count++; Set<ONDEXConcept> compounds = accessions.get(accession); for (ONDEXConcept c : compounds) { graph.getFactory().createRelation(c, activity, rtActivity, evidencetype); } String key = getTagValue("target__chemblid", eElement); if (!targets.containsKey(key)) { ONDEXConcept c = graph.getFactory().createConcept(key, dsCHEMBL, ccTarget, evidencetype); c.createConceptName(getTagValue("target__name", eElement), true); c.createConceptAccession(key, dsTARGET, false); targets.put(key, c); } ONDEXConcept target = targets.get(key); ONDEXRelation r = graph.getFactory().createRelation(activity, target, rtOccin, evidencetype); r.createAttribute(anConf, Double.valueOf(getTagValue("target__confidence", eElement)), false); } } } } fireEventOccurred(new GeneralOutputEvent("Total assays parsed:" + count, getCurrentMethodName())); }
11
Code Sample 1: @Override public void run() { File file = new File(LogHandler.path); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date()); cal.add(GregorianCalendar.DAY_OF_YEAR, -1); String oldTime = LogHandler.dateFormat.format(cal.getTime()); return file.getName().toLowerCase().startsWith(oldTime); } }; File[] list = file.listFiles(filter); if (list.length > 0) { FileInputStream in; int read = 0; byte[] data = new byte[1024]; for (int i = 0; i < list.length; i++) { try { in = new FileInputStream(LogHandler.path + list[i].getName()); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(LogHandler.path + list[i].getName() + ".temp")); while ((read = in.read(data, 0, 1024)) != -1) out.write(data, 0, read); in.close(); out.close(); new File(LogHandler.path + list[i].getName() + ".temp").renameTo(new File(LogHandler.path + list[i].getName() + ".gz")); list[i].delete(); } catch (FileNotFoundException e) { TrackingServer.incExceptionCounter(); e.printStackTrace(); } catch (IOException ioe) { } } } } Code Sample 2: private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); }
00
Code Sample 1: protected String loadPage(String url_string) { try { URL url = new URL(url_string); HttpURLConnection connection = null; InputStream is = null; try { connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); if (response == HttpURLConnection.HTTP_ACCEPTED || response == HttpURLConnection.HTTP_OK) { is = connection.getInputStream(); String page = ""; while (page.length() < MAX_PAGE_SIZE) { byte[] buffer = new byte[2048]; int len = is.read(buffer); if (len < 0) { break; } page += new String(buffer, 0, len); } return (page); } else { informFailure("httpinvalidresponse", "" + response); return (null); } } finally { try { if (is != null) { is.close(); } if (connection != null) { connection.disconnect(); } } catch (Throwable e) { Debug.printStackTrace(e); } } } catch (Throwable e) { informFailure("httploadfail", e.toString()); return (null); } } Code Sample 2: private static BundleInfo[] getBundleInfoArray(String location) throws IOException { URL url = new URL(location + BUNDLE_LIST_FILE); BufferedReader br = null; List<BundleInfo> list = new ArrayList<BundleInfo>(); try { br = new BufferedReader(new InputStreamReader(url.openStream())); while (true) { String line = br.readLine(); if (line == null) { break; } int pos1 = line.indexOf('='); if (pos1 < 0) { continue; } BundleInfo info = new BundleInfo(); info.bundleSymbolicName = line.substring(0, pos1); info.location = line.substring(pos1 + 1); list.add(info); } if (!setBundleInfoName(location + BUNDLE_NAME_LIST_FILE + "_" + Locale.getDefault().getLanguage(), list)) { setBundleInfoName(location + BUNDLE_NAME_LIST_FILE, list); } return list.toArray(BUNDLE_INFO_EMPTY_ARRAY); } finally { if (br != null) { br.close(); } } }
00
Code Sample 1: public List<SatelliteElementSet> parseTLE(String urlString) throws IOException { List<SatelliteElementSet> elementSets = new ArrayList<SatelliteElementSet>(); BufferedReader reader = null; try { String line = null; int i = 0; URL url = new URL(urlString); String[] lines = new String[3]; reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { i++; switch(i) { case 1: { lines[0] = line; break; } case 2: { lines[1] = line; break; } case 3: { lines[2] = line; Long catnum = Long.parseLong(StringUtils.strip(lines[1].substring(2, 7))); long setnum = Long.parseLong(StringUtils.strip(lines[1].substring(64, 68))); elementSets.add(new SatelliteElementSet(catnum, lines, setnum, Calendar.getInstance(TZ).getTime())); i = 0; break; } default: { throw new IOException("TLE string did not contain three elements"); } } } } finally { if (null != reader) { reader.close(); } } return elementSets; } Code Sample 2: public void run() { try { ThreadGroup transfers = new ThreadGroup("transfers"); URL url = new URL("jar:http://jopenrpg.sourceforge.net/files/dev/pythonlib.jar!/"); JarURLConnection juc = (JarURLConnection) url.openConnection(); File top = new File(System.getProperty("user.home"), "jopenrpg"); final JarFile jarfile = juc.getJarFile(); Enumeration enumer = jarfile.entries(); while (enumer.hasMoreElements()) { final JarEntry entry = (JarEntry) enumer.nextElement(); final File f = new File(top, entry.getName()); if (entry.isDirectory()) { f.mkdirs(); } else { if (!entry.getName().startsWith("META-INF")) new Thread(transfers, new Runnable() { public void run() { try { BufferedReader br = new BufferedReader(new InputStreamReader(jarfile.getInputStream(entry))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f))); StringBuffer buf = new StringBuffer(); while (br.ready()) { buf.append(br.read()); } bw.write(buf.toString(), 0, buf.length()); bw.close(); br.close(); } catch (Exception ex) { System.out.println(ex); } } }).start(); } } while (transfers.activeCount() > 0) yield(); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(ReferenceManager.getInstance().getMainFrame(), "Jython libraries installed."); } }); } catch (Exception ex) { ex.printStackTrace(); } }
11
Code Sample 1: public void writeToFile(File out) throws IOException, DocumentException { FileChannel inChannel = new FileInputStream(pdf_file).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void copyFile(String from, String to, boolean append) throws IOException { FileChannel in = new FileInputStream(from).getChannel(); FileChannel out = new FileOutputStream(to, append).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(BSIZE); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } }
11
Code Sample 1: public void setDefaultMailBox(final int domainId, final int userId) { final EmailAddress defaultMailbox = cmDB.getDefaultMailbox(domainId); try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty(defaultMailbox == null ? "domain.setDefaultMailbox" : "domain.updateDefaultMailbox")); if (defaultMailbox == null) { psImpl.setInt(1, domainId); psImpl.setInt(2, userId); } else { psImpl.setInt(1, userId); psImpl.setInt(2, domainId); } psImpl.executeUpdate(); } }); connection.commit(); cmDB.updateDomains(null, null); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } Code Sample 2: public int executeUpdateJT(String sql, Object[][] paramsList) { Connection connection = null; connection = this.getConnection(); try { connection.setAutoCommit(false); } catch (SQLException e1) { e1.printStackTrace(); } PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < paramsList.length; i++) { if (connection != null && !connection.isClosed()) { InputStream is = null; if (paramsList[i].length > 0) { for (int j = 0; j < paramsList[i].length; j++) { Object obj = paramsList[i][j]; if (obj.getClass().equals(Class.forName("java.io.File"))) { File file = (File) obj; is = new FileInputStream(file); preparedStatement.setBinaryStream(j + 1, is, (int) file.length()); } else if (obj.getClass().equals(Class.forName("java.util.Date"))) { java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); preparedStatement.setString(j + 1, sdf.format((Date) obj)); } else { preparedStatement.setObject(j + 1, obj); } } } preparedStatement.executeUpdate(); if (is != null) { is.close(); } ; } } } catch (Exception e) { System.out.println("发生错误,数据回滚!"); e.printStackTrace(); try { connection.rollback(); return 0; } catch (SQLException e1) { e1.printStackTrace(); } } try { connection.commit(); return 1; } catch (SQLException e) { e.printStackTrace(); } finally { try { preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { log.error("未能正确关闭数据库连接!", e); System.out.println("未能正确关闭数据库连接!"); e.printStackTrace(); } } return -1; }
00
Code Sample 1: private static HttpURLConnection getConnection(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Accept", "application/zip;text/html"); return conn; } Code Sample 2: private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; fis = new FileInputStream(src); fos = new FileOutputStream(dst); byte[] buffer = new byte[16384]; int read = 0; while ((read = fis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fis.close(); fos.flush(); fos.close(); }
00
Code Sample 1: public boolean createProject(String projectName, String export) { IProgressMonitor progressMonitor = new NullProgressMonitor(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(projectName); try { if (!project.exists()) { project.create(progressMonitor); } project.open(progressMonitor); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, progressMonitor); IJavaProject javaProject = JavaCore.create(project); IFolder binFolder = project.getFolder("bin"); IFolder outputFolder = project.getFolder(export); if (!binFolder.exists()) { binFolder.create(false, true, null); } javaProject.setOutputLocation(outputFolder.getFullPath(), progressMonitor); List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(); IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall(); LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall); for (LibraryLocation element : locations) { entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null)); } javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null); IFolder sourceFolder = project.getFolder("src"); if (!sourceFolder.exists()) { sourceFolder.create(false, true, null); } IPackageFragmentRoot rootfolder = javaProject.getPackageFragmentRoot(sourceFolder); IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1]; System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length); newEntries[oldEntries.length] = JavaCore.newSourceEntry(rootfolder.getPath()); javaProject.setRawClasspath(newEntries, null); IPackageFragment pack; if (rootfolder.getPackageFragment("") == null) { pack = rootfolder.createPackageFragment("", true, progressMonitor); } else { pack = rootfolder.getPackageFragment(""); } StringBuffer buffer = new StringBuffer(); buffer.append("\n"); buffer.append(source); ICompilationUnit cu = pack.createCompilationUnit("ProcessingApplet.java", buffer.toString(), false, null); return true; } catch (CoreException e) { e.printStackTrace(); } return false; } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, String myImagesBehaviour) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(directoryPath + "images.xml"); SAXBuilder builder = new SAXBuilder(false); try { Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); int i = 0; TIGDataBase.activateTransactions(); while (j.hasNext() && !stop && !cancel) { current = i; i++; Element image = (Element) j.next(); String name = image.getAttributeValue("name"); List categories = image.getChildren("category"); Iterator k = categories.iterator(); if (exists(list, name)) { String pathSrc = directoryPath.concat(name); String pathDst = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase() + File.separator; String folder = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase(); if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.REPLACE_IMAGES"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); TIGDataBase.deleteAsociatedOfImage(idImage); } pathDst = pathDst.concat(name); } if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.ADD_IMAGES"))) { Vector aux = new Vector(); aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); int fileCount = 0; if (aux.size() != 0) { while (aux.size() != 0) { fileCount++; aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.')) + "_" + fileCount); } pathDst = pathDst + name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); name = name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); } else { pathDst = pathDst.concat(name); } } String pathThumbnail = (pathDst.substring(0, pathDst.lastIndexOf("."))).concat("_th.jpg"); File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertImageDB(name.substring(0, name.lastIndexOf('.')), name); int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); while (k.hasNext()) { Element category = (Element) k.next(); int idCategory = TIGDataBase.insertConceptDB(category.getValue()); TIGDataBase.insertAsociatedDB(idCategory, idImage); } } else { errorImages = errorImages + System.getProperty("line.separator") + name; } } TIGDataBase.executeQueries(); current = lengthOfTask; } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public String getSummaryText() { if (summaryText == null) { for (Iterator iter = xdcSources.values().iterator(); iter.hasNext(); ) { XdcSource source = (XdcSource) iter.next(); File packageFile = new File(source.getFile().getParentFile(), "xdc-package.html"); if (packageFile.exists()) { Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { summaryText = buf.substring(pos1 + 6, pos2); } else { summaryText = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); summaryText = ""; } catch (IOException e) { LOG.error(e.getMessage(), e); summaryText = ""; } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } break; } else { summaryText = ""; } } } return summaryText; } Code Sample 2: private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static String tinyUrl(String url) { HttpURLConnection httpURLConnection = null; OutputStream httpOutputStream = null; String responseStr = null; try { URLConnection con = new URL("http://is.gd/api.php?longurl=" + url).openConnection(); if(con != null) { httpURLConnection = (HttpURLConnection)con; } else { return url; } httpURLConnection.setRequestMethod("get"); httpURLConnection.setDoOutput(true); httpOutputStream = httpURLConnection.getOutputStream(); BufferedReader httpBufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); responseStr = HttpHelp.readBufferedContent(httpBufferedReader); if (responseStr != null && responseStr.length() > 0 && responseStr.indexOf("http") != -1) { return responseStr; } } catch(Exception e) { } finally { try { httpOutputStream.close(); httpURLConnection.disconnect(); } catch(Exception e) { } } return url; }
11
Code Sample 1: public static String md5Hash(String inString) throws TopicSpacesException { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(inString.getBytes()); byte[] array = md5.digest(); StringBuffer buf = new StringBuffer(); int len = array.length; for (int i = 0; i < len; i++) { int b = array[i] & 0xFF; buf.append(Integer.toHexString(b)); } return buf.toString(); } catch (Exception x) { throw new TopicSpacesException(x); } } Code Sample 2: public static String makeMD5(String input) throws Exception { String dstr = null; byte[] digest; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); digest = md.digest(); dstr = new BigInteger(1, digest).toString(16); if (dstr.length() % 2 > 0) { dstr = "0" + dstr; } } catch (Exception e) { throw new Exception("Erro inesperado em makeMD5(): " + e.toString(), e); } return dstr; }
00
Code Sample 1: public void run() { try { URL url = new URL("http://pokedev.org/time.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringTokenizer s = new StringTokenizer(in.readLine()); m_day = Integer.parseInt(s.nextToken()); m_hour = Integer.parseInt(s.nextToken()); m_minutes = Integer.parseInt(s.nextToken()); in.close(); } catch (Exception e) { System.out.println("ERROR: Cannot reach time server, reverting to local time"); Calendar cal = Calendar.getInstance(); m_hour = cal.get(Calendar.HOUR_OF_DAY); m_minutes = 0; m_day = 0; } while (m_isRunning) { m_minutes = m_minutes == 59 ? 0 : m_minutes + 1; if (m_minutes == 0) { if (m_hour == 23) { incrementDay(); m_hour = 0; } else { m_hour += 1; } } m_hour = m_hour == 23 ? 0 : m_hour + 1; if (System.currentTimeMillis() - m_lastWeatherUpdate >= 3600000) { generateWeather(); m_lastWeatherUpdate = System.currentTimeMillis(); } try { Thread.sleep(60000); } catch (Exception e) { } } System.out.println("INFO: Time Service stopped"); } Code Sample 2: private String addEqError(EquivalencyException e, int namespaceId) throws SQLException { List l = Arrays.asList(e.getListOfEqErrors()); int size = l.size(); String sql = getClassifyDAO().getStatement(TABLE_KEY, "ADD_CLASSIFY_EQ_ERROR"); PreparedStatement ps = null; conn.setAutoCommit(false); try { deleteCycleError(namespaceId); deleteEqError(namespaceId); long conceptGID1 = -1; long conceptGID2 = -1; ps = conn.prepareStatement(sql); for (int i = 0; i < l.size(); i++) { EqError error = (EqError) l.get(i); ConceptRef ref1 = error.getConcept1(); ConceptRef ref2 = error.getConcept2(); conceptGID1 = getConceptGID(ref1, namespaceId); conceptGID2 = getConceptGID(ref2, namespaceId); ps.setLong(1, conceptGID1); ps.setLong(2, conceptGID2); ps.setInt(3, namespaceId); int result = ps.executeUpdate(); if (result == 0) { throw new SQLException("unable to add eq error: " + sql); } } conn.commit(); return "EquivalencyException: Concept: " + conceptGID1 + " namespaceId: " + namespaceId + " conceptGID2: " + conceptGID2 + ((size > 1) ? "...... more" : ""); } catch (SQLException sqle) { conn.rollback(); throw sqle; } catch (Exception ex) { conn.rollback(); throw toSQLException(ex, "cannot add eq errors"); } finally { conn.setAutoCommit(true); if (ps != null) { ps.close(); } } }
11
Code Sample 1: public static void copyfile(String src, String dst) throws IOException { dst = new File(dst).getAbsolutePath(); new File(new File(dst).getParent()).mkdirs(); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void filter(File source, File destination, MNamespace mNamespace) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(source)); BufferedWriter writer = new BufferedWriter(new FileWriter(destination)); int line = 0; int column = 0; Stack parseStateStack = new Stack(); parseStateStack.push(new ParseState(mNamespace)); for (Iterator i = codePieces.iterator(); i.hasNext(); ) { NamedCodePiece cp = (NamedCodePiece) i.next(); while (line < cp.getStartLine()) { line++; column = 0; writer.write(reader.readLine()); writer.newLine(); } while (column < cp.getStartPosition()) { writer.write(reader.read()); column++; } cp.write(writer, parseStateStack, column); while (line < cp.getEndLine()) { line++; column = 0; reader.readLine(); } while (column < cp.getEndPosition()) { column++; reader.read(); } } String data; while ((data = reader.readLine()) != null) { writer.write(data); writer.newLine(); } reader.close(); writer.close(); }
11
Code Sample 1: void IconmenuItem5_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (getPath() != null && !getPath().equals("")) { jFileChooser1.setCurrentDirectory(new File(getPath())); jFileChooser1.setSelectedFile(new File(getPath())); } if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getPath().lastIndexOf(separator); String imgName = getPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setPath(newPath); if (getDefaultPath() == null || getDefaultPath().equals("")) { String msgString = "E' stata selezionata un'immagine da associare all'IconShape, ma non e' " + "stata selezionata ancora nessun'immagine di default. Imposto quella scelta anche come " + "immagine di default?"; if (JOptionPane.showConfirmDialog(null, msgString.substring(0, Math.min(msgString.length(), getFatherPanel().MAX_DIALOG_MSG_SZ)), "choose one", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { setDefaultPath(newPath); createDefaultImage(); } } createImage(); } } Code Sample 2: private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.close(); }
00
Code Sample 1: @Override public void run() { while (true) { StringBuilder buffer = new StringBuilder(128); buffer.append("insert into DOMAIN ( ").append(LS); buffer.append(" DOMAIN_ID, TOP_DOMAIN_ID, DOMAIN_HREF, ").append(LS); buffer.append(" DOMAIN_RANK, DOMAIN_TYPE, DOMAIN_STATUS, ").append(LS); buffer.append(" DOMAIN_ICO_CREATED, DOMAIN_CDATE ").append(LS); buffer.append(") values ( ").append(LS); buffer.append(" null ,null, ?,").append(LS); buffer.append(" 1, 2, 1, ").append(LS); buffer.append(" 0, now() ").append(LS); buffer.append(") ").append(LS); String sqlInsert = buffer.toString(); boolean isAutoCommit = false; int i = 0; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = ConnHelper.getConnection(); conn.setAutoCommit(isAutoCommit); pstmt = conn.prepareStatement(sqlInsert); for (i = 0; i < 10; i++) { String lock = "" + ((int) (Math.random() * 100000000)) % 100; pstmt.setString(1, lock); pstmt.executeUpdate(); } if (!isAutoCommit) conn.commit(); rs = pstmt.executeQuery("select max(DOMAIN_ID) from DOMAIN"); if (rs.next()) { String str = System.currentTimeMillis() + " " + rs.getLong(1); } } catch (Exception e) { try { if (!isAutoCommit) conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(System.out); } String msg = System.currentTimeMillis() + " " + Thread.currentThread().getName() + " - " + i + " " + e.getMessage() + LS; FileIO.writeToFile("D:/DEAD_LOCK.txt", msg, true, "GBK"); } finally { ConnHelper.close(conn, pstmt, rs); } } } Code Sample 2: private void fillTemplate(String resource, OutputStream outputStream, Map<String, String> replacements) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { for (String key : replacements.keySet()) { String value = replacements.get(key); if (key != null) { line = line.replace(key, value); } } writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); }
00
Code Sample 1: private void sendBinaryFile(File file) throws IOException, CVSException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); if (m_bCompressFiles) { GZIPOutputStream gzipOut = null; InputStream gzipIn = null; File gzipFile = null; try { gzipFile = File.createTempFile("javacvs", "tmp"); gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile))); int b; while ((b = in.read()) != -1) gzipOut.write((byte) b); gzipOut.close(); long gzipLength = gzipFile.length(); sendLine("z" + Long.toString(gzipLength)); gzipIn = new BufferedInputStream(new FileInputStream(gzipFile)); for (long i = 0; i < gzipLength; i++) { b = gzipIn.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } finally { if (gzipOut != null) gzipOut.close(); if (gzipIn != null) gzipIn.close(); if (gzipFile != null) gzipFile.delete(); } } else { long nLength = file.length(); sendLine(Long.toString(nLength)); for (long i = 0; i < nLength; i++) { int b = in.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } Code Sample 2: public String md5sum(String toCompute) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toCompute.getBytes()); java.math.BigInteger hash = new java.math.BigInteger(1, md.digest()); return hash.toString(16); }
00
Code Sample 1: private void insert() throws SQLException, NamingException { Logger logger = getLogger(); if (logger.isDebugEnabled()) { logger.debug("enter - " + getClass().getName() + ".insert()"); } try { if (logger.isInfoEnabled()) { logger.info("insert(): Create new sequencer record for " + getName()); } Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(dataSourceName); conn = ds.getConnection(); conn.setReadOnly(false); stmt = conn.prepareStatement(INSERT_SEQ); stmt.setString(INS_NAME, getName()); stmt.setLong(INS_NEXT_KEY, defaultInterval * 2); stmt.setLong(INS_INTERVAL, defaultInterval); stmt.setLong(INS_UPDATE, System.currentTimeMillis()); try { if (stmt.executeUpdate() != 1) { nextId = -1L; logger.warn("insert(): Failed to create sequencer entry for " + getName() + " (no error message)"); } else if (logger.isInfoEnabled()) { nextId = defaultInterval; nextSeed = defaultInterval * 2; interval = defaultInterval; logger.info("insert(): First ID will be " + nextId); } } catch (SQLException e) { logger.warn("insert(): Error inserting row into database, possible concurrency issue: " + e.getMessage()); if (logger.isDebugEnabled()) { e.printStackTrace(); } nextId = -1L; } if (!conn.getAutoCommit()) { conn.commit(); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException ignore) { } } if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) { } } if (conn != null) { if (!conn.getAutoCommit()) { try { conn.rollback(); } catch (SQLException ignore) { } } try { conn.close(); } catch (SQLException ignore) { } } } } finally { if (logger.isDebugEnabled()) { logger.debug("exit - " + getClass().getName() + ".insert()"); } } } Code Sample 2: protected void discoverFactories() { DataSourceRegistry registry = this; try { ClassLoader loader = DataSetURI.class.getClassLoader(); Enumeration<URL> urls; if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { if (s.trim().length() > 0) { List<String> extensions = null; List<String> mimeTypes = null; String factoryClassName = s; try { Class c = Class.forName(factoryClassName); DataSourceFactory f = (DataSourceFactory) c.newInstance(); try { Method m = c.getMethod("extensions", new Class[0]); extensions = (List<String>) m.invoke(f, new Object[0]); } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { ex.printStackTrace(); } try { Method m = c.getMethod("mimeTypes", new Class[0]); mimeTypes = (List<String>) m.invoke(f, new Object[0]); } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { ex.printStackTrace(); } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } if (extensions != null) { for (String e : extensions) { registry.registerExtension(factoryClassName, e, null); } } if (mimeTypes != null) { for (String m : mimeTypes) { registry.registerMimeType(factoryClassName, m); } } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void testDoPost() throws Exception { URL url = null; url = new URL("http://127.0.0.1:" + connector.getLocalPort() + "/test/dump/info?query=foo"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.addRequestProperty(HttpHeaders.CONTENT_TYPE, MimeTypes.FORM_ENCODED); connection.addRequestProperty(HttpHeaders.CONTENT_LENGTH, "10"); connection.getOutputStream().write("abcd=1234\n".getBytes()); connection.getOutputStream().flush(); connection.connect(); String s0 = IO.toString(connection.getInputStream()); assertTrue(s0.startsWith("<html>")); assertTrue(s0.indexOf("<td>POST</td>") > 0); assertTrue(s0.indexOf("abcd:&nbsp;</th><td>1234") > 0); } Code Sample 2: public String encrypt(String password) { String encrypted_pass = ""; ByteArrayOutputStream output = null; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte byte_array[] = md.digest(); output = new ByteArrayOutputStream(byte_array.length); output.write(byte_array); encrypted_pass = output.toString("UTF-8"); System.out.println("password: " + encrypted_pass); } catch (Exception e) { System.out.println("Exception thrown: " + e.getMessage()); } return encrypted_pass; }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: @HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } }
00
Code Sample 1: public boolean download(URL url, File file) { OutputStream out = null; URLConnection conn = null; InputStream in = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[4096]; int numRead; long numWritten = 0; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; } } catch (Exception e) { System.out.println(e); return false; } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { return false; } } return true; } Code Sample 2: public static String ReadURLString(String str) throws IOException { try { URL url = new URL(str); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); String inputLine; String line = ""; int i = 0; while ((inputLine = in.readLine()) != null) { line += inputLine + "\n"; } is.close(); isr.close(); in.close(); return line; } catch (Exception e) { e.printStackTrace(); } return ""; }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void test2() throws Exception { SpreadsheetDocument document = new SpreadsheetDocument(); Sheet sheet = new Sheet("Planilha 1"); sheet.setLandscape(true); Row row = new Row(); row.setHeight(20); sheet.getMerges().add(new IntegerCellMerge(0, 0, 0, 5)); sheet.getImages().add(new Image(new FileInputStream("D:/image001.jpg"), 0, 0, ImageType.JPEG, 80, 60)); for (int i = 0; i < 10; i++) { Cell cell = new Cell(); cell.setValue("Celula " + i); cell.setBackgroundColor(new Color(192, 192, 192)); cell.setUnderline(true); cell.setBold(true); cell.setItalic(true); cell.setFont("Times New Roman"); cell.setFontSize(10); cell.setFontColor(new Color(255, 0, 0)); Border border = new Border(); border.setWidth(1); border.setColor(new Color(0, 0, 0)); cell.setLeftBorder(border); cell.setTopBorder(border); cell.setRightBorder(border); cell.setBottomBorder(border); row.getCells().add(cell); sheet.getColumnsWith().put(new Integer(i), new Integer(25)); } sheet.getRows().add(row); document.getSheets().add(sheet); FileOutputStream fos = new FileOutputStream("D:/teste2.xls"); SpreadsheetDocumentWriter writer = HSSFSpreadsheetDocumentWriter.getInstance(); writer.write(document, fos); fos.close(); }
11
Code Sample 1: @Test public void testWriteAndRead() throws Exception { JCFS.configureLoopback(dir); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); int i; Vector images = new Vector(); images = dataBase.allImageSearch(); lengthOfTask = images.size() * 2; String directory = directoryPath + "Images" + myDirectory.separator; File newDirectoryFolder = new File(directory); newDirectoryFolder.mkdirs(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); doc = domBuilder.newDocument(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Element dbElement = doc.createElement("dataBase"); for (i = 0; ((i < images.size()) && !stop); i++) { current = i; String element = (String) images.elementAt(i); String pathSrc = "Images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(myDirectory.separator) + 1, pathSrc.length()); String pathDst = directory + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector keyWords = new Vector(); keyWords = dataBase.asociatedConceptSearch((String) images.elementAt(i)); Element imageElement = doc.createElement("image"); Element imageNameElement = doc.createElement("name"); imageNameElement.appendChild(doc.createTextNode(name)); imageElement.appendChild(imageNameElement); for (int j = 0; j < keyWords.size(); j++) { Element keyWordElement = doc.createElement("keyWord"); keyWordElement.appendChild(doc.createTextNode((String) keyWords.elementAt(j))); imageElement.appendChild(keyWordElement); } dbElement.appendChild(imageElement); } try { doc.appendChild(dbElement); File dst = new File(directory.concat("Images")); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF-8")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(bufferWriter); transformer.transform(source, result); bufferWriter.close(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } current = lengthOfTask; }
00
Code Sample 1: public void process(String src, String dest) { try { KanjiDAO kanjiDAO = KanjiDAOFactory.getDAO(); MorphologicalAnalyzer mecab = MorphologicalAnalyzer.getInstance(); if (mecab.isActive()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), "UTF8")); String line; bw.write("// // // \r\n$title=\r\n$singer=\r\n$id=\r\n\r\n + _______ // 0 0 0 0 0 0 0\r\n\r\n"); while ((line = br.readLine()) != null) { System.out.println(line); String segment[] = line.split("//"); String japanese = null; String english = null; if (segment.length > 1) english = segment[1].trim(); if (segment.length > 0) japanese = segment[0].trim().replaceAll(" ", "_"); boolean first = true; if (japanese != null) { ArrayList<ExtractedWord> wordList = mecab.extractWord(japanese); Iterator<ExtractedWord> iter = wordList.iterator(); while (iter.hasNext()) { ExtractedWord word = iter.next(); if (first) { first = false; bw.write("*"); } else bw.write(" "); if (word.isParticle) bw.write("- "); else bw.write("+ "); if (!word.original.equals(word.reading)) { System.out.println("--> " + JapaneseString.toRomaji(word.original) + " / " + JapaneseString.toRomaji(word.reading)); KReading[] kr = ReadingAnalyzer.analyzeReadingStub(word.original, word.reading, kanjiDAO); if (kr != null) { for (int i = 0; i < kr.length; i++) { if (i > 0) bw.write(" "); bw.write(kr[i].kanji); if (kr[i].type != KReading.KANA) { bw.write("|"); bw.write(kr[i].reading); } } } else { bw.write(word.original); bw.write("|"); bw.write(word.reading); } } else { bw.write(word.original); } bw.write(" // \r\n"); } if (english != null) { bw.write(english); bw.write("\r\n"); } bw.write("\r\n"); } } br.close(); bw.close(); } else { System.out.println("Mecab couldn't be initialized"); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { _log.error(nsae, nsae); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } byte[] raw = mDigest.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(raw); }
11
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); StringBuilder hashStringBuf = new StringBuilder("{SHA}"); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { log.error("Error getting password hash - " + nsae.getMessage()); return null; } }
00
Code Sample 1: public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { Log.error(e.getMessage(), e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); } Code Sample 2: private Element getXmlFromGeoNetwork(String urlIn, Session userSession) throws FailedActionException { Element results = null; try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); String cookie = (String) userSession.getAttribute("usercookie.object"); if (cookie != null) conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); } finally { in.close(); } } catch (Exception e) { throw new FailedActionException(FailedActionReason.SYSTEM_ERROR); } return results; }
11
Code Sample 1: public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public void guardarRecordatorio() { try { if (espaciosLlenos()) { guardarCantidad(); String dat = ""; String filenametxt = String.valueOf("recordatorio" + cantidadArchivos + ".txt"); String filenamezip = String.valueOf("recordatorio" + cantidadArchivos + ".zip"); cantidadArchivos++; dat += identificarDato(datoSeleccionado) + "\n"; dat += String.valueOf(mesTemporal) + "\n"; dat += String.valueOf(anoTemporal) + "\n"; dat += horaT.getText() + "\n"; dat += lugarT.getText() + "\n"; dat += actividadT.getText() + "\n"; File archivo = new File(filenametxt); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(dat); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filenamezip); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File(filenametxt); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry(filenametxt); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); JOptionPane.showMessageDialog(null, "El recordatorio ha sido guardado con exito", "Recordatorio Guardado", JOptionPane.INFORMATION_MESSAGE); marco.hide(); marco.dispose(); establecerMarca(); table.clearSelection(); } else JOptionPane.showMessageDialog(null, "Debe llenar los espacios de Hora, Lugar y Actividad", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: public GGProvinces getListProvinces() throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.geo.getListProvinces")); qparams.add(new BasicNameValuePair("key", this.key)); String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGProvinces provinces = JAXB.unmarshal(content, GGProvinces.class); return provinces; } Code Sample 2: public static void main(String args[]) { if (args.length < 1) { System.err.println("usage: java copyURL URL [LocalFile]"); System.exit(1); } try { URL url = new URL(args[0]); System.out.println("Opening connection to " + args[0] + "..."); URLConnection urlC = url.openConnection(); InputStream is = url.openStream(); System.out.print("Copying resource (type: " + urlC.getContentType()); Date date = new Date(urlC.getLastModified()); System.out.flush(); FileOutputStream fos = null; if (args.length < 2) { String localFile = null; StringTokenizer st = new StringTokenizer(url.getFile(), "/"); while (st.hasMoreTokens()) localFile = st.nextToken(); fos = new FileOutputStream(localFile); } else fos = new FileOutputStream(args[1]); int oneChar, count = 0; while ((oneChar = is.read()) != -1) { fos.write(oneChar); count++; } is.close(); fos.close(); System.out.println(count + " byte(s) copied"); } catch (MalformedURLException e) { System.err.println(e.toString()); } catch (IOException e) { System.err.println(e.toString()); } }
11
Code Sample 1: public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } } Code Sample 2: private void copyFile(File sourceFile, File targetFile) { beNice(); dispatchEvent(SynchronizationEventType.FileCopy, sourceFile, targetFile); File temporaryFile = new File(targetFile.getPath().concat(".jnstemp")); while (temporaryFile.exists()) { try { beNice(); temporaryFile.delete(); beNice(); } catch (Exception ex) { } } try { if (targetFile.exists()) { targetFile.delete(); } FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(temporaryFile); byte[] buffer = new byte[204800]; int readBytes = 0; int counter = 0; while ((readBytes = fis.read(buffer)) != -1) { counter++; updateStatus("... processing fragment " + String.valueOf(counter)); fos.write(buffer, 0, readBytes); } fis.close(); fos.close(); temporaryFile.renameTo(targetFile); temporaryFile.setLastModified(sourceFile.lastModified()); targetFile.setLastModified(sourceFile.lastModified()); } catch (IOException e) { Exception dispatchedException = new Exception("ERROR: Copy File( " + sourceFile.getPath() + ", " + targetFile.getPath() + " )"); dispatchEvent(dispatchedException, sourceFile, targetFile); } dispatchEvent(SynchronizationEventType.FileCopyDone, sourceFile, targetFile); }
11
Code Sample 1: private static byte[] getLoginHashSHA(final char[] password, final int seed) throws GGException { try { final MessageDigest hash = MessageDigest.getInstance("SHA1"); hash.update(new String(password).getBytes()); hash.update(GGUtils.intToByte(seed)); return hash.digest(); } catch (final NoSuchAlgorithmException e) { LOG.error("SHA1 algorithm not usable", e); throw new GGException("SHA1 algorithm not usable!", e); } } Code Sample 2: public static String md5(String text) { String encrypted = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); encrypted = hex(md.digest()); } catch (NoSuchAlgorithmException nsaEx) { } return encrypted; }
11
Code Sample 1: @Test public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, null); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); } Code Sample 2: private synchronized Frame addFrame(INSERT_TYPE type, File source) throws IOException { if (source == null) throw new NullPointerException("Parameter 'source' is null"); if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath()); if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath()); File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(frames_.size())); if (newLocation.compareTo(source) != 0) { switch(type) { case MOVE: source.renameTo(newLocation); break; case COPY: FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(newLocation).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); break; } } Frame f = new Frame(newLocation); f.createThumbNail(); frames_.add(f); return f; }
11
Code Sample 1: public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); } Code Sample 2: public void writeFile(String resource, InputStream is) throws IOException { File f = prepareFsReferenceAsFile(resource); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); try { IOUtils.copy(is, bos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); } }
00
Code Sample 1: @Override public void excluir(QuestaoMultiplaEscolha q) throws Exception { PreparedStatement stmt = null; String sql = "DELETE FROM questao WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: private InputStream execute(String filter, String query) { client = new DefaultHttpClient(); String url = getURL(); String trenn = "?"; if (filter != null) { url += trenn + "filter=" + filter; trenn = "&"; } if (query != null) { url += trenn + "query=" + query; } HttpGet get = new HttpGet(url); System.out.println("get: " + url); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); return entity.getContent(); } catch (ClientProtocolException e) { } catch (IOException e) { } return null; }
00
Code Sample 1: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } } Code Sample 2: public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.apache.jasper.runtime.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); String username = "test"; String password = "test"; int providerId = 1; if (request.getParameter("providerId") != null) providerId = Integer.parseInt(request.getParameter("providerId")); String thisPageContextAddress = "http://localhost:8080" + request.getContextPath(); String thisPageServingAddress = thisPageContextAddress + "/index.jsp"; String token = ""; String token_timeout = (String) request.getParameter("token_timeout"); String referer = request.getHeader("Referer"); if (token_timeout != null && token_timeout.equals("true")) { System.out.println("token timeout for referer" + referer); if (referer != null) { if (request.getSession().getServletContext().getAttribute("token_timeout_processing_lock") == null) { request.getSession().getServletContext().setAttribute("token_timeout_processing_lock", true); byte[] buff = null; BufferedInputStream bis = null; URL url = new URL(thisPageContextAddress + "/ServerAdminServlet?action=login&username=" + username + "&password=" + password); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); InputStream in = urlc.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); token = token.replaceAll("[\\r\\f]", ""); token = token.trim(); request.getSession().getServletContext().setAttribute("token", token); out.println(token); request.getSession().getServletContext().removeAttribute("token_timeout_processing_lock"); } else out.println("token_timeout_processing_lock"); } } else { if (request.getSession().getServletContext().getAttribute("token") == null || request.getSession().getServletContext().getAttribute("token").equals("")) { byte[] buff = null; BufferedInputStream bis = null; URL url = new URL(thisPageContextAddress + "/ServerAdminServlet?action=login&username=" + username + "&password=" + password); URLConnection urlc = url.openConnection(); int length = urlc.getContentLength(); InputStream in = urlc.getInputStream(); buff = new byte[length]; int bytesRead = 0; while (bytesRead < length) { bytesRead += in.read(buff, bytesRead, in.available()); } token = new String(buff); token = token.replaceAll("[\\r\\f]", ""); token = token.trim(); request.getSession().getServletContext().setAttribute("token", token); } out.write("\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <title>AJAX test </title>\n"); out.write(" <link rel=\"stylesheet\" href=\"css/default.css\" type=\"text/css\" />\n"); out.write("\n"); out.write(" <script type=\"text/javascript\" src=\"../OpenLayers-2.8/OpenLayers.js\"></script>\n"); out.write(" <script type=\"text/javascript\">\n"); out.write("\n"); out.write(" var map, layer;\n"); out.write("\n"); out.write(" var token = \""); out.print(request.getSession().getServletContext().getAttribute("token")); out.write("\";\n"); out.write("\n"); out.write("\n"); out.write(" function init(){\n"); out.write("\n"); out.write(" OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;\n"); out.write("\n"); out.write(" var options = {\n"); out.write(" maxExtent: new OpenLayers.Bounds(0, 0, 3000000, 9000000),\n"); out.write(" tileSize :new OpenLayers.Size(250, 250),\n"); out.write(" units: 'm',\n"); out.write(" projection: 'EPSG:3006',\n"); out.write(" resolutions : [1.3,2.6,4,6.6,13.2,26.5,66.1,132.3,264.6,793.8,1322.9,2645.8,13229.2,26458.3]\n"); out.write(" }\n"); out.write("\n"); out.write(" map = new OpenLayers.Map('swedenMap', options);\n"); out.write("\n"); out.write(" layer = new OpenLayers.Layer.TMS(\"TMS\", \"http://localhost:8080/WebGISTileServer/TMSServletProxy/\",\n"); out.write(" { layername: token + '/7', type: 'png' });\n"); out.write("\n"); out.write(" map.addLayer(layer);\n"); out.write("\n"); out.write(" map.addControl( new OpenLayers.Control.PanZoom() );\n"); out.write(" map.addControl( new OpenLayers.Control.PanZoomBar() );\n"); out.write(" map.addControl( new OpenLayers.Control.MouseDefaults());\n"); out.write(" map.addControl( new OpenLayers.Control.MousePosition());\n"); out.write("\n"); out.write(" map.setCenter(new OpenLayers.LonLat(555555, 6846027), 2);\n"); out.write(" }\n"); out.write(" </script>\n"); out.write(" </head>\n"); out.write(" <body onload=\"init()\">\n"); out.write("\n"); out.write(" <div id=\"container\">\n"); out.write("\n"); out.write(" <div id=\"header\">\n"); out.write(" <h1 id=\"logo\">\n"); out.write(" <span>ASP</span> MapServices\n"); out.write(" <small>Web mapping. <span>EASY</span></small>\n"); out.write(" </h1>\n"); out.write("\n"); out.write(" <ul id=\"menu\">\n"); out.write(" <li><a href=\"default.html\">Home</a></li>\n"); out.write(" <li><a href=\"demo_world.jsp\">Demonstration</a></li>\n"); out.write(" <li style=\"border-right: none;\"><a href=\"contact.html\">Contact</a></li>\n"); out.write(" </ul>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div id=\"body\">\n"); out.write(" <ul id=\"maps-menu\">\n"); out.write(" <li><a href=\"demo_world.jsp\">World</a></li>\n"); out.write(" <li><a href=\"demo_sweden_rt90.jsp\">Sweden RT90</a></li>\n"); out.write(" <li><a href=\"demo_sweden_sweref99.jsp\">Sweden SWEREF99</a></li>\n"); out.write(" </ul>\n"); out.write("\n"); out.write(" <div id=\"swedenMap\" style=\"height:600px\"></div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </body>\n"); out.write("\n"); out.write("\n"); out.write(" </head>\n"); out.write("\n"); out.write("</html>"); } out.write('\n'); out.write('\n'); } catch (Throwable t) { if (!(t instanceof SkipPageException)) { out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
11
Code Sample 1: public void copyFile2(String src, String dest) throws IOException { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(src); fw = new FileWriter(dest); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(src); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { throw new FileCopyException(src + " " + MM.PHRASES.getPhrase("35")); } catch (IOException ioe) { throw new FileCopyException(MM.PHRASES.getPhrase("36")); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } } Code Sample 2: public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) dir.mkdir(); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public void connect(String method, String data, String urlString, Properties properties, boolean allowredirect) throws Exception { if (urlString != null) { try { url_ = new URL(url_, urlString); } catch (Exception e) { throw new Exception("Invalid URL"); } } try { httpURLConnection_ = (HttpURLConnection) url_.openConnection(siteThread_.getProxy()); httpURLConnection_.setDoInput(true); httpURLConnection_.setDoOutput(true); httpURLConnection_.setUseCaches(false); httpURLConnection_.setRequestMethod(method); httpURLConnection_.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); httpURLConnection_.setInstanceFollowRedirects(allowredirect); if (properties != null) { for (Object propertyKey : properties.keySet()) { String propertyValue = properties.getProperty((String) propertyKey); if (propertyValue.equalsIgnoreCase("Content-Length")) { httpURLConnection_.setFixedLengthStreamingMode(0); } httpURLConnection_.setRequestProperty((String) propertyKey, propertyValue); } } int connectTimeout = httpURLConnection_.getConnectTimeout(); if (data != null) { post(data); } httpURLConnection_.connect(); } catch (Exception e) { throw new Exception("Connection failed with url " + url_); } } Code Sample 2: public void testClickToCallOutDirection() throws Exception { init(); SipCall[] receiverCalls = new SipCall[receiversCount]; receiverCalls[0] = sipPhoneReceivers[0].createSipCall(); receiverCalls[1] = sipPhoneReceivers[1].createSipCall(); receiverCalls[0].listenForIncomingCall(); receiverCalls[1].listenForIncomingCall(); logger.info("Trying to reach url : " + CLICK2DIAL_URL + CLICK2DIAL_PARAMS); URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS); InputStream in = url.openConnection().getInputStream(); byte[] buffer = new byte[10000]; int len = in.read(buffer); String httpResponse = ""; for (int q = 0; q < len; q++) httpResponse += (char) buffer[q]; logger.info("Received the follwing HTTP response: " + httpResponse); receiverCalls[0].waitForIncomingCall(timeout); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.OK, "OK", 0)); receiverCalls[1].waitForIncomingCall(timeout); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.OK, "OK", 0)); assertTrue(receiverCalls[1].waitForAck(timeout)); assertTrue(receiverCalls[0].waitForAck(timeout)); assertTrue(receiverCalls[0].disconnect()); assertTrue(receiverCalls[1].waitForDisconnect(timeout)); assertTrue(receiverCalls[1].respondToDisconnect()); }
00
Code Sample 1: public static String sendGetRequest(String endpoint, String requestParameters) { if (endpoint == null) return null; String result = null; if (endpoint.startsWith("http://")) { try { StringBuffer data = new StringBuffer(); String urlStr = endpoint; if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { Logger.getLogger(HTTPClient.class.getClass().getName()).log(Level.FINE, "Could not connect to URL, is the service online?"); } } return result; } Code Sample 2: private static byte[] tryLoadFile(String path) throws IOException { InputStream in = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); return out.toByteArray(); }
11
Code Sample 1: public static void gunzip(File gzippedFile, File destinationFile) throws IOException { int buffer = 2048; FileInputStream in = new FileInputStream(gzippedFile); GZIPInputStream zipin = new GZIPInputStream(in); byte[] data = new byte[buffer]; FileOutputStream out = new FileOutputStream(destinationFile); int length; while ((length = zipin.read(data, 0, buffer)) != -1) out.write(data, 0, length); out.close(); zipin.close(); } Code Sample 2: public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(imageFile.separator) + 1, path.length())); File imageFile = new File(path); directoryPath = "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, 1).toUpperCase() + imageFile.separator + imageName; File newFile = new File(imagePath); int i = 1; while (newFile.exists()) { imagePath = "." + imageFile.separator + "Images" + imageFile.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); newFile = new File(imagePath); i++; } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); dataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } }
00
Code Sample 1: public boolean loadFile(String inpfile) { if (osmlContainer == null) return false; hApdx.clear(); try { BufferedReader in = null; if (inpfile.indexOf("http://") >= 0) { URL url = null; url = new URL(inpfile); URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStreamReader is = new InputStreamReader(conn.getInputStream()); in = new BufferedReader(is); } else { in = new BufferedReader(new FileReader(inpfile)); } String pline = null; while ((pline = in.readLine()) != null) { StringTokenizer tok = new StringTokenizer(pline, "\t\n\r"); if (tok.countTokens() < 2) continue; String name = tok.nextToken(); String apdx = tok.nextToken(); String note = ""; if (tok.countTokens() > 0) note = tok.nextToken(); if (name.length() == 0 || apdx.length() == 0) continue; OmicElementContainer element = (OmicElementContainer) OmicElementContainer.createContainer(); element.setName(name); element.setNote(note); element.addAppendix(apdx); String keys[] = commaPattern.split(apdx); for (int j = 0; j < keys.length; j++) { ArrayList v = (ArrayList) hApdx.get(keys[j]); if (v == null) v = new ArrayList(); v.add(element); hApdx.put(keys[j], v); } } in.close(); } catch (MalformedURLException mfe) { System.out.println("MalformedURLException"); return false; } catch (IOException ioe) { System.out.println("IOException"); return false; } System.out.println("appendix name list size " + hApdx.size()); if (bElementDirected) { int nCount = 0; ArrayList<OmicElementContainer> omicElementList = osmlContainer.getAllOmicElementContainers(); for (OmicElementContainer element : omicElementList) { String name = element.getName(); String apdx = element.getAppendix(); if (name.length() == 0) continue; String names[] = commaPattern.split(name); String apdxs[] = commaPattern.split(apdx); String list[] = new String[names.length + apdxs.length]; for (int j = 0; j < names.length; j++) list[j] = names[j]; for (int j = 0; j < apdxs.length; j++) list[j + names.length] = apdxs[j]; for (int j = 0; j < list.length; j++) { ArrayList v = (ArrayList) hApdx.get(list[j]); if (v == null) continue; for (int k = 0; k < v.size(); k++) { OmicElementContainer appendix = (OmicElementContainer) v.get(k); element.addAppendix(appendix.getName()); nCount++; } } } System.out.println("match appendix element " + nCount + " items"); } if (bFunctionDirected) { int nCount = 0; FunctionalClassContainer functions[] = osmlContainer.getFunctionalClassContainer("[@container=all]"); ArrayList vFunction = new ArrayList(); for (int i = 0; i < functions.length; i++) { if (!vFunction.contains(functions[i])) vFunction.add(functions[i]); } for (int i = 0; i < vFunction.size(); i++) { FunctionalClassContainer function = (FunctionalClassContainer) vFunction.get(i); String name = function.getName(); if (name.length() == 0) continue; String names[] = name.split(","); for (int j = 0; j < names.length; j++) { ArrayList v = (ArrayList) hApdx.get(names[j]); if (v == null) continue; for (int k = 0; k < v.size(); k++) { OmicElementContainer appendix = (OmicElementContainer) v.get(k); functions[i].addOmicElementContainer(appendix); nCount++; } } } System.out.println("match appendix function " + nCount + " items"); } return true; } Code Sample 2: private void documentFileChooserActionPerformed(java.awt.event.ActionEvent evt) { if (evt.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { File selectedFile = documentFileChooser.getSelectedFile(); File collectionCopyFile; String newDocumentName = selectedFile.getName(); Document newDocument = new Document(newDocumentName); if (activeCollection.containsDocument(newDocument)) { int matchingFilenameDistinguisher = 1; StringBuilder distinguisherReplacer = new StringBuilder(); newDocumentName = newDocumentName.concat("(" + matchingFilenameDistinguisher + ")"); newDocument.setDocumentName(newDocumentName); while (activeCollection.containsDocument(newDocument)) { matchingFilenameDistinguisher++; newDocumentName = distinguisherReplacer.replace(newDocumentName.length() - 2, newDocumentName.length() - 1, new Integer(matchingFilenameDistinguisher).toString()).toString(); newDocument.setDocumentName(newDocumentName); } } Scanner tokenizer = null; FileChannel fileSource = null; FileChannel collectionDestination = null; HashMap<String, Integer> termHashMap = new HashMap<String, Integer>(); Index collectionIndex = activeCollection.getIndex(); int documentTermMaxFrequency = 0; int currentTermFrequency; try { tokenizer = new Scanner(new BufferedReader(new FileReader(selectedFile))); tokenizer.useDelimiter(Pattern.compile("\\p{Space}|\\p{Punct}|\\p{Cntrl}")); String nextToken; while (tokenizer.hasNext()) { nextToken = tokenizer.next().toLowerCase(); if (!nextToken.isEmpty()) if (termHashMap.containsKey(nextToken)) termHashMap.put(nextToken, termHashMap.get(nextToken) + 1); else termHashMap.put(nextToken, 1); } Term newTerm; for (String term : termHashMap.keySet()) { newTerm = new Term(term); if (!collectionIndex.termExists(newTerm)) collectionIndex.addTerm(newTerm); currentTermFrequency = termHashMap.get(term); if (currentTermFrequency > documentTermMaxFrequency) documentTermMaxFrequency = currentTermFrequency; collectionIndex.addOccurence(newTerm, newDocument, currentTermFrequency); } activeCollection.addDocument(newDocument); String userHome = System.getProperty("user.home"); String fileSeparator = System.getProperty("file.separator"); collectionCopyFile = new File(userHome + fileSeparator + "Infrared" + fileSeparator + activeCollection.getDocumentCollectionName() + fileSeparator + newDocumentName); collectionCopyFile.createNewFile(); fileSource = new FileInputStream(selectedFile).getChannel(); collectionDestination = new FileOutputStream(collectionCopyFile).getChannel(); collectionDestination.transferFrom(fileSource, 0, fileSource.size()); } catch (FileNotFoundException e) { System.err.println(e.getMessage() + " This error should never occur! The file was just selected!"); return; } catch (IOException e) { JOptionPane.showMessageDialog(this, "An I/O error occured during file transfer!", "File transfer I/O error", JOptionPane.WARNING_MESSAGE); return; } finally { try { if (tokenizer != null) tokenizer.close(); if (fileSource != null) fileSource.close(); if (collectionDestination != null) collectionDestination.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (evt.getActionCommand().equalsIgnoreCase(JFileChooser.CANCEL_SELECTION)) processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); }
11
Code Sample 1: private static String getHashString(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); MessageDigest md; md = MessageDigest.getInstance(algorithm); md.update(text.getBytes("UTF-8"), 0, text.length()); byte[] hash = md.digest(); return convertToHex(hash); } Code Sample 2: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: public void downloadClicked() { String s_url; try { double minlat = Double.parseDouble(minLat.text()); double maxlat = Double.parseDouble(maxLat.text()); double minlong = Double.parseDouble(minLong.text()); double maxlong = Double.parseDouble(maxLong.text()); s_url = "http://www.openstreetmap.org/api/0.5/map?bbox=" + minlong + "," + minlat + "," + maxlong + "," + maxlat; } catch (Exception e) { QMessageBox.critical(this, "Coordinates Error", "Please check the coordinates entered. Make sure to use proper float values."); return; } try { mylayout.removeWidget(dataWidget); dataWidget.hide(); mylayout.addWidget(downloadWidget, 0, 0, 1, 4); downloadWidget.show(); repaint(); update(); URL url = new URL(s_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); new Osm2Model(con.getInputStream()); mainapp.setStatusbarText("OSM data successful imported", 1000); mainapp.activateMapDisplay(); hide(); } catch (MalformedURLException e) { QMessageBox.critical(this, "OSM import failed", "Data could not be retrieved as download URL is erroneos."); } catch (IOException e) { QMessageBox.critical(this, "OSM import failed", "I/O error, aborting."); } mylayout.removeWidget(downloadWidget); downloadWidget.hide(); mylayout.addWidget(dataWidget, 0, 0, 1, 4); dataWidget.show(); } Code Sample 2: private static InputStream openFileOrURL(String url) throws IOException { if (url.startsWith("resource:")) { return DcmRcv.class.getClassLoader().getResourceAsStream(url.substring(9)); } try { return new URL(url).openStream(); } catch (MalformedURLException e) { return new FileInputStream(url); } }
00
Code Sample 1: public static void downloadFromUrl(URL url, String localFilename, String userAgent) throws IOException { InputStream is = null; FileOutputStream fos = null; System.setProperty("java.net.useSystemProxies", "true"); try { URLConnection urlConn = url.openConnection(); if (userAgent != null) { urlConn.setRequestProperty("User-Agent", userAgent); } is = urlConn.getInputStream(); fos = new FileOutputStream(localFilename); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { try { if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } } Code Sample 2: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public InputStream getResource(FCValue name) throws FCException { Element el = _factory.getElementWithID(name.getAsString()); if (el == null) { throw new FCException("Could not find resource \"" + name + "\""); } String urlString = el.getTextTrim(); if (!urlString.startsWith("http")) { try { log.debug("Get resource: " + urlString); URL url; if (urlString.startsWith("file:")) { url = new URL(urlString); } else { url = getClass().getResource(urlString); } return url.openStream(); } catch (Exception e) { throw new FCException("Failed to load resource.", e); } } else { try { FCService http = getRuntime().getServiceFor(FCService.HTTP_DOWNLOAD); return http.perform(new FCValue[] { name }).getAsInputStream(); } catch (Exception e) { throw new FCException("Failed to load resource.", e); } } }
00
Code Sample 1: public static String getTextFromUrl(final String url) throws IOException { final String lineSeparator = System.getProperty("line.separator"); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line).append(lineSeparator); } return result.toString(); } finally { InputOutputUtil.close(bufferedReader, inputStreamReader); } } Code Sample 2: public static void load(String path) { if (path.length() < 1) { Log.userinfo("Cannot open a file whose name has zero length.", Log.ERROR); } if (!loadtime) { if (path.equals(Globals.getStartupFilePath())) { Log.userinfo("Cannot reload startup file.", Log.ERROR); } } BufferedReader buffReader = null; if (path.indexOf("://") != -1) { URL url = null; try { url = new URL(path); } catch (MalformedURLException e) { Log.userinfo("Malformed URL: \"" + path + "\"", Log.ERROR); } try { String encoding = Toolkit.getDeclaredXMLEncoding(url.openStream()); buffReader = new BufferedReader(new InputStreamReader(url.openStream(), encoding)); } catch (IOException e) { Log.userinfo("I/O error trying to read \"" + path + "\"", Log.ERROR); } } else { if (path.indexOf(ASTERISK) != -1) { String[] files = null; try { files = Toolkit.glob(path, workingDirectory); } catch (FileNotFoundException e) { Log.userinfo(e.getMessage(), Log.ERROR); } if (files != null) { for (int index = 0; index < files.length; index++) { load(files[index]); } return; } } File toRead = new File(path); if (toRead.isAbsolute()) { workingDirectory = toRead.getParent(); } if (loadedFiles.contains(toRead)) { if (loadtime) { return; } } else { loadedFiles.add(toRead); } if (toRead.exists() && !toRead.isDirectory()) { try { String encoding = Toolkit.getDeclaredXMLEncoding(new FileInputStream(path)); buffReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), encoding)); } catch (IOException e) { Log.userinfo("I/O error trying to read \"" + path + "\"", Log.ERROR); return; } if (Globals.isWatcherActive()) { AIMLWatcher.addWatchFile(path); } } else { if (!toRead.exists()) { Log.userinfo("\"" + path + "\" does not exist!", Log.ERROR); } if (toRead.isDirectory()) { Log.userinfo("\"" + path + "\" is a directory!", Log.ERROR); } } } new AIMLReader(path, buffReader, new AIMLLoader(path)).read(); }
00
Code Sample 1: private void prepareQueryResultData(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!WorkDirectory.isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.SINGLE_FILE, zer.getName(), fcopyName, ZipEntryRef.WITH_REL)); } Code Sample 2: public BigInteger calculateMd5(String input) throws FileSystemException { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes()); byte[] messageDigest = digest.digest(); BigInteger bigInt = new BigInteger(1, messageDigest); return bigInt; } catch (Exception e) { throw new FileSystemException(e); } }
00
Code Sample 1: public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "[email protected]", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); } Code Sample 2: public static String cryptoSHA(String _strSrc) { try { BASE64Encoder encoder = new BASE64Encoder(); MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update(_strSrc.getBytes()); byte[] buffer = sha.digest(); return encoder.encode(buffer); } catch (Exception err) { System.out.println(err); } return ""; }
00
Code Sample 1: public int read(String name) { status = STATUS_OK; try { name = name.trim(); if (name.indexOf("://") > 0) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; } Code Sample 2: public static void copy(File srcFile, File destFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); final byte[] buf = new byte[4096]; int read; while ((read = in.read(buf)) >= 0) { out.write(buf, 0, read); } } finally { try { if (in != null) in.close(); } catch (IOException ioe) { } try { if (out != null) out.close(); } catch (IOException ioe) { } } }
11
Code Sample 1: private static void includePodDependencies(Curnit curnit, JarOutputStream jarout) throws IOException { Properties props = new Properties(); Collection<Pod> pods = curnit.getReferencedPods(); for (Pod pod : pods) { PodUuid podId = pod.getPodId(); URL weburl = PodArchiveResolver.getSystemResolver().getUrl(podId); String urlString = ""; if (weburl != null) { String uriPath = weburl.getPath(); String zipPath = CurnitFile.WITHINCURNIT_BASEPATH + uriPath; jarout.putNextEntry(new JarEntry(zipPath)); IOUtils.copy(weburl.openStream(), jarout); jarout.closeEntry(); urlString = CurnitFile.WITHINCURNIT_PROTOCOL + uriPath; } props.put(podId.toString(), urlString); } jarout.putNextEntry(new JarEntry(CurnitFile.PODSREFERENCED_NAME)); props.store(jarout, "pod dependencies"); jarout.closeEntry(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
00
Code Sample 1: private String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_BILL")); pst.setDate(1, new java.sql.Date(bill.getDate().getTime())); pst.setInt(2, bill.getIdAccount()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from bill"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; }
00
Code Sample 1: public boolean isValid(WizardContext context) { if (serviceSelection < 0) { return false; } ServiceReference selection = (ServiceReference) serviceList.getElementAt(serviceSelection); if (selection == null) { return false; } String function = (String) context.getAttribute(ServiceWizard.ATTRIBUTE_FUNCTION); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE_REFERENCE, selection); URL url = selection.getResourceURL(); InputStream inputStream = null; try { inputStream = url.openStream(); InputSource inputSource = new InputSource(inputStream); JdbcService service = ServiceDigester.parseService(inputSource, IsqlToolkit.getSharedEntityResolver()); context.setAttribute(ServiceWizard.ATTRIBUTE_SERVICE, service); return true; } catch (IOException error) { if (!ServiceWizard.FUNCTION_DELETE.equals(function)) { String loc = url.toExternalForm(); String message = messages.format("SelectServiceStep.failed_to_load_service_from_url", loc); context.showErrorDialog(error, message); } else { return true; } } catch (Exception error) { String message = messages.format("SelectServiceStep.service_load_error", url.toExternalForm()); context.showErrorDialog(error, message); } return false; } Code Sample 2: @Override public void readMessages(final Messages messages) throws LocatorException { try { final InputStream in = url.openStream(); try { final Properties properties = new Properties(); properties.load(in); messages.add(locale, properties); } finally { in.close(); } } catch (final IOException e) { throw new LocatorException("Failed to read messages from URL: " + url, e); } }
00
Code Sample 1: private byte[] getBytes(String resource) throws IOException { InputStream is = HttpServletFileDownloadTest.class.getResourceAsStream(resource); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); IOUtils.closeQuietly(is); return out.toByteArray(); } Code Sample 2: public void url2SaveAsFile(String urlStr, String saveAsFileName) throws Exception { URL url = new URL(urlStr); URLConnection uc = url.openConnection(); File f = new File(saveAsFileName); if (!f.exists()) { FileOutputStream fos = new FileOutputStream(f); BufferedInputStream bis = new BufferedInputStream(uc.getInputStream()); byte[] buffer = new byte[4096]; int readCount = 0; while ((readCount = bis.read(buffer)) != -1) { fos.write(buffer, 0, readCount); } fos.flush(); fos.close(); bis.close(); } }
11
Code Sample 1: public static String generateHash(String msg) throws NoSuchAlgorithmException { if (msg == null) { throw new IllegalArgumentException("Input string can not be null"); } MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(msg.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); String hashText = bigInt.toString(16); while (hashText.length() < 32) { hashText = "0" + hashText; } return hashText; } Code Sample 2: private boolean keysMatch(String keyNMinusOne, String keyN) { boolean match = false; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(keyNMinusOne.getBytes()); byte[] hashedBytes = digest.digest(); String encodedHashedKey = new String(com.Ostermiller.util.Base64.encode(hashedBytes)); match = encodedHashedKey.equals(keyN); } catch (NoSuchAlgorithmException e) { } return match; }
00
Code Sample 1: private String encryptUserPassword(int userId, String password) { password = password.trim(); if (password.length() == 0) { return ""; } else { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException ex) { throw new BoardRuntimeException(ex); } md.update(String.valueOf(userId).getBytes()); md.update(password.getBytes()); byte b[] = md.digest(); StringBuffer sb = new StringBuffer(1 + b.length * 2); for (int i = 0; i < b.length; i++) { int ii = b[i]; if (ii < 0) { ii = 256 + ii; } sb.append(getHexadecimalValue2(ii)); } return sb.toString(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void exportGestureSet(List<GestureSet> sets, File file) { try { FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(exportGestureSetsAsStream(sets), outputStream); outputStream.close(); } catch (FileNotFoundException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets. Export File not found.", e); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not export Gesture Sets.", e); } } Code Sample 2: private String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
00
Code Sample 1: protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; } Code Sample 2: public void run() { if (getCommand() == null) throw new IllegalArgumentException("Given command is null!"); if (getSocketProvider() == null) throw new IllegalArgumentException("Given connection is not open!"); if (getCommand() instanceof ListCommand) { try { setReply(ReplyWorker.readReply(getSocketProvider(), true)); setStatus(ReplyWorker.FINISHED); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } return; } else if (getCommand() instanceof RetrieveCommand) { RetrieveCommand retrieveCommand = (RetrieveCommand) getCommand(); if (retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_I || retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Download file: " + retrieveCommand.getFromFile().toString()); FileOutputStream out = null; FileChannel channel = null; if (getDownloadMethod() == RetrieveCommand.FILE_BASED) { out = new FileOutputStream(retrieveCommand.getToFile().getFile()); channel = out.getChannel(); if (retrieveCommand.getResumePosition() != -1) { try { channel.position(retrieveCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } int amount; try { while ((amount = getSocketProvider().read(buffer)) != -1) { if (amount == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); setStatus(ReplyWorker.FINISHED); if (channel != null) channel.close(); if (this.outputPipe != null) this.outputPipe.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for download!"); return; } else if (getCommand() instanceof StoreCommand) { StoreCommand storeCommand = (StoreCommand) getCommand(); if (storeCommand.getToFile().getTransferType().intern() == Command.TYPE_I || storeCommand.getToFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Upload file: " + storeCommand.getFromFile()); InputStream in = storeCommand.getStream(); int amount; int socketWrite; int socketAmount = 0; if (in instanceof FileInputStream) { FileChannel channel = ((FileInputStream) in).getChannel(); if (storeCommand.getResumePosition() != -1) { try { channel.position(storeCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } try { while ((amount = channel.read(buffer)) != -1) { buffer.flip(); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount += socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); channel.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } else { try { while ((amount = in.read(buffer.array())) != -1) { buffer.flip(); buffer.limit(amount); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount = socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); in.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { in.close(); getSocketProvider().close(); } catch (Exception e) { } } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for upload!"); } else throw new IllegalArgumentException("Given command is not supported!"); }
00
Code Sample 1: private void doUpdate(final boolean notifyOnChange) { if (!validServerUrl) { return; } boolean tempBuildClean = true; List failedBuilds = new ArrayList(); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { Matcher matcher = ROW_PARSER_PATTERN.matcher(line); if (matcher.matches() && checkAllProjects) { String project = matcher.group(GROUP_PROJECT); String status = matcher.group(GROUP_STATUS); if (status.equals(MessageUtils.getString("ccOutput.status.failed"))) { tempBuildClean = false; failedBuilds.add(project); } } } } catch (IOException e) { serverReachable = false; if (notifyOnChange) { monitor.notifyServerUnreachable(MessageUtils.getString("error.readError", new String[] { url.toString() })); } return; } if (notifyOnChange && buildClean && !tempBuildClean) { monitor.notifyBuildFailure(MessageUtils.getString("message.buildFailed", new Object[] { failedBuilds.get(0) })); } if (notifyOnChange && !buildClean && tempBuildClean) { monitor.notifyBuildFixed(MessageUtils.getString("message.allBuildsClean")); } buildClean = tempBuildClean; monitor.setStatus(buildClean); serverReachable = true; } Code Sample 2: private InputStream urlToInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", IE); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.connect(); String encoding = conn.getContentEncoding(); if ((encoding != null) && encoding.equalsIgnoreCase("gzip")) return new GZIPInputStream(conn.getInputStream()); else if ((encoding != null) && encoding.equalsIgnoreCase("deflate")) return new InflaterInputStream(conn.getInputStream(), new Inflater(true)); else return conn.getInputStream(); }
11
Code Sample 1: public static void copyFile3(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public static String getMD5(String password) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); String pwd = new BigInteger(1, md5.digest()).toString(16); return pwd; } catch (Exception e) { logger.error(e.getMessage()); } return password; } Code Sample 2: @Override public InputStream getDataStream(int bufferSize) throws IOException { InputStream in = manager == null ? url.openStream() : manager.getResourceInputStream(this); if (in instanceof ByteArrayInputStream || in instanceof BufferedInputStream) { return in; } return bufferSize == 0 ? new BufferedInputStream(in) : new BufferedInputStream(in, bufferSize); }