label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public void writeData(String name, int items, int mznum, int mzscale, long tstart, long tdelta, int[] peaks) { PrintWriter file = getWriter(name + ".txt"); file.println("999 9999"); file.println("Doe, John"); file.println("TEST Lab"); if (mzscale == 1) file.println("PALMS Positive Ion Data"); else if (mzscale == -1) file.println("PALMS Negative Ion Data"); else file.println("PALMS GJIFJIGJ Ion Data"); file.println("TEST Mission"); file.println("1 1"); file.println("1970 01 01 2008 07 09"); file.println("0"); file.println("TIME (UT SECONDS)"); file.println(mznum + 4); for (int i = 0; i < mznum + 4; i++) file.println("1.0"); for (int i = 0; i < mznum + 4; i++) file.println("9.9E29"); file.println("TOTION total MCP signal (electron units)"); file.println("HMASS high mass integral (fraction)"); file.println("UNLIST (unlisted low mass peaks (fraction)"); file.println("UFO unidentified peaks (fraction)"); for (int i = 1; i <= mznum; i++) file.println("MS" + i + " (fraction)"); int header2length = 13; file.println(header2length); for (int i = 0; i < header2length; i++) file.println("1.0"); for (int i = 0; i < header2length; i++) file.println("9.9E29"); file.println("AirCraftTime aircraft time (s)"); file.println("INDEX index ()"); file.println("SCAT scatter (V)"); file.println("JMETER joule meter ()"); file.println("ND neutral density (fraction)"); file.println("SCALEA Mass scale intercept (us)"); file.println("SCALEB mass scale slope (us)"); file.println("NUMPKS number of peaks ()"); file.println("CONF confidence (coded)"); file.println("CAT preliminary category ()"); file.println("AeroDiam aerodynamic diameter (um)"); file.println("AeroDiam1p7 aero diam if density=1.7 (um)"); file.println("TOTBACK total background subtracted (electron units)"); file.println("0"); file.println("0"); String nothing = "0.000000"; for (int i = 0; i < items; i++) { file.println(tstart + (tdelta * i)); file.println(tstart + (tdelta * i) - 3); file.println(i + 1); for (int j = 0; j < 15; j++) file.println(Math.random()); boolean peaked = false; for (int k = 1; k <= mznum; k++) { for (int j = 0; j < peaks.length && !peaked; j++) if (k == peaks[j]) { double randData = (int) (1000000 * (j + 1)); file.println(randData / 1000000); peaked = true; } if (!peaked) file.println(nothing); peaked = false; } } try { Scanner test = new Scanner(f); while (test.hasNext()) { System.out.println(test.nextLine()); } System.out.println("test"); } catch (Exception e) { } file.close(); } Code Sample 2: private void unzipData(ZipFile zipfile, ZipEntry entry) { if (entry.getName().equals("backUpExternalInfo.out")) { File outputFile = new File("temp", entry.getName()); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } try { BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException e) { throw new BackupException(e.getMessage()); } } }
00
Code Sample 1: public static InputStream executePost(String path, Map<String, String> params) throws Exception { HttpPost httpPost = new HttpPost(path); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> param : params.entrySet()) { postParams.add(new BasicNameValuePair(param.getKey(), param.getValue())); } HttpEntity entity = new UrlEncodedFormEntity(postParams, "UTF-8"); httpPost.setEntity(entity); HttpResponse httpResponse = sClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return httpResponse.getEntity().getContent(); } else { return null; } } 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; }
11
Code Sample 1: public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; } Code Sample 2: public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) { if (inputStream == null && out == null) { return false; } try { FileChannel fci = inputStream.getChannel(); FileChannel fco = out.getChannel(); fco.transferFrom(fci, 0, fci.size()); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { FileUtil.safeClose(inputStream); FileUtil.safeClose(out); } }
11
Code Sample 1: private void copyImage(ProjectElement e) throws Exception { String fn = e.getName(); if (!fn.toLowerCase().endsWith(".png")) { if (fn.contains(".")) { fn = fn.substring(0, fn.lastIndexOf('.')) + ".png"; } else { fn += ".png"; } } File img = new File(resFolder, fn); File imgz = new File(resoutFolder.getAbsolutePath(), fn + ".zlib"); boolean copy = true; if (img.exists() && config.containsKey(img.getName())) { long modified = Long.parseLong(config.get(img.getName())); if (modified >= img.lastModified()) { copy = false; } } if (copy) { convertImage(e.getFile(), img); config.put(img.getName(), String.valueOf(img.lastModified())); } DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(imgz))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(img)); int read; while ((read = in.read()) != -1) { out.write(read); } out.close(); in.close(); imageFiles.add(imgz); imageNames.put(imgz, e.getName()); } Code Sample 2: public static File insertFileInto(File zipFile, File toInsert, String targetPath) { Zip64File zip64File = null; try { boolean compress = false; zip64File = new Zip64File(zipFile); FileEntry testEntry = getFileEntry(zip64File, targetPath); if (testEntry != null && testEntry.getMethod() == FileEntry.iMETHOD_DEFLATED) { compress = true; } processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath, toInsert), compress); if (testEntry != null) { log.info("[insertFileInto] Entry exists: " + testEntry.getName()); log.info("[insertFileInto] Will delete this entry before inserting: " + toInsert.getName()); if (!testEntry.isDirectory()) { zip64File.delete(testEntry.getName()); } else { log.info("[insertFileInto] Entry is a directory. " + "Will delete all files contained in this entry and insert " + toInsert.getName() + "and all nested files."); if (!targetPath.contains("/")) { targetPath = targetPath + "/"; } deleteFileEntry(zip64File, testEntry); log.info("[insertFileInto] Entry successfully deleted."); } log.info("[insertFileInto] Writing new Entry: " + targetPath); EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } else { EntryOutputStream out = null; if (!compress) { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_STORED, new Date(toInsert.lastModified())); } else { out = zip64File.openEntryOutputStream(targetPath, FileEntry.iMETHOD_DEFLATED, new Date(toInsert.lastModified())); } if (toInsert.isDirectory()) { out.flush(); out.close(); log.info("[insertFileInto] Finished writing entry: " + targetPath); List<String> containedPaths = normalizePaths(toInsert); List<File> containedFiles = listAllFilesAndFolders(toInsert, new ArrayList<File>()); log.info("[insertFileInto] Added entry is a folder."); log.info("[insertFileInto] Adding all nested files: "); for (int i = 0; i < containedPaths.size(); i++) { File currentFile = containedFiles.get(i); String currentPath = targetPath.replace("/", "") + File.separator + containedPaths.get(i); EntryOutputStream loop_out = null; if (!compress) { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_STORED, new Date(currentFile.lastModified())); } else { loop_out = zip64File.openEntryOutputStream(currentPath, FileEntry.iMETHOD_DEFLATED, new Date(currentFile.lastModified())); } if (currentFile.isFile()) { InputStream loop_in = new FileInputStream(currentFile); IOUtils.copyLarge(loop_in, loop_out); loop_in.close(); } log.info("[insertFileInto] Added: " + currentPath); loop_out.flush(); loop_out.close(); } } else { InputStream in = new FileInputStream(toInsert); IOUtils.copyLarge(in, out); in.close(); out.flush(); out.close(); } } log.info("[insertFileInto] Done! Added " + toInsert.getName() + " to zip."); zip64File.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new File(zip64File.getDiskFile().getFileName()); }
11
Code Sample 1: @Override protected void doFetch(HttpServletRequest request, HttpServletResponse response) throws IOException, GadgetException { if (request.getHeader("If-Modified-Since") != null) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } String host = request.getHeader("Host"); if (!lockedDomainService.isSafeForOpenProxy(host)) { String msg = "Embed request for url " + getParameter(request, URL_PARAM, "") + " made to wrong domain " + host; logger.info(msg); throw new GadgetException(GadgetException.Code.INVALID_PARAMETER, msg); } HttpRequest rcr = buildHttpRequest(request, URL_PARAM); HttpResponse results = requestPipeline.execute(rcr); if (results.isError()) { HttpRequest fallbackRcr = buildHttpRequest(request, FALLBACK_URL_PARAM); if (fallbackRcr != null) { results = requestPipeline.execute(fallbackRcr); } } if (contentRewriterRegistry != null) { try { results = contentRewriterRegistry.rewriteHttpResponse(rcr, results); } catch (RewritingException e) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e); } } for (Map.Entry<String, String> entry : results.getHeaders().entries()) { String name = entry.getKey(); if (!DISALLOWED_RESPONSE_HEADERS.contains(name.toLowerCase())) { response.addHeader(name, entry.getValue()); } } String responseType = results.getHeader("Content-Type"); if (!StringUtils.isEmpty(rcr.getRewriteMimeType())) { String requiredType = rcr.getRewriteMimeType(); if (requiredType.endsWith("/*") && !StringUtils.isEmpty(responseType)) { requiredType = requiredType.substring(0, requiredType.length() - 2); if (!responseType.toLowerCase().startsWith(requiredType.toLowerCase())) { response.setContentType(requiredType); responseType = requiredType; } } else { response.setContentType(requiredType); responseType = requiredType; } } setResponseHeaders(request, response, results); if (results.getHttpStatusCode() != HttpResponse.SC_OK) { response.sendError(results.getHttpStatusCode()); } IOUtils.copy(results.getResponse(), response.getOutputStream()); } Code Sample 2: public void copyToZip(ZipOutputStream zout, String entryName) throws IOException { close(); ZipEntry entry = new ZipEntry(entryName); zout.putNextEntry(entry); if (!isEmpty() && this.tmpFile.exists()) { InputStream in = new FileInputStream(this.tmpFile); IOUtils.copyTo(in, zout); in.close(); } zout.flush(); zout.closeEntry(); delete(); }
11
Code Sample 1: public void sendContent(OutputStream out, Range range, Map map, String string) throws IOException, NotAuthorizedException, BadRequestException { System.out.println("sendContent " + file); RFileInputStream in = new RFileInputStream(file); try { IOUtils.copyLarge(in, out); } finally { in.close(); } } Code Sample 2: private static void createNonCompoundData(String dir, String type) { try { Set s = new HashSet(); File nouns = new File(dir + "index." + type); FileInputStream fis = new FileInputStream(nouns); InputStreamReader reader = new InputStreamReader(fis); StringBuffer sb = new StringBuffer(); int chr = reader.read(); while (chr >= 0) { if (chr == '\n' || chr == '\r') { String line = sb.toString(); if (line.length() > 0) { if (line.charAt(0) != ' ') { String[] spaceSplit = PerlHelp.split(line); if (spaceSplit[0].indexOf('_') < 0) { s.add(spaceSplit[0]); } } } sb.setLength(0); } else { sb.append((char) chr); } chr = reader.read(); } System.out.println(type + " size=" + s.size()); File output = new File(dir + "nonCompound." + type + "s.gz"); FileOutputStream fos = new FileOutputStream(output); GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos)); PrintWriter writer = new PrintWriter(gzos); writer.println("# This file was extracted from WordNet data, the following copyright notice"); writer.println("# from WordNet is attached."); writer.println("#"); writer.println("# This software and database is being provided to you, the LICENSEE, by "); writer.println("# Princeton University under the following license. By obtaining, using "); writer.println("# and/or copying this software and database, you agree that you have "); writer.println("# read, understood, and will comply with these terms and conditions.: "); writer.println("# "); writer.println("# Permission to use, copy, modify and distribute this software and "); writer.println("# database and its documentation for any purpose and without fee or "); writer.println("# royalty is hereby granted, provided that you agree to comply with "); writer.println("# the following copyright notice and statements, including the disclaimer, "); writer.println("# and that the same appear on ALL copies of the software, database and "); writer.println("# documentation, including modifications that you make for internal "); writer.println("# use or for distribution. "); writer.println("# "); writer.println("# WordNet 1.7 Copyright 2001 by Princeton University. All rights reserved. "); writer.println("# "); writer.println("# THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR "); writer.println("# IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON "); writer.println("# UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- "); writer.println("# ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE "); writer.println("# OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT "); writer.println("# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR "); writer.println("# OTHER RIGHTS. "); writer.println("# "); writer.println("# The name of Princeton University or Princeton may not be used in"); writer.println("# advertising or publicity pertaining to distribution of the software"); writer.println("# and/or database. Title to copyright in this software, database and"); writer.println("# any associated documentation shall at all times remain with"); writer.println("# Princeton University and LICENSEE agrees to preserve same. "); for (Iterator i = s.iterator(); i.hasNext(); ) { String mwe = (String) i.next(); writer.println(mwe); } writer.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public Savable loadResource(String name, PrimitiveLoader loader) { Savable objeto = null; URL url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getCompiledExtension()); if (url == null) { url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getPrimitiveExtension()); if (url != null) { try { objeto = loader.loadResource(name, url.openStream()); File file = ResourceLocator.replaceExtension(url, loader.getCompiledExtension()); BinaryExporter.getInstance().save(objeto, file); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } } else { try { objeto = BinaryImporter.getInstance().load(url.openStream()); } catch (IOException e) { e.printStackTrace(); } } return objeto; } Code Sample 2: public int extractDocumentsInternal(DocumentHolder holder, DocumentFactory docFactory) { FTPClient client = new FTPClient(); try { client.connect(site, port == 0 ? 21 : port); client.login(user, password); visitDirectory(client, "", path, holder, docFactory); client.disconnect(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { } return fileCount; }
11
Code Sample 1: public static void createZipFromDataset(String localResourceId, File dataset, File metadata) { CommunicationLogger.warning("System entered ZipFactory"); try { String tmpDir = System.getProperty("java.io.tmpdir"); String outFilename = tmpDir + "/" + localResourceId + ".zip"; CommunicationLogger.warning("File name: " + outFilename); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; FileInputStream in = new FileInputStream(dataset); out.putNextEntry(new ZipEntry(dataset.getName())); int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in = new FileInputStream(metadata); out.putNextEntry(new ZipEntry(metadata.getName())); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.closeEntry(); in.close(); out.close(); } catch (IOException e) { System.out.println("IO EXCEPTION: " + e.getMessage()); } } Code Sample 2: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
00
Code Sample 1: public File download(Show s) throws Exception { Collection<String> exclude = Util.toCollection((List<String>) this.exclude.clone(), Util.nonNullString(s.getExclude()).split(",")); URL url = new URL("http://v3.newzbin.com/search/" + buildQuery(s)); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (!Util.containsNone(line, exclude)) continue; String id = line.split("\",\"", 3)[1]; File downloaded = download(s, id); if (downloaded != null) return downloaded; } return null; } Code Sample 2: public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
11
Code Sample 1: private static boolean genCustomerLocationsFileAndCustomerIndexFile(String completePath, String masterFile, String CustLocationsFileName, String CustIndexFileName) { try { TIntObjectHashMap CustInfoHash = new TIntObjectHashMap(480189, 1); File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC = new FileInputStream(inFile).getChannel(); File outFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel outC1 = new FileOutputStream(outFile1, true).getChannel(); File outFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel outC2 = new FileOutputStream(outFile2, true).getChannel(); int fileSize = (int) inC.size(); int totalNoDataRows = fileSize / 7; for (int i = 1; i <= totalNoDataRows; i++) { ByteBuffer mappedBuffer = ByteBuffer.allocate(7); inC.read(mappedBuffer); mappedBuffer.position(0); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); mappedBuffer.clear(); if (CustInfoHash.containsKey(customer)) { TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); locations.add(i); CustInfoHash.put(customer, locations); } else { TIntArrayList locations = new TIntArrayList(); locations.add(i); CustInfoHash.put(customer, locations); } } int[] customers = CustInfoHash.keys(); Arrays.sort(customers); int count = 1; for (int i = 0; i < customers.length; i++) { int customer = customers[i]; TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); int noRatingsForCust = locations.size(); ByteBuffer outBuf1 = ByteBuffer.allocate(12); outBuf1.putInt(customer); outBuf1.putInt(count); outBuf1.putInt(count + noRatingsForCust - 1); outBuf1.flip(); outC1.write(outBuf1); count += noRatingsForCust; for (int j = 0; j < locations.size(); j++) { ByteBuffer outBuf2 = ByteBuffer.allocate(4); outBuf2.putInt(locations.get(j)); outBuf2.flip(); outC2.write(outBuf2); } } inC.close(); outC1.close(); outC2.close(); return true; } catch (IOException e) { System.err.println(e); return false; } } Code Sample 2: public boolean downloadFile(String sourceFilename, String targetFilename) throws RQLException { checkFtpClient(); InputStream in = null; try { in = ftpClient.retrieveFileStream(sourceFilename); if (in == null) { return false; } FileOutputStream target = new FileOutputStream(targetFilename); IOUtils.copy(in, target); in.close(); target.close(); return ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Download of file with name " + sourceFilename + " via FTP from server " + server + " failed.", ex); } }
11
Code Sample 1: public static void copy(File src, File dest) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } }
11
Code Sample 1: public void executaAlteracoes() { Album album = Album.getAlbum(); Photo[] fotos = album.getFotos(); Photo f; int ultimoFotoID = -1; int albumID = album.getAlbumID(); sucesso = true; PainelWebFotos.setCursorWait(true); albumID = recordAlbumData(album, albumID); sucesso = recordFotoData(fotos, ultimoFotoID, albumID); String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID; File diretorioAlbum = new File(caminhoAlbum); if (!diretorioAlbum.isDirectory()) { if (!diretorioAlbum.mkdir()) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n�o pode ser criado. abortando"); return; } } for (int i = 0; i < fotos.length; i++) { f = fotos[i]; if (f.getCaminhoArquivo().length() > 0) { try { FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel(); FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel(); canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size()); canalOrigem = null; canalDestino = null; } catch (Exception e) { Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e); sucesso = false; } } } prepareThumbsAndFTP(fotos, albumID, caminhoAlbum); prepareExtraFiles(album, caminhoAlbum); fireChangesToGUI(fotos); dispatchAlbum(); PainelWebFotos.setCursorWait(false); } Code Sample 2: public static void copyWithClose(InputStream is, OutputStream os) throws IOException { try { IOUtils.copy(is, os); } catch (IOException ioe) { try { if (os != null) os.close(); } catch (Exception e) { } try { if (is != null) is.close(); } catch (Exception e) { } } }
00
Code Sample 1: public void addUser(String username, String password, String filename) { String data = ""; try { open(filename); MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); data = username + " " + encPasswd + "\r\n"; } try { long length = file.length(); file.seek(length); file.write(data.getBytes()); } catch (IOException ex) { ex.printStackTrace(); } close(); } catch (NoSuchAlgorithmException ex) { } } Code Sample 2: public static void main(String[] argArray) { if (argArray.length == 0) { System.out.println("Usage: java -jar doc-analyzer.jar url | file"); } List<URL> urlList = new LinkedList<URL>(); for (String urlStr : argArray) { if (!(urlStr.startsWith("http") || urlStr.startsWith("file"))) { if (urlStr.indexOf("*") > -1) { if (urlStr.indexOf("**") > -1) { } continue; } else { if (!urlStr.startsWith("/")) { File workDir = new File(System.getProperty("user.dir")); urlStr = workDir.getPath() + "/" + urlStr; } urlStr = "file:" + urlStr; } } try { URL url = new URL(urlStr); urlList.add(url); } catch (MalformedURLException murle) { System.err.println(murle); } } for (URL url : urlList) { try { Document doc = builder.build(url.openStream()); Element element = doc.getRootElement(); Map<String, Long> numberOfElementMap = countElement(element); System.out.println("Overview of tags in '" + url + "':"); for (String elementName : new TreeSet<String>(numberOfElementMap.keySet())) { System.out.println(" " + elementName + ": " + numberOfElementMap.get(elementName)); } } catch (JDOMException jdome) { System.err.println(jdome.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } }
00
Code Sample 1: private void save() { int[] selection = list.getSelectionIndices(); String dir = System.getProperty("user.dir"); for (int i = 0; i < selection.length; i++) { File src = files[selection[i]]; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath(dir); dialog.setFileName(src.getName()); String destination = dialog.open(); if (destination != null) { File dest = new File(destination); try { dest.createNewFile(); FileChannel srcC = new FileInputStream(src).getChannel(); FileChannel destC = new FileOutputStream(dest).getChannel(); destC.transferFrom(srcC, 0, srcC.size()); destC.close(); srcC.close(); updateSaved(selection[i], true); files[selection[i]] = dest; } catch (FileNotFoundException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } catch (IOException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } } } } Code Sample 2: private static void userAuth(String challenge) throws IOException { try { MessageDigest md = MessageDigest.getInstance("BrokenMD4"); String passwd = null; if (System.getProperty("jarsync.password.gui") != null) { JPasswordField pass = new JPasswordField(); JPanel panel = new JPanel(new GridLayout(2, 1)); panel.add(new JLabel("Password:")); panel.add(pass); JOptionPane.showMessageDialog(null, panel, remoteUser + '@' + remoteHost + "'s Password", JOptionPane.QUESTION_MESSAGE); passwd = new String(pass.getPassword()); } else { System.out.print(remoteUser + '@' + remoteHost + "'s password: "); passwd = Util.readLine(System.in); System.out.println(); } md.update(new byte[4]); md.update(passwd.getBytes("US-ASCII")); md.update(challenge.getBytes("US-ASCII")); byte[] response = md.digest(); Util.writeASCII(out, remoteUser + " " + Util.base64(response) + '\n'); out.flush(); } catch (NoSuchAlgorithmException nsae) { throw new IOException("could not create message digest."); } }
11
Code Sample 1: public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } Code Sample 2: public boolean downloadFile(String sourceFilename, String targetFilename) throws RQLException { checkFtpClient(); InputStream in = null; try { in = ftpClient.retrieveFileStream(sourceFilename); if (in == null) { return false; } FileOutputStream target = new FileOutputStream(targetFilename); IOUtils.copy(in, target); in.close(); target.close(); return ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Download of file with name " + sourceFilename + " via FTP from server " + server + " failed.", ex); } }
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 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(); }
00
Code Sample 1: private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { GTLogger.getInstance().error(e); } } catch (FileNotFoundException e) { GTLogger.getInstance().error(e); } } Code Sample 2: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain;charset=UTF-8"); request.setCharacterEncoding("utf-8"); HttpURLConnection httpConn = null; byte[] result = null; try { byte[] bytes = HttpUtil.getHttpURLReturnData(request); if (-1 == bytes.length || 23 > bytes.length) throw new Exception(); MsgPrint.showMsg("========byte length" + bytes.length); String userTag = request.getParameter("userTag"); String isEncrypt = request.getParameter("isEncrypt"); URL httpurl = new URL(ProtocolContanst.TRANSFERS_URL + userTag + "&isEncrypt=" + isEncrypt); httpConn = (HttpURLConnection) httpurl.openConnection(); httpConn.setDoOutput(true); httpConn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); OutputStream outputStream = httpConn.getOutputStream(); outputStream.write(bytes); outputStream.close(); InputStream is = httpConn.getInputStream(); if (0 >= httpConn.getContentLength()) { throw new Exception(); } byte[] resultBytes = new byte[httpConn.getContentLength()]; byte[] tempByte = new byte[1024]; int length = 0; int index = 0; while ((length = is.read(tempByte)) != -1) { System.arraycopy(tempByte, 0, resultBytes, index, length); index += length; } is.close(); result = resultBytes; } catch (Exception e) { } ServletOutputStream sos = response.getOutputStream(); if (null != result) { response.setContentLength(result.length); sos.write(result); } else { response.setContentLength(26); sos.write(new byte[] { 48, 48, 55, -23, 3, 56, 49, 54, 57, 55, 49, 51, 54, 72, 71, 52, 48, 1, 3, 3, 48, 48, 48, 48, 48, 48 }); } sos.flush(); sos.close(); }
00
Code Sample 1: private void saveStateAsLast(URL url) { InputStream sourceStream = null; OutputStream destinationStream = null; File lastBundlesTxt = getLastBundleInfo(); try { try { destinationStream = new FileOutputStream(lastBundlesTxt); sourceStream = url.openStream(); SimpleConfiguratorUtils.transferStreams(sourceStream, destinationStream); } finally { if (destinationStream != null) destinationStream.close(); if (sourceStream != null) sourceStream.close(); } } catch (IOException e) { } } Code Sample 2: public void fillTableValues() { java.util.ArrayList cpool = newgen.presentation.NewGenMain.getAppletInstance().getCataloguingPool(); String xmlreq = AdministrationXMLGenerator.getInstance().getPoolChronologicalSubDivision("4", cpool); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); java.util.List onelist = rootelement.getChildren(); for (int i = 0; i < onelist.size(); i++) { Element rec = (Element) onelist.get(i); Object[] r = new Object[7]; String[] chronolib = new String[2]; chronolib[0] = rec.getChild("ChronologicalSubDivisionId").getText(); chronolib[1] = rec.getChild("LibraryId").getText(); this.chronoid_libid.add(chronolib); r[0] = rec.getChild("ChronologicalSubDivision").getText(); this.dtmSearch.addRow(r); } } catch (Exception e) { System.out.println(e); } }
11
Code Sample 1: private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: protected static boolean copyFile(File src, File dest) { try { if (!dest.exists()) { dest.createNewFile(); } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); byte[] temp = new byte[1024 * 8]; int readSize = 0; do { readSize = fis.read(temp); fos.write(temp, 0, readSize); } while (readSize == temp.length); temp = null; fis.close(); fos.flush(); fos.close(); } catch (Exception e) { return false; } return true; }
00
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: @Override public void writeToContent(Object principal, String uniqueId, InputStream ins) throws IOException, ContentException { if (writable) { URL url = buildURL(uniqueId); URLConnection connection = url.openConnection(); OutputStream outs = connection.getOutputStream(); try { ContentUtil.pipe(ins, outs); } finally { try { outs.close(); } catch (Exception ex) { log.log(Level.WARNING, "unable to close " + url, ex); } } } else { throw new ContentException("not writable"); } }
11
Code Sample 1: static final void saveModule(Module module, DBConnector connector) throws IOException { String type = "pre"; if (module.isPreModule()) type = "pre"; else if (module.isPostModule()) type = "post"; else if (module.isExceptionModule()) type = "exception"; else throw new IllegalArgumentException("Module must be of a known type."); Properties props = module.getState(); Connection con = null; PreparedStatement ps = null; Statement st = null; try { con = connector.getDB(); con.setAutoCommit(false); st = con.createStatement(); st.executeUpdate("DELETE FROM instance where id=" + module.getId()); st.executeUpdate("DELETE FROM instance_property where instance_id=" + module.getId()); ps = con.prepareStatement("INSERT INTO instance VALUES (?, ?, ?, ?)"); ps.setInt(1, module.getId()); ps.setBoolean(2, module.getActive()); ps.setString(3, module.getClass().getName()); ps.setString(4, type); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("INSERT INTO instance_property values(?, ?, ?)"); for (Enumeration<Object> keys = props.keys(); keys.hasMoreElements(); ) { String key = (String) keys.nextElement(); String value = props.getProperty(key); ps.setInt(1, module.getId()); ps.setString(2, key); ps.setString(3, value); ps.addBatch(); } ps.executeBatch(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } throw new IOException(e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (SQLException ignore) { } } if (ps != null) { try { ps.close(); } catch (SQLException ignore) { } } if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } } Code Sample 2: public static boolean update(Orgao orgao) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); String sql = "update orgao set nome = (?) where id_orgao= ?"; pst = c.prepareStatement(sql); pst.setString(1, orgao.getNome()); pst.setInt(2, orgao.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("[OrgaoDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
00
Code Sample 1: public static String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String out = ""; for (int i = 0; i < digest.length; i++) { out += digest[i]; } return out; } catch (NoSuchAlgorithmException e) { System.err.println("Manca l'MD5 (piuttosto strano)"); } return ""; } Code Sample 2: public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
00
Code Sample 1: private void downloadFile(String directory, String fileName) { URL url = null; String urlstr = updateURL + directory + fileName; int position = 0; try { Logger.msg(threadName + "Download new file from " + urlstr); url = new URL(urlstr); URLConnection conn = url.openConnection(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(updateDirectory + System.getProperty("file.separator") + fileName)); int i = in.read(); while (i != -1) { if (isInterrupted()) { setWasInterrupted(); in.close(); out.flush(); out.close(); interrupt(); return; } out.write(i); i = in.read(); position += 1; if (position % 1000 == 0) { Enumeration<DownloadFilesListener> en = listener.elements(); while (en.hasMoreElements()) { DownloadFilesListener currentListener = en.nextElement(); currentListener.progress(1000); } } } Enumeration<DownloadFilesListener> en = listener.elements(); while (en.hasMoreElements()) { DownloadFilesListener currentListener = en.nextElement(); currentListener.progress(1000); } in.close(); out.flush(); out.close(); Logger.msg(threadName + "Saved file " + fileName + " to " + updateDirectory + System.getProperty("file.separator") + fileName); } catch (Exception e) { Logger.err(threadName + "Error (" + e.toString() + ")"); } } Code Sample 2: public JarClassLoader(ClassLoader parent) { super(parent); initLogger(); hmClass = new HashMap<String, Class<?>>(); lstJarFile = new ArrayList<JarFileInfo>(); hsDeleteOnExit = new HashSet<File>(); String sUrlTopJar = null; pd = getClass().getProtectionDomain(); CodeSource cs = pd.getCodeSource(); URL urlTopJar = cs.getLocation(); String protocol = urlTopJar.getProtocol(); JarFileInfo jarFileInfo = null; if ("http".equals(protocol) || "https".equals(protocol)) { try { urlTopJar = new URL("jar:" + urlTopJar + "!/"); JarURLConnection jarCon = (JarURLConnection) urlTopJar.openConnection(); JarFile jarFile = jarCon.getJarFile(); jarFileInfo = new JarFileInfo(jarFile, jarFile.getName(), null, null); logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", urlTopJar, protocol); } catch (Exception e) { logError(LogArea.JAR, "Failure to load HTTP JAR: %s %s", urlTopJar, e.toString()); return; } } if ("file".equals(protocol)) { try { sUrlTopJar = URLDecoder.decode(urlTopJar.getFile(), "UTF-8"); } catch (UnsupportedEncodingException e) { logError(LogArea.JAR, "Failure to decode URL: %s %s", urlTopJar, e.toString()); return; } File fileJar = new File(sUrlTopJar); if (fileJar.isDirectory()) { logInfo(LogArea.JAR, "Loading from exploded directory: %s", sUrlTopJar); return; } try { jarFileInfo = new JarFileInfo(new JarFile(fileJar), fileJar.getName(), null, null); logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", sUrlTopJar, protocol); } catch (IOException e) { logError(LogArea.JAR, "Not a JAR: %s %s", sUrlTopJar, e.toString()); return; } } try { if (jarFileInfo == null) { throw new IOException(String.format("Unknown protocol %s", protocol)); } loadJar(jarFileInfo); } catch (IOException e) { logError(LogArea.JAR, "Not valid URL: %s %s", urlTopJar, e.toString()); return; } checkShading(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { shutdown(); } }); }
00
Code Sample 1: private void process(int optind, String args[]) throws IOException, XMLStreamException { final int srlimit = 500; final QName att_title = new QName("title"); final QName att_sroffset = new QName("sroffset"); String sroffset = null; String srnamespace = null; if (!this.srnamespaces.isEmpty()) { StringBuilder sb = new StringBuilder(); for (Integer i : this.srnamespaces) { if (sb.length() > 0) sb.append("|"); sb.append(String.valueOf(i)); } srnamespace = sb.toString(); } StringBuilder terms = new StringBuilder(); while (optind < args.length) { if (terms.length() > 0) terms.append(" "); terms.append(args[optind++]); } while (true) { String url = this.base_api + "?action=query" + "&list=search" + "&format=xml" + "&srsearch=" + URLEncoder.encode(terms.toString(), "UTF-8") + (srnamespace != null ? "&srnamespace=" + srnamespace : "") + (sroffset == null ? "" : "&sroffset=" + sroffset) + "&srlimit=" + srlimit + "&srwhat=text&srprop=timestamp"; sroffset = null; LOG.info(url); XMLEventReader reader = this.xmlInputFactory.createXMLEventReader(openStream(url)); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement e = event.asStartElement(); String name = e.getName().getLocalPart(); Attribute att = null; if (name.equals("p") && (att = e.getAttributeByName(att_title)) != null) { System.out.println(att.getValue()); } else if (name.equals("search") && (att = e.getAttributeByName(att_sroffset)) != null) { sroffset = att.getValue(); } } } reader.close(); if (sroffset == null) break; } } Code Sample 2: public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); }
11
Code Sample 1: public static String calculateSHA1(String data, String key) throws NoSuchAlgorithmException, UnsupportedEncodingException { data += key; MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(data.getBytes("iso-8859-1"), 0, data.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
00
Code Sample 1: public void run() { FTPClient ftp = null; try { StarkHhDownloaderEtcProperties etcProperties = new StarkHhDownloaderEtcProperties(getUri()); StarkHhDownloaderVarProperties varProperties = new StarkHhDownloaderVarProperties(getUri()); ftp = new FTPClient(); int reply; ftp.connect(etcProperties.getHostname()); log("Connecting to ftp server at " + etcProperties.getHostname() + "."); log("Server replied with '" + ftp.getReplyString() + "'."); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw UserException.newOk("FTP server refused connection."); } log("Connected to server, now logging in."); ftp.login(etcProperties.getUsername(), etcProperties.getPassword()); log("Server replied with '" + ftp.getReplyString() + "'."); List<String> directories = etcProperties.getDirectories(); for (int i = 0; i < directories.size(); i++) { log("Checking the directory '" + directories.get(i) + "'."); boolean found = false; FTPFile[] filesArray = ftp.listFiles(directories.get(i)); List<FTPFile> files = Arrays.asList(filesArray); Collections.sort(files, new Comparator<FTPFile>() { public int compare(FTPFile file1, FTPFile file2) { if (file2.getTimestamp().getTime().equals(file1.getTimestamp().getTime())) { return file2.getName().compareTo(file1.getName()); } else { return file1.getTimestamp().getTime().compareTo(file2.getTimestamp().getTime()); } } }); for (FTPFile file : files) { if (file.getType() == FTPFile.FILE_TYPE && (varProperties.getLastImportDate(i) == null ? true : (file.getTimestamp().getTime().equals(varProperties.getLastImportDate(i).getDate()) ? file.getName().compareTo(varProperties.getLastImportName(i)) < 0 : file.getTimestamp().getTime().after(varProperties.getLastImportDate(i).getDate())))) { String fileName = directories.get(i) + "\\" + file.getName(); if (file.getSize() == 0) { log("Ignoring '" + fileName + "'because it has zero length"); } else { log("Attempting to download '" + fileName + "'."); InputStream is = ftp.retrieveFileStream(fileName); if (is == null) { reply = ftp.getReplyCode(); throw UserException.newOk("Can't download the file '" + file.getName() + "', server says: " + reply + "."); } log("File stream obtained successfully."); hhImporter = new HhDataImportProcess(getContract().getId(), new Long(0), is, fileName + ".df2", file.getSize()); hhImporter.run(); List<VFMessage> messages = hhImporter.getMessages(); hhImporter = null; if (messages.size() > 0) { for (VFMessage message : messages) { log(message.getDescription()); } throw UserException.newInvalidParameter("Problem loading file."); } } if (!ftp.completePendingCommand()) { throw UserException.newOk("Couldn't complete ftp transaction: " + ftp.getReplyString()); } varProperties.setLastImportDate(i, new MonadDate(file.getTimestamp().getTime())); varProperties.setLastImportName(i, file.getName()); found = true; } } if (!found) { log("No new files found."); } } } catch (UserException e) { try { log(e.getVFMessage().getDescription()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (IOException e) { try { log(e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (Throwable e) { try { log("Exception: " + e.getClass().getName() + " Message: " + e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } ChellowLogger.getLogger().logp(Level.SEVERE, "ContextListener", "contextInitialized", "Can't initialize context.", e); } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); log("Logged out."); } catch (IOException ioe) { } catch (ProgrammerException e) { } catch (UserException e) { } } } } Code Sample 2: 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) { } } } }
00
Code Sample 1: public void testManageSources() throws Exception { this.getTestTool().manageSources(this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getModule("Module"), this.getTestSourcesDirectory()); final File implementationDirectory = this.getTestSourcesDirectory(); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); final File specificationDirectory = this.getTestSourcesDirectory(); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("IllegalImplementationSource.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); IOUtils.copy(this.getClass().getResourceAsStream("IllegalSpecificationSource.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); try { this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); Assert.fail("Expected IOException not thrown."); } catch (IOException e) { Assert.assertNotNull(e.getMessage()); System.out.println(e.toString()); } try { this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); Assert.fail("Expected IOException not thrown."); } catch (IOException e) { Assert.assertNotNull(e.getMessage()); System.out.println(e.toString()); } this.getTestTool().setProfile("DOES_NOT_EXIST"); this.getTestTool().manageSources(this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getModule("Module"), this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), this.getTestSourcesDirectory()); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), this.getTestSourcesDirectory()); } Code Sample 2: public boolean delete(int id) { boolean deletionOk = false; Connection conn = null; try { conn = db.getConnection(); conn.setAutoCommit(false); String sql = "DELETE FROM keyphrases WHERE website_id=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); deletionOk = ps.executeUpdate() == 1; ps.close(); sql = "DELETE FROM websites WHERE id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, id); boolean success = ps.executeUpdate() == 1; deletionOk = deletionOk && success; ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException sqle) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException sex) { throw new OsseoFailure("SQL error: roll back failed. ", sex); } throw new OsseoFailure("SQL error: cannot remove website with id " + id + ".", sqle); } finally { db.putConnection(conn); } return deletionOk; }
00
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.debug("Random GUID error: " + e.getMessage()); } 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: private void loadMascotLibrary() { if (isMascotLibraryLoaded) return; try { boolean isLinux = false; boolean isAMD64 = false; String mascotLibraryFile; if (Configurator.getOSName().toLowerCase().contains("linux")) { isLinux = true; } if (Configurator.getOSArch().toLowerCase().contains("amd64")) { isAMD64 = true; } if (isLinux) { if (isAMD64) { mascotLibraryFile = "libmsparserj-64.so"; } else { mascotLibraryFile = "libmsparserj-32.so"; } } else { if (isAMD64) { mascotLibraryFile = "msparserj-64.dll"; } else { mascotLibraryFile = "msparserj-32.dll"; } } logger.warn("Using: " + mascotLibraryFile); URL mascot_lib = MascotDAO.class.getClassLoader().getResource(mascotLibraryFile); if (mascot_lib != null) { logger.debug("Mascot library URL: " + mascot_lib); tmpMascotLibraryFile = File.createTempFile("libmascot.so.", ".tmp", new File(System.getProperty("java.io.tmpdir"))); InputStream in = mascot_lib.openStream(); OutputStream out = new FileOutputStream(tmpMascotLibraryFile); IOUtils.copy(in, out); in.close(); out.close(); System.load(tmpMascotLibraryFile.getAbsolutePath()); isMascotLibraryLoaded = true; } else { throw new ConverterException("Could not load Mascot Library for system: " + Configurator.getOSName() + Configurator.getOSArch()); } } catch (IOException e) { throw new ConverterException("Error loading Mascot library: " + e.getMessage(), e); } }
11
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, "ispyb@esrf.fr", "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 void fileCopy(File inFile, File outFile) { try { FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { System.err.println("Hubo un error de entrada/salida!!!"); } }
11
Code Sample 1: private void pack() { String szImageDir = m_szBasePath + "Images"; File fImageDir = new File(szImageDir); fImageDir.mkdirs(); String ljIcon = System.getProperty("user.home"); ljIcon += System.getProperty("file.separator") + "MochaJournal" + System.getProperty("file.separator") + m_szUsername + System.getProperty("file.separator") + "Cache"; File fUserDir = new File(ljIcon); File[] fIcons = fUserDir.listFiles(); int iSize = fIcons.length; for (int i = 0; i < iSize; i++) { try { File fOutput = new File(fImageDir, fIcons[i].getName()); if (!fOutput.exists()) { fOutput.createNewFile(); FileOutputStream fOut = new FileOutputStream(fOutput); FileInputStream fIn = new FileInputStream(fIcons[i]); while (fIn.available() > 0) fOut.write(fIn.read()); } } catch (IOException e) { System.err.println(e); } } try { FileOutputStream fOut; InputStream fLJIcon = getClass().getResourceAsStream("/org/homedns/krolain/MochaJournal/Images/userinfo.gif"); File fLJOut = new File(fImageDir, "user.gif"); if (!fLJOut.exists()) { fOut = new FileOutputStream(fLJOut); while (fLJIcon.available() > 0) fOut.write(fLJIcon.read()); } fLJIcon = getClass().getResourceAsStream("/org/homedns/krolain/MochaJournal/Images/communitynfo.gif"); fLJOut = new File(fImageDir, "comm.gif"); if (!fLJOut.exists()) { fOut = new FileOutputStream(fLJOut); while (fLJIcon.available() > 0) fOut.write(fLJIcon.read()); } fLJIcon = getClass().getResourceAsStream("/org/homedns/krolain/MochaJournal/Images/icon_private.gif"); fLJOut = new File(fImageDir, "icon_private.gif"); if (!fLJOut.exists()) { fOut = new FileOutputStream(fLJOut); while (fLJIcon.available() > 0) fOut.write(fLJIcon.read()); } fLJIcon = getClass().getResourceAsStream("/org/homedns/krolain/MochaJournal/Images/icon_protected.gif"); fLJOut = new File(fImageDir, "icon_protected.gif"); if (!fLJOut.exists()) { fOut = new FileOutputStream(fLJOut); while (fLJIcon.available() > 0) fOut.write(fLJIcon.read()); } } catch (IOException e) { System.err.println(e); } } Code Sample 2: @Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { in = LOADER.getResourceAsStream(RES_PKG + filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { 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 unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
00
Code Sample 1: private BibtexDatabase importInspireEntries(String key, OutputPrinter frame) { String url = constructUrl(key); try { HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("User-Agent", "Jabref"); InputStream inputStream = conn.getInputStream(); INSPIREBibtexFilterReader reader = new INSPIREBibtexFilterReader(new InputStreamReader(inputStream)); ParserResult pr = BibtexParser.parse(reader); return pr.getDatabase(); } catch (IOException e) { frame.showMessage(Globals.lang("An Exception ocurred while accessing '%0'", url) + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } catch (RuntimeException e) { frame.showMessage(Globals.lang("An Error occurred while fetching from INSPIRE source (%0):", new String[] { url }) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE); } return null; } Code Sample 2: public InputLattice(String file, int type, boolean convertJoinMeet) throws FileNotFoundException, IOException { InputStream latStream = null; labels = new Vector(); upperCoversVector = new Vector(); Vector upperCovers = new Vector(); edgeColors = new Hashtable(); Vector upperCovering = new Vector(); int level = 0; String str; String currentElt = null; String cover = null; boolean first = true; StreamTokenizer in; switch(type) { case FILE: latStream = new FileInputStream(file); break; case STRING: latStream = new StringBufferInputStream(file); break; case URL: URL url = new URL("http", Config.HOST, Config.PORT, "/" + Config.HASSE + "/" + Config.URL_STREAMER + file); System.out.println("url is " + url); URLConnection connection = url.openConnection(); latStream = new DataInputStream(connection.getInputStream()); break; } in = new StreamTokenizer(latStream); in.wordChars('^', '_'); in.wordChars('*', '.'); while (in.nextToken() != StreamTokenizer.TT_EOF) { if (in.ttype == StreamTokenizer.TT_WORD || in.ttype == StreamTokenizer.TT_NUMBER || in.ttype == '"') { if (in.ttype == StreamTokenizer.TT_NUMBER) { str = "" + Math.round(in.nval); } else { str = in.sval; } if (convertJoinMeet && level > 1) { str = stringSubstitute(str, joinStr, joinSign); str = stringSubstitute(str, meetStr, meetSign); } if (level == 1) { name = new String(str); } if (level == 2) { labels.addElement(str); currentElt = str; } if (level == 3) { upperCovers.addElement(str); } if (level == 4) { if (first) { upperCovers.addElement(str); cover = str; first = false; } else { edgeColors.put(new Edge(currentElt, cover), str); } } } if (in.ttype == '(') { level++; if (level == 3) upperCovers = new Vector(); } if (in.ttype == ')') { level--; if (level == 3) first = true; if (level == 2) upperCoversVector.addElement(upperCovers); if (level == 0) { if (latStream != null) latStream.close(); return; } } } }
11
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: public String getDigest(String s) throws Exception { MessageDigest md = MessageDigest.getInstance(hashName); md.update(s.getBytes()); byte[] dig = md.digest(); return Base16.toHexString(dig); }
00
Code Sample 1: public static void copyFile(File in, File out) { int len; byte[] buffer = new byte[1024]; try { FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len); fin.close(); fout.close(); } catch (IOException ex) { } } Code Sample 2: public static void doIt(String action) { int f = -1; Statement s = null; Connection connection = null; try { init(); log.info("<<< Looking up UserTransaction >>>"); UserTransaction usertransaction = (UserTransaction) context.lookup("java:comp/UserTransaction"); log.info("<<< beginning the transaction >>>"); usertransaction.begin(); log.info("<<< Connecting to xadatasource >>>"); connection = xadatasource.getConnection(); log.info("<<< Connected >>>"); s = connection.createStatement(); s.executeUpdate("update testdata set foo=foo + 1 where id=1"); if ((action != null) && action.equals("commit")) { log.info("<<< committing the transaction >>>"); usertransaction.commit(); } else { log.info("<<< rolling back the transaction >>>"); usertransaction.rollback(); } log.info("<<< transaction complete >>>"); } catch (Exception e) { log.error("doIt", e); } finally { try { s.close(); connection.close(); } catch (Exception x) { log.error("problem closing statement/connection", x); } } }
00
Code Sample 1: protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; } Code Sample 2: public final void provisionGSLAM() { try { UUID[] slaUUID = new UUID[] { new UUID("AG-1") }; SLA[] slas = sslamContext.getSLARegistry().getIQuery().getSLA(slaUUID); for (SLA s : slas) { Party[] parties = s.getParties(); System.out.println("SLA Info :::" + s.getUuid().toString()); for (Party p : parties) { System.out.println("Printing gslam_epr value for Party" + p.getId() + "--" + p.getAgreementRole()); System.out.println(parties[0].getPropertyValue(new STND("gslam_epr"))); } } sslamContext.getSLARegistry().getIRegister().register(slas[0], slaUUID, SLAState.OBSERVED); String xmlFile2Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "provision.xml"; String soapAction = ""; URL url; url = new URL(syntaxConverterNegotiationWSURL); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; FileInputStream fin = new FileInputStream(xmlFile2Send); ByteArrayOutputStream bout = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin, bout); fin.close(); byte[] b = bout.toByteArray(); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn.setRequestProperty("SOAPAction", soapAction); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder db; db = factory.newDocumentBuilder(); org.xml.sax.InputSource inStream = new org.xml.sax.InputSource(); inStream.setCharacterStream(new java.io.StringReader(response.toString())); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: GSLAM\n" + "Interface Name: negotiate/coordinage\n" + "Operation Name: Provision\n" + "Input:Type " + "void" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println(response.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (RegistrationFailureException e) { e.printStackTrace(); } catch (SLAManagerContextException e) { e.printStackTrace(); } catch (InvalidUUIDException e) { e.printStackTrace(); } }
00
Code Sample 1: private HashMap<String, GCVote> getVotes(ArrayList<String> waypoints, boolean blnSleepBeforeDownload) { if (blnSleepBeforeDownload) { try { Thread.sleep(PACKET_SLEEP_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } final String strWaypoints = this.join(waypoints, ","); try { String strParameters = URLEncoder.encode("waypoints", "UTF-8") + "=" + URLEncoder.encode(strWaypoints, "UTF-8"); if (this.mstrUsername.length() > 0) { strParameters += "&" + URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(this.mstrUsername, "UTF-8"); if (this.mstrPassword.length() > 0) { strParameters += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(this.mstrPassword, "UTF-8"); } } final URL url = new URL(BASE_URL_GET_VOTE); URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(strParameters); osw.flush(); final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(false); saxParserFactory.setNamespaceAware(true); final SAXParser saxParser = saxParserFactory.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); final GCVoteHandler gcVoteHandler = new GCVoteHandler(); xmlReader.setContentHandler(gcVoteHandler); xmlReader.parse(new InputSource(new InputStreamReader(conn.getInputStream()))); return gcVoteHandler.getVotes(); } catch (Exception e) { e.printStackTrace(); return null; } } Code Sample 2: private void getDownloadLink() throws Exception { status = UploadStatus.GETTINGLINK; NULogger.getLogger().info("Now Getting Download link..."); HttpClient client = new DefaultHttpClient(); HttpGet h = new HttpGet(uploadresponse); h.setHeader("Referer", postURL); if (zShareAccount.loginsuccessful) { h.setHeader("Cookie", zShareAccount.getSidcookie() + ";" + zShareAccount.getMysessioncookie()); } else { h.setHeader("Cookie", sidcookie + ";" + mysessioncookie); } HttpResponse res = client.execute(h); HttpEntity entity = res.getEntity(); linkpage = EntityUtils.toString(entity); linkpage = linkpage.replaceAll("\n", ""); downloadlink = CommonUploaderTasks.parseResponse(linkpage, "value=\"", "\""); deletelink = CommonUploaderTasks.parseResponse(linkpage, "delete.html?", "\""); deletelink = "http://www.zshare.net/delete.html?" + deletelink; downURL = downloadlink; delURL = deletelink; NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink); NULogger.getLogger().log(Level.INFO, "Delete Link : {0}", deletelink); uploadFinished(); }
11
Code Sample 1: private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } } Code Sample 2: public static void concatenateOutput(File[] inputFiles, File outputFile) { int numberOfInputFiles = inputFiles.length; byte lf = (byte) '\n'; try { FileOutputStream fos = new FileOutputStream(outputFile); FileChannel outfc = fos.getChannel(); System.out.println("Processing " + inputFiles[0].getPath()); FileInputStream fis = new FileInputStream(inputFiles[0]); FileChannel infc = fis.getChannel(); int bufferCapacity = 100000; ByteBuffer bb = ByteBuffer.allocate(bufferCapacity); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); for (int f = 1; f < numberOfInputFiles; f++) { System.out.println("Processing " + inputFiles[f].getPath()); fis = new FileInputStream(inputFiles[f]); infc = fis.getChannel(); bb.clear(); int bytesread = infc.read(bb); bb.flip(); byte b = bb.get(); while (b != lf) { b = bb.get(); } outfc.write(bb); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); } outfc.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } }
00
Code Sample 1: @Override public List<WebSearchResult> search(String term) { List<GoogleResult> results = null; try { URL url = new URL(GoogleWebSearch.GOOGLE_URL + URLEncoder.encode(term, GoogleWebSearch.CHARSET)); Reader reader = new InputStreamReader(url.openStream(), GoogleWebSearch.CHARSET); GoogleResponse jsonResults = new Gson().fromJson(reader, GoogleResponse.class); results = jsonResults.getResponseData().getResults(); } catch (Exception e) { e.printStackTrace(); } List<WebSearchResult> googleResults = new ArrayList<WebSearchResult>(); if (results != null) { googleResults.addAll(results); } return googleResults; } Code Sample 2: public static InputStream getInputStream(URL url) throws IOException { if (url.getProtocol().equals("resource")) { Resources res = SpeakReceiver._context.getResources(); String resname = url.getFile(); resname = resname.split("\\.[a-z0-9]{3}")[0]; int id = res.getIdentifier(resname, "raw", "com.l1ghtm4n.text2speech"); if (id == 0) { throw new NotFoundException(); } else return res.openRawResource(id); } else { return url.openStream(); } }
11
Code Sample 1: public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new DocumentListException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); } Code Sample 2: public void putFile(CompoundName file, FileInputStream fileInput) throws IOException { File fullDir = new File(REMOTE_BASE_DIR.getCanonicalPath()); for (int i = 0; i < file.size() - 1; i++) fullDir = new File(fullDir, file.get(i)); fullDir.mkdirs(); File outputFile = new File(fullDir, file.get(file.size() - 1)); FileOutputStream outStream = new FileOutputStream(outputFile); for (int byteIn = fileInput.read(); byteIn != -1; byteIn = fileInput.read()) outStream.write(byteIn); fileInput.close(); outStream.close(); }
00
Code Sample 1: public String getNextObjectId() throws SQLException { long nextserial = 1; String s0 = "lock table serials in exclusive mode"; String s1 = "SELECT nextserial FROM serials WHERE tablename = 'SERVER_OIDS'"; String s2; try { Statement stmt = dbconnect.connection.createStatement(); stmt.executeUpdate(s0); ResultSet rs = stmt.executeQuery(s1); if (!rs.next()) { s2 = "insert into serials (tablename,nextserial) values ('SERVER_OIDS', " + (nextserial) + ")"; } else { nextserial = rs.getLong(1) + 1; s2 = "update serials set nextserial=" + (nextserial) + " where tablename='SERVER_OIDS'"; } stmt.executeUpdate(s2); dbconnect.connection.commit(); rs.close(); stmt.close(); return "" + nextserial; } catch (SQLException e) { dbconnect.connection.rollback(); throw e; } } 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(); } }
00
Code Sample 1: private static void copy(String sourceName, String destName) throws IOException { File source = new File(sourceName); File dest = new File(destName); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public static void main(String[] args) { if (args.length != 2) { printUsage(); } String url = args[0]; String path = args[1]; BufferedReader pbsFileReader = null; try { pbsFileReader = new BufferedReader(new FileReader(path)); } catch (FileNotFoundException ex) { System.err.println("Pbs file " + path + " not found"); System.exit(1); } String line = ""; HttpURLConnection conn = null; BufferedWriter out = null; BufferedReader in = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); while (true) { line = pbsFileReader.readLine(); if (line == null) { break; } out.write(line); out.newLine(); System.err.println(line); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); line = ""; while (true) { line = in.readLine(); if (line == null) { break; } System.out.println(line); } out.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
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: public void run() { try { IOUtils.copy(is, os); os.flush(); } catch (IOException ioe) { logger.error("Unable to copy", ioe); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
11
Code Sample 1: public Object execute(Connection connection) throws JAXRException { RegistryObject registryObject = connection.getRegistryService().getBusinessQueryManager().getRegistryObject(id); if (registryObject instanceof ExtrinsicObject) { ExtrinsicObject extrinsicObject = (ExtrinsicObject) registryObject; DataHandler dataHandler = extrinsicObject.getRepositoryItem(); if (dataHandler != null) { response.setContentType("text/html"); try { PrintWriter out = response.getWriter(); InputStream is = dataHandler.getInputStream(); try { final XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("div"); xmlStreamWriter.writeStartElement("textarea"); xmlStreamWriter.writeAttribute("name", "repositoryItem"); xmlStreamWriter.writeAttribute("class", "xml"); xmlStreamWriter.writeAttribute("style", "display:none"); IOUtils.copy(new XmlInputStreamReader(is), new XmlStreamTextWriter(xmlStreamWriter)); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("script"); xmlStreamWriter.writeAttribute("class", "javascript"); xmlStreamWriter.writeCharacters("dp.SyntaxHighlighter.HighlightAll('repositoryItem');"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } finally { is.close(); } } catch (Throwable ex) { log.error("Error while trying to format repository item " + id, ex); } } else { } } else { } return null; } Code Sample 2: public static int fileUpload(long lngFileSize, InputStream inputStream, String strFilePath, String strFileName) throws IOException { String SEPARATOR = System.getProperty("file.separator"); if (lngFileSize > (10 * 1024 * 1024)) { return -1; } InputStream is = null; FileOutputStream fos = null; try { File dir = new File(strFilePath); if (!dir.exists()) dir.mkdirs(); is = inputStream; fos = new FileOutputStream(new File(strFilePath + SEPARATOR + strFileName)); IOUtils.copy(is, fos); } catch (Exception ex) { return -2; } finally { try { fos.close(); is.close(); } catch (Exception ex2) { } } return 0; }
11
Code Sample 1: public static Properties parse() { try { String userHome = System.getProperty("user.home"); File dsigFolder = new File(userHome, ".dsig"); if (!dsigFolder.exists() && !dsigFolder.mkdir()) { throw new IOException("Could not create .dsig folder in user home directory"); } File settingsFile = new File(dsigFolder, "settings.properties"); if (!settingsFile.exists()) { InputStream is = UserHomeSettingsParser.class.getResourceAsStream("/defaultSettings.properties"); if (is != null) { IOUtils.copy(is, new FileOutputStream(settingsFile)); } } if (settingsFile.exists()) { Properties p = new Properties(); FileInputStream fis = new FileInputStream(settingsFile); p.load(fis); IOUtils.closeQuietly(fis); return p; } } catch (IOException e) { logger.warn("Error while initialize settings", e); } return null; } 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 { closeQuietly(in); closeQuietly(out); } return success; }
11
Code Sample 1: public void run() { FileInputStream src; try { src = new FileInputStream(srcName); } catch (FileNotFoundException e) { e.printStackTrace(); return; } FileOutputStream dest; FileChannel srcC = src.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(BUFFER_SIZE); try { int i = 1; int fileNo = 0; long maxByte = this.maxSize << 10; long nbByte = srcC.size(); long nbFile = (nbByte / maxByte) + 1; for (fileNo = 0; fileNo < nbFile; fileNo++) { long fileByte = 0; String destName = srcName + "_" + fileNo; dest = new FileOutputStream(destName); FileChannel destC = dest.getChannel(); while ((i > 0) && fileByte < maxByte) { i = srcC.read(buf); buf.flip(); fileByte += i; destC.write(buf); buf.compact(); } destC.close(); dest.close(); } } catch (IOException e1) { e1.printStackTrace(); return; } } Code Sample 2: public static void copyFile(File in, File out) throws ObclipseException { try { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } catch (FileNotFoundException e) { Msg.error("The file ''{0}'' to copy does not exist!", e, in.getAbsolutePath()); } catch (IOException e) { Msg.ioException(in, out, e); } }
11
Code Sample 1: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } Code Sample 2: private static String fetchImageViaHttp(URL imgUrl) throws IOException { String sURL = imgUrl.toString(); String imgFile = imgUrl.getPath(); HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection(); String uri = null; try { cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("Cache-Control", "no-cache"); RequestContext ctx = RequestContext.get(); if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent); cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1)); cnx.connect(); if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null; InputStream imgData = cnx.getInputStream(); String ext = FilenameUtils.getExtension(imgFile).toLowerCase(); if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg"; uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext; File fileDest = new File(img_path + uri); if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(fileDest); try { IOUtils.copy(imgData, fos); } finally { IOUtils.closeQuietly(imgData); IOUtils.closeQuietly(fos); } } finally { cnx.disconnect(); } return RequestContext.get().contextPath() + "/uploads/img/" + uri; }
00
Code Sample 1: public boolean load() { if (getFilename() != null && getFilename().length() > 0) { try { File file = new File(PreferencesManager.loadDirectoryLocation("macros") + File.separator + getFilename()); URL url = file.toURL(); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); String macro_text = ""; while (line != null) { macro_text = macro_text.concat(line); line = br.readLine(); if (line != null) { macro_text = macro_text.concat(System.getProperty("line.separator")); } } code = macro_text; } catch (Exception e) { System.err.println("Exception at StoredMacro.load(): " + e.toString()); return false; } } return true; } Code Sample 2: public static List<String> retrieveLanguages() throws Exception { List<String> result = new ArrayList<String>(); URL url = new URL("http://translatewiki.net/w/i.php?title=Special:MessageGroupStats&group=out-osm-site"); String str = StreamUtil.toString(url.openStream()); Pattern pattern = Pattern.compile(".*language=([^;\"]+).*"); Matcher m = pattern.matcher(str); while (m.find()) { String lang = m.group(1); if (!result.contains(lang)) { result.add(lang); } } return result; }
11
Code Sample 1: public static void appendFile(String namePrefix, File baseDir, File file, ZipOutputStream zipOut) throws IOException { Assert.Arg.notNull(baseDir, "baseDir"); Assert.Arg.notNull(file, "file"); Assert.Arg.notNull(zipOut, "zipOut"); if (namePrefix == null) namePrefix = ""; String path = FileSystemUtils.getRelativePath(baseDir, file); ZipEntry zipEntry = new ZipEntry(namePrefix + path); zipOut.putNextEntry(zipEntry); InputStream fileInput = FileUtils.openInputStream(file); try { org.apache.commons.io.IOUtils.copyLarge(fileInput, zipOut); } finally { fileInput.close(); } } Code Sample 2: protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try { boolean isMultipart = FileUpload.isMultipartContent(request); Store storeInstance = getStoreInstance(request); if (isMultipart) { Map fields = new HashMap(); Vector files = new Vector(); List items = diskFileUpload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); files.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } if (files.size() > 0) { storeInstance.send(files, 0, Charset.defaultCharset().displayName()); } } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
00
Code Sample 1: protected String getHashCode(String value) { if (log.isDebugEnabled()) log.debug("getHashCode(...) -> begin"); String retVal = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(value.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; i++) { sb.append(this.toHexString(digest[i])); } retVal = sb.toString(); if (log.isDebugEnabled()) log.debug("getHashCode(...) -> hashcode = " + retVal); } catch (Exception e) { log.error("getHashCode(...) -> error occured generating hashcode ", e); } if (log.isDebugEnabled()) log.debug("getHashCode(...) -> end"); return retVal; } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
00
Code Sample 1: private void getInfoFromXML() { final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true); setProgressBarIndeterminateVisibility(true); Thread t3 = new Thread() { public void run() { waiting(200); txtinfo.post(new Runnable() { public void run() { txtinfo.setText("Searching"); } }); try { URL url = new URL(urlAddress); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); XMLHandlerReviews myXMLHandler = new XMLHandlerReviews(); xr.setContentHandler(myXMLHandler); xr.parse(new InputSource(url.openStream())); if (statuscode != 200 && statuscode != 206) { throw new Exception(); } nReviewsOnPage = myXMLHandler.nItems; statuscode = myXMLHandler.statuscode; if (nReviewsOnPage > 0) { authors = new String[nReviewsOnPage]; reviews = new String[nReviewsOnPage]; ratings = new String[nReviewsOnPage]; titles = new String[nReviewsOnPage]; listtext = new String[nReviewsOnPage]; for (int i = 0; i < nReviewsOnPage; i++) { reviews[i] = myXMLHandler.reviews[i]; authors[i] = myXMLHandler.authors[i]; titles[i] = myXMLHandler.titles[i]; ratings[i] = myXMLHandler.ratings[i]; if (authors[i] == null || authors[i] == "") { authors[i] = "Anonymous"; } if (ratings[i] == null || ratings[i] == "") { listtext[i] = titles[i] + " - " + reviews[i] + " - " + authors[i]; } else { listtext[i] = "Score: " + ratings[i] + " - " + titles[i] + " - " + reviews[i] + " - " + authors[i]; } } nTotalReviews = myXMLHandler.nTotalItems; final int fnmin = iFirstReviewOnPage; final int fnmax = iFirstReviewOnPage + nReviewsOnPage - 1; final int fntotalitems = nTotalReviews; if (nTotalReviews > fnmax) { nextButton.post(new Runnable() { public void run() { nextButton.setVisibility(0); } }); } else { nextButton.post(new Runnable() { public void run() { nextButton.setVisibility(8); } }); } if (iFirstReviewOnPage > 1) { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(0); } }); } else if (nTotalReviews > fnmax) { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(8); } }); } else { previousButton.post(new Runnable() { public void run() { previousButton.setVisibility(4); } }); } txtinfo.post(new Runnable() { public void run() { if (title != null && title != "") { txtinfo.setText(title + "\n" + getString(R.string.showing) + " " + fnmin + " " + getString(R.string.through) + " " + fnmax + " " + getString(R.string.of) + " " + fntotalitems); } else { txtinfo.setText(getString(R.string.showing) + " " + fnmin + " " + getString(R.string.through) + " " + fnmax + " " + getString(R.string.of) + " " + fntotalitems); } } }); handlerSetList.sendEmptyMessage(0); } else { txtinfo.post(new Runnable() { public void run() { txtinfo.setText(title + getString(R.string.no_reviews_for_this_album)); } }); } } catch (Exception e) { final Exception ef = e; txtinfo.post(new Runnable() { public void run() { txtinfo.setText(R.string.search_failed); } }); } dialog.dismiss(); handlerDoneLoading.sendEmptyMessage(0); } }; t3.start(); } Code Sample 2: public long copyFile(String baseDirStr, String fileName, String file2FullPath) throws Exception { long plussQuotaSize = 0; if (!baseDirStr.endsWith(sep)) { baseDirStr += sep; } BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; String file1FullPath = new String(baseDirStr + fileName); if (!file1FullPath.equalsIgnoreCase(file2FullPath)) { File file1 = new File(file1FullPath); if (file1.exists() && (file1.isFile())) { File file2 = new File(file2FullPath); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } else { throw new Exception("Source file not exist ! file1FullPath = (" + file1FullPath + ")"); } } return plussQuotaSize; }
00
Code Sample 1: public void executeRequest(OperationContext context) throws Throwable { long t1 = System.currentTimeMillis(); GetPortrayMapCapabilitiesParams params = context.getRequestOptions().getGetPortrayMapCapabilitiesOptions(); String srvCfg = context.getRequestContext().getApplicationConfiguration().getCatalogConfiguration().getParameters().getValue("openls.portrayMap"); String sUrl = srvCfg + "?f=json&pretty=true"; URL url = new URL(sUrl); URLConnection conn = url.openConnection(); String line = ""; String sResponse = ""; InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader rd = new BufferedReader(isr); while ((line = rd.readLine()) != null) { sResponse += line; } rd.close(); parseResponse(params, sResponse); long t2 = System.currentTimeMillis(); LOGGER.info("PERFORMANCE: " + (t2 - t1) + " ms spent performing service"); } 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(); } } }
11
Code Sample 1: public static void CreateBackupOfDataFile(String _src, String _dest) { try { File src = new File(_src); File dest = new File(_dest); if (new File(_src).exists()) { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
11
Code Sample 1: public static String getSignature(String s) { try { final AsciiEncoder coder = new AsciiEncoder(); final MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(s.getBytes("UTF-8")); final byte[] digest = msgDigest.digest(); return coder.encode(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalStateException(); } } Code Sample 2: public RespID(PublicKey key) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString keyHash = new DEROctetString(digest.digest()); this.id = new ResponderID(keyHash); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
00
Code Sample 1: public WordEntry[] getVariants(String word) throws MatchPackException { String upperWord = word.toUpperCase(); if (variantsDictionary == null) { try { long start = System.currentTimeMillis(); URL url = this.getClass().getResource("varlex.dic"); ObjectInputStream si = new ObjectInputStream(url.openStream()); variantsDictionary = (Map) si.readObject(); long end = System.currentTimeMillis(); System.out.println("loaded " + (end - start) + "ms"); si.close(); } catch (Exception e) { throw new MatchPackException("cannot load: varlex.dic " + e.getMessage()); } } List l = (List) variantsDictionary.get(upperWord); if (l == null) { return new WordEntry[0]; } return (WordEntry[]) l.toArray(new WordEntry[0]); } Code Sample 2: private static String connect(String apiURL, boolean secure) throws IOException { String baseUrl; if (secure) baseUrl = "https://todoist.com/API/"; else baseUrl = "http://todoist.com/API/"; URL url = new URL(baseUrl + apiURL); URLConnection c = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder toReturn = new StringBuilder(""); String toAppend; while ((toAppend = in.readLine()) != null) toReturn.append(toAppend); return toReturn.toString(); }
11
Code Sample 1: private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } 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 copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); }
00
Code Sample 1: public void testRoundTrip_1(String resource) throws Exception { long start1 = System.currentTimeMillis(); File originalFile = File.createTempFile("RoundTripTest", "testRoundTrip_1"); FileOutputStream fos = new FileOutputStream(originalFile); IOUtils.copy(getClass().getResourceAsStream(resource), fos); fos.close(); long start2 = System.currentTimeMillis(); IsoFile isoFile = new IsoFile(new FileInputStream(originalFile).getChannel()); long start3 = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel wbc = Channels.newChannel(baos); long start4 = System.currentTimeMillis(); Walk.through(isoFile); long start5 = System.currentTimeMillis(); isoFile.getBox(wbc); wbc.close(); long start6 = System.currentTimeMillis(); System.err.println("Preparing tmp copy took: " + (start2 - start1) + "ms"); System.err.println("Parsing took : " + (start3 - start2) + "ms"); System.err.println("Writing took : " + (start6 - start3) + "ms"); System.err.println("Walking took : " + (start5 - start4) + "ms"); byte[] a = IOUtils.toByteArray(getClass().getResourceAsStream(resource)); byte[] b = baos.toByteArray(); Assert.assertArrayEquals(a, b); } Code Sample 2: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
00
Code Sample 1: private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: public synchronized String encrypt(String plaintext) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.reset(); md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
11
Code Sample 1: private String convert(InputStream input, String encoding) throws Exception { Process p = Runtime.getRuntime().exec("tidy -q -f /dev/null -wrap 0 --output-xml yes --doctype omit --force-output true --new-empty-tags " + emptyTags + " --quote-nbsp no -utf8"); Thread t = new CopyThread(input, p.getOutputStream()); t.start(); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(p.getInputStream(), output); p.waitFor(); t.join(); return output.toString(); } Code Sample 2: private byte[] digestFile(File file, MessageDigest digest) throws IOException { DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest); IOUtils.copy(in, new NullOutputStream()); in.close(); return in.getMessageDigest().digest(); }
00
Code Sample 1: public static String encryptSHA(String pwd) throws NoSuchAlgorithmException { MessageDigest d = java.security.MessageDigest.getInstance("SHA-1"); d.reset(); d.update(pwd.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(d.digest()); } Code Sample 2: public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; }
00
Code Sample 1: public static String md5Encode(String pass) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); return bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La librería java.security no implemente MD5"); } } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
00
Code Sample 1: public void delete(Channel channel) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(channel.getPath(), "1", connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); String sqlStr = "delete from t_ip_channel where channel_path=?"; preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); sqlStr = "delete from t_ip_channel_order where channel_order_site = ?"; preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException ex) { connection.rollback(); log.error("ɾ��Ƶ��ʧ�ܣ�channelPath=" + channel.getPath(), ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } } 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 crypt(String password, String salt) throws java.security.NoSuchAlgorithmException { int saltEnd; int len; int value; int i; MessageDigest hash1; MessageDigest hash2; byte[] digest; byte[] passwordBytes; byte[] saltBytes; StringBuffer result; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if ((saltEnd = salt.indexOf('$')) != -1) { salt = salt.substring(0, saltEnd); } if (salt.length() > 8) { salt = salt.substring(0, 8); } hash1 = MessageDigest.getInstance("MD5"); hash1.update(password.getBytes()); hash1.update(magic.getBytes()); hash1.update(salt.getBytes()); hash2 = MessageDigest.getInstance("MD5"); hash2.update(password.getBytes()); hash2.update(salt.getBytes()); hash2.update(password.getBytes()); digest = hash2.digest(); for (len = password.length(); len > 0; len -= 16) { hash1.update(digest, 0, len > 16 ? 16 : len); } passwordBytes = password.getBytes(); for (i = password.length(); i > 0; i >>= 1) { if ((i & 1) == 1) { hash1.update((byte) 0); } else { hash1.update(passwordBytes, 0, 1); } } result = new StringBuffer(magic); result.append(salt); result.append("$"); digest = hash1.digest(); saltBytes = salt.getBytes(); for (i = 0; i < 1000; i++) { hash2.reset(); if ((i & 1) == 1) { hash2.update(passwordBytes); } else { hash2.update(digest); } if (i % 3 != 0) { hash2.update(saltBytes); } if (i % 7 != 0) { hash2.update(passwordBytes); } if ((i & 1) != 0) { hash2.update(digest); } else { hash2.update(passwordBytes); } digest = hash2.digest(); } value = ((digest[0] & 0xff) << 16) | ((digest[6] & 0xff) << 8) | (digest[12] & 0xff); result.append(to64(value, 4)); value = ((digest[1] & 0xff) << 16) | ((digest[7] & 0xff) << 8) | (digest[13] & 0xff); result.append(to64(value, 4)); value = ((digest[2] & 0xff) << 16) | ((digest[8] & 0xff) << 8) | (digest[14] & 0xff); result.append(to64(value, 4)); value = ((digest[3] & 0xff) << 16) | ((digest[9] & 0xff) << 8) | (digest[15] & 0xff); result.append(to64(value, 4)); value = ((digest[4] & 0xff) << 16) | ((digest[10] & 0xff) << 8) | (digest[5] & 0xff); result.append(to64(value, 4)); value = digest[11] & 0xff; result.append(to64(value, 2)); return result.toString(); } Code Sample 2: private List<Token> generateTokens(int tokenCount) throws XSServiceException { final List<Token> tokens = new ArrayList<Token>(tokenCount); final Random r = new Random(); String t = Long.toString(new Date().getTime()) + Integer.toString(r.nextInt()); final MessageDigest m; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new XSServiceException("Error while creating tokens"); } for (int i = 0; i < tokenCount; ++i) { final Token token = new Token(); token.setValid(true); m.update(t.getBytes(), 0, t.length()); String md5 = new BigInteger(1, m.digest()).toString(16); while (md5.length() < 32) { md5 = String.valueOf(r.nextInt(9)) + md5; } t = md5.substring(0, 8) + "-" + md5.substring(8, 16) + "-" + md5.substring(16, 24) + "-" + md5.substring(24, 32); logger.debug("Generated token #" + (i + 1) + ": " + t); token.setTokenString(t); tokens.add(token); } return tokens; }
00
Code Sample 1: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("GET REQUEST OR RESPONSE - Send content: " + file.getAbsolutePath()); FileInputStream in = null; try { in = new FileInputStream(file); int bytes = IOUtils.copy(in, out); LOGGER.debug("wrote bytes: " + bytes); out.flush(); } finally { IOUtils.closeQuietly(in); } } Code Sample 2: public String getHTTPContent(String sUrl, String encode, String cookie, String host, String referer) { HttpURLConnection connection = null; InputStream in = null; StringBuffer strResult = new StringBuffer(); try { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); if (!isStringNull(host)) this.setHttpInfo(connection, cookie, host, referer); connection.connect(); int httpStatus = connection.getResponseCode(); if (httpStatus != 200) log.info("getHTTPConent error httpStatus - " + httpStatus); in = new BufferedInputStream(connection.getInputStream()); String inputLine = null; byte[] b = new byte[40960]; int len = 0; while ((len = in.read(b)) > 0) { inputLine = new String(b, 0, len, encode); strResult.append(inputLine.replaceAll("[\t\n\r ]", " ")); } in.close(); } catch (IOException e) { log.warn("SpiderUtil getHTTPConent IOException -> ", e); } finally { if (in != null) try { in.close(); } catch (IOException e) { } } return strResult.toString(); }
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 transfer(File src, File dest, boolean removeSrc) throws FileNotFoundException, IOException { Log.warning("source: " + src); Log.warning("dest: " + dest); if (!src.canRead()) { throw new IOException("can not read src file: " + src); } if (!dest.getParentFile().isDirectory()) { if (!dest.getParentFile().mkdirs()) { throw new IOException("failed to make directories: " + dest.getParent()); } } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); Log.warning("starting transfer from position " + fcin.position() + " to size " + fcin.size()); fcout.transferFrom(fcin, 0, fcin.size()); Log.warning("closing streams and channels"); fcin.close(); fcout.close(); fis.close(); fos.close(); if (removeSrc) { Log.warning("deleting file " + src); src.delete(); } }
00
Code Sample 1: private void getDirectories() throws IOException { if (user == null || ukey == null) { System.out.println("user and or ukey null"); } if (directories != null) { if (directories.length != 0) { System.out.println("directories already present"); return; } } HttpPost requestdirectories = new HttpPost(GET_DIRECTORIES_KEY_URL + "?ukey=" + ukey.getValue() + "&user=" + user.getValue()); HttpResponse dirResponse = getHttpClient().execute(requestdirectories); String ds = EntityUtils.toString(dirResponse.getEntity()); dirResponse.getEntity().consumeContent(); getDirectories(ds); } Code Sample 2: public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); }
00
Code Sample 1: @Override public synchronized void deletePersistenceQueryStatistics(Integer elementId, String contextName, String project, String name, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getPersistenceQueryStatisticsSchemaAndTableName() + " FROM " + this.getPersistenceQueryStatisticsSchemaAndTableName() + " INNER JOIN " + this.getPersistenceQueryElementsSchemaAndTableName() + " ON " + this.getPersistenceQueryElementsSchemaAndTableName() + ".element_id = " + this.getPersistenceQueryStatisticsSchemaAndTableName() + ".element_id WHERE "; if (elementId != null) { queryString = queryString + " elementId = ? AND "; } if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if ((project != null)) { queryString = queryString + " project LIKE ? AND "; } if ((name != null)) { queryString = queryString + " name LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (elementId != null) { preparedStatement.setLong(indexCounter, elementId.longValue()); indexCounter = indexCounter + 1; } if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if ((project != null)) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if ((name != null)) { preparedStatement.setString(indexCounter, name); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting persistence query statistics.", e); } finally { this.releaseConnection(connection); } } Code Sample 2: public void testRenderRules() { try { MappingManager manager = new MappingManager(); OWLOntologyManager omanager = OWLManager.createOWLOntologyManager(); OWLOntology srcOntology; OWLOntology targetOntology; manager.loadMapping(rulesDoc.toURL()); srcOntology = omanager.loadOntologyFromPhysicalURI(srcURI); targetOntology = omanager.loadOntologyFromPhysicalURI(targetURI); manager.setSourceOntology(srcOntology); manager.setTargetOntology(targetOntology); Graph srcGraph = manager.getSourceGraph(); Graph targetGraph = manager.getTargetGraph(); System.out.println("Starting to render..."); FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(srcGraph); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); System.out.println("View updated with graph..."); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); System.out.println("Finished writing"); writer.close(); System.out.println("Finished render... XML is:"); System.out.println(writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
00
Code Sample 1: @Override public void action(String msg, String uri, Gateway gateway) throws Exception { String city = "成都"; if (msg.indexOf("#") != -1) { city = msg.substring(msg.indexOf("#") + 1); } String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode={city}&theUserID="; url = url.replace("{city}", URLEncoder.encode(city, "UTF8")); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); if (conn.getResponseCode() == 200) { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(conn.getInputStream()); List strings = doc.getRootElement().getChildren(); String[] sugguestions = getText(strings.get(6)).split("\n"); StringBuffer buffer = new StringBuffer(); buffer.append("欢迎使用MapleSMS的天气服务!\n"); buffer.append("你查询的是 " + getText(strings.get(1)) + "的天气。\n"); buffer.append(getText(strings.get(4)) + "。\n"); buffer.append(getText(strings.get(5)) + "。\n"); buffer.append(sugguestions[0] + "\n"); buffer.append(sugguestions[1] + "\n"); buffer.append(sugguestions[7] + "\n"); buffer.append("感谢你使用MapleSMS的天气服务!祝你愉快!"); gateway.sendSMS(uri, buffer.toString()); } else { gateway.sendSMS(uri, "对不起,你输入的城市格式有误,请检查后再试~"); } } Code Sample 2: protected int getResponseCode(String address) throws Exception { URL url = new URL(address); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setUseCaches(false); try { con.connect(); return con.getResponseCode(); } finally { con.disconnect(); } }
00
Code Sample 1: void load(URL url) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); Vector3f scale = new Vector3f(1, 1, 1); Group currentGroup = new Group(); currentGroup.name = "default"; groups.add(currentGroup); String line; while ((line = r.readLine()) != null) { String[] params = line.split(" +"); if (params.length == 0) continue; String command = params[0]; if (params[0].equals("v")) { Vector3f vertex = new Vector3f(Float.parseFloat(params[1]) * scale.x, Float.parseFloat(params[2]) * scale.y, Float.parseFloat(params[3]) * scale.z); verticies.add(vertex); radius = Math.max(radius, vertex.length()); } if (command.equals("center")) { epicenter = new Vector3f(Float.parseFloat(params[1]), Float.parseFloat(params[2]), Float.parseFloat(params[3])); } else if (command.equals("f")) { Face f = new Face(); for (int i = 1; i < params.length; i++) { String parts[] = params[i].split("/"); Vector3f v = verticies.get(Integer.parseInt(parts[0]) - 1); f.add(v); } currentGroup.faces.add(f); } else if (command.equals("l")) { Line l = new Line(); for (int i = 1; i < params.length; i++) { Vector3f v = verticies.get(Integer.parseInt(params[i]) - 1); l.add(v); } currentGroup.lines.add(l); } else if (command.equals("g") && params.length > 1) { currentGroup = new Group(); currentGroup.name = params[1]; groups.add(currentGroup); } else if (command.equals("scale")) { scale = new Vector3f(Float.parseFloat(params[1]), Float.parseFloat(params[2]), Float.parseFloat(params[3])); } } r.close(); } Code Sample 2: public static String getServerVersion() throws IOException { URL url; url = new URL(CHECKVERSIONURL); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(false); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); InputStream in = httpURLConnection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); out.flush(); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); String buffer; String[] lines; String version = ""; buffer = out.toString(); lines = StringUtils.split(buffer); for (int i = 0; i < lines.length; i++) { if (lines[i].startsWith("version=")) { version = lines[i].substring(8).trim(); break; } } return version; }
11
Code Sample 1: public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && wanted.containsKey(name)) { FileOutputStream out = new FileOutputStream(wanted.get(name)); IOUtils.copy(stream, out); out.close(); } else { if (downstreamParser != null) { downstreamParser.parse(stream, handler, metadata, context); } } } Code Sample 2: public String[][] getProjectTreeData() { String[][] treeData = null; String filename = dms_home + FS + "temp" + FS + username + "projects.xml"; String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjects"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "projects.xml"; System.out.println(urldata); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("j"); int num = nodelist.getLength(); treeData = new String[num][5]; for (int i = 0; i < num; i++) { treeData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "i")); treeData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "pi")); treeData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "p")); treeData[i][3] = ""; treeData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } return treeData; }
11
Code Sample 1: public static void copyFile(String source, String destination, boolean overwrite) { File sourceFile = new File(source); try { File destinationFile = new File(destination); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile)); int temp = 0; while ((temp = bis.read()) != -1) bos.write(temp); bis.close(); bos.close(); } catch (Exception e) { } return; } Code Sample 2: public static void copyFile(File input, File output) throws Exception { FileReader in = new FileReader(input); FileWriter out = new FileWriter(output); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; } Code Sample 2: 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()); }
00
Code Sample 1: public static final InputStream openStream(Bundle bundle, IPath file, boolean localized) throws IOException { URL url = null; if (!localized) { url = findInPlugin(bundle, file); if (url == null) url = findInFragments(bundle, file); } else { url = FindSupport.find(bundle, file); } if (url != null) return url.openStream(); throw new IOException("Cannot find " + file.toString()); } Code Sample 2: public String getScript(String script, String params) { params = params.replaceFirst("&", "?"); StringBuffer document = new StringBuffer(); try { URL url = new URL(script + params); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { document.append(line + "\n"); } reader.close(); } catch (Exception e) { return e.toString(); } return document.toString(); }
11
Code Sample 1: @Test public void testCopy_inputStreamToOutputStream_IO84() throws Exception { long size = (long) Integer.MAX_VALUE + (long) 1; InputStream in = new NullInputStreamTest(size); OutputStream out = new OutputStream() { @Override public void write(int b) throws IOException { } @Override public void write(byte[] b) throws IOException { } @Override public void write(byte[] b, int off, int len) throws IOException { } }; assertEquals(-1, IOUtils.copy(in, out)); in.close(); assertEquals("copyLarge()", size, IOUtils.copyLarge(in, out)); } Code Sample 2: public static void getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map<String, String> _headers, Map<String, String> _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; _url = encodeURL(_url); HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams methodParams = ((HttpMethodBase) method).getParams(); if (methodParams == null) { methodParams = new HttpMethodParams(); ((HttpMethodBase) method).setParams(methodParams); } if (_timeout < 0) methodParams.setSoTimeout(0); else methodParams.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("Content-Type", _contentType); } if (_headers == null || !_headers.containsKey("User-Agent")) { if (_headers == null) _headers = new HashMap<String, String>(); _headers.put("User-Agent", DEFAULT_USERAGENT); } if (_headers != null) { Iterator<Map.Entry<String, String>> iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator<Map.Entry<String, String>> iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); httpClient.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); InputStream instream = null; try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { LOG.warn("Http Satus:" + status + ",Url:" + _url); if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); } catch (IOException err) { LOG.error("Failed to access " + _url, err); throw err; } finally { IOUtils.closeQuietly(instream); if (method != null) method.releaseConnection(); } }
11
Code Sample 1: public static void main(String[] args) throws IOException { MSPack pack = new MSPack(new FileInputStream(args[0])); String[] files = pack.getFileNames(); for (int i = 0; i < files.length; i++) System.out.println(i + ": " + files[i] + ": " + pack.getLengths()[i]); System.out.println("Writing " + files[files.length - 1]); InputStream is = pack.getInputStream(files.length - 1); OutputStream os = new FileOutputStream(files[files.length - 1]); int n; byte[] buf = new byte[4096]; while ((n = is.read(buf)) != -1) os.write(buf, 0, n); os.close(); is.close(); } Code Sample 2: protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); }
11
Code Sample 1: public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; } Code Sample 2: public boolean addMeFile(File f) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(directory + f.getName()))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(f)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); if (!PatchManager.mute) System.out.println("added : " + directory + f.getName()); } catch (IOException e) { System.out.println("copy directory : " + e); return false; } return true; }
11
Code Sample 1: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } Code Sample 2: private static boolean unzipWithWarning(File source, File targetDirectory, OverwriteValue policy) { try { if (!source.exists()) return false; ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; byte[] buffer = new byte[1024]; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; File newFile = new File(targetDirectory, zipEntry.getName()); if (newFile.exists()) { switch(policy.value) { case NO_TO_ALL: continue; case YES_TO_ALL: break; default: switch(policy.value = confirmOverwrite(zipEntry.getName())) { case NO_TO_ALL: case NO: continue; default: } } } newFile.getParentFile().mkdirs(); int bytesRead; FileOutputStream output = new FileOutputStream(newFile); while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.closeEntry(); } input.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
00
Code Sample 1: public static File copyFile(File srcFile, File destFolder, FileCopyListener copyListener) { File dest = new File(destFolder, srcFile.getName()); try { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; long totalSize = srcFile.length(); boolean canceled = false; if (copyListener == null) { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } } else { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); if (!copyListener.updateCheck(readLength, totalSize)) { canceled = true; break; } } } in.close(); out.close(); if (canceled) { dest.delete(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } Code Sample 2: private File copyFromURL(URL url, String dir) throws IOException { File urlFile = new File(url.getFile()); File dest = new File(dir, urlFile.getName()); logger.log("Extracting " + urlFile.getName() + " to " + dir + "..."); FileOutputStream os = new FileOutputStream(dest); InputStream is = url.openStream(); byte data[] = new byte[4096]; int ct; while ((ct = is.read(data)) >= 0) os.write(data, 0, ct); is.close(); os.close(); logger.log("ok\n"); return dest; }
00
Code Sample 1: private String endcodePassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); Base64 base64 = new Base64(); String hash = new String(base64.encode(raw)); return hash; } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { sourceChannel.close(); destinationChannel.close(); } }
00
Code Sample 1: public int update(BusinessObject o) throws DAOException { int update = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_CURRENCY")); pst.setString(1, curr.getName()); pst.setInt(2, curr.getIdBase()); pst.setDouble(3, curr.getValue()); pst.setInt(4, curr.getId()); update = pst.executeUpdate(); if (update <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (update > 1) { connection.rollback(); throw new DAOException("Number of rows > 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 update; } Code Sample 2: public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); InputStream is = CheckAvailability.class.getResourceAsStream("/isbns.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String isbn = null; HttpGet get = null; while ((isbn = br.readLine().split(" ")[0]) != null) { System.out.println("Target url: \n\t" + String.format(isbnSearchUrl, isbn)); get = new HttpGet(String.format(isbnSearchUrl, isbn)); HttpResponse resp = httpclient.execute(get); Scanner s = new Scanner(resp.getEntity().getContent()); String pattern = s.findWithinHorizon("((\\d*) hold[s]? on first copy returned of (\\d*) )?[cC]opies", 0); if (pattern != null) { MatchResult match = s.match(); if (match.groupCount() == 3) { if (match.group(2) == null) { System.out.println(isbn + ": copies available"); } else { System.out.println(isbn + ": " + match.group(2) + " holds on " + match.group(3) + " copies"); } } } else { System.out.println(isbn + ": no match"); } get.abort(); } }
00
Code Sample 1: private void addEMInformation() { try { long emDate = System.currentTimeMillis(); if (_local == true) { File emFile = new File("emprotz.dat"); if (!emFile.exists()) { return; } emDate = emFile.lastModified(); } if (emDate > this._emFileDate) { this._emFileDate = emDate; this._emDate = emDate; for (int ii = 0; ii < this._projectInfo.size(); ii++) { Information info = getInfo(ii); if (info != null) { info._emDeadline = null; info._emFrames = null; info._emValue = null; } } Reader reader = null; if (_local == true) { reader = new FileReader("emprotz.dat"); } else { StringBuffer urlName = new StringBuffer(); urlName.append("http://home.comcast.net/"); urlName.append("~wxdude1/emsite/download/"); urlName.append("emprotz.zip"); try { URL url = new URL(urlName.toString()); InputStream stream = url.openStream(); ZipInputStream zip = new ZipInputStream(stream); zip.getNextEntry(); reader = new InputStreamReader(zip); } catch (MalformedURLException mue) { mue.printStackTrace(); } } BufferedReader file = new BufferedReader(reader); try { String line1 = null; int count = 0; while ((line1 = file.readLine()) != null) { String line2 = (line1 != null) ? file.readLine() : null; String line3 = (line2 != null) ? file.readLine() : null; String line4 = (line3 != null) ? file.readLine() : null; count++; if ((count > 1) && (line1 != null) && (line2 != null) && (line3 != null) && (line4 != null)) { if (line1.length() > 2) { int posBegin = line1.indexOf("\"", 0); int posEnd = line1.indexOf("\"", posBegin + 1); if ((posBegin >= 0) && (posEnd >= 0)) { String project = line1.substring(posBegin + 1, posEnd - posBegin); int projectNum = Integer.parseInt(project); Integer deadline = Integer.valueOf(line2.trim()); Double value = Double.valueOf(line3.trim()); Integer frames = Integer.valueOf(line4.trim()); Information info = getInfo(projectNum); if (info == null) { info = createInfo(projectNum); } if (info._emValue == null) { info._emDeadline = deadline; info._emFrames = frames; info._emValue = value; } } } } } } catch (Exception e) { e.printStackTrace(); } finally { file.close(); } } } catch (FileNotFoundException e) { } catch (IOException e) { } } Code Sample 2: public static synchronized void repartition(File[] sourceFiles, File targetDirectory, String prefix, long maxUnitBases, long maxUnitEntries) throws Exception { if (!targetDirectory.exists()) { if (!targetDirectory.mkdirs()) throw new Exception("Could not create directory " + targetDirectory.getAbsolutePath()); } File tmpFile = new File(targetDirectory, "tmp.fasta"); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel fco = fos.getChannel(); for (File file : sourceFiles) { FileInputStream fis = new FileInputStream(file); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(64000); while (fci.read(buffer) > 0) { buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); } fco.close(); FastaFile fastaFile = new FastaFile(tmpFile); fastaFile.split(targetDirectory, prefix, maxUnitBases, maxUnitEntries); tmpFile.delete(); }
00
Code Sample 1: protected void performInsertTest() throws Exception { Connection conn = connect(); EntityDescriptor ed = repository.getEntityDescriptor(User.class); User testUser = new User(); Date now = new Date(); conn.setAutoCommit(false); testUser.setUsername("rednose"); testUser.setUCreated("dbUtilTest"); testUser.setUModified("dbUtilTest"); testUser.setDtCreated(now); testUser.setDtModified(now); String sql = dbUtil.genInsert(ed, testUser); Statement st = conn.createStatement(); long id = 0; System.err.println("Insert: " + sql); int rv = st.executeUpdate(sql, dbUtil.supportsGeneratedKeyQuery() ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); if (rv > 0) { if (dbUtil.supportsGeneratedKeyQuery()) { ResultSet rs = st.getGeneratedKeys(); if (rs.next()) id = rs.getLong(1); } else { id = queryId(ed, now, "dbUtilTest", conn, dbUtil); } if (id > 0) testUser.setId(id); else rv = 0; } conn.rollback(); assertTrue("oups, insert failed?", id != 0); System.err.println("successfully created user with id #" + id + " temporarily"); } Code Sample 2: private String checkForUpdate() { InputStream is = null; try { URL url = new URL(CHECK_UPDATES_URL); try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", "TinyLaF"); Object content = conn.getContent(); if (!(content instanceof InputStream)) { return "An exception occured while checking for updates." + "\n\nException was: Content is no InputStream"; } is = (InputStream) content; } catch (IOException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } } catch (MalformedURLException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } try { BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buff = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buff.append(line); } in.close(); return buff.toString(); } catch (IOException ex) { return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName(); } }
11
Code Sample 1: @Override public void run() { log.debug("Now running...."); log.debug("Current env. variables:"); try { this.infoNotifiers("Environment parameters after modifications:"); this.logEnvironment(); this.infoNotifiers("Dump thread will now run..."); this.endNotifiers(); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } List<String> cmd = new LinkedList<String>(); cmd.add("gzip"); cmd.add(info.getDumpFileName()); File basePath = this.pb.directory(); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.process = this.pb.start(); this.process.waitFor(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } info.setDumpFileName(info.getDumpFileName() + ".gz"); info.setMD5SumFileName(info.getDumpFileName() + ".md5sum"); cmd = new LinkedList<String>(); cmd.add("md5sum"); cmd.add("-b"); cmd.add(info.getDumpFileName()); log.debug("Executing: " + StringUtils.join(cmd.iterator(), ' ')); this.pb = new ProcessBuilder(cmd); this.pb.directory(basePath); this.process = this.pb.start(); BufferedOutputStream md5sumFileOut = new BufferedOutputStream(new FileOutputStream(basePath.getAbsolutePath() + File.separatorChar + info.getMD5SumFileName())); IOUtils.copy(this.process.getInputStream(), md5sumFileOut); this.process.waitFor(); md5sumFileOut.flush(); md5sumFileOut.close(); if (this.process.exitValue() != 0) { this.startNotifiers(); this.infoNotifiers("Dump GZip MD5Sum Failed. Return status: " + this.process.exitValue()); this.endNotifiers(); return; } else { this.startNotifiers(); this.infoNotifiers("Dump, gzip and md5sum sucessfuly completed."); this.endNotifiers(); } } catch (IOException e) { String message = "IOException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (InterruptedException e) { String message = "InterruptedException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } catch (IntegrationException e) { String message = "IntegrationException launching command: " + e.getMessage(); log.error(message, e); throw new IllegalStateException(message, e); } } Code Sample 2: private void collectImageFile(@NotNull final Progress progress, @NotNull final File collectedDirectory) throws IOException { final File file = new File(collectedDirectory, ActionBuilderUtils.getString(ACTION_BUILDER, "configSource.image.name")); final FileOutputStream fos = new FileOutputStream(file); try { final FileChannel outChannel = fos.getChannel(); try { final int numOfFaceObjects = faceObjects.size(); progress.setLabel(ActionBuilderUtils.getString(ACTION_BUILDER, "archCollectImages"), numOfFaceObjects); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); final Charset charset = Charset.forName("ISO-8859-1"); int i = 0; for (final FaceObject faceObject : faceObjects) { final String face = faceObject.getFaceName(); final String path = archFaceProvider.getFilename(face); try { final FileInputStream fin = new FileInputStream(path); try { final FileChannel inChannel = fin.getChannel(); final long imageSize = inChannel.size(); byteBuffer.clear(); byteBuffer.put(("IMAGE " + (faceObjects.isIncludeFaceNumbers() ? i + " " : "") + imageSize + " " + face + "\n").getBytes(charset)); byteBuffer.flip(); outChannel.write(byteBuffer); inChannel.transferTo(0L, imageSize, outChannel); } finally { fin.close(); } } catch (final FileNotFoundException ignored) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorFileNotFound", path); return; } catch (final IOException e) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorIOException", path, e); return; } if (i++ % 100 == 0) { progress.setValue(i); } } progress.setValue(faceObjects.size()); } finally { outChannel.close(); } } finally { fos.close(); } }
00
Code Sample 1: public void setContentMD5() { MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); contentMD5 = null; } messagedigest.update(content.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } contentMD5 = chk; } Code Sample 2: @Test public void testMark() throws IllegalArgumentException, IOException { Assert.assertNotNull(this.m_detector); File f = new File("testdocuments/voiddocument/Voiderror.htm"); Assert.assertTrue("Test file " + f.getAbsolutePath() + " does not exist. ", f.exists()); URL url = f.toURL(); this.m_detector.detectCodepage(url.openStream(), 200); }
00
Code Sample 1: private String md5(String s) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } Code Sample 2: public static void main(String args[]) { try { URL url = new URL("http://www.hungry.com/"); InputStream stream = url.openStream(); int size = 0; while (-1 != stream.read()) { size++; } stream.close(); System.out.println("PASSED: new URL() size=" + size); } catch (Exception e) { System.out.println("FAILED: " + e); } }
00
Code Sample 1: public boolean connect() { try { int reply; ftp.connect(server, port); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { if (ftp.login(username, password)) { ftp.enterLocalPassiveMode(); return true; } } else { ftp.disconnect(); System.out.println("FTP server refused connection."); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { } } System.out.println("Could not connect to server."); } return false; } Code Sample 2: public byte[] loadClassFirst(final String className) { if (className.equals("com.sun.sgs.impl.kernel.KernelContext")) { final URL url = Thread.currentThread().getContextClassLoader().getResource("com/sun/sgs/impl/kernel/KernelContext.0.9.6.class.bin"); if (url != null) { try { return StreamUtil.read(url.openStream()); } catch (IOException e) { } } throw new IllegalStateException("Unable to load KernelContext.0.9.6.class.bin"); } return null; }
00
Code Sample 1: public static InputStream getResourceInputStream(final URL url) throws IOException { File file = url2file(url); if (file != null) { return new BufferedInputStream(new FileInputStream(file)); } if (!"jar".equalsIgnoreCase(url.getProtocol())) { return url.openStream(); } String urlStr = url.toExternalForm(); if (urlStr.endsWith("!/")) { throw new FileNotFoundException(url.toExternalForm()); } int p = urlStr.indexOf("!/"); if (p == -1) { throw new MalformedURLException(url.toExternalForm()); } String path = urlStr.substring(p + 2); file = url2file(new URL(urlStr.substring(4, p))); if (file == null) { return url.openStream(); } JarFile jarFile = new JarFile(file); try { ZipEntry entry = jarFile.getEntry(path); if (entry == null) { throw new FileNotFoundException(url.toExternalForm()); } InputStream in = jarFile.getInputStream(entry); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); copyStream(in, out, 1024); return new ByteArrayInputStream(out.toByteArray()); } finally { in.close(); } } finally { jarFile.close(); } } Code Sample 2: protected BufferedReader getDataReader() { BufferedReader in = null; PrintWriter out = null; try { String line; URL url = new URL(this.catalog.getCatalogURL()); Debug.output("Catalog URL:" + url.toString()); in = new BufferedReader(new InputStreamReader(url.openStream())); File dir = (File) SessionHandler.getServletContext().getAttribute("javax.servlet.context.tempdir"); File temp = new File(dir, TEMP); Debug.output("Temp file:" + temp.toString()); out = new PrintWriter(new BufferedWriter(new FileWriter(temp))); while ((line = in.readLine()) != null) { out.println(line); } Debug.output("Temp file size:" + temp.length()); return new BufferedReader(new FileReader(temp)); } catch (IOException e) { throw new SeismoException(e); } finally { Util.close(in); Util.close(out); } }
00
Code Sample 1: @TestTargetNew(level = TestLevel.COMPLETE, notes = "Test fails: IOException expected but IllegalStateException is thrown: ticket 128", method = "getInputStream", args = { }) public void test_getInputStream_DeleteJarFileUsingURLConnection() throws Exception { String jarFileName = ""; String entry = "text.txt"; String cts = System.getProperty("java.io.tmpdir"); File tmpDir = new File(cts); File jarFile = tmpDir.createTempFile("file", ".jar", tmpDir); jarFileName = jarFile.getPath(); FileOutputStream jarFileOutputStream = new FileOutputStream(jarFileName); JarOutputStream out = new JarOutputStream(new BufferedOutputStream(jarFileOutputStream)); JarEntry jarEntry = new JarEntry(entry); out.putNextEntry(jarEntry); out.write(new byte[] { 'a', 'b', 'c' }); out.close(); URL url = new URL("jar:file:" + jarFileName + "!/" + entry); URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStream is = conn.getInputStream(); is.close(); assertTrue(jarFile.delete()); } Code Sample 2: public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; }
00
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: protected IStatus run(IProgressMonitor monitor) { try { updateRunning = true; distributor = getFromFile("[SERVER]", "csz", getAppPath() + "/server.ini"); MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); if (MAC.equals("not_found") || serial.equals("not_found") || !serial.startsWith(distributor)) { try { MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini"); serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini"); } catch (Exception e) { System.out.println(e); } } else { try { url = new URL("http://" + getFromFile("[SERVER]", "url", getAppPath() + "/server.ini")); } catch (MalformedURLException e) { System.out.println(e); } download = "/download2.php?distributor=" + distributor + "&&mac=" + MAC + "&&serial=" + serial; readXML(); if (htmlMessage.contains("error")) { try { PrintWriter pw = new PrintWriter(getAppPath() + "/register.ini"); pw.write(""); pw.close(); } catch (IOException e) { System.out.println(e); } setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } } else { if (!getDBVersion().equals(latestVersion)) { try { OutputStream out = null; HttpURLConnection conn = null; InputStream in = null; int size; try { URL url = new URL(fileLoc); String outFile = getAppPath() + "/temp/" + getFileName(url); File oFile = new File(outFile); oFile.delete(); out = new BufferedOutputStream(new FileOutputStream(outFile)); monitor.beginTask("Connecting to NWD Server", 100); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(20000); conn.connect(); if (conn.getResponseCode() / 100 != 2) { System.out.println("Error: " + conn.getResponseCode()); return null; } monitor.worked(100); monitor.done(); size = conn.getContentLength(); monitor.beginTask("Download Worm Definition", size); in = conn.getInputStream(); byte[] buffer; String downloadedSize; long numWritten = 0; boolean status = true; while (status) { if (size - numWritten > 1024) { buffer = new byte[1024]; } else { buffer = new byte[(int) (size - numWritten)]; } int read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); numWritten += read; downloadedSize = Long.toString(numWritten / 1024) + " KB"; monitor.worked(read); monitor.subTask(downloadedSize + " of " + Integer.toString(size / 1024) + " KB"); if (size == numWritten) { status = false; } if (monitor.isCanceled()) return Status.CANCEL_STATUS; } if (in != null) { in.close(); } if (out != null) { out.close(); } try { ZipFile zFile = new ZipFile(outFile); Enumeration all = zFile.entries(); while (all.hasMoreElements()) { ZipEntry zEntry = (ZipEntry) all.nextElement(); long zSize = zEntry.getSize(); if (zSize > 0) { if (zEntry.getName().endsWith("script")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[0]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } else if (zEntry.getName().endsWith("data")) { InputStream instream = zFile.getInputStream(zEntry); FileOutputStream fos = new FileOutputStream(oldLoc[1]); int ch; while ((ch = instream.read()) != -1) { fos.write(ch); } instream.close(); fos.close(); } } } File xFile = new File(outFile); xFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); } try { monitor.done(); monitor.beginTask("Install Worm Definition", 10000); monitor.worked(2500); CorePlugin.getDefault().getRawPacketHandler().removeRawPacketListener(p); p = null; if (!wormDB.getConn().isClosed()) { shutdownDB(); } System.out.println(wormDB.getConn().isClosed()); for (int i = 0; i < 2; i++) { try { Process pid = Runtime.getRuntime().exec("cmd /c copy \"" + oldLoc[i].replace("/", "\\") + "\" \"" + newLoc[i].replace("/", "\\") + "\"/y"); } catch (Exception e) { e.printStackTrace(); } new File(oldLoc[i]).deleteOnExit(); } monitor.worked(2500); initialArray(); p = new PacketPrinter(); CorePlugin.getDefault().getRawPacketHandler().addRawPacketListener(p); monitor.worked(2500); monitor.done(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction()); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } System.out.println(e); } finally { } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults2(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2()); } e.printStackTrace(); } } else { cancel(); setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco); if (isModal(this)) { showResults1(); } else { setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE); setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction1()); } } } } return Status.OK_STATUS; } catch (Exception e) { showResults2(); return Status.OK_STATUS; } finally { lock.release(); updateRunning = false; if (getValue("AUTO_UPDATE")) schedule(10800000); } }
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: private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
00
Code Sample 1: public static String generateMD5(String clear) { byte hash[] = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(clear.getBytes()); hash = md5.digest(); } catch (NoSuchAlgorithmException e) { } if (hash != null) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String tmp = Integer.toHexString(0xFF & hash[i]); if (tmp.length() == 1) { tmp = "0" + tmp; } hexString.append(tmp); } return hexString.toString(); } else { return null; } } Code Sample 2: public void test3() throws FileNotFoundException, IOException { Decoder decoder1 = new MP3Decoder(new FileInputStream("/home/marc/tmp/test1.mp3")); Decoder decoder2 = new OggDecoder(new FileInputStream("/home/marc/tmp/test1.ogg")); FileOutputStream out = new FileOutputStream("/home/marc/tmp/test.pipe"); IOUtils.copy(decoder1, out); IOUtils.copy(decoder2, out); }
00
Code Sample 1: public static String hash(String plainText) throws Exception { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(plainText.getBytes(), 0, plainText.length()); String hash = new BigInteger(1, m.digest()).toString(16); if (hash.length() == 31) { hash = "0" + hash; } return hash; } Code Sample 2: private static void testTidy() { try { String url = "http://groups.google.com/group/dengues/files"; java.io.InputStream is = new java.net.URL(url).openStream(); org.w3c.dom.Document doc = dengues.system.HTMLWebHelper.parseDOM(is); org.w3c.dom.NodeList list = doc.getElementsByTagName("td"); org.w3c.dom.Element stockTypeElement = null; for (int i = 0; i < list.getLength(); i++) { org.w3c.dom.Node item = list.item(i); String content = dengues.system.HTMLWebHelper.getContent(item); String convert = dengues.system.HTMLWebHelper.convert(content); if (convert.equals("zDevil")) { stockTypeElement = (org.w3c.dom.Element) item.getParentNode().getParentNode(); break; } } if (stockTypeElement != null) { org.w3c.dom.NodeList trList = stockTypeElement.getElementsByTagName("tr"); for (int i = 0; i < trList.getLength(); i++) { org.w3c.dom.NodeList trListChildren = trList.item(i).getChildNodes(); if (trListChildren.getLength() > 2) { org.w3c.dom.Node node_0 = trListChildren.item(0); org.w3c.dom.Node node_1 = trListChildren.item(1); String content = dengues.system.HTMLWebHelper.getContent(node_0); String convert_0 = dengues.system.HTMLWebHelper.convert(content); content = dengues.system.HTMLWebHelper.getContent(node_1); String convert_1 = dengues.system.HTMLWebHelper.convert(content); if (!"".equals(convert_0)) { System.out.println(convert_0 + " => " + convert_1); } } } } is.close(); } catch (java.net.MalformedURLException ex) { ex.printStackTrace(); } catch (java.io.IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: @Override protected IStatus run(IProgressMonitor monitor) { final int BUFFER_SIZE = 1024; final int DISPLAY_BUFFER_SIZE = 8196; File sourceFile = new File(_sourceFile); File destFile = new File(_destFile); if (sourceFile.exists()) { try { Log.getInstance(FileCopierJob.class).debug(String.format("Start copy of %s to %s", _sourceFile, _destFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); monitor.beginTask(Messages.getString("FileCopierJob.MainTask") + " " + _sourceFile, (int) ((sourceFile.length() / DISPLAY_BUFFER_SIZE) + 4)); monitor.worked(1); byte[] buffer = new byte[BUFFER_SIZE]; int stepRead = 0; int read; boolean copying = true; while (copying) { read = bis.read(buffer); if (read > 0) { bos.write(buffer, 0, read); stepRead += read; } else { copying = false; } if (monitor.isCanceled()) { bos.close(); bis.close(); deleteFile(_destFile); return Status.CANCEL_STATUS; } if (stepRead >= DISPLAY_BUFFER_SIZE) { monitor.worked(1); stepRead = 0; } } bos.flush(); bos.close(); bis.close(); monitor.worked(1); } catch (Exception e) { processError("Error while copying: " + e.getMessage()); } Log.getInstance(FileCopierJob.class).debug("End of copy."); return Status.OK_STATUS; } else { processError(Messages.getString("FileCopierJob.ErrorSourceDontExists") + sourceFile.getAbsolutePath()); return Status.CANCEL_STATUS; } } Code Sample 2: public static long checksum(IFile file) throws IOException { InputStream contents; try { contents = file.getContents(); } catch (CoreException e) { throw new CausedIOException("Failed to calculate checksum.", e); } CheckedInputStream in = new CheckedInputStream(contents, new Adler32()); try { IOUtils.copy(in, new NullOutputStream()); } catch (IOException e) { throw new CausedIOException("Failed to calculate checksum.", e); } finally { IOUtils.closeQuietly(in); } return in.getChecksum().getValue(); }
00
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: @Override public void aggregate() { Connection connection = null; PreparedStatement prestm = null; try { if (logger.isInfoEnabled()) logger.info("aggregate table <" + origin + "> start..."); Class.forName(driver); connection = DriverManager.getConnection(url, username, password); String tableExistsResult = ""; prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';"); ResultSet rs = prestm.executeQuery(); if (rs.next()) tableExistsResult = rs.getString(1); rs.close(); prestm.close(); if (StringUtils.isBlank(tableExistsResult)) { String createTableSql = ""; prestm = connection.prepareStatement("show create table " + getOrigin() + ";"); rs = prestm.executeQuery(); if (rs.next()) createTableSql = rs.getString(2); rs.close(); prestm.close(); createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`"); createTableSql = createTableSql.replaceAll("auto_increment", ""); createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", ""); Matcher matcher = stripRelationTablePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll(""); matcher = normalizePattern.matcher(createTableSql); if (matcher.find()) createTableSql = matcher.replaceAll("\n )"); Statement stm = connection.createStatement(); stm.execute(createTableSql); if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!"); } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists"); long currentRows = 0L; prestm = connection.prepareStatement("select count(*) from " + origin); rs = prestm.executeQuery(); if (rs.next()) currentRows = rs.getLong(1); rs.close(); prestm.close(); if (logger.isInfoEnabled()) logger.info("found " + currentRows + " record"); prestm = connection.prepareStatement("select max(d_insDate) from " + destination); rs = prestm.executeQuery(); Date from = null; if (rs.next()) from = rs.getTimestamp(1); rs.close(); prestm.close(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String fromStr = null; if (from != null) fromStr = sdf.format(from); if (logger.isInfoEnabled()) logger.info("last record date:" + fromStr); if (currentRows > 0) { connection.setAutoCommit(false); if (from != null && fromStr != null) { prestm = connection.prepareStatement("INSERT INTO " + destination + " SELECT * FROM " + origin + " WHERE d_insDate > '" + fromStr + "'"); if (logger.isDebugEnabled()) logger.debug("Query: INSERT INTO " + destination + " SELECT * FROM " + origin + " WHERE d_insDate > '" + fromStr + "'"); } else { prestm = connection.prepareStatement("INSERT INTO " + destination + " SELECT * FROM " + origin); if (logger.isDebugEnabled()) logger.debug("Query: INSERT INTO " + destination + " SELECT * FROM " + origin); } int rows = prestm.executeUpdate(); prestm.close(); if (logger.isInfoEnabled()) logger.info(" > " + rows + " rows aggregated"); connection.commit(); } else if (logger.isInfoEnabled()) logger.info("no aggregation need"); if (logger.isInfoEnabled()) logger.info("aggregate table " + origin + " end"); } catch (SQLException e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante l'aggregazione dei dati della tabella " + origin, e)); try { connection.rollback(); } catch (SQLException e1) { } } catch (Throwable e) { logger.error(e, e); if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante l'aggregazione dei dati della tabella " + origin, e)); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { if (prestm != null) prestm.close(); } catch (SQLException e) { } try { if (connection != null) connection.close(); } catch (SQLException e) { } } }
11
Code Sample 1: public static boolean writeFileByChars(Reader pReader, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pReader, fw); fw.flush(); fw.close(); pReader.close(); flag = true; } catch (Exception e) { LOG.error("将字符流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: @Override public synchronized void deleteHardDiskStatistics(String contextName, String path, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getHardDiskInvocationsSchemaAndTableName() + " FROM " + this.getHardDiskInvocationsSchemaAndTableName() + " INNER JOIN " + this.getHardDiskElementsSchemaAndTableName() + " ON " + this.getHardDiskElementsSchemaAndTableName() + ".element_id = " + this.getHardDiskInvocationsSchemaAndTableName() + ".element_id WHERE "; if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if (path != null) { queryString = queryString + " path LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if (path != null) { preparedStatement.setString(indexCounter, path); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting disk statistics.", e); } finally { this.releaseConnection(connection); } } Code Sample 2: public static Image loadImage(URL url) throws IOException { BufferedInputStream in = new BufferedInputStream(url.openStream()); try { return getLoader(url.getFile()).loadImage(in); } finally { in.close(); } }
00
Code Sample 1: private long getNextHighValue() throws Exception { Connection con = null; PreparedStatement psGetHighValue = null; PreparedStatement psUpdateHighValue = null; ResultSet rs = null; long high = -1L; int isolation = -1; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); psGetHighValue = con.prepareStatement(strGetHighValue); psGetHighValue.setString(1, this.name); for (rs = psGetHighValue.executeQuery(); rs.next(); ) { high = rs.getLong("high"); } psUpdateHighValue = con.prepareStatement(strUpdateHighValue); psUpdateHighValue.setLong(1, high + 1L); psUpdateHighValue.setString(2, this.name); psUpdateHighValue.executeUpdate(); } catch (SQLException e) { if (con != null) { con.rollback(); } throw e; } finally { if (psUpdateHighValue != null) { psUpdateHighValue.close(); } close(dbo, psGetHighValue, rs); } return high; } Code Sample 2: public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
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 Model loadModel(URL url, String filenameBase, SourceModelType modelType, URL baseURL, String skin, float scale, int flags, AppearanceFactory appFactory, GeometryFactory geomFactory, NodeFactory nodeFactory, AnimationFactory animFactory, SpecialItemsHandler siHandler, Model model) throws IOException, IncorrectFormatException, ParsingException { boolean convertZup2Yup = modelType.getConvertFlag(flags); switch(modelType) { case AC3D: AC3DPrototypeLoader.load(url.openStream(), baseURL, appFactory, geomFactory, nodeFactory, true, model, siHandler); break; case ASE: AseReader.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case BSP: BSPPrototypeLoader.load(url.openStream(), filenameBase, baseURL, geomFactory, true, 0.03f, appFactory, nodeFactory, model, GroupType.BSP_TREE, siHandler); break; case CAL3D: break; case COLLADA: convertZup2Yup = true; COLLADALoader.load(baseURL, url.openStream(), appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD2: MD2File.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD3: MD3File.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); break; case MD5: { Object[][][] boneWeights = MD5MeshReader.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, animFactory, siHandler, model); ((SpecialItemsHandlerImpl) siHandler).flush(); List<URL> animResources = new ResourceLocator(baseURL).findAllResources("md5anim", true, false); for (URL animURL : animResources) { String filename = LoaderUtils.extractFilenameWithoutExt(animURL); MD5AnimationReader.load(animURL.openStream(), filename, baseURL, appFactory, geomFactory, convertZup2Yup, scale, nodeFactory, model.getShapes(), boneWeights, animFactory, siHandler, model); } } break; case MS3D: break; case OBJ: GroupNode rootGroup = model; if (scale != 1.0f) { TransformGroup scaleGroup = new TransformGroup(); scaleGroup.getTransform().setScale(scale); model.addChild(scaleGroup); model.setMainGroup(scaleGroup); rootGroup = scaleGroup; } OBJPrototypeLoader.load(url.openStream(), baseURL, appFactory, skin, geomFactory, convertZup2Yup, scale, nodeFactory, siHandler, rootGroup); break; case TDS: TDSFile.load(url.openStream(), baseURL, appFactory, geomFactory, convertZup2Yup, nodeFactory, animFactory, siHandler, model); } return (model); }
11
Code Sample 1: private void copyFile(File orig, File dest) { byte[] buffer = new byte[1024]; try { FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(dest, true); int readBytes = 0; do { readBytes = fis.read(buffer); if (readBytes > 0) fos.write(buffer, 0, readBytes); } while (readBytes > 0); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public CopyAllDataToOtherFolderResponse CopyAllDataToOtherFolder(DPWSContext context, CopyAllDataToOtherFolder CopyAllDataInps) throws DPWSException { CopyAllDataToOtherFolderResponse cpyRp = new CopyAllDataToOtherFolderResponseImpl(); int hany = 0; String errorMsg = null; try { if ((rootDir == null) || (rootDir.length() == (-1))) { errorMsg = LocalStorVerify.ISNT_ROOTFLD; } else { String sourceN = CopyAllDataInps.getSourceName(); String targetN = CopyAllDataInps.getTargetName(); if (LocalStorVerify.isValid(sourceN) && LocalStorVerify.isValid(targetN)) { String srcDir = rootDir + File.separator + sourceN; String trgDir = rootDir + File.separator + targetN; if (LocalStorVerify.isLength(srcDir) && LocalStorVerify.isLength(trgDir)) { for (File fs : new File(srcDir).listFiles()) { File ft = new File(trgDir + '\\' + fs.getName()); FileChannel in = null, out = null; try { in = new FileInputStream(fs).getChannel(); out = new FileOutputStream(ft).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); hany++; } } } else { errorMsg = LocalStorVerify.FLD_TOOLNG; } } else { errorMsg = LocalStorVerify.ISNT_VALID; } } } catch (Throwable tr) { tr.printStackTrace(); errorMsg = tr.getMessage(); hany = (-1); } if (errorMsg != null) { } cpyRp.setNum(hany); return cpyRp; }
00
Code Sample 1: public void connect() throws IOException { if (this.connection == null) { this.connection = (HttpURLConnection) (new URL(url)).openConnection(); this.connection.setRequestMethod("POST"); this.connection.setUseCaches(false); this.connection.setDoOutput(true); } } Code Sample 2: public static void ExtraeArchivoJAR(String Archivo, String DirJAR, String DirDestino) { FileInputStream entrada = null; FileOutputStream salida = null; try { File f = new File(DirDestino + separador + Archivo); try { f.createNewFile(); } catch (Exception sad) { sad.printStackTrace(); } InputStream source = OP_Proced.class.getResourceAsStream(DirJAR + "/" + Archivo); BufferedInputStream in = new BufferedInputStream(source); FileOutputStream out = new FileOutputStream(f); int ch; while ((ch = in.read()) != -1) out.write(ch); in.close(); out.close(); } catch (IOException ex) { System.out.println(ex); } finally { if (entrada != null) { try { entrada.close(); } catch (IOException ex) { ex.printStackTrace(); } } if (salida != null) { try { salida.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
11
Code Sample 1: private void copyResources(File oggDecDir, String[] resources, String resPrefix) throws FileNotFoundException, IOException { for (int i = 0; i < resources.length; i++) { String res = resPrefix + resources[i]; InputStream is = this.getClass().getResourceAsStream(res); if (is == null) throw new IllegalArgumentException("cannot find resource '" + res + "'"); File file = new File(oggDecDir, resources[i]); if (!file.exists() || file.length() == 0) { FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copyStreams(is, fos); } finally { fos.close(); } } } } Code Sample 2: private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }