label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } Code Sample 2: protected static int[] sort(int[] arr) { for (int i = arr.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: protected void copyFile(File sourceFile, File destFile) { FileChannel in = null; FileChannel out = null; try { if (!verifyOrCreateParentPath(destFile.getParentFile())) { throw new IOException("Parent directory path " + destFile.getAbsolutePath() + " did not exist and could not be created"); } if (destFile.exists() || destFile.createNewFile()) { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } else { throw new IOException("Couldn't create file for " + destFile.getAbsolutePath()); } } catch (IOException ioe) { if (destFile.exists() && destFile.length() < sourceFile.length()) { destFile.delete(); } ioe.printStackTrace(); } finally { try { in.close(); } catch (Throwable t) { } try { out.close(); } catch (Throwable t) { } destFile.setLastModified(sourceFile.lastModified()); } }
11
Code Sample 1: private static FileChannel getFileChannel(File file, boolean isOut, boolean append) throws OpenR66ProtocolSystemException { FileChannel fileChannel = null; try { if (isOut) { FileOutputStream fileOutputStream = new FileOutputStream(file.getPath(), append); fileChannel = fileOutputStream.getChannel(); if (append) { try { fileChannel.position(file.length()); } catch (IOException e) { } } } else { if (!file.exists()) { throw new OpenR66ProtocolSystemException("File does not exist"); } FileInputStream fileInputStream = new FileInputStream(file.getPath()); fileChannel = fileInputStream.getChannel(); } } catch (FileNotFoundException e) { throw new OpenR66ProtocolSystemException("File not found", e); } return fileChannel; } Code Sample 2: public static final boolean zipUpdate(String zipfile, String name, String oldname, byte[] contents, boolean delete) { try { File temp = File.createTempFile("atf", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); OutputStream os = new BufferedOutputStream(new FileOutputStream(temp)); ZipInputStream zin = new ZipInputStream(in); ZipOutputStream zout = new ZipOutputStream(os); ZipEntry e; ZipEntry e2; byte buffer[] = new byte[TEMP_FILE_BUFFER_SIZE]; int bytesRead; boolean found = false; boolean rename = false; String oname = name; if (oldname != null) { name = oldname; rename = true; } while ((e = zin.getNextEntry()) != null) { if (!e.isDirectory()) { String ename = e.getName(); if (delete && ename.equals(name)) continue; e2 = new ZipEntry(rename ? oname : ename); zout.putNextEntry(e2); if (ename.equals(name)) { found = true; zout.write(contents); } else { while ((bytesRead = zin.read(buffer)) != -1) zout.write(buffer, 0, bytesRead); } zout.closeEntry(); } } if (!found && !delete) { e = new ZipEntry(name); zout.putNextEntry(e); zout.write(contents); zout.closeEntry(); } zin.close(); zout.close(); File fp = new File(zipfile); fp.delete(); MLUtil.copyFile(temp, fp); temp.delete(); return (true); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } return (false); }
11
Code Sample 1: 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; } Code Sample 2: @Test public void testWrite() { System.out.println("write"); final File[] files = { new File(sharePath) }; System.out.println("Creating hash..."); String initHash = MD5File.MD5Directory(files[0]); System.out.println("Hash: " + initHash); Share readShare = ShareUtility.createShare(files, "TestShare"); System.out.println("Creating shares..."); final ShareFolder[] readers = ShareUtility.cropShareToParts(readShare, PARTS); System.out.println("Reading and writing shares..."); done = 0; for (int i = 0; i < PARTS; i++) { final int j = i; new Thread() { public void run() { ShareFolder part = (ShareFolder) ObjectClone.clone(readers[j]); ShareFileReader reader = new ShareFileReader(readers[j], files[0]); ShareFileWriter writer = new ShareFileWriter(part, new File("Downloads/" + readers[j].getName())); long tot = 0; byte[] b = new byte[(int) (Math.random() * 10000)]; while (tot < readers[j].getSize()) { reader.read(b); byte[] bwrite = new byte[(int) (Math.random() * 10000) + b.length]; System.arraycopy(b, 0, bwrite, 0, b.length); writer.write(bwrite, b.length); tot += b.length; } done++; System.out.println((int) (done * 100.0 / PARTS) + "% Complete"); } }.start(); } while (done < PARTS) { Thread.yield(); } File resultFile = new File("Downloads/" + readShare.getName()); System.out.println("Creating hash of written share..."); String resultHash = MD5File.MD5Directory(resultFile); System.out.println("Init hash: " + initHash); System.out.println("Result hash: " + resultHash); assertEquals(initHash, resultHash); }
11
Code Sample 1: public void run() { BufferedReader reader = null; log = "Downloading... " + name; setChanged(); notifyObservers(); try { Date marker = to; int previousSize = 0; list.clear(); do { previousSize = list.size(); URL url = new URL(createLink(from, marker)); reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; while ((line = reader.readLine()) != null) { try { IQuoteHistorical quote = parse(line + ","); if (quote != null && !list.contains(quote)) list.add(quote); else System.err.println(line); } catch (ParseException e) { e.printStackTrace(); } } if (list.size() > 0) marker = list.get(list.size() - 1).getData(); } while (marker.after(from) && previousSize != list.size()); log = "download Completed!"; } catch (MalformedURLException e) { e.printStackTrace(); log = e.getMessage(); } catch (IOException e) { e.printStackTrace(); log = e.getMessage(); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); log = e.getMessage(); } } setChanged(); notifyObservers(); } Code Sample 2: public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout) throws Throwable { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); con.setConnectTimeout(timeout); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public void updateDb(int scriptNumber) throws SQLException, IOException { String pathName = updatesPackage.replace(".", "/"); InputStream in = getClass().getClassLoader().getResourceAsStream(pathName + "/" + scriptNumber + ".sql"); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String script = out.toString("UTF-8"); String[] statements = script.split(";"); for (String statement : statements) { getJdbcTemplate().execute(statement); } }
11
Code Sample 1: public static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; } Code Sample 2: public String getChallengers() { InputStream is = null; String result = ""; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(domain); httppost.setEntity(new UrlEncodedFormEntity(library)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + ","); } is.close(); result = sb.toString(); if (result.equals("null,")) { return "none"; } else return result; } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return "none"; }
11
Code Sample 1: public static void main(String[] args) { FTPClient client = new FTPClient(); String sFTP = "ftp.servidor.com"; String sUser = "usuario"; String sPassword = "pasword"; try { System.out.println("Conectandose a " + sFTP); client.connect(sFTP); client.login(sUser, sPassword); System.out.println(client.printWorkingDirectory()); client.changeWorkingDirectory("\\httpdocs"); System.out.println(client.printWorkingDirectory()); System.out.println("Desconectando."); client.logout(); client.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: private static void getFileFtp(String user, String password, String host, int port, String fileName, String location) throws Exception { Log.info("\nretrieve " + fileName + NEW_LINE); FTPClient client = new FTPClient(); client.connect(host, port); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("FTP fail to connect"); } if (!client.login(user, password)) { throw new Exception("FTP fail to login"); } try { File locationFile = new File(location); File dest = new File(locationFile, fileName); if (dest.exists()) { dest.delete(); } else { locationFile.mkdirs(); } boolean status = client.changeWorkingDirectory("/"); Log.info("chdir-status:" + status + NEW_LINE); client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); client.setFileType(FTPClient.BINARY_FILE_TYPE); client.enterLocalActiveMode(); InputStream in = client.retrieveFileStream(fileName); if (in == null) { Log.error("Input stream is null\n"); throw new Exception("Fail to retrieve file " + fileName); } Thread.sleep(3000); saveInputStreamToFile(in, new File(location, fileName)); } finally { client.disconnect(); } }
00
Code Sample 1: public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: 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 version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public synchronized void run() { logger.info("SEARCH STARTED"); JSONObject json = null; logger.info("Opening urlConnection"); URLConnection connection = null; try { connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); } catch (IOException e) { logger.warn("PROBLEM CONTACTING GOOGLE"); e.printStackTrace(); } String line; StringBuilder builder = new StringBuilder(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } } catch (IOException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } logger.info("Google RET: " + builder.toString()); try { json = new JSONObject(builder.toString()); json.append("query", q); } catch (JSONException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } sc.onSearchFinished(json); }
00
Code Sample 1: public void init() throws IOException { if (this.inputStream == null) this.inputStream = new BufferedInputStream(url.openStream()); else { this.inputStream.close(); this.inputStream = new BufferedInputStream(url.openStream()); } } Code Sample 2: public void loadJar(final String extName, final String url, final String fileName, final IProgressListener pl) throws Exception { pl.setName(fileName); pl.setProgress(0); pl.setFinished(false); pl.setStarted(true); String installDirName = extDir + File.separator + extName; Log.log("extension installation directory: " + installDirName); File installDir = new File(installDirName); if (!installDir.exists()) { if (!installDir.mkdirs()) { throw new Exception("ExtensionLoader.loadJar: Cannot create install directory: " + installDirName); } } URL downloadURL = new URL(url + fileName); File jarFile = new File(installDirName, fileName); File indexFile = null; long urlTimeStamp = downloadURL.openConnection().getLastModified(); String indexFileName = ""; int idx = fileName.lastIndexOf("."); if (idx > 0) { indexFileName = fileName.substring(0, idx); } else { indexFileName = fileName; } indexFileName = indexFileName + ".idx"; Log.log("index filename: " + indexFileName); boolean isDirty = true; if (jarFile.exists()) { Log.log("extensionfile already exists: " + fileName); indexFile = new File(installDir, indexFileName); if (indexFile.exists()) { Log.log("indexfile already exists"); long cachedTimeStamp = readTimeStamp(indexFile); isDirty = !(cachedTimeStamp == urlTimeStamp); Log.log("cached file dirty: " + isDirty + ", url timestamp: " + urlTimeStamp + " cache stamp: " + cachedTimeStamp); } else { Log.log("indexfile doesn't exist, assume cache is dirty"); } } if (isDirty) { if (jarFile.exists()) { if (indexFile != null && indexFile.exists()) { Log.log("deleting old index file"); indexFile.delete(); } indexFile = new File(installDirName, indexFileName); Log.log("deleting old cached file"); jarFile.delete(); } downloadJar(downloadURL, jarFile, pl); indexFile = new File(installDir, indexFileName); Log.log("writing timestamp to index file"); writeTimeStamp(indexFile, urlTimeStamp); } addJar(jarFile); }
00
Code Sample 1: public void run() { if (isRunning) return; isRunning = true; Core core = Core.getInstance(); URL url = null; InputStream input = null; DataInputStream datastream; try { url = new URL(Constants.UpdateCheckUrl); } catch (MalformedURLException e) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } try { input = url.openStream(); } catch (IOException e) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } datastream = new DataInputStream(new BufferedInputStream(input)); String line = null; try { line = datastream.readLine(); } catch (IOException e) { e.printStackTrace(); if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } if (line == null) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } if (line.trim().equalsIgnoreCase(Constants.version)) { if (!firstRun) core.showMessage(0, core.getString("checkUpdateButton"), core.getString("versionMatch")); } else { core.showMessage(1, core.getString("checkUpdateButton"), core.getString("errorNewerVersion") + ": " + line); } isRunning = false; } Code Sample 2: public URLConnection getConnection() throws IOException { URLConnection con = url.openConnection(); con.setConnectTimeout(30 * 1000); if (username == null || "".equals(username) || password == null || "".equals(password)) return con; if (wsseMode) { con.setRequestProperty("X-WSSE", getWsseHeaderValue()); return con; } Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { PasswordAuthentication auth = null; if (username != null && password != null) { auth = new PasswordAuthentication(username, password.toCharArray()); } return auth; } }); return con; }
00
Code Sample 1: public static String toMd5(String s) { String res = ""; try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); res = toHexString(messageDigest); } catch (NoSuchAlgorithmException e) { } return res; } Code Sample 2: public static void download(URL url, File file, String userAgent) throws IOException { URLConnection conn = url.openConnection(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } InputStream in = conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); StreamUtil.copyThenClose(in, out); }
00
Code Sample 1: public void testGetRequestWithRefresh() throws Exception { expect(request.getParameter(ProxyBase.REFRESH_PARAM)).andReturn("120").anyTimes(); Capture<HttpRequest> requestCapture = new Capture<HttpRequest>(); expect(pipeline.execute(capture(requestCapture))).andReturn(new HttpResponse(RESPONSE_BODY)); replay(); handler.fetch(request, recorder); HttpRequest httpRequest = requestCapture.getValue(); assertEquals("public,max-age=120", recorder.getHeader("Cache-Control")); assertEquals(120, httpRequest.getCacheTtl()); } Code Sample 2: public static DBData resolveDBasURL(java.net.URL url) throws Exception { DBData data = null; InputStream fi = null; EnhancedStreamTokenizer tokenizer = null; try { fi = url.openStream(); tokenizer = new EnhancedStreamTokenizer(new BufferedReader(new InputStreamReader(fi))); initializeTokenizer(tokenizer); } catch (Exception e) { Console.getInstance().println("\nError occured while opening URL '" + url.toString() + "'"); Console.getInstance().println(e); return null; } if (tokenizer != null) { try { } finally { System.gc(); } } return data; }
11
Code Sample 1: public static boolean joinFiles(File dest, Collection<File> sources) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fos = new FileOutputStream(dest); for (File source : sources) { fis = new FileInputStream(source); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; } fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("error joining files to " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; } Code Sample 2: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
00
Code Sample 1: protected String contentString() { String result = null; URL url; String encoding = null; try { url = url(); URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); for (Enumeration e = bindingKeys().objectEnumerator(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); if (key.startsWith("?")) { connection.setRequestProperty(key.substring(1), valueForBinding(key).toString()); } } if (connection.getContentEncoding() != null) { encoding = connection.getContentEncoding(); } if (encoding == null) { encoding = (String) valueForBinding("encoding"); } if (encoding == null) { encoding = "UTF-8"; } InputStream stream = connection.getInputStream(); byte bytes[] = ERXFileUtilities.bytesFromInputStream(stream); stream.close(); result = new String(bytes, encoding); } catch (IOException ex) { throw NSForwardException._runtimeExceptionForThrowable(ex); } return result; } Code Sample 2: public int print(String type, String url, String attrs) throws PrinterException { try { return print(type, (new URL(url)).openStream(), attrs); } catch (Exception e) { e.printStackTrace(); throw new PrinterException(e); } }
11
Code Sample 1: public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); } Code Sample 2: public void actionPerformed(ActionEvent ev) { if (fileChooser == null) { fileChooser = new JFileChooser(); ExtensionFileFilter fileFilter = new ExtensionFileFilter("Device profile (*.jar, *.zip)"); fileFilter.addExtension("jar"); fileFilter.addExtension("zip"); fileChooser.setFileFilter(fileFilter); } if (fileChooser.showOpenDialog(SwingSelectDevicePanel.this) == JFileChooser.APPROVE_OPTION) { String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); JarFile jar = null; try { jar = new JarFile(fileChooser.getSelectedFile()); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } urls[0] = fileChooser.getSelectedFile().toURL(); } catch (IOException e) { Message.error("Error reading file: " + fileChooser.getSelectedFile().getName() + ", " + Message.getCauseMessage(e), e); return; } finally { if (jar != null) { try { jar.close(); } catch (IOException ignore) { } } } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileChooser.getSelectedFile().getName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { String entryName = (String) it.next(); try { devices.put(entryName, DeviceImpl.create(emulatorContext, classLoader, entryName, J2SEDevice.class)); } catch (IOException e) { Message.error("Error parsing device profile, " + Message.getCauseMessage(e), e); return; } } for (Enumeration en = lsDevicesModel.elements(); en.hasMoreElements(); ) { DeviceEntry entry = (DeviceEntry) en.nextElement(); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), fileChooser.getSelectedFile().getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(fileChooser.getSelectedFile(), deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } lsDevicesModel.addElement(entry); Config.addDeviceEntry(entry); } lsDevices.setSelectedValue(entry, true); } catch (IOException e) { Message.error("Error adding device profile, " + Message.getCauseMessage(e), e); return; } } }
11
Code Sample 1: public static String md5Hash(String inString) throws TopicSpacesException { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(inString.getBytes()); byte[] array = md5.digest(); StringBuffer buf = new StringBuffer(); int len = array.length; for (int i = 0; i < len; i++) { int b = array[i] & 0xFF; buf.append(Integer.toHexString(b)); } return buf.toString(); } catch (Exception x) { throw new TopicSpacesException(x); } } Code Sample 2: public String login(HttpSession callingSession, String username, String password) { String token = null; String customer = null; int timeoutInSeconds = 0; HashSet<Integer> tileProviderIds = new HashSet<Integer>(); boolean bLoginOk = false; String dbPassword = (String) em.createNamedQuery("getCustomerPasswordByUsername").setParameter("username", username).getSingleResult(); if (dbPassword.equals(password)) { CustomerElement ce = (CustomerElement) em.createNamedQuery("getCustomerByUsername").setParameter("username", username).getSingleResult(); customer = ce.getName(); timeoutInSeconds = ce.getTimeout(); String[] tileProviderIdsArray = ce.getTileProvideridsArray(); for (String tileProviderId : tileProviderIdsArray) tileProviderIds.add(Integer.parseInt(tileProviderId)); bLoginOk = true; } if (bLoginOk) { token = SessionHandler.getInstance().alreadyGotValidSession(customer); if (token == null) { Random random = new Random(); token = callingSession.getId() + new Date().getTime() + random.nextLong(); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Unable to digest the token.", e); } md5.update(token.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)); } token = sb.toString(); SessionHandler.getInstance().registerValidSession(token, customer, timeoutInSeconds, tileProviderIds); } } return token; }
00
Code Sample 1: public static final String getContent(String address) { String content = ""; OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new ByteArrayOutputStream(); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); } content = out.toString(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } return content; } Code Sample 2: protected void setRankOrder() { this.rankOrder = new int[values.length]; for (int i = 0; i < rankOrder.length; i++) { rankOrder[i] = i; assert (!Double.isNaN(values[i])); } for (int i = rankOrder.length - 1; i >= 0; i--) { boolean swapped = false; for (int j = 0; j < i; j++) if (values[rankOrder[j]] < values[rankOrder[j + 1]]) { int r = rankOrder[j]; rankOrder[j] = rankOrder[j + 1]; rankOrder[j + 1] = r; } } }
11
Code Sample 1: 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; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } } Code Sample 2: @Override protected void setUp() throws Exception { this.logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN); File repoFolder = new File("target/repository"); removeRepository(repoFolder); InputStream repoConfigIn = getClass().getResourceAsStream(REPO_CONFIG_FILE); File tempRepoConfigFile = File.createTempFile("repository", "xml"); tempRepoConfigFile.deleteOnExit(); OutputStream tempRepoConfigOut = new FileOutputStream(tempRepoConfigFile); try { IOUtils.copy(repoConfigIn, tempRepoConfigOut); } finally { repoConfigIn.close(); tempRepoConfigOut.close(); } Repository repo = new TransientRepository(tempRepoConfigFile.getAbsolutePath(), "target/repository"); ServerAdapterFactory factory = new ServerAdapterFactory(); RemoteRepository remoteRepo = factory.getRemoteRepository(repo); reg = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); reg.rebind(REMOTE_REPO_NAME, remoteRepo); session = repo.login(new SimpleCredentials(LOGIN, PWD.toCharArray()), WORKSPACE); InputStream nodeTypeDefIn = getClass().getResourceAsStream(MQ_JCR_XML_NODETYPES_FILE); JackrabbitInitializerHelper.setupRepository(session, new InputStreamReader(nodeTypeDefIn), ""); }
00
Code Sample 1: public void open(final String method, final java.net.URL url, boolean asyncFlag, final String userName, final String password) throws java.io.IOException { this.abort(); Proxy proxy = this.proxy; URLConnection c = proxy == null || proxy == Proxy.NO_PROXY ? url.openConnection() : url.openConnection(proxy); synchronized (this) { this.connection = c; this.isAsync = asyncFlag; this.requestMethod = method; this.requestURL = url; this.requestUserName = userName; this.requestPassword = password; } this.changeState(HttpRequest.STATE_LOADING, 0, null, null); } Code Sample 2: public InetSocketAddress getServerAddress() throws IOException { URL url = new URL(ADDRESS_SERVER_URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoOutput(true); con.setReadTimeout(2000); con.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = rd.readLine(); if (line == null) throw new IOException("Cannot read address from address server"); String addr[] = line.split(" ", 2); return new InetSocketAddress(addr[0], Integer.valueOf(addr[1])); }
11
Code Sample 1: @Override public void execute(String[] args) throws Exception { Options cmdLineOptions = getCommandOptions(); try { GnuParser parser = new GnuParser(); CommandLine commandLine = parser.parse(cmdLineOptions, TolvenPlugin.getInitArgs()); String srcRepositoryURLString = commandLine.getOptionValue(CMD_LINE_SRC_REPOSITORYURL_OPTION); Plugins libraryPlugins = RepositoryMetadata.getRepositoryPlugins(new URL(srcRepositoryURLString)); String srcPluginId = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_ID_OPTION); PluginDetail plugin = RepositoryMetadata.getPluginDetail(srcPluginId, libraryPlugins); if (plugin == null) { throw new RuntimeException("Could not locate plugin: " + srcPluginId + " in repository: " + srcRepositoryURLString); } String srcPluginVersionString = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_VERSION_OPTION); PluginVersionDetail srcPluginVersion = null; if (srcPluginVersion == null) { srcPluginVersion = RepositoryMetadata.getLatestVersion(plugin); } else { srcPluginVersion = RepositoryMetadata.getPluginVersionDetail(srcPluginVersionString, plugin); } if (plugin == null) { throw new RuntimeException("Could not find a plugin version for: " + srcPluginId + " in repository: " + srcRepositoryURLString); } String destPluginId = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_ID_OPTION); FileUtils.deleteDirectory(getPluginTmpDir()); URL srcURL = new URL(srcPluginVersion.getUri()); File newPluginDir = new File(getPluginTmpDir(), destPluginId); try { InputStream in = null; FileOutputStream out = null; File tmpZip = new File(getPluginTmpDir(), new File(srcURL.getFile()).getName()); try { in = srcURL.openStream(); out = new FileOutputStream(tmpZip); IOUtils.copy(in, out); TolvenZip.unzip(tmpZip, newPluginDir); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (tmpZip != null) { tmpZip.delete(); } } File pluginManifestFile = new File(newPluginDir, "tolven-plugin.xml"); if (!pluginManifestFile.exists()) { throw new RuntimeException(srcURL.toExternalForm() + "has no plugin manifest"); } Plugin pluginManifest = RepositoryMetadata.getPlugin(pluginManifestFile.toURI().toURL()); pluginManifest.setId(destPluginId); String destPluginVersion = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_VERSION_OPTION); if (destPluginVersion == null) { destPluginVersion = DEFAULT_DEST_VERSION; } pluginManifest.setVersion(destPluginVersion); String pluginManifestXML = RepositoryMetadata.getPluginManifest(pluginManifest); FileUtils.writeStringToFile(pluginManifestFile, pluginManifestXML); File pluginFragmentManifestFile = new File(newPluginDir, "tolven-plugin-fragment.xml"); if (pluginFragmentManifestFile.exists()) { PluginFragment pluginManifestFragment = RepositoryMetadata.getPluginFragment(pluginFragmentManifestFile.toURI().toURL()); Requires requires = pluginManifestFragment.getRequires(); if (requires == null) { throw new RuntimeException("No <requires> detected for plugin fragment in: " + srcURL.toExternalForm()); } if (requires.getImport().size() != 1) { throw new RuntimeException("There should be only one import for plugin fragment in: " + srcURL.toExternalForm()); } requires.getImport().get(0).setPluginId(destPluginId); requires.getImport().get(0).setPluginVersion(destPluginVersion); String pluginFragmentManifestXML = RepositoryMetadata.getPluginFragmentManifest(pluginManifestFragment); FileUtils.writeStringToFile(pluginFragmentManifestFile, pluginFragmentManifestXML); } String destDirname = commandLine.getOptionValue(CMD_LINE_DEST_DIR_OPTION); File destDir = new File(destDirname); File destZip = new File(destDir, destPluginId + "-" + destPluginVersion + ".zip"); destDir.mkdirs(); TolvenZip.zip(newPluginDir, destZip); } finally { if (newPluginDir != null) { FileUtils.deleteDirectory(newPluginDir); } } } catch (ParseException ex) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getName(), cmdLineOptions); throw new RuntimeException("Could not parse command line for: " + getClass().getName(), ex); } } Code Sample 2: public void render(ServiceContext serviceContext) throws Exception { if (serviceContext.getTemplateName() == null) throw new Exception("no Template defined for service: " + serviceContext.getServiceInfo().getRefName()); File f = new File(serviceContext.getTemplateName()); serviceContext.getResponse().setContentLength((int) f.length()); InputStream in = new FileInputStream(f); IOUtils.copy(in, serviceContext.getResponse().getOutputStream(), 0, (int) f.length()); in.close(); }
11
Code Sample 1: public he3Decode(String in_file) { try { File out = new File(in_file + extension); File in = new File(in_file); int file_size = (int) in.length(); FileInputStream in_stream = new FileInputStream(in_file); out.createNewFile(); FileOutputStream out_stream = new FileOutputStream(out.getName()); ByteArrayOutputStream os = new ByteArrayOutputStream(file_size); byte byte_arr[] = new byte[8]; int buff_size = byte_arr.length; int _fetched = 0; int _chars_read = 0; System.out.println(appname + ".\n" + "decoding: " + in_file + "\n" + "decoding to: " + in_file + extension + "\n" + "\nreading: "); while (_fetched < file_size) { _chars_read = in_stream.read(byte_arr, 0, buff_size); if (_chars_read == -1) break; os.write(byte_arr, 0, _chars_read); _fetched += _chars_read; System.out.print("*"); } System.out.print("\ndecoding: "); out_stream.write(_decode((ByteArrayOutputStream) os)); System.out.print("complete\n\n"); } catch (java.io.FileNotFoundException fnfEx) { System.err.println("Exception: " + fnfEx.getMessage()); } catch (java.io.IOException ioEx) { System.err.println("Exception: " + ioEx.getMessage()); } } Code Sample 2: @Test public void shouldDownloadFileUsingPublicLink() throws Exception { String bucketName = "test-" + UUID.randomUUID(); Service service = new WebClientService(credentials); service.createBucket(bucketName); File file = folder.newFile("foo.txt"); FileUtils.writeStringToFile(file, UUID.randomUUID().toString()); service.createObject(bucketName, file.getName(), file, new NullProgressListener()); String publicUrl = service.getPublicUrl(bucketName, file.getName(), new DateTime().plusDays(5)); File saved = folder.newFile("saved.txt"); InputStream input = new URL(publicUrl).openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(saved); IOUtils.copy(input, output); output.close(); assertThat("Corrupted download", Files.computeMD5(saved), equalTo(Files.computeMD5(file))); service.deleteObject(bucketName, file.getName()); service.deleteBucket(bucketName); }
11
Code Sample 1: public static void joinFiles(FileValidator validator, File target, File[] sources) { FileOutputStream fos = null; try { if (!validator.verifyFile(target)) return; fos = new FileOutputStream(target); FileInputStream fis = null; byte[] bytes = new byte[512]; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); int nbread = 0; try { while ((nbread = fis.read(bytes)) > -1) { fos.write(bytes, 0, nbread); } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { fis.close(); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } } Code Sample 2: public static void main(String[] args) throws Exception { File rootDir = new File("C:\\dev\\workspace_fgd\\gouvqc_crggid\\WebContent\\WEB-INF\\upload"); File storeDir = new File(rootDir, "storeDir"); File workDir = new File(rootDir, "workDir"); LoggerFacade loggerFacade = new CommonsLoggingLogger(logger); final FileResourceManager frm = new SmbFileResourceManager(storeDir.getPath(), workDir.getPath(), true, loggerFacade); frm.start(); final String resourceId = "811375c8-7cae-4429-9a0e-9222f47dab45"; { if (!frm.resourceExists(resourceId)) { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); FileInputStream inputStream = new FileInputStream(resourceId); frm.createResource(txId, resourceId); OutputStream outputStream = frm.writeResource(txId, resourceId); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); frm.prepareTransaction(txId); frm.commitTransaction(txId); } } for (int i = 0; i < 30; i++) { final int index = i; new Thread() { @Override public void run() { try { String txId = frm.generatedUniqueTxId(); frm.startTransaction(txId); InputStream inputStream = frm.readResource(resourceId); frm.prepareTransaction(txId); frm.commitTransaction(txId); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (début)"); } String contenu = TikaUtils.getParsedContent(inputStream, "file.pdf"); synchronized (System.out) { System.out.println(index + " ***********************" + txId + " (fin)"); } } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } catch (ResourceManagerException e) { throw new RuntimeException(e); } catch (TikaException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }.start(); } Thread.sleep(60000); frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); }
00
Code Sample 1: @Override public MapInfo getMap(int mapId) { MapInfo info = mapCache.get(mapId); if (info != null && info.getContent() == null) { if (info.getInfo().get("fileName") == null) { if (mapId != lastRequestedMap) { lastRequestedMap = mapId; System.out.println("MapLoaderClient::getMap:requesting map from server " + mapId); serverConnection.sendMessage(new MessageFetch(FetchType.map.name(), mapId)); } } else { try { System.out.println("MapLoaderClient::getMap:loading map from file " + info.getInfo().get("fileName")); BufferedReader bufferedreader; URL fetchUrl = new URL(localMapContextUrl, info.getInfo().get("fileName")); URLConnection urlconnection = fetchUrl.openConnection(); if (urlconnection.getContentEncoding() != null) { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding())); } else { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8")); } String line; StringBuilder mapContent = new StringBuilder(); while ((line = bufferedreader.readLine()) != null) { mapContent.append(line); mapContent.append("\n"); } info.setContent(mapContent.toString()); fireMapChanged(info); } catch (IOException _ex) { System.err.println("MapLoaderClient::getMap:: Can't read from " + info.getInfo().get("fileName")); } } } return info; } Code Sample 2: void readData() { String[] nextLine; int line; double value; URL url = null; String FileToRead; try { for (int i = 0; i < names.length; i++) { FileToRead = "data/" + names[i] + ".csv"; url = new URL(ja.getCodeBase(), FileToRead); System.out.println(url.toString()); InputStream in = url.openStream(); CSVReader reader = new CSVReader(new InputStreamReader(in)); line = 0; while ((nextLine = reader.readNext()) != null) { allset.months[line] = Integer.parseInt(nextLine[0].substring(0, 2)); allset.years[line] = Integer.parseInt(nextLine[0].substring(6, 10)); value = Double.parseDouble(nextLine[1]); allset.values.getDataRef()[line][i] = value; line++; } } } catch (IOException e) { System.err.println("File Read Exception"); } }
00
Code Sample 1: public static int load(Context context, URL url) throws Exception { int texture[] = new int[1]; GLES20.glGenTextures(1, texture, 0); int textureId = texture[0]; GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId); InputStream is = url.openStream(); Bitmap tmpBmp; try { tmpBmp = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch (IOException e) { } } GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_NEAREST); MyGLUtils.checkGlError("glTexParameterf GL_TEXTURE_MIN_FILTER"); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); MyGLUtils.checkGlError("glTexParameterf GL_TEXTURE_MAG_FILTER"); GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, tmpBmp, 0); MyGLUtils.checkGlError("texImage2D"); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); MyGLUtils.checkGlError("glGenerateMipmap"); tmpBmp.recycle(); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); return textureId; } Code Sample 2: public void initForEncryption() throws CryptographyException, IOException { String ownerPassword = pdDocument.getOwnerPasswordForEncryption(); String userPassword = pdDocument.getUserPasswordForEncryption(); if (ownerPassword == null) { ownerPassword = ""; } if (userPassword == null) { userPassword = ""; } PDStandardEncryption encParameters = (PDStandardEncryption) pdDocument.getEncryptionDictionary(); int permissionInt = encParameters.getPermissions(); int revision = encParameters.getRevision(); int length = encParameters.getLength() / 8; COSArray idArray = document.getDocumentID(); if (idArray == null || idArray.size() < 2) { idArray = new COSArray(); try { MessageDigest md = MessageDigest.getInstance("MD5"); BigInteger time = BigInteger.valueOf(System.currentTimeMillis()); md.update(time.toByteArray()); md.update(ownerPassword.getBytes()); md.update(userPassword.getBytes()); md.update(document.toString().getBytes()); byte[] id = md.digest(this.toString().getBytes()); COSString idString = new COSString(); idString.append(id); idArray.add(idString); idArray.add(idString); document.setDocumentID(idArray); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e); } } COSString id = (COSString) idArray.getObject(0); encryption = new PDFEncryption(); byte[] o = encryption.computeOwnerPassword(ownerPassword.getBytes("ISO-8859-1"), userPassword.getBytes("ISO-8859-1"), revision, length); byte[] u = encryption.computeUserPassword(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encryptionKey = encryption.computeEncryptedKey(userPassword.getBytes("ISO-8859-1"), o, permissionInt, id.getBytes(), revision, length); encParameters.setOwnerKey(o); encParameters.setUserKey(u); document.setEncryptionDictionary(encParameters.getCOSDictionary()); }
00
Code Sample 1: public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public float stampPerson(PEntry pe) throws SQLException { conn.setAutoCommit(false); float result; try { Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("SELECT now();"); rset.next(); Timestamp now = rset.getTimestamp("now()"); Calendar cal = new GregorianCalendar(); cal.setTime(now); if (pe.getState() != 0) { for (int i = 0; i < pe.getOpenItems().size(); i++) { Workitem wi = (Workitem) pe.getOpenItems().get(i); long diff = now.getTime() - wi.getIntime(); float diffp = diff * (float) 1f / pe.getOpenItems().size(); stmt.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + wi.getStampZkId() + "';"); } rset = stmt.executeQuery("SELECT intime FROM stamppersonal WHERE stamppersonalid='" + pe.getState() + "';"); rset.next(); long inDate = rset.getLong("intime"); long diff = (now.getTime() - inDate); stmt.executeUpdate("UPDATE stamppersonal SET outtime='" + now.getTime() + "', diff='" + diff + "' WHERE stamppersonalid='" + pe.getState() + "';"); stmt.executeUpdate("UPDATE personal SET stamppersonalid='0' WHERE personalnr='" + pe.getPersonalId() + "';"); stmt.executeUpdate("UPDATE personalyearworktime SET worktime=worktime+" + (float) diff / 3600000f + " WHERE year=" + cal.get(Calendar.YEAR) + " AND personalid='" + pe.getPersonalId() + "';"); rset = stmt.executeQuery("SELECT SUM(diff) AS twt FROM stamppersonal WHERE personalid='" + pe.getPersonalId() + "' AND datum='" + cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH) + "';"); rset.next(); result = (float) rset.getInt("twt") / 3600000f; } else { stmt.executeUpdate("INSERT INTO stamppersonal SET personalid='" + pe.getPersonalId() + "', intime='" + now.getTime() + "', datum='" + cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH) + "';"); rset = stmt.executeQuery("SELECT stamppersonalid FROM stamppersonal WHERE personalid='" + pe.getPersonalId() + "' AND outtime='0' ORDER BY stamppersonalid DESC LIMIT 1;"); rset.next(); int sppid = rset.getInt("stamppersonalid"); stmt.executeUpdate("UPDATE personal SET stamppersonalid='" + sppid + "' WHERE personalnr='" + pe.getPersonalId() + "';"); Calendar yest = new GregorianCalendar(); yest.setTime(now); yest.add(Calendar.DAY_OF_YEAR, -1); rset = stmt.executeQuery("SELECT SUM(diff) AS twt FROM stamppersonal WHERE personalid='" + pe.getPersonalId() + "' AND datum='" + cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH) + "';"); rset.next(); float today = (float) rset.getInt("twt") / 3600000f; rset = stmt.executeQuery("SELECT worktime FROM personalyearworktime WHERE personalid='" + pe.getPersonalId() + "' AND year='" + cal.get(Calendar.YEAR) + "';"); rset.next(); float ist = rset.getFloat("worktime") - today; rset = stmt.executeQuery("SELECT duetime FROM dueworktime WHERE datum='" + yest.get(Calendar.YEAR) + "-" + (yest.get(Calendar.MONTH) + 1) + "-" + yest.get(Calendar.DAY_OF_MONTH) + "' AND personalid='" + pe.getPersonalId() + "';"); rset.next(); result = ist - rset.getFloat("duetime"); } } catch (SQLException sqle) { conn.rollback(); conn.setAutoCommit(true); throw sqle; } conn.commit(); conn.setAutoCommit(true); return result; }
00
Code Sample 1: public static boolean insereLicao(final Connection con, Licao lic, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodLicao(con, lic); String titulo = lic.getTitulo().replaceAll("['\"]", ""); String coment = lic.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO licao VALUES(" + lic.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO lic_aut VALUES(" + lic.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "LICAO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } } Code Sample 2: private void copy(File source, File destination) throws PackageException { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(destination); byte[] buff = new byte[1024]; int len; while ((len = in.read(buff)) > 0) out.write(buff, 0, len); in.close(); out.close(); } catch (IOException e) { throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString()); } }
11
Code Sample 1: public void dispatch(com.sun.star.util.URL aURL, com.sun.star.beans.PropertyValue[] aArguments) { if (aURL.Protocol.compareTo("org.openoffice.oosvn.oosvn:") == 0) { OoDocProperty docProperty = getProperty(); settings.setCancelFired(false); if (aURL.Path.compareTo("svnUpdate") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (NullPointerException ex) { new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; new DialogFileChooser(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = -1; if (logs.length == 0) { error("Sorry, the specified repository is empty."); return; } new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); if (settings.getCancelFired()) return; File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File[] tempFiles = tempDir.listFiles(); File anyOdt = null; File thisOdt = null; for (int j = 0; j < tempFiles.length; j++) { if (tempFiles[j].toString().endsWith(".odt")) anyOdt = tempFiles[j]; if (tempFiles[j].toString().equals(settings.getCheckoutDoc()) && settings.getCheckoutDoc() != null) thisOdt = tempFiles[j]; } if (thisOdt != null) anyOdt = thisOdt; String url; if (settings.getCheckoutDoc() == null || !settings.getCheckoutDoc().equals(anyOdt.getName())) { File newOdt = new File(settings.getCheckoutPath() + "/" + anyOdt.getName()); if (newOdt.exists()) newOdt.delete(); anyOdt.renameTo(newOdt); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } url = "file:///" + newOdt.getPath().replace("\\", "/"); svnInfo.renameTo(newSvnInfo); anyOdt = newOdt; loadDocumentFromUrl(url); settings.setCheckoutDoc(anyOdt.getName()); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } else { try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } url = "file:///" + anyOdt.getPath().replace("\\", "/"); XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, m_xFrame); PropertyValue property[] = new PropertyValue[1]; property[0] = new PropertyValue(); property[0].Name = "URL"; property[0].Value = url; XMultiServiceFactory xMSF = createProvider(); Object objDispatchHelper = m_xServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", m_xContext); XDispatchHelper xDispatchHelper = (XDispatchHelper) UnoRuntime.queryInterface(XDispatchHelper.class, objDispatchHelper); xDispatchHelper.executeDispatch(xDispatchProvider, ".uno:CompareDocuments", "", 0, property); } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnCommit") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Collection logs = svnWorker.getLogs(settings); long headRevision = svnWorker.getHeadRevisionNumber(logs); long committedRevision = -1; new DialogCommitMessage(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } if (headRevision == 0) { File impDir = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import"); if (impDir.exists()) if (deleteFileDir(impDir) == false) { error("Error while creating temporary import directory."); return; } if (!impDir.mkdirs()) { error("Error while creating temporary import directory."); return; } File impFile = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import/" + settings.getCheckoutDoc()); try { FileChannel srcChannel = new FileInputStream(settings.getCheckoutPath() + "/" + settings.getCheckoutDoc()).getChannel(); FileChannel dstChannel = new FileOutputStream(impFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { error("Error while importing file", ex); return; } final String checkoutPath = settings.getCheckoutPath(); try { settings.setCheckoutPath(impDir.toString()); committedRevision = svnWorker.importDirectory(settings, false).getNewRevision(); } catch (Exception ex) { settings.setCheckoutPath(checkoutPath); error("Error while importing file", ex); return; } settings.setCheckoutPath(checkoutPath); if (impDir.exists()) if (deleteFileDir(impDir) == false) error("Error while creating temporary import directory."); try { File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); svnInfo.renameTo(newSvnInfo); if (deleteFileDir(tempDir) == false) { error("Error while managing working copy"); } try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } catch (Exception ex) { error("Error while checking out a working copy for the location", ex); } showMessageBox("Import succesful", "Succesfully imported as revision no. " + committedRevision); return; } else { try { committedRevision = svnWorker.commit(settings, false).getNewRevision(); } catch (Exception ex) { error("Error while committing changes. If the file is not working copy, you must use 'Checkout / Update' first.", ex); } if (committedRevision == -1) { showMessageBox("Update - no changes", "No changes was made. Maybe you must just save the changes."); } else { showMessageBox("Commit succesfull", "Commited as revision no. " + committedRevision); } } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnHistory") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = settings.getCheckoutVersion(); settings.setCheckoutVersion(-99); new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); settings.setCheckoutVersion(checkVersion); } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("settings") == 0) { try { settings = getSerializedSettings(docProperty); } catch (NoSerializedSettingsException ex) { try { settings.setCheckout(docProperty.getDocURL()); } catch (Exception exx) { } } catch (Exception ex) { error("Error getting settings; maybe you" + " need to save your document." + " If this is your first" + " checkout of the document, use Checkout" + " function directly."); return; } new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when saving settings.", ex); } return; } if (aURL.Path.compareTo("about") == 0) { showMessageBox("OoSvn :: About", "Autor: �t�p�n Cenek ([email protected])"); return; } } } 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()); }
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: void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } }
00
Code Sample 1: public static byte[] computeMD5(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(s.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } } Code Sample 2: private String readLine(final String urlStr) { BufferedReader reader; String line = null; try { URL url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream())); line = reader.readLine(); } catch (MalformedURLException e) { log.error(e, e); } catch (IOException e) { log.error(e, e); } return line; }
11
Code Sample 1: public void copy(File from, String to) throws SystemException { assert from != null; File dst = new File(folder, to); dst.getParentFile().mkdirs(); FileChannel in = null; FileChannel out = null; try { if (!dst.exists()) dst.createNewFile(); in = new FileInputStream(from).getChannel(); out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { throw new SystemException(e); } finally { try { if (in != null) in.close(); } catch (Exception e1) { } try { if (out != null) out.close(); } catch (Exception e1) { } } } Code Sample 2: @Override public String getPath() { InputStream in = null; OutputStream out = null; File file = null; try { file = File.createTempFile("java-storage_" + RandomStringUtils.randomAlphanumeric(32), ".tmp"); file.deleteOnExit(); out = new FileOutputStream(file); in = openStream(); IOUtils.copy(in, out); } catch (IOException e) { throw new RuntimeException(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } if (file != null && file.exists()) { return file.getPath(); } return null; }
11
Code Sample 1: private String save(UploadedFile imageFile) { try { File saveFld = new File(imageFolder + File.separator + userDisplay.getUser().getUsername()); if (!saveFld.exists()) { if (!saveFld.mkdir()) { logger.info("Unable to create folder: " + saveFld.getAbsolutePath()); return null; } } File tmp = File.createTempFile("img", "img"); IOUtils.copy(imageFile.getInputstream(), new FileOutputStream(tmp)); File thumbnailImage = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png"); File fullResolution = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png"); BufferedImage image = ImageIO.read(tmp); Image thumbnailIm = image.getScaledInstance(310, 210, Image.SCALE_SMOOTH); BufferedImage thumbnailBi = new BufferedImage(thumbnailIm.getWidth(null), thumbnailIm.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics bg = thumbnailBi.getGraphics(); bg.drawImage(thumbnailIm, 0, 0, null); bg.dispose(); ImageIO.write(thumbnailBi, "png", thumbnailImage); ImageIO.write(image, "png", fullResolution); if (!tmp.delete()) { logger.info("Unable to delete: " + tmp.getAbsolutePath()); } String imageId = UUID.randomUUID().toString(); imageBean.addImage(imageId, new ImageRecord(imageFile.getFileName(), fullResolution.getAbsolutePath(), thumbnailImage.getAbsolutePath(), userDisplay.getUser().getUsername())); return imageId; } catch (Throwable t) { logger.log(Level.SEVERE, "Unable to save the image.", t); return null; } } Code Sample 2: @Test public void testWriteModel() { Model model = new Model(); model.setName("MY_MODEL1"); Stereotype st1 = new Stereotype(); st1.setName("Pirulito1"); PackageObject p1 = new PackageObject("p1"); ClassType type1 = new ClassType("Class1"); type1.setStereotype(st1); type1.addMethod(new Method("doSomething")); p1.add(type1); ClassType type2 = new ClassType("Class2"); Method m2 = new Method("doSomethingElse"); m2.setType(type1); type2.addMethod(m2); p1.add(type2); Generalization g = new Generalization(); g.setSource(type1); g.setTarget(type1); p1.add(g); model.add(p1); ModelWriter writer = new ModelWriter(); try { File modelFile = new File("target", "test.model"); writer.write(model, modelFile); File xmlFile = new File("target", "test.xml"); xmlFile.createNewFile(); IOUtils.copy(new GZIPInputStream(new FileInputStream(modelFile)), new FileOutputStream(xmlFile)); } catch (IOException e) { log.error(e.getMessage(), e); Assert.fail(e.getMessage()); } }
11
Code Sample 1: public static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } } Code Sample 2: public void searchEntity(HttpServletRequest req, HttpServletResponse resp, SearchCommand command) { setHeader(resp); logger.debug("Search: Looking for the entity with the id:" + command.getSearchedid()); String login = command.getLogin(); String password = command.getPassword(); SynchronizableUser currentUser = userAccessControl.authenticate(login, password); if (currentUser != null) { try { File tempFile = File.createTempFile("medoo", "search"); OutputStream fos = new FileOutputStream(tempFile); syncServer.searchEntity(currentUser, command.getSearchedid(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); } catch (ImogSerializationException ex) { logger.error(ex.getMessage(), ex); } } else { try { OutputStream out = resp.getOutputStream(); out.write("-ERROR-".getBytes()); out.flush(); out.close(); logger.debug("Search: user " + login + " has not been authenticated"); } catch (IOException ioe) { ioe.printStackTrace(); } } }
11
Code Sample 1: private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); } Code Sample 2: public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
11
Code Sample 1: private void copyFile(File file, File targetFile) { try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] tmp = new byte[8192]; int read = -1; while ((read = bis.read(tmp)) > 0) { bos.write(tmp, 0, read); } bis.close(); bos.close(); } catch (Exception e) { if (!targetFile.delete()) { System.err.println("Ups, created copy cant be deleted (" + targetFile.getAbsolutePath() + ")"); } } } Code Sample 2: public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) { URL url = getRecurso(pantalla); try { IOUtils.copy(url.openStream(), response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void testclass(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.emptyClass(ClassWriter.ACC_PUBLIC, "TestClass", "java/lang/Object"); MethodInfo newMethod = writer.addMethod(ClassWriter.ACC_PUBLIC | ClassWriter.ACC_STATIC, "main", "([Ljava/lang/String;)V"); CodeAttribute attribute = newMethod.getCodeAttribute(); int constantIndex = writer.getStringConstantIndex("It's alive! It's alive!!"); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int methodRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); ArrayList instructions = new ArrayList(); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); operands = new byte[1]; operands[0] = (byte) constantIndex; instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("ldc"), 0, operands, false)); operands = new byte[2]; NetByte.intToPair(methodRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("return"), 0, null, false)); attribute.insertInstructions(0, 0, instructions); attribute.setMaxLocals(1); attribute.codeCheck(); System.out.println("constantIndex=" + constantIndex + " fieldRef=" + fieldRefIndex + " methodRef=" + methodRefIndex); writer.writeClass(new FileOutputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); writer.readClass(new FileInputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); }
11
Code Sample 1: private List<File> ungzipFile(File directory, File compressedFile) throws IOException { List<File> files = new ArrayList<File>(); TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile))); try { TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { log.warn("TAR archive contains directories which are being ignored"); entry = in.getNextTarEntry(); continue; } String fn = new File(entry.getName()).getName(); if (fn.startsWith(".")) { log.warn("TAR archive contains a hidden file which is being ignored"); entry = in.getNextTarEntry(); continue; } File targetFile = new File(directory, fn); if (targetFile.exists()) { log.warn("TAR archive contains duplicate filenames, only the first is being extracted"); entry = in.getNextTarEntry(); continue; } files.add(targetFile); log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath()); OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream entryIn = new FileInputStream(entry.getFile()); IOUtils.copy(entryIn, fout); fout.close(); entryIn.close(); } } finally { in.close(); } return files; } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: private List<String> readUrl(URL url) throws IOException { List<String> lines = new ArrayList<String>(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { lines.add(str); } in.close(); return lines; } Code Sample 2: private Image getIcon(Element e) { if (!addIconsToButtons) { return null; } else { NodeList nl = e.getElementsByTagName("rc:iconURL"); if (nl.getLength() > 0) { String urlString = nl.item(0).getTextContent(); try { Image img = new Image(Display.getCurrent(), new URL(urlString).openStream()); return img; } catch (Exception exception) { logger.warn("Can't read " + urlString + " using default icon instead."); } } return new Image(Display.getCurrent(), this.getClass().getResourceAsStream("/res/default.png")); } }
11
Code Sample 1: public void onUploadClicked(Event event) { Media[] medias = null; try { medias = Fileupload.get("Select one or more files to upload to " + "the current directory.", "Upload Files", 5); } catch (Exception e) { log.error("An exception occurred when displaying the file " + "upload dialog", e); } if (medias == null) { return; } for (Media media : medias) { String name = media.getName(); CSPath potentialFile = model.getPathForFile(name); if (media.isBinary()) { CSPathOutputStream writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathOutputStream(potentialFile); IOUtils.copy(media.getStreamData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } else { CSPathWriter writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathWriter(potentialFile); IOUtils.write(media.getStringData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } model.fileCleanup(potentialFile); updateFileGrid(); } } Code Sample 2: private void fileMaker() { try { long allData = 0; double a = 10; int range = 0; int blockLength = 0; File newFile = new File(mfr.getFilename() + ".part"); if (newFile.exists()) { newFile.delete(); } ArrayList<DataRange> rangeList = null; byte[] data = null; newFile.createNewFile(); ByteBuffer buffer = ByteBuffer.allocate(mfr.getBlocksize()); FileChannel rChannel = new FileInputStream(inputFileName).getChannel(); FileChannel wChannel = new FileOutputStream(newFile, true).getChannel(); System.out.println(); System.out.print("File completion: "); System.out.print("|----------|"); openConnection(); http.getResponseHeader(); for (int i = 0; i < fileMap.length; i++) { fileOffset = fileMap[i]; if (fileOffset != -1) { rChannel.read(buffer, fileOffset); buffer.flip(); wChannel.write(buffer); buffer.clear(); } else { if (!rangeQueue) { rangeList = rangeLookUp(i); range = rangeList.size(); openConnection(); http.setRangesRequest(rangeList); http.sendRequest(); http.getResponseHeader(); data = http.getResponseBody(mfr.getBlocksize()); allData += http.getAllTransferedDataLength(); } if ((i * mfr.getBlocksize() + mfr.getBlocksize()) < mfr.getLength()) { blockLength = mfr.getBlocksize(); } else { blockLength = (int) ((int) (mfr.getBlocksize()) + (mfr.getLength() - (i * mfr.getBlocksize() + mfr.getBlocksize()))); } buffer.put(data, (range - rangeList.size()) * mfr.getBlocksize(), blockLength); buffer.flip(); wChannel.write(buffer); buffer.clear(); rangeList.remove(0); if (rangeList.isEmpty()) { rangeQueue = false; } } if ((((double) i / ((double) fileMap.length - 1)) * 100) >= a) { progressBar(((double) i / ((double) fileMap.length - 1)) * 100); a += 10; } } newFile.setLastModified(getMTime()); sha = new SHA1(newFile); if (sha.SHA1sum().equals(mfr.getSha1())) { System.out.println("\nverifying download...checksum matches OK"); System.out.println("used " + (mfr.getLength() - (mfr.getBlocksize() * missing)) + " " + "local, fetched " + (mfr.getBlocksize() * missing)); new File(mfr.getFilename()).renameTo(new File(mfr.getFilename() + ".zs-old")); newFile.renameTo(new File(mfr.getFilename())); allData += mfr.getLengthOfMetafile(); System.out.println("really downloaded " + allData); double overhead = ((double) (allData - (mfr.getBlocksize() * missing)) / ((double) (mfr.getBlocksize() * missing))) * 100; System.out.println("overhead: " + df.format(overhead) + "%"); } else { System.out.println("\nverifying download...checksum don't match"); System.out.println("Deleting temporary file"); newFile.delete(); System.exit(1); } } catch (IOException ex) { System.out.println("Can't read or write, check your permissions."); System.exit(1); } }
00
Code Sample 1: public static void pingSearchEngine(String engineURL) throws MalformedURLException, UnsupportedEncodingException { if ((ConfigurationManager.getProperty("http.proxy.host") != null) && (ConfigurationManager.getProperty("http.proxy.port") != null)) { System.setProperty("proxySet", "true"); System.setProperty("proxyHost", ConfigurationManager.getProperty("http.proxy.host")); System.getProperty("proxyPort", ConfigurationManager.getProperty("http.proxy.port")); } String sitemapURL = ConfigurationManager.getProperty("dspace.url") + "/sitemap"; URL url = new URL(engineURL + URLEncoder.encode(sitemapURL, "UTF-8")); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer resp = new StringBuffer(); while ((inputLine = in.readLine()) != null) { resp.append(inputLine).append("\n"); } in.close(); if (connection.getResponseCode() == 200) { log.info("Pinged " + url.toString() + " successfully"); } else { log.warn("Error response pinging " + url.toString() + ":\n" + resp); } } catch (IOException e) { log.warn("Error pinging " + url.toString(), e); } } Code Sample 2: public static String getMD5(String text) { if (text == null) { return null; } String result = null; try { MessageDigest md5 = MessageDigest.getInstance(ALG_MD5); md5.update(text.getBytes(ENCODING)); result = "" + new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; }
00
Code Sample 1: private void initialize(OAIRepository repo, String u, String v, String params) throws OAIException { oParent = repo; strVerb = v; strBaseURL = u; strParams = params; strResumptionToken = ""; iResumptionCount = 0; boolInitialized = false; boolValidResponse = false; iIndex = 1; iCount = -1; iCursor = -1; iRealCursor = -1; iCompleteListSize = -1; if (!strVerb.equals("ListIdentifiers") && !strVerb.equals("ListMetadataFormats") && !strVerb.equals("ListRecords") && !strVerb.equals("ListSets")) { throw new OAIException(OAIException.INVALID_VERB_ERR, "Invalid verb"); } if (strBaseURL.length() == 0) { throw new OAIException(OAIException.NO_BASE_URL_ERR, "No baseURL"); } if (params.length() > 0) { if (params.charAt(0) != '&') { params = "&" + params; } } try { URL url = new URL(strBaseURL + "?verb=" + strVerb + params); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http = oParent.frndTrySend(http); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); if (oParent.getValidation() == OAIRepository.VALIDATION_VERY_STRICT) { docFactory.setValidating(true); } else { docFactory.setValidating(false); } DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); try { xml = docBuilder.parse(http.getInputStream()); boolValidResponse = true; } catch (IllegalArgumentException iae) { throw new OAIException(OAIException.CRITICAL_ERR, iae.getMessage()); } catch (SAXException se) { if (oParent.getValidation() != OAIRepository.VALIDATION_LOOSE) { throw new OAIException(OAIException.XML_PARSE_ERR, se.getMessage() + " Try loose validation."); } else { try { http.disconnect(); url = new URL(strBaseURL + "?verb=" + strVerb + params); http = (HttpURLConnection) url.openConnection(); http = oParent.frndTrySend(http); xml = docBuilder.parse(priCreateDummyResponse(http.getInputStream())); } catch (SAXException se2) { throw new OAIException(OAIException.XML_PARSE_ERR, se2.getMessage()); } } } namespaceNode = xml.createElement(strVerb); namespaceNode.setAttribute("xmlns:oai", OAIRepository.XMLNS_OAI + strVerb); namespaceNode.setAttribute("xmlns:dc", OAIRepository.XMLNS_DC); PrefixResolverDefault prefixResolver = new PrefixResolverDefault(namespaceNode); XPath xpath = new XPath("//oai:" + strVerb + "/oai:" + priGetMainNodeName(), null, prefixResolver, XPath.SELECT, null); XPathContext xpathSupport = new XPathContext(); int ctxtNode = xpathSupport.getDTMHandleFromNode(xml); XObject list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); Node node = list.nodeset().nextNode(); if (node == null) { namespaceNode.setAttribute("xmlns:oai", OAIRepository.XMLNS_OAI_2_0); prefixResolver = new PrefixResolverDefault(namespaceNode); xpath = new XPath("/oai:OAI-PMH", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); node = list.nodeset().nextNode(); if (node == null) { namespaceNode.setAttribute("xmlns:oai", OAIRepository.XMLNS_OAI_1_0 + strVerb); } else { xpath = new XPath("oai:OAI-PMH/oai:error", null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); NodeList nl = list.nodelist(); if (nl.getLength() > 0) { oParent.frndSetErrors(nl); throw new OAIException(OAIException.OAI_ERR, oParent.getLastOAIError().getCode() + ": " + oParent.getLastOAIError().getReason()); } } } xpath = new XPath("//oai:" + strVerb + "/oai:" + priGetMainNodeName(), null, prefixResolver, XPath.SELECT, null); list = xpath.execute(xpathSupport, ctxtNode, prefixResolver); nodeList = list.nodelist(); boolInitialized = true; oParent.frndSetNamespaceNode(namespaceNode); xpath = new XPath("//oai:requestURL | //oai:request", null, prefixResolver, XPath.SELECT, null); node = xpath.execute(xpathSupport, ctxtNode, prefixResolver).nodeset().nextNode(); if (node != null) { oParent.frndSetRequest(node); } oParent.frndSetResponseDate(getResponseDate()); docFactory = null; docBuilder = null; url = null; prefixResolver = null; xpathSupport = null; xpath = null; } catch (TransformerException te) { throw new OAIException(OAIException.CRITICAL_ERR, te.getMessage()); } catch (MalformedURLException mue) { throw new OAIException(OAIException.CRITICAL_ERR, mue.getMessage()); } catch (FactoryConfigurationError fce) { throw new OAIException(OAIException.CRITICAL_ERR, fce.getMessage()); } catch (ParserConfigurationException pce) { throw new OAIException(OAIException.CRITICAL_ERR, pce.getMessage()); } catch (IOException ie) { throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage()); } } Code Sample 2: protected String getGraphPath(String name) throws ServletException { String hash; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(name.getBytes()); hash = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to hash file name: " + e); } File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); return tempDir.getAbsolutePath() + File.separatorChar + hash; }
00
Code Sample 1: public boolean addFavBoard(BoardObject board) throws NetworkException, ContentException { String url = HttpConfig.bbsURL() + HttpConfig.BBS_FAV_ADD + board.getId(); HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(url); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isHttp200(response) && HTTPUtil.isXmlContentType(response)) { HTTPUtil.consume(response.getEntity()); return true; } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } } Code Sample 2: public void get(String path, File fileToGet) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, this.endpointPort); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp get server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); OutputStream output = new FileOutputStream(fileToGet.getName()); if (ftp.retrieveFile(path, output) != true) { ftp.logout(); output.close(); throw new IOException("FTP get exception, maybe file not found"); } ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } }
11
Code Sample 1: @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType(req.getContentType()); IOUtils.copy(req.getReader(), resp.getWriter()); } Code Sample 2: private void copyThemeProviderClass() throws Exception { InputStream is = getClass().getResourceAsStream("/zkthemer/ThemeProvider.class"); if (is == null) throw new RuntimeException("Cannot find ThemeProvider.class"); File outFile = new File(theme.getJarRootFile(), "zkthemer/ThemeProvider.class"); outFile.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(outFile); IOUtils.copy(is, out); out.close(); FileUtils.writeStringToFile(new File(theme.getJarRootFile(), "zkthemer.properties"), "theme=" + theme.getName() + "\r\nfileList=" + fileList.deleteCharAt(fileList.length() - 1).toString()); }
11
Code Sample 1: public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) { boolean flag = false; try { FileOutputStream fos = new FileOutputStream(pFile, pAppend); IOUtils.copy(pIs, fos); fos.flush(); fos.close(); pIs.close(); flag = true; } catch (Exception e) { LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); }
00
Code Sample 1: private String generateStorageDir(String stringToBeHashed) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(stringToBeHashed.getBytes()); byte[] hashedKey = digest.digest(); return Util.encodeArrayToHexadecimalString(hashedKey); } Code Sample 2: public ProgramSymbol deleteProgramSymbol(int id) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramSymbols " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); query = "DELETE FROM ProgramSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return programSymbol; }
11
Code Sample 1: private static void replaceEntityMappings(File signserverearpath, File entityMappingXML) throws ZipException, IOException { ZipInputStream earFile = new ZipInputStream(new FileInputStream(signserverearpath)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream tempZip = new ZipOutputStream(baos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("signserver-ejb.jar")) { content = replaceEntityMappings(content, entityMappingXML); next = new ZipEntry("signserver-ejb.jar"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); FileOutputStream fos = new FileOutputStream(signserverearpath); fos.write(baos.toByteArray()); fos.close(); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public static void resourceToFile(final String resource, final String filePath) throws IOException { log.debug("Classloader is " + IOCopyUtils.class.getClassLoader()); InputStream in = IOCopyUtils.class.getResourceAsStream(resource); if (in == null) { log.warn("Resource not '" + resource + "' found. Try to prefix with '/'"); in = IOCopyUtils.class.getResourceAsStream("/" + resource); } if (in == null) { throw new IOException("Resource not '" + resource + "' found."); } final File file = new File(filePath); final OutputStream out = FileUtils.openOutputStream(file); final int bytes = IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)"); } Code Sample 2: private void redownloadResource(SchemaResource resource) { if (_redownloadSet != null) { if (_redownloadSet.contains(resource)) return; _redownloadSet.add(resource); } String filename = resource.getFilename(); String schemaLocation = resource.getSchemaLocation(); String digest = null; if (schemaLocation == null || filename == null) return; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { URL url = new URL(schemaLocation); URLConnection conn = url.openConnection(); conn.addRequestProperty("User-Agent", USER_AGENT); conn.addRequestProperty("Accept", "application/xml, text/xml, */*"); DigestInputStream input = digestInputStream(conn.getInputStream()); IOUtil.copyCompletely(input, buffer); digest = HexBin.bytesToString(input.getMessageDigest().digest()); } catch (Exception e) { warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); return; } if (digest.equals(resource.getSha1()) && fileExists(filename)) { warning("Resource " + filename + " is unchanged from " + schemaLocation + "."); return; } try { InputStream source = new ByteArrayInputStream(buffer.toByteArray()); writeInputStreamToFile(source, filename); } catch (IOException e) { warning("Could not write to file " + filename + " for " + schemaLocation + ":" + e.getMessage()); return; } warning("Refreshed " + filename + " from " + schemaLocation); }
00
Code Sample 1: public static void convert(URL url, PrintWriter writer, String server) { try { XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON); XPath xpe = xpf.newXPath(); InputStream is = null; try { is = url.openStream(); } catch (IOException e) { e.printStackTrace(); } Document doc = readFromStream(is); xpe.setNamespaceContext(new NamespaceContext() { public String getNamespaceURI(String s) { if (s.equals("tns")) { return "http://services.remote/"; } else if (s.equals("xsd")) { return "http://www.w3.org/2001/XMLSchema"; } else if (s.equals("soap")) { return "http://schemas.xmlsoap.org/wsdl/soap/"; } else if (s.equals(XMLConstants.DEFAULT_NS_PREFIX)) { return "http://schemas.xmlsoap.org/wsdl/"; } else { return null; } } public String getPrefix(String s) { return null; } public Iterator getPrefixes(String s) { return null; } }); Element defs = (Element) xpe.compile("/*:definitions").evaluate(doc, XPathConstants.NODE); defs.setAttribute("xmlns", "http://schemas.xmlsoap.org/wsdl/"); Node schemaLocation = (Node) xpe.compile("/*:definitions/*:types/xsd:schema/xsd:import/@schemaLocation").evaluate(doc, XPathConstants.NODE); String sl = schemaLocation.getNodeValue(); for (int i = 0; i < 3; i++) sl = sl.substring(sl.indexOf('/') + 1); schemaLocation.setNodeValue(server + "/" + sl); Node location = (Node) xpe.compile("/*:definitions/*:service/*:port/soap:address/@location").evaluate(doc, XPathConstants.NODE); String l = location.getNodeValue(); for (int i = 0; i < 3; i++) l = l.substring(l.indexOf('/') + 1); location.setNodeValue(server + "/" + l); write(doc, writer); } catch (XPathFactoryConfigurationException e) { e.printStackTrace(); System.err.println("Error:" + e); } catch (XPathExpressionException e) { e.printStackTrace(); System.err.println("Error:" + e); } } Code Sample 2: public static boolean delete(String url, int ip, int port) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("DELETE"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.connect(); return request.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (IOException e) { e.printStackTrace(); } return false; }
00
Code Sample 1: private boolean undefSeqLen = true; private boolean undefItemLen = true; private boolean fmi = true; /** Creates a new instance of Acr2Dcm */ public Acr2Dcm() { } public void setStudyUID(String uid) { this.studyUID = uid; } public void setSeriesUID(String uid) { this.seriesUID = uid; } public void setInstUID(String uid) { this.instUID = uid; } public void setClassUID(String uid) { this.classUID = uid; } public void setSkipGroupLen(boolean skipGroupLen) { Code Sample 2: private void copy(File fin, File fout) throws IOException { FileOutputStream out = null; FileInputStream in = null; try { out = new FileOutputStream(fout); in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } } catch (IOException _e) { throw _e; } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: public static void cpdir(File src, File dest) throws BrutException { dest.mkdirs(); File[] files = src.listFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; File destFile = new File(dest.getPath() + File.separatorChar + file.getName()); if (file.isDirectory()) { cpdir(file, destFile); continue; } try { InputStream in = new FileInputStream(file); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); } catch (IOException ex) { throw new BrutException("Could not copy file: " + file, ex); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static void copy(File source, File destination) throws IOException { InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); in.close(); out.close(); } Code Sample 2: public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
11
Code Sample 1: public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: protected String readUrl(String urlString) throws IOException { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String inputLine; while ((inputLine = in.readLine()) != null) response += inputLine; in.close(); return response; } Code Sample 2: public static CMLUnitList createUnitList(URL url) throws IOException, CMLException { Document dictDoc = null; InputStream in = null; try { in = url.openStream(); dictDoc = new CMLBuilder().build(in); } catch (NullPointerException e) { e.printStackTrace(); throw new CMLException("NULL " + e.getMessage() + S_SLASH + e.getCause() + " in " + url); } catch (ValidityException e) { throw new CMLException(S_EMPTY + e.getMessage() + S_SLASH + e.getCause() + " in " + url); } catch (ParsingException e) { e.printStackTrace(); throw new CMLException(e, " in " + url); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } CMLUnitList dt = null; if (dictDoc != null) { Element root = dictDoc.getRootElement(); if (root instanceof CMLUnitList) { dt = new CMLUnitList((CMLUnitList) root); } else { } } if (dt != null) { dt.indexEntries(); } return dt; }
11
Code Sample 1: private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } } Code Sample 2: private void writeInputStreamToFile(InputStream stream, File file) { try { FileOutputStream fOut = new FileOutputStream(file); IOUtils.copy(stream, fOut); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private Reader getReader(String uri, Query query) throws SourceException { if (OntoramaConfig.DEBUG) { System.out.println("uri = " + uri); } InputStreamReader reader = null; try { System.out.println("class UrlSource, uri = " + uri); URL url = new URL(uri); URLConnection connection = url.openConnection(); reader = new InputStreamReader(connection.getInputStream()); } catch (MalformedURLException urlExc) { throw new SourceException("Url " + uri + " specified for this ontology source is not well formed, error: " + urlExc.getMessage()); } catch (IOException ioExc) { throw new SourceException("Couldn't read input data source for " + uri + ", error: " + ioExc.getMessage()); } return reader; } Code Sample 2: private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); IOUtils.copy(vds.getContentStream(), m_zout); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } }
00
Code Sample 1: @Override public BufferedImageAndBytes load(T thing) { String iurl = resolver.getUrl(thing); URL url; for (int k = 0; k < nTries; k++) { if (k > 0) { logger.debug("retry #" + k); } try { url = new URL(iurl); URLConnection connection = url.openConnection(); if (userAgent != null) { connection.setRequestProperty("User-Agent", userAgent); } InputStream is = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(40000); int b; while ((b = is.read()) != -1) { baos.write(b); } is.close(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedImage image = ImageIO.read(bais); return new BufferedImageAndBytes(image, bytes); } catch (MalformedURLException e) { continue; } catch (IOException e) { continue; } } return null; } Code Sample 2: protected StringBuffer readURL(java.net.URL url) throws IOException { StringBuffer result = new StringBuffer(4096); InputStreamReader reader = new InputStreamReader(url.openStream()); for (; ; ) { char portion[] = new char[4096]; int numRead = reader.read(portion, 0, portion.length); if (numRead < 0) break; result.append(portion, 0, numRead); } dout("Read " + result.length() + " bytes."); return result; }
11
Code Sample 1: public String hash(String text) { try { MessageDigest md = MessageDigest.getInstance(hashFunction); md.update(text.getBytes(charset)); byte[] raw = md.digest(); return new String(encodeHex(raw)); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public static String generateHash(String value) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(value.getBytes()); } catch (NoSuchAlgorithmException e) { log.error("Could not find the requested hash method: " + e.getMessage()); } byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } return hexString.toString(); }
00
Code Sample 1: public static void copy(String pstrFileFrom, String pstrFileTo) { try { FileChannel srcChannel = new FileInputStream(pstrFileFrom).getChannel(); FileChannel dstChannel = new FileOutputStream(pstrFileTo).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: public void load() throws ResourceInstantiationException { if (null == url) { throw new ResourceInstantiationException("URL not set (null)."); } try { BufferedReader defReader = new BomStrippingInputStreamReader((url).openStream(), ENCODING); String line; LinearNode node; while (null != (line = defReader.readLine())) { node = new LinearNode(line); try { this.add(node); } catch (GateRuntimeException ex) { throw new ResourceInstantiationException(ex); } } defReader.close(); isModified = false; } catch (Exception x) { throw new ResourceInstantiationException(x); } }
00
Code Sample 1: public static ContextInfo login(Context pContext, String pUsername, String pPwd, String pDeviceid) { HttpClient lClient = new DefaultHttpClient(); StringBuilder lBuilder = new StringBuilder(); ContextInfo lContextInfo = null; HttpPost lHttpPost = new HttpPost(new StringBuilder().append("http://").append(LoginActivity.mIpAddress.getText().toString()).append("/ZJWHServiceTest/GIS_Duty.asmx/PDALoginCheck").toString()); List<NameValuePair> lNameValuePairs = new ArrayList<NameValuePair>(2); lNameValuePairs.add(new BasicNameValuePair("username", pUsername)); lNameValuePairs.add(new BasicNameValuePair("password", pPwd)); lNameValuePairs.add(new BasicNameValuePair("deviceid", pDeviceid)); try { lHttpPost.setEntity(new UrlEncodedFormEntity(lNameValuePairs)); HttpResponse lResponse = lClient.execute(lHttpPost); BufferedReader lHeader = new BufferedReader(new InputStreamReader(lResponse.getEntity().getContent())); for (String s = lHeader.readLine(); s != null; s = lHeader.readLine()) { lBuilder.append(s); } String lResult = lBuilder.toString(); lResult = DataParseUtil.handleResponse(lResult); lContextInfo = LoginParseUtil.onlineParse(lResult); lContextInfo.setDeviceid(pDeviceid); if (0 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(0); } else if (1 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(1); updateUserInfo(pContext, lContextInfo); } else if (2 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(2); } else if (3 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(3); } } catch (Exception e) { return lContextInfo; } return lContextInfo; } Code Sample 2: private static Long statusSWGCraftTime() { long current = System.currentTimeMillis() / 1000L; if (current < (previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY)) return previousStatusTime; URL url = null; try { synchronized (previousStatusTime) { if (current >= previousStatusCheck + SWGCraft.STATUS_CHECK_DELAY) { url = SWGCraft.getStatusTextURL(); String statusTime = ZReader.read(url.openStream()); previousStatusTime = Long.valueOf(statusTime); previousStatusCheck = current; } return previousStatusTime; } } catch (UnknownHostException e) { SWGCraft.showUnknownHostDialog(url, e); } catch (Throwable e) { SWGAide.printDebug("cmgr", 1, "SWGResourceManager:statusSWGCraftTime:", e.toString()); } return Long.valueOf(0); }
00
Code Sample 1: public ViewedCandidates postViewedCandidates(ViewedCandidates viewedCandidates) throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpPost req = new HttpPost(remoteHost.getUrl() + "/cand/viewed"); req.setHeader("Accept-Encoding", "gzip"); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); XMLWriter.write(out, viewedCandidates); ByteArrayInputStream in2 = new ByteArrayInputStream(out.toByteArray()); req.setEntity(new InputStreamEntity(in2, -1)); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof ViewedCandidates) { ViewedCandidates p = (ViewedCandidates) xmlable; return p; } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for ViewedCandidates"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } } Code Sample 2: void copyFile(File inputFile, File outputFile) { try { FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: private void transferFile(String fileName) throws SocketException, IOException, Exception { FTPClient client = new FTPClient(); client.connect(server.getExternalName(), server.getPort()); int reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("Failed connecting to server"); } client.login(server.getDefaultUserName(), server.getDefaultUserPassword()); reply = client.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new Exception("Failed connecting to server"); } InputStream stream = getClass().getClassLoader().getResourceAsStream("res/conf/ftpd.properties"); client.storeFile(fileName, stream); File transfferedFile = new File(server.getServerRootDirectory(), fileName); assertTrue(transfferedFile.exists()); assertTrue(transfferedFile.delete()); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void copy(File source, File dest) throws Exception { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public CountModel(URL url) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; list = new ArrayList<CountModelItem>(); map = new HashMap<String, CountModelItem>(); line = in.readLine(); int n = 1; String[] rowAttrib; CountModelItem item; while ((line = in.readLine()) != null) { rowAttrib = line.split(";"); item = new CountModelItem(n, Integer.valueOf(rowAttrib[1]).intValue(), Integer.valueOf(rowAttrib[2]).intValue(), Integer.valueOf(rowAttrib[3]).intValue(), rowAttrib[0]); list.add(item); map.put(item.getHash(), item); n++; } in.close(); }
00
Code Sample 1: public void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: public Bitmap getImage() throws IOException { int recordBegin = 78 + 8 * mCount; Bitmap result = null; FileChannel channel = new FileInputStream(mFile).getChannel(); channel.position(mRecodeOffset[mPage]); ByteBuffer bodyBuffer; if (mPage + 1 < mCount) { int length = mRecodeOffset[mPage + 1] - mRecodeOffset[mPage]; bodyBuffer = channel.map(MapMode.READ_ONLY, mRecodeOffset[mPage], length); byte[] tmpCache = new byte[bodyBuffer.capacity()]; bodyBuffer.get(tmpCache); FileOutputStream o = new FileOutputStream("/sdcard/test.bmp"); o.write(tmpCache); o.flush(); o.getFD().sync(); o.close(); result = BitmapFactory.decodeByteArray(tmpCache, 0, length); } else { } channel.close(); return result; }
11
Code Sample 1: private static boolean validateSshaPwd(String sSshaPwd, String sUserPwd) { boolean b = false; if (sSshaPwd != null && sUserPwd != null) { if (sSshaPwd.startsWith(SSHA_PREFIX)) { sSshaPwd = sSshaPwd.substring(SSHA_PREFIX.length()); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); md.update(sUserPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); b = MessageDigest.isEqual(hash, baPwdHash); } catch (Exception exc) { exc.printStackTrace(); } } } return b; } Code Sample 2: @Override public String encodePassword(String rawPass, Object salt) throws DataAccessException { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.reset(); digest.update(((String) salt).getBytes("UTF-8")); return new String(digest.digest(rawPass.getBytes("UTF-8"))); } catch (Throwable e) { throw new DataAccessException("Error al codificar la contrase�a", e) { private static final long serialVersionUID = 3880106673612870103L; }; } }
11
Code Sample 1: private boolean getCached(Get g) throws IOException { boolean ret = false; File f = getCachedFile(g); if (f.exists()) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(f); os = new FileOutputStream(getDestFile(g)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; } Code Sample 2: public static void proxyRequest(IPageContext context, Writer writer, String proxyPath) throws IOException { URLConnection connection = new URL(proxyPath).openConnection(); connection.setDoInput(true); connection.setDoOutput(false); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "text/html; charset=UTF-8"); connection.setReadTimeout(30000); connection.setConnectTimeout(5000); Enumeration<String> e = context.httpRequest().getHeaderNames(); while (e.hasMoreElements()) { String name = e.nextElement(); if (name.equalsIgnoreCase("HOST") || name.equalsIgnoreCase("Accept-Encoding") || name.equalsIgnoreCase("Authorization")) continue; Enumeration<String> headers = context.httpRequest().getHeaders(name); while (headers.hasMoreElements()) { String header = headers.nextElement(); connection.setRequestProperty(name, header); } } if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod(context.httpRequest().getMethod()); if ("POST".equalsIgnoreCase(context.httpRequest().getMethod()) || "PUT".equalsIgnoreCase(context.httpRequest().getMethod())) { Enumeration<String> names = context.httpRequest().getParameterNames(); StringBuilder body = new StringBuilder(); while (names.hasMoreElements()) { String key = names.nextElement(); for (String value : context.parameters(key)) { if (body.length() > 0) { body.append('&'); } try { body.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException ex) { } } } if (body.length() > 0) { connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(body.toString()); out.close(); } } } try { IOUtils.copy(connection.getInputStream(), writer); } catch (IOException ex) { writer.write("<span>SSI Error: " + ex.getMessage() + "</span>"); } }
11
Code Sample 1: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: public int openUrl(String url, String method, Bundle params) { int result = 0; try { if (method.equals("GET")) { url = url + "?" + Utility.encodeUrl(params); } String response = ""; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " RenrenAndroidSDK"); if (!method.equals("GET")) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(Utility.encodeUrl(params).getBytes("UTF-8")); } response = Utility.read(conn.getInputStream()); JSONObject json = new JSONObject(response); try { int code = json.getInt("result"); if (code > 0) result = 1; } catch (Exception e) { result = json.getInt("error_code"); errmessage = json.getString("error_msg"); } } catch (Exception e) { result = -1; } return result; } Code Sample 2: private String fazHttpRequest(String u) { StringBuilder str = new StringBuilder(); URL url = null; URLConnection urlC = null; try { url = new URL(u.toString()); urlC = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { str.append(inputLine); } in.close(); } catch (Exception e) { System.out.println("[fazHttpRequest]" + e); } return (str.length() > 0) ? str.toString() : null; }
00
Code Sample 1: private String generateCode(String seed) { try { Security.addProvider(new FNVProvider()); MessageDigest digest = MessageDigest.getInstance("FNV-1a"); digest.update((seed + UUID.randomUUID().toString()).getBytes()); byte[] hash1 = digest.digest(); String sHash1 = "m" + (new String(LibraryBase64.encode(hash1))).replaceAll("=", "").replaceAll("-", "_"); return sHash1; } catch (Exception e) { e.printStackTrace(); } return ""; } Code Sample 2: private File newFile(File oldFile) throws IOException { int counter = 0; File nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName()); while (nFile.exists()) { nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName() + "_" + counter); } IOUtils.copyFile(oldFile, nFile); return nFile; }
00
Code Sample 1: public static Coordinate getCoordenadas(String RCoURL) { Coordinate coord = new Coordinate(); String pURL; String iniPC1 = "<pc1>"; String iniPC2 = "<pc2>"; String finPC1 = "</pc1>"; String finPC2 = "</pc2>"; String iniX = "<xcen>"; String iniY = "<ycen>"; String finX = "</xcen>"; String finY = "</ycen>"; String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; boolean error = false; int ini, fin; if (RCoURL.contains("/") || RCoURL.contains("\\") || RCoURL.contains(".")) pURL = RCoURL; else { if (RCoURL.length() > 14) pURL = baseURL[1].replace("<RC>", RCoURL.substring(0, 14)); else pURL = baseURL[1].replace("<RC>", RCoURL); } try { URL url = new URL(pURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniPC1)) { ini = str.indexOf(iniPC1) + iniPC1.length(); fin = str.indexOf(finPC1); coord.setDescription(str.substring(ini, fin)); } if (str.contains(iniPC2)) { ini = str.indexOf(iniPC2) + iniPC2.length(); fin = str.indexOf(finPC2); coord.setDescription(coord.getDescription().concat(str.substring(ini, fin))); } if (str.contains(iniX)) { ini = str.indexOf(iniX) + iniX.length(); fin = str.indexOf(finX); coord.setLongitude(Double.parseDouble(str.substring(ini, fin))); } if (str.contains(iniY)) { ini = str.indexOf(iniY) + iniY.length(); fin = str.indexOf(finY); coord.setLatitude(Double.parseDouble(str.substring(ini, fin))); } } } in.close(); } catch (Exception e) { System.err.println(e); } return coord; } Code Sample 2: private ArrayList execAtParentServer(ArrayList paramList) throws Exception { ArrayList outputList = null; String message = ""; try { HashMap serverUrlMap = InitXml.getInstance().getServerMap(); Iterator it = serverUrlMap.keySet().iterator(); while (it.hasNext()) { String server = (String) it.next(); String serverUrl = (String) serverUrlMap.get(server); serverUrl = serverUrl + Primer3Manager.servletName; URL url = new URL(serverUrl); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("actionType=designparent"); for (int i = 0; i < paramList.size(); i++) { Primer3Param param = (Primer3Param) paramList.get(i); if (i == 0) { buf.append("&sequence=" + param.getSequence()); buf.append("&upstream_size" + upstreamSize); buf.append("&downstreamSize" + downstreamSize); buf.append("&MARGIN_LENGTH=" + marginLength); buf.append("&OVERLAP_LENGTH=" + overlapLength); buf.append("&MUST_XLATE_PRODUCT_MIN_SIZE=" + param.getPrimerProductMinSize()); buf.append("&MUST_XLATE_PRODUCT_MAX_SIZE=" + param.getPrimerProductMaxSize()); buf.append("&PRIMER_PRODUCT_OPT_SIZE=" + param.getPrimerProductOptSize()); buf.append("&PRIMER_MAX_END_STABILITY=" + param.getPrimerMaxEndStability()); buf.append("&PRIMER_MAX_MISPRIMING=" + param.getPrimerMaxMispriming()); buf.append("&PRIMER_PAIR_MAX_MISPRIMING=" + param.getPrimerPairMaxMispriming()); buf.append("&PRIMER_MIN_SIZE=" + param.getPrimerMinSize()); buf.append("&PRIMER_OPT_SIZE=" + param.getPrimerOptSize()); buf.append("&PRIMER_MAX_SIZE=" + param.getPrimerMaxSize()); buf.append("&PRIMER_MIN_TM=" + param.getPrimerMinTm()); buf.append("&PRIMER_OPT_TM=" + param.getPrimerOptTm()); buf.append("&PRIMER_MAX_TM=" + param.getPrimerMaxTm()); buf.append("&PRIMER_MAX_DIFF_TM=" + param.getPrimerMaxDiffTm()); buf.append("&PRIMER_MIN_GC=" + param.getPrimerMinGc()); buf.append("&PRIMER_OPT_GC_PERCENT=" + param.getPrimerOptGcPercent()); buf.append("&PRIMER_MAX_GC=" + param.getPrimerMaxGc()); buf.append("&PRIMER_SELF_ANY=" + param.getPrimerSelfAny()); buf.append("&PRIMER_SELF_END=" + param.getPrimerSelfEnd()); buf.append("&PRIMER_NUM_NS_ACCEPTED=" + param.getPrimerNumNsAccepted()); buf.append("&PRIMER_MAX_POLY_X=" + param.getPrimerMaxPolyX()); buf.append("&PRIMER_GC_CLAMP=" + param.getPrimerGcClamp()); } buf.append("&target=" + param.getPrimerSequenceId() + "," + (param.getTarget())[0] + "," + (param.getTarget())[1]); } PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); outputList = (ArrayList) ois.readObject(); ois.close(); } } catch (IOException e1) { e1.printStackTrace(); } if ((outputList == null || outputList.size() == 0) && message != null && message.length() > 0) { throw new Exception(message); } return outputList; }
11
Code Sample 1: void copyFileOnPeer(String path, RServerInfo peerserver, boolean allowoverwrite) throws IOException { RFile file = new RFile(path); OutputStream out = null; FileInputStream in = null; try { in = fileManager.openFileRead(path); out = localClient.openWrite(file, false, WriteMode.TRANSACTED, 1, peerserver, !allowoverwrite); IOUtils.copyLarge(in, out); out.close(); out = null; } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (out != null) { try { out.close(); } catch (Throwable t) { } } } } Code Sample 2: public static URL toFileUrl(URL location) throws IOException { String protocol = location.getProtocol().intern(); if (protocol != "jar") throw new IOException("cannot explode " + location); JarURLConnection juc = (JarURLConnection) location.openConnection(); String path = juc.getEntryName(); String parentPath = parentPathOf(path); File tempDir = createTempDir("jartemp"); JarFile jarFile = juc.getJarFile(); for (Enumeration<JarEntry> en = jarFile.entries(); en.hasMoreElements(); ) { ZipEntry entry = en.nextElement(); if (entry.isDirectory()) continue; String entryPath = entry.getName(); if (entryPath.startsWith(parentPath)) { File dest = new File(tempDir, entryPath); dest.getParentFile().mkdirs(); InputStream in = jarFile.getInputStream(entry); OutputStream out = new FileOutputStream(dest); IOUtils.copy(in, out); dest.deleteOnExit(); } } File realFile = new File(tempDir, path); return realFile.toURL(); }
00
Code Sample 1: public Gif(URL url) throws BadElementException, IOException { super(url); type = GIF; InputStream is = null; try { is = url.openStream(); if (is.read() != 'G' || is.read() != 'I' || is.read() != 'F') { throw new BadElementException(url.toString() + " is not a valid GIF-file."); } skip(is, 3); scaledWidth = is.read() + (is.read() << 8); setRight((int) scaledWidth); scaledHeight = is.read() + (is.read() << 8); setTop((int) scaledHeight); } finally { if (is != null) { is.close(); } plainWidth = width(); plainHeight = height(); } } Code Sample 2: public void testPreparedStatement0009() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } pstmt.close(); assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); con.commit(); pstmt = con.prepareStatement("insert into #t0009 values (?, ?)"); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); pstmt.close(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, rowsToAdd); con.commit(); stmt.close(); con.setAutoCommit(true); }
00
Code Sample 1: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ejb.bprocess.OAIPMH.AutoHarvesterSession ahSession = home.create(); java.util.Vector vector = new java.util.Vector(1, 1); Integer libraryId = new Integer(1); String xmlstr = ""; String str = ""; String arr[] = new String[2]; String[] subarr = new String[4]; String mdPrefix = "", mdPrefixValue = ""; String from = "", fromValue = ""; String until = "", untilValue = ""; String set = "", setValue = ""; String oai_pmhRequest = request.getParameter("verb"); String oai_pmhQuery = request.getQueryString(); String urlStr = ""; urlStr = "http://" + request.getServerName() + ":" + request.getServerPort() + "/newgenlibctxt/HarvestServlet"; String attribute = oai_pmhQuery; String arguments = attribute.substring(attribute.indexOf("?") + 1); StringTokenizer st = new StringTokenizer(arguments, "&"); int i = 0; int j = 0; int z = 0; int count = 0; String type = ""; while (st.hasMoreTokens()) { arr[i] = st.nextToken(); StringTokenizer subst = new StringTokenizer(arr[i], "="); while (subst.hasMoreTokens()) { subarr[j] = subst.nextToken(); j++; } i++; count++; } int mdfCount = 0, fromCount = 0, untilCount = 0, setCount = 0; ListRecords lr = new ListRecords(); for (int k = 0; k < j; k += 2) { if (subarr[k].equals("from")) { from = "from"; fromCount++; fromValue = subarr[k + 1]; fromValue = lr.validateDate(fromValue); } else if (subarr[k].equals("until")) { until = "until"; untilCount++; untilValue = subarr[k + 1]; untilValue = lr.validateDate(untilValue); } } if (fromValue.equals("") && untilCount == 1) { fromValue = lr.validateDate("0001-01-01"); } else if (untilValue.equals("") && fromCount == 1) { String a = (new Resdate()).getDate(); untilValue = a.substring(0, a.indexOf("T")); } System.out.println("This is fromValue:" + fromValue); System.out.println("This is untilValue:" + untilValue); vector = ahSession.getHarvestLibrary(null, libraryId); String harlibraryId = ""; if (vector.size() > 0) { for (int k = 0; k < vector.size(); k = k + 3) { harlibraryId = vector.elementAt(k).toString(); String harvesturl = vector.elementAt(k + 1).toString(); String status = vector.elementAt(k + 2).toString(); if (status.equals("A")) { String oai_pmhRequest1 = request.getParameter("verb"); String oai_pmhQuery1 = request.getQueryString(); urlStr = "http://" + harvesturl + ":8080/newgenlibctxt/oai2.0?verb=ListRecords&metadataPrefix=marc21&from=" + fromValue + "&until=" + untilValue + ""; boolean resExists = true; for (int n = 0; resExists == true; n++) { java.net.URL url = new java.net.URL(urlStr); java.net.URLConnection urlCon = url.openConnection(); urlCon.setDoInput(true); urlCon.connect(); InputStream is = urlCon.getInputStream(); System.out.println("input" + is.available()); org.jdom.input.SAXBuilder sb = new org.jdom.input.SAXBuilder(); org.jdom.Document doc = sb.build(is); xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc); System.out.println("xmlStr:" + xmlstr); doc = null; sb = null; java.util.Vector vec = new java.util.Vector(); vec = ahSession.autoInitialHarvest(null, xmlstr, harlibraryId); String resT = doc.getRootElement().getChildText("resumptionToken", doc.getRootElement().getNamespace()); if (!(resT == null)) { urlStr = "http://" + harvesturl + ":8080/newgenlibctxt/oai2.0?verb=ListRecords&resumptionToken=" + resT; } else { resExists = false; } } } else if (status.equals("B")) { java.io.File file = new java.io.File(harvesturl); java.io.File[] file1 = file.listFiles(); for (int b = 0; b < file1.length; b++) { File file2 = (File) file1[b]; System.out.println("File2:" + file2); long lastmodifed = file2.lastModified(); StringTokenizer st1 = new StringTokenizer(fromValue, "-"); String dar[] = new String[3]; java.util.Calendar c1 = java.util.Calendar.getInstance(); int g = 0; while (st1.hasMoreElements()) { dar[g] = st1.nextToken(); g++; } c1.set(Integer.parseInt(dar[0]), Integer.parseInt(dar[1]), Integer.parseInt(dar[2])); StringTokenizer st2 = new StringTokenizer(untilValue, "-"); String dar1[] = new String[3]; java.util.Calendar c2 = java.util.Calendar.getInstance(); int d = 0; while (st2.hasMoreElements()) { dar1[d] = st2.nextToken(); d++; } c2.set(Integer.parseInt(dar1[0]), Integer.parseInt(dar1[1]), Integer.parseInt(dar1[2])); java.util.Calendar c3 = java.util.Calendar.getInstance(); c3.setTimeInMillis(lastmodifed); c3.set(java.util.Calendar.HOUR, 0); c3.set(java.util.Calendar.AM_PM, java.util.Calendar.AM); c3.set(java.util.Calendar.MINUTE, 0); c3.set(java.util.Calendar.SECOND, 0); c3.set(java.util.Calendar.MILLISECOND, 0); java.util.Date d1 = c1.getTime(); java.util.Date d2 = c2.getTime(); java.util.Date d3 = c3.getTime(); System.out.println("This is d1:" + d1); System.out.println("This is d2:" + d2); System.out.println("This is d3:" + d3); if (d3.after(d1) && d3.before(d2)) { org.jdom.input.SAXBuilder sb1 = new org.jdom.input.SAXBuilder(); org.jdom.Document doc1 = sb1.build(new java.io.FileInputStream(file2)); xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc1); java.util.Vector vec = new java.util.Vector(); vec = ahSession.autoInitialHarvest(null, xmlstr, harlibraryId); } } } } } } catch (Exception ex) { ex.printStackTrace(); } } 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 String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: private DataFileType[] getDataFiles(Collection<ContentToSend> contentsToSend) { DataFileType[] files = new DataFileType[contentsToSend.size()]; int fileIndex = 0; for (ContentToSend contentToSend : contentsToSend) { DataFileType dataFile = DataFileType.Factory.newInstance(); dataFile.setFilename(contentToSend.getFileName()); dataFile.setId("D" + fileIndex); dataFile.setMimeType(contentToSend.getMimeType()); dataFile.setContentType(DataFileType.ContentType.EMBEDDED_BASE_64); final StringWriter stringWriter = new StringWriter(); final OutputStream encodeStream = Base64.newEncoder(stringWriter, 0, null); final InputStream is = contentToSend.getInputStream(); try { long sizeCopied = IOUtils.copyLarge(is, encodeStream); dataFile.setSize(BigDecimal.valueOf(sizeCopied)); } catch (IOException e) { throw new RuntimeException("Failed to get input to the file to be sent", e); } finally { IOUtils.closeQuietly(encodeStream); IOUtils.closeQuietly(is); } dataFile.setStringValue(stringWriter.toString()); files[fileIndex++] = dataFile; } return files; }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String requestURI = req.getRequestURI(); logger.info("The requested URI: {}", requestURI); String parameter = requestURI.substring(requestURI.lastIndexOf(ARXIVID_ENTRY) + ARXIVID_ENTRY_LENGTH); int signIndex = parameter.indexOf(StringUtil.ARXIVID_SEGMENTID_DELIMITER); String arxivId = signIndex != -1 ? parameter.substring(0, signIndex) : parameter; String segmentId = signIndex != -1 ? parameter.substring(signIndex + 1) : null; if (arxivId == null) { logger.error("The request with an empty arxiv id parameter"); return; } String filePath = segmentId == null ? format("/opt/mocassin/aux-pdf/%s" + StringUtil.arxivid2filename(arxivId, "pdf")) : "/opt/mocassin/pdf/" + StringUtil.segmentid2filename(arxivId, Integer.parseInt(segmentId), "pdf"); if (!new File(filePath).exists()) { filePath = format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf")); } try { FileInputStream fileInputStream = new FileInputStream(filePath); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(fileInputStream, byteArrayOutputStream); resp.setContentType("application/pdf"); resp.setHeader("Content-disposition", String.format("attachment; filename=%s", StringUtil.arxivid2filename(arxivId, "pdf"))); ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(byteArrayOutputStream.toByteArray()); outputStream.close(); } catch (FileNotFoundException e) { logger.error("Error while downloading: PDF file= '{}' not found", filePath); } catch (IOException e) { logger.error("Error while downloading the PDF file", e); } } Code Sample 2: public static void compress(final File zip, final Map<InputStream, String> entries) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); InputStream in = null; try { for (InputStream inputStream : entries.keySet()) { in = inputStream; ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in))); out.putNextEntry(zipEntry); IOUtils.copy(in, out); out.closeEntry(); in.close(); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
11
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } Code Sample 2: private void nioBuild() { try { final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 4); final FileChannel out = new FileOutputStream(dest).getChannel(); for (File part : parts) { setState(part.getName(), BUILDING); FileChannel in = new FileInputStream(part).getChannel(); while (in.read(buffer) > 0) { buffer.flip(); written += out.write(buffer); buffer.clear(); } in.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: 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(); } Code Sample 2: public static void generate(final InputStream input, String format, Point dimension, IPath outputLocation) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = outputLocation.toFile(); ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); return; } } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
11
Code Sample 1: private static void copyFile(File source, File dest, boolean visibleFilesOnly) throws IOException { if (visibleFilesOnly && isHiddenOrDotFile(source)) { return; } if (dest.exists()) { System.err.println("Destination File Already Exists: " + dest); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } Code Sample 2: private void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException { ZipOutputStream zipOutput = null; try { zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target))); for (File file : files) { BufferedInputStream fileInput = null; File cachePathName = new File(cacheFolder, file.getPath()); try { if (!cachePathName.exists()) { throw new CacheOperationException("Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it " + "has gone missing (cause unknown). This can indicate implementation or deployment " + "error. Aborting export operation as a safety precaution.", cachePathName.getPath(), target.getAbsolutePath(), account.getOid()); } fileInput = new BufferedInputStream(new FileInputStream(cachePathName)); ZipEntry entry = new ZipEntry(file.getPath()); entry.setSize(cachePathName.length()); entry.setTime(cachePathName.lastModified()); zipOutput.putNextEntry(entry); cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath()); int count, total = 0; int buffer = 2048; byte[] data = new byte[buffer]; while ((count = fileInput.read(data, 0, buffer)) != -1) { zipOutput.write(data, 0, count); total += count; } zipOutput.flush(); if (total != cachePathName.length()) { throw new CacheOperationException("Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). " + "This could have occured either due implementation error or file I/O error. " + "Aborting archive operation to prevent a potentially corrupt export archive to " + "be created.", total, cachePathName.length(), cachePathName.getPath(), account.getOid()); } else { cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total, cachePathName.length(), file.getPath()); } } catch (SecurityException e) { throw new ConfigurationException("Security manager has denied r/w access when attempting to read file ''{0}'' and " + "write it to archive ''{1}'' (Account : {2}) : {3}", e, cachePathName.getPath(), target, account.getOid(), e.getMessage()); } catch (IllegalArgumentException e) { throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (FileNotFoundException e) { throw new CacheOperationException("Attempted to include file ''{0}'' in export archive but it has gone missing " + "(Account : {1}). Possible implementation error in local file cache. Aborting " + "export operation as a precaution ({2})", e, cachePathName.getPath(), account.getOid(), e.getMessage()); } catch (ZipException e) { throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (IOException e) { throw new CacheOperationException("I/O error while creating export archive for account ID = {0}. " + "Operation aborted ({1})", e, account.getOid(), e.getMessage()); } finally { if (zipOutput != null) { try { zipOutput.closeEntry(); } catch (Throwable t) { cacheLog.warn("Unable to close zip entry for file ''{0}'' in export archive ''{1}'' " + "(Account : {2}) : {3}.", t, file.getPath(), target.getAbsolutePath(), account.getOid(), t.getMessage()); } } if (fileInput != null) { try { fileInput.close(); } catch (Throwable t) { cacheLog.warn("Failed to close input stream from file ''{0}'' being added " + "to export archive (Account : {1}) : {2}", t, cachePathName.getPath(), account.getOid(), t.getMessage()); } } } } } catch (FileNotFoundException e) { throw new CacheOperationException("Unable to create target export archive ''{0}'' for account {1) : {2}", e, target, account.getOid(), e.getMessage()); } finally { try { if (zipOutput != null) { zipOutput.close(); } } catch (Throwable t) { cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target, t.getMessage()); } } }
11
Code Sample 1: public void uploadFile(File inputFile, String targetFile) throws IOException { System.out.println("Uploading " + inputFile.getName() + " to " + targetFile); File outputFile = new File(targetFile); if (targetFile.endsWith("/")) { outputFile = new File(outputFile, inputFile.getName()); } else if (outputFile.getParentFile().exists() == false) { outputFile.getParentFile().mkdirs(); } if (inputFile.renameTo(outputFile) == false) { InputStream in = new FileInputStream(inputFile); OutputStream out = new FileOutputStream(outputFile); byte[] line = new byte[16384]; int bytes = -1; while ((bytes = in.read(line)) != -1) out.write(line, 0, bytes); in.close(); out.close(); } } Code Sample 2: protected boolean writeFile(Interest outstandingInterest) throws IOException { File fileToWrite = ccnNameToFilePath(outstandingInterest.name()); Log.info("CCNFileProxy: extracted request for file: " + fileToWrite.getAbsolutePath() + " exists? ", fileToWrite.exists()); if (!fileToWrite.exists()) { Log.warning("File {0} does not exist. Ignoring request.", fileToWrite.getAbsoluteFile()); return false; } FileInputStream fis = null; try { fis = new FileInputStream(fileToWrite); } catch (FileNotFoundException fnf) { Log.warning("Unexpected: file we expected to exist doesn't exist: {0}!", fileToWrite.getAbsolutePath()); return false; } CCNTime modificationTime = new CCNTime(fileToWrite.lastModified()); ContentName versionedName = VersioningProfile.addVersion(new ContentName(_prefix, outstandingInterest.name().postfix(_prefix).components()), modificationTime); CCNFileOutputStream ccnout = new CCNFileOutputStream(versionedName, _handle); ccnout.addOutstandingInterest(outstandingInterest); byte[] buffer = new byte[BUF_SIZE]; int read = fis.read(buffer); while (read >= 0) { ccnout.write(buffer, 0, read); read = fis.read(buffer); } fis.close(); ccnout.close(); return true; }
11
Code Sample 1: public static void main(String[] args) { String fe = null, fk = null, f1 = null, f2 = null; DecimalFormat df = new DecimalFormat("000"); int key = 0; int i = 1; for (; ; ) { System.out.println("==================================================="); System.out.println("\n2009 BME\tTeam ESC's Compare\n"); System.out.println("===================================================\n"); System.out.println(" *** Menu ***\n"); System.out.println("1. Fajlok osszehasonlitasa"); System.out.println("2. Hasznalati utasitas"); System.out.println("3. Kilepes"); System.out.print("\nKivalasztott menu szama: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { key = reader.read(); switch(key) { case '3': System.exit(0); break; case '2': System.out.println("\n @author Bedo Zotlan - F3VFDE"); System.out.println("Team ESC's Compare"); System.out.println("2009."); System.out.println(); System.out.println("(1) A program ket fajl osszahesonlitasat vegzi. A fajloknak a program gyokerkonyvtaraban kell lenniuk!"); System.out.println("(2) A menubol ertelem szeruen valasztunk az opciok kozul, majd a program keresere megadjuk a ket osszehasonlitando " + "fajl nevet kiterjesztessel egyutt, kulonben hibat kapunk!"); System.out.println("(3) Miutan elvegeztuk az osszehasonlitasokat a program mindegyiket kimenti a compare_xxx.txt fajlba, azonban ha kilepunk a programbol, " + "majd utana ismet elinditjuk es elkezdunk osszehasonlitasokat vegezni, akkor felulirhatja " + "az elozo futtatasbol kapott fajlainkat, erre kulonosen figyelni kell!"); System.out.println("(4) A kimeneti compare_xxx.txt fajlon kivul minden egyes osszehasonlitott fajlrol csinal egy <fajl neve>.<fajl kiterjesztese>.numbered " + "nevu fajlt, ami annyiban ter el az eredeti fajloktol, hogy soronkent sorszamozva vannak!"); System.out.println("(5) Egy nem ures es egy ures fajl osszehasonlitasa utan azt az eredmenyt kapjuk, hogy \"OK, megyezenek!\". Ez termeszetesen hibas" + " es a kimeneti fajlunk is ures lesz. Ezt szinten keruljuk el, ne hasonlitsunk ures fajlokhoz mas fajlokat!"); System.out.println("(6) A fajlok megtekintesehez Notepad++ 5.0.0 verzioja ajanlott legalabb!\n"); break; case '1': { System.out.print("\nAz etalon adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fe = (inFileName + ".numbered"); f1 = inFileName; String aLine; while ((aLine = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } System.out.print("A kapott adatokat tartalmazo fajl neve: "); try { int lnNo = 1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inFileName = br.readLine(); BufferedReader bin = new BufferedReader(new FileReader(inFileName)); BufferedWriter bout = new BufferedWriter(new FileWriter(inFileName + ".numbered")); fk = (inFileName + ".numbered"); f2 = inFileName; String aLine_k; while ((aLine_k = bin.readLine()) != null) bout.write("Line " + df.format(lnNo++) + ": " + aLine_k + "\n"); bin.close(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajlnev"); } try { int lnNo_c = 1; int mstk = 0; BufferedReader bin_e = new BufferedReader(new FileReader(fe)); BufferedReader bin_k = new BufferedReader(new FileReader(fk)); BufferedWriter bout = new BufferedWriter(new FileWriter("compare_" + i++ + ".txt")); Calendar actDate = Calendar.getInstance(); bout.write("==================================================\n"); bout.write("\n2009 BME\tTeam ESC's Compare"); bout.write("\n" + actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n\n"); bout.write("==================================================\n"); bout.write("Az etalon ertekekkel teli fajl neve: " + f1 + "\n"); bout.write("A kapott ertekekkel teli fajl neve: " + f2 + "\n\n"); System.out.println("==================================================\n"); System.out.println("\n2009 BME\tTeam ESC's Compare"); System.out.println(actDate.get(Calendar.YEAR) + "." + (actDate.get(Calendar.MONTH) + 1) + "." + actDate.get(Calendar.DATE) + ".\n" + actDate.get(Calendar.HOUR) + ":" + actDate.get(Calendar.MINUTE) + "\n"); System.out.println("==================================================\n"); System.out.println("\nAz etalon ertekekkel teli fajl neve: " + f1); System.out.println("A kapott ertekekkel teli fajl neve: " + f2 + "\n"); String aLine_c1 = null, aLine_c2 = null; File fa = new File(fe); File fb = new File(fk); if (fa.length() != fb.length()) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!\n Kulonbozo meretu fajlok: " + fa.length() + " byte illetve " + fb.length() + " byte!\n"); } else { while (((aLine_c1 = bin_e.readLine()) != null) && ((aLine_c2 = bin_k.readLine()) != null)) if (aLine_c1.equals(aLine_c2)) { } else { mstk++; bout.write("#" + df.format(lnNo_c) + ": HIBA --> \t" + f1 + " : " + aLine_c1 + " \n\t\t\t\t\t" + f2 + " : " + aLine_c2 + "\n"); System.out.println("#" + df.format(lnNo_c) + ": HIBA -->\t " + f1 + " : " + aLine_c1 + " \n\t\t\t" + f2 + " : " + aLine_c2 + "\n"); lnNo_c++; } if (mstk != 0) { bout.write("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); bout.write("\nHibas sorok szama: " + mstk); System.out.println("\nOsszehasonlitas eredmenye: HIBA, nincs egyezes!"); System.out.println("Hibas sorok szama: " + mstk); } else { bout.write("\nOsszehasonlitas eredmenye: OK, megegyeznek!"); System.out.println("\nOsszehasonlitas eredm�nye: OK, megegyeznek!\n"); } } bin_e.close(); bin_k.close(); fa.delete(); fb.delete(); bout.close(); } catch (IOException e) { System.out.println("Hibas fajl"); } break; } } } catch (Exception e) { System.out.println("A fut�s sor�n hiba t�rt�nt!"); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void setUserPassword(final List<NewUser> users) { try { final List<Integer> usersToRemoveFromCache = new ArrayList<Integer>(); connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.updatePassword")); Iterator<NewUser> iter = users.iterator(); NewUser user; PasswordHasher ph; while (iter.hasNext()) { user = iter.next(); ph = PasswordFactory.getInstance().getPasswordHasher(); psImpl.setString(1, ph.hashPassword(user.password)); psImpl.setString(2, ph.getSalt()); psImpl.setInt(3, user.userId); psImpl.executeUpdate(); usersToRemoveFromCache.add(user.userId); } } }); List<JESRealmUser> list = (List<JESRealmUser>) new ProcessEnvelope().executeObject(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public Object executeProcessReturnObject() throws SQLException { List<JESRealmUser> list = new ArrayList<JESRealmUser>(users.size() + 10); psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realms.user.load")); Iterator<NewUser> iter = users.iterator(); NewUser user; while (iter.hasNext()) { user = iter.next(); psImpl.setInt(1, user.userId); rsImpl = psImpl.executeQuery(); while (rsImpl.next()) { list.add(new JESRealmUser(user.username, user.userId, rsImpl.getInt("realm_id"), rsImpl.getInt("domain_id"), user.password, rsImpl.getString("realm_name_lower_case"))); } } return list; } }); final List<JESRealmUser> encrypted = new ArrayList<JESRealmUser>(list.size()); Iterator<JESRealmUser> iter = list.iterator(); JESRealmUser jesRealmUser; Realm realm; while (iter.hasNext()) { jesRealmUser = iter.next(); realm = cm.getRealm(jesRealmUser.realm); encrypted.add(new JESRealmUser(null, jesRealmUser.userId, jesRealmUser.realmId, jesRealmUser.domainId, PasswordFactory.getInstance().getPasswordHasher().hashRealmPassword(jesRealmUser.username.toLowerCase(locale), realm.getFullRealmName().equals("null") ? "" : realm.getFullRealmName(), jesRealmUser.password), null)); } new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("realms.user.update")); Iterator<JESRealmUser> iter = encrypted.iterator(); JESRealmUser jesRealmUser; while (iter.hasNext()) { jesRealmUser = iter.next(); psImpl.setString(1, jesRealmUser.password); psImpl.setInt(2, jesRealmUser.realmId); psImpl.setInt(3, jesRealmUser.userId); psImpl.setInt(4, jesRealmUser.domainId); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUsers(usersToRemoveFromCache); } catch (GeneralSecurityException e) { log.error(e); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } throw new RuntimeException("Error updating Realms. Unable to continue Operation."); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } Code Sample 2: protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Session session = HibernateUtil.getInstance().getSession(); response.setBufferSize(65536); ServletOutputStream outStream = response.getOutputStream(); File file = null; FileData fileData = null; try { String fileParameter = request.getParameter("file"); String disposition = request.getParameter("disposition"); if (fileParameter == null || fileParameter.equals("")) { String pi = request.getPathInfo(); int lastSlashIndex = pi.lastIndexOf("/") + 1; fileParameter = pi.substring(lastSlashIndex, pi.indexOf("_", pi.lastIndexOf("/"))); } if (fileParameter == null || fileParameter.equals("")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.flushBuffer(); Logger.log("file parameter not specified"); return; } if (disposition == null || disposition.equals("")) { String pi = request.getPathInfo(); String filename = pi.substring(pi.lastIndexOf("/") + 1); int underscoreIndex = filename.indexOf("_") + 1; disposition = filename.substring(underscoreIndex, filename.indexOf("_", underscoreIndex)); } file = (File) session.load(File.class, new Long(fileParameter)); Logger.log("Content requested=" + file.getName() + ":" + fileParameter + " Referral: " + request.getParameter("referer")); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long fileDate = file.getLastModifiedDate() - (file.getLastModifiedDate() % 1000); if (fileDate <= ifModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } response.setContentType(file.getContentType()); response.setHeader("Content-Description", file.getName()); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); response.flushBuffer(); Logger.log("Conditional GET: " + file.getName()); return; } User authUser = baseService.getAuthenticatedUser(session, request, response); if (!SecurityHelper.doesUserHavePermission(session, authUser, file, Permission.PERM.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.flushBuffer(); Logger.log("Forbidden content requested: " + fileParameter); return; } String contentType = file.getContentType(); response.setContentType(contentType); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } String name = file.getName(); response.setHeader("Content-Description", name); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); java.io.File possibleDataFile = new java.io.File(BaseSystem.getTempDir() + file.getNameOnDisk()); if (possibleDataFile.exists()) { Logger.log("File exists in " + BaseSystem.getTempDir() + " pulling " + possibleDataFile.getName()); FileInputStream fileInputStream = new FileInputStream(possibleDataFile); try { IOUtils.copy(fileInputStream, outStream); } finally { try { fileInputStream.close(); } catch (Throwable t) { } } } else { List<FileData> fileDataList = HibernateUtil.getInstance().executeQuery(session, "from " + FileData.class.getSimpleName() + " where permissibleObject.id = " + file.getId()); if (fileDataList.size() == 0) { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); Logger.log("Requested content not found: " + fileParameter); response.flushBuffer(); return; } fileData = (FileData) fileDataList.get(0); FileOutputStream fileOutputStream = null; try { java.io.File tmpDir = new java.io.File(BaseSystem.getTempDir()); tmpDir.mkdirs(); fileOutputStream = new FileOutputStream(possibleDataFile); IOUtils.write(fileData.getData(), fileOutputStream); } catch (Throwable t) { Logger.log(t); } finally { try { fileOutputStream.close(); } catch (Throwable t) { } } IOUtils.write(fileData.getData(), outStream); } } catch (Throwable t) { Logger.log(t); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.flushBuffer(); } catch (Throwable tt) { } try { response.reset(); response.resetBuffer(); } catch (Throwable tt) { } } finally { file = null; fileData = null; try { outStream.flush(); } catch (Throwable t) { } try { outStream.close(); } catch (Throwable t) { } try { session.close(); } catch (Throwable t) { } } }
00
Code Sample 1: public List<SysSequences> getSeqs() throws Exception { List<SysSequences> list = new ArrayList<SysSequences>(); Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("update ss_sys_sequences set next_value=next_value+step_value"); ps.executeUpdate(); ps.close(); ps = conn.prepareStatement("select * from ss_sys_sequences"); ResultSet rs = ps.executeQuery(); while (rs.next()) { SysSequences seq = new SysSequences(); seq.setTableName(rs.getString(1)); long nextValue = rs.getLong(2); long stepValue = rs.getLong(3); seq.setNextValue(nextValue - stepValue); seq.setStepValue(stepValue); list.add(seq); } rs.close(); ps.close(); conn.commit(); } catch (Exception e) { conn.rollback(); e.printStackTrace(); } finally { try { conn.setAutoCommit(true); } catch (Exception e) { } ConnectUtil.closeConn(conn); } return list; } Code Sample 2: public String mdHesla(String password) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
11
Code Sample 1: public Atividade insertAtividade(Atividade atividade) throws SQLException { Connection conn = null; String insert = "insert into Atividade (idatividade, requerente_idrequerente, datacriacao, datatermino, valor, tipoatividade, descricao, fase_idfase, estado) " + "values " + "(nextval('seq_atividade'), " + atividade.getRequerente().getIdRequerente() + ", " + "'" + atividade.getDataCriacao() + "', '" + atividade.getDataTermino() + "', '" + atividade.getValor() + "', '" + atividade.getTipoAtividade().getIdTipoAtividade() + "', '" + atividade.getDescricao() + "', " + atividade.getFaseIdFase() + ", " + atividade.getEstado() + ")"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_atividade"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { atividade.setIdAtividade(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; } Code Sample 2: public void processSaveCompany(Company companyBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_COMPANY " + "SET " + " full_name = ?, " + " short_name = ?, " + " address = ?, " + " telefon_buh = ?, " + " telefon_chief = ?, " + " chief = ?, " + " buh = ?, " + " fax = ?, " + " email = ?, " + " icq = ?, " + " short_client_info = ?, " + " url = ?, " + " short_info = ? " + "WHERE ID_FIRM = ? and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, companyBean.getName()); ps.setString(num++, companyBean.getShortName()); ps.setString(num++, companyBean.getAddress()); ps.setString(num++, ""); ps.setString(num++, ""); ps.setString(num++, companyBean.getCeo()); ps.setString(num++, companyBean.getCfo()); ps.setString(num++, ""); ps.setString(num++, ""); RsetTools.setLong(ps, num++, null); ps.setString(num++, ""); ps.setString(num++, companyBean.getWebsite()); ps.setString(num++, companyBean.getInfo()); RsetTools.setLong(ps, num++, companyBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
11
Code Sample 1: public static InputSource getInputSource(URL url) throws IOException { String proto = url.getProtocol().toLowerCase(); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI-PMH only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder ua = new StringBuilder("Java/"); ua.append(System.getProperty("java.version")); ua.append(" ("); ua.append(OAIHarvester.class.getName()); ua.append(')'); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; } Code Sample 2: public static TestResponse post(String urlString, byte[] data, String contentType, String accept) throws IOException { HttpURLConnection httpCon = null; byte[] result = null; byte[] errorResult = null; try { URL url = new URL(urlString); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); httpCon.setRequestProperty("Content-Type", contentType); httpCon.setRequestProperty("Accept", accept); if (data != null) { OutputStream output = httpCon.getOutputStream(); output.write(data); output.close(); } BufferedInputStream in = new BufferedInputStream(httpCon.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { os.write(next); next = in.read(); } os.flush(); result = os.toByteArray(); os.close(); } catch (IOException e) { e.printStackTrace(); } finally { InputStream errorStream = httpCon.getErrorStream(); if (errorStream != null) { BufferedInputStream errorIn = new BufferedInputStream(errorStream); ByteArrayOutputStream errorOs = new ByteArrayOutputStream(); int errorNext = errorIn.read(); while (errorNext > -1) { errorOs.write(errorNext); errorNext = errorIn.read(); } errorOs.flush(); errorResult = errorOs.toByteArray(); errorOs.close(); } return new TestResponse(httpCon.getResponseCode(), errorResult, result); } }
11
Code Sample 1: public static byte[] generateHash(String strPassword, byte[] salt) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(strPassword.getBytes(CHAR_ENCODING)); md.update(salt); return md.digest(); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: public static String encrypt(String input) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(input.getBytes("UTF-8")); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public boolean refresh() { try { synchronized (text) { stream = (new URL(url)).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } text = sb.toString(); } price = 0; date = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return false; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; } Code Sample 2: private void saveAttachment(long messageId, Part attachment, boolean saveAsNew) throws IOException, MessagingException { long attachmentId = -1; Uri contentUri = null; int size = -1; File tempAttachmentFile = null; if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) { attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); } if (attachment.getBody() != null) { Body body = attachment.getBody(); if (body instanceof LocalAttachmentBody) { contentUri = ((LocalAttachmentBody) body).getContentUri(); } else { InputStream in = attachment.getBody().getInputStream(); tempAttachmentFile = File.createTempFile("att", null, mAttachmentsDir); FileOutputStream out = new FileOutputStream(tempAttachmentFile); size = IOUtils.copy(in, out); in.close(); out.close(); } } if (size == -1) { String disposition = attachment.getDisposition(); if (disposition != null) { String s = MimeUtility.getHeaderParameter(disposition, "size"); if (s != null) { size = Integer.parseInt(s); } } } if (size == -1) { size = 0; } String storeData = Utility.combine(attachment.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ','); String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name"); String contentId = attachment.getContentId(); if (attachmentId == -1) { ContentValues cv = new ContentValues(); cv.put("message_id", messageId); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("store_data", storeData); cv.put("size", size); cv.put("name", name); cv.put("mime_type", attachment.getMimeType()); cv.put("content_id", contentId); attachmentId = mDb.insert("attachments", "message_id", cv); } else { ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("size", size); cv.put("content_id", contentId); cv.put("message_id", messageId); mDb.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (tempAttachmentFile != null) { File attachmentFile = new File(mAttachmentsDir, Long.toString(attachmentId)); tempAttachmentFile.renameTo(attachmentFile); attachment.setBody(new LocalAttachmentBody(contentUri, mContext)); ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); mDb.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (attachment instanceof LocalAttachmentBodyPart) { ((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId); } }
00
Code Sample 1: public void run() { if (isRunning) return; isRunning = true; Core core = Core.getInstance(); URL url = null; InputStream input = null; DataInputStream datastream; try { url = new URL(Constants.UpdateCheckUrl); } catch (MalformedURLException e) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } try { input = url.openStream(); } catch (IOException e) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } datastream = new DataInputStream(new BufferedInputStream(input)); String line = null; try { line = datastream.readLine(); } catch (IOException e) { e.printStackTrace(); if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } if (line == null) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } if (line.trim().equalsIgnoreCase(Constants.version)) { if (!firstRun) core.showMessage(0, core.getString("checkUpdateButton"), core.getString("versionMatch")); } else { core.showMessage(1, core.getString("checkUpdateButton"), core.getString("errorNewerVersion") + ": " + line); } isRunning = false; } Code Sample 2: public static String sendGetRequest(String endpoint, String requestParameters) { String result = null; if (endpoint.startsWith("http://")) { try { System.setProperty("java.net.useSystemProxies", "true"); String urlStr = endpoint; if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } rd.close(); result = sb.toString(); } catch (Exception e) { DebuggerQueue.addDebug(HTTPClient.class.getName(), Level.ERROR, "Error during download url %s error: %s", endpoint, e.getMessage()); } } return result; }
11
Code Sample 1: 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 { closeQuietly(in); closeQuietly(out); } return success; } Code Sample 2: @Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("summarysort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("summarysort :: INPATH not given."); return 3; } final String outS = (String) parser.getOptionValue(outputDirOpt); final Path wrkDir = new Path(args.get(0)), in = new Path(args.get(1)), out = outS == null ? null : new Path(outS); final boolean verbose = parser.getBoolean(verboseOpt); final Configuration conf = getConf(); final Timer t = new Timer(); try { @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = sortOne(conf, in, wrkDir, "summarysort", ""); System.out.printf("summarysort :: Waiting for job completion...\n"); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("summarysort :: Job failed."); return 4; } System.out.printf("summarysort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("summarysort :: Merging output..."); t.start(); final FileSystem srcFS = wrkDir.getFileSystem(conf); final FileSystem dstFS = out.getFileSystem(conf); final OutputStream outs = dstFS.create(out); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, in.getName() + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("summarysort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("summarysort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("summarysort :: Output merging failed: %s\n", e); return 5; } return 0; }
00
Code Sample 1: public static void bubble_sort(Sortable[] objects) { for (int i = objects.length; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (objects[j].greater_than(objects[j + 1])) { Sortable tmp = objects[j]; objects[j] = objects[j + 1]; objects[j + 1] = tmp; flipped = true; } } if (!flipped) return; } } Code Sample 2: public static String encryptPass2(String pass) throws UnsupportedEncodingException { String passEncrypt; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } md5.update(pass.getBytes()); String dis = new String(md5.digest(), 10); passEncrypt = dis.toString(); return passEncrypt; }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing 'file' Arg"); return; } int mfid = NumberUtils.toInt(arg); Object sageFile = MediaFileAPI.GetMediaFileForID(mfid); if (sageFile == null) { resp.sendError(404, "Sage File not found " + mfid); return; } int seconds = NumberUtils.toInt(req.getParameter("ss"), -1); long offset = NumberUtils.toLong(req.getParameter("sb"), -1); if (seconds < 0 && offset < 0) { resp.sendError(501, "Missing 'ss' or 'sb' args"); return; } int width = NumberUtils.toInt(req.getParameter("w"), 320); int height = NumberUtils.toInt(req.getParameter("h"), 320); File dir = new File(Phoenix.getInstance().getUserCacheDir(), "videothumb/" + mfid); if (!dir.exists()) { dir.mkdirs(); } String prefix = ""; if (offset > 0) { prefix = "O" + offset; } else { prefix = "S" + seconds; } File f = new File(dir, prefix + "_" + width + "_" + height + ".jpg").getCanonicalFile(); if (!f.exists()) { try { generateThumbnailNew(sageFile, f, seconds, offset, width, height); } catch (Exception e) { e.printStackTrace(); resp.sendError(503, "Failed to generate thumbnail\n " + e.getMessage()); return; } } if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } resp.setContentType("image/jpeg"); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } } Code Sample 2: public static void main(String[] a) throws Exception { HashMap<String, Integer> numberOfOccurencesOfThisComboe = new HashMap<String, Integer>(); HashMap<String, String> fileToCATHMapping = new HashMap<String, String>(); ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; String reducedComboForFilteringOut = allEntries[1] + allEntries[2] + allEntries[3]; fileToCATHMapping.put(fileName, reducedComboForFilteringOut); if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } for (String fileName : allFilesToBeCopied) { String reducedComboForFilteringOut = fileToCATHMapping.get(fileName); if (!numberOfOccurencesOfThisComboe.containsKey(reducedComboForFilteringOut)) { numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, 1); } else { Integer thisCounter = numberOfOccurencesOfThisComboe.get(reducedComboForFilteringOut); thisCounter = thisCounter + 1; numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, thisCounter); } } HashSet<String> isSingleElement = new HashSet<String>(); for (Entry<String, Integer> thisEntry : numberOfOccurencesOfThisComboe.entrySet()) { if (thisEntry.getValue() == 1) { System.out.println("single: " + thisEntry.getKey()); isSingleElement.add(thisEntry.getKey()); } else { System.out.println("not single: " + thisEntry.getKey()); } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { if (!isSingleElement.contains(fileToCATHMapping.get(file))) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: public IntactOntology parseOboFile(URL url, boolean keepTemporaryFile) throws PsiLoaderException { if (url == null) { throw new IllegalArgumentException("Please give a non null URL."); } StringBuffer buffer = new StringBuffer(1024 * 8); try { System.out.println("Loading URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()), 1024); String line; int lineCount = 0; while ((line = in.readLine()) != null) { lineCount++; buffer.append(line).append(NEW_LINE); if ((lineCount % 20) == 0) { System.out.print("."); System.out.flush(); if ((lineCount % 500) == 0) { System.out.println(" " + lineCount); } } } in.close(); File tempDirectory = new File(System.getProperty("java.io.tmpdir", "tmp")); if (!tempDirectory.exists()) { if (!tempDirectory.mkdirs()) { throw new IOException("Cannot create temp directory: " + tempDirectory.getAbsolutePath()); } } System.out.println("Using temp directory: " + tempDirectory.getAbsolutePath()); File tempFile = File.createTempFile("psimi.v25.", ".obo", tempDirectory); tempFile.deleteOnExit(); tempFile.deleteOnExit(); System.out.println("The OBO file is temporary store as: " + tempFile.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(tempFile), 1024); out.write(buffer.toString()); out.flush(); out.close(); return parseOboFile(tempFile); } catch (IOException e) { throw new PsiLoaderException("Error while loading URL (" + url + ")", e); } } Code Sample 2: public List<String> generate(String geronimoVersion, String geronimoHome, String instanceNumber) { geronimoRepository = geronimoHome + "/repository"; Debug.logInfo("The WASCE or Geronimo Repository is " + geronimoRepository, module); Classpath classPath = new Classpath(System.getProperty("java.class.path")); List<File> elements = classPath.getElements(); List<String> jar_version = new ArrayList<String>(); String jarPath = null; String jarName = null; String newJarName = null; String jarNameSimple = null; String jarVersion = "1.0"; int lastDash = -1; for (File f : elements) { if (f.exists()) { if (f.isFile()) { jarPath = f.getAbsolutePath(); jarName = f.getName(); String jarNameWithoutExt = (String) jarName.subSequence(0, jarName.length() - 4); lastDash = jarNameWithoutExt.lastIndexOf("-"); if (lastDash > -1) { jarVersion = jarNameWithoutExt.substring(lastDash + 1, jarNameWithoutExt.length()); jarNameSimple = jarNameWithoutExt.substring(0, lastDash); boolean alreadyVersioned = 0 < StringUtil.removeRegex(jarVersion, "[^.0123456789]").length(); if (!alreadyVersioned) { jarVersion = "1.0"; jarNameSimple = jarNameWithoutExt; newJarName = jarNameWithoutExt + "-" + jarVersion + ".jar"; } else { newJarName = jarName; } } else { jarVersion = "1.0"; jarNameSimple = jarNameWithoutExt; newJarName = jarNameWithoutExt + "-" + jarVersion + ".jar"; } jar_version.add(jarNameSimple + "#" + jarVersion); String targetDirectory = geronimoRepository + "/org/ofbiz/" + jarNameSimple + "/" + jarVersion; File targetDir = new File(targetDirectory); if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { Debug.logFatal("Unable to create target directory - " + targetDirectory, module); return null; } } if (!targetDirectory.endsWith("/")) { targetDirectory = targetDirectory + "/"; } String newCompleteJarName = targetDirectory + newJarName; File newJarFile = new File(newCompleteJarName); try { FileChannel srcChannel = new FileInputStream(jarPath).getChannel(); FileChannel dstChannel = new FileOutputStream(newCompleteJarName).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); Debug.log("Created jar file : " + newJarName + " in WASCE or Geronimo repository", module); srcChannel.close(); dstChannel.close(); } catch (IOException e) { Debug.logFatal("Unable to create jar file - " + newJarName + " in WASCE or Geronimo repository (certainly already exists)", module); return null; } } } } List<ComponentConfig.WebappInfo> webApps = ComponentConfig.getAllWebappResourceInfos(); File geronimoWebXml = new File(System.getProperty("ofbiz.home") + "/framework/appserver/templates/" + geronimoVersion + "/geronimo-web.xml"); for (ComponentConfig.WebappInfo webApp : webApps) { if (null != webApp) { parseTemplate(geronimoWebXml, webApp); } } return jar_version; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: private static boolean hardCopy(File sourceFile, File destinationFile, StringBuffer errorLog) { boolean result = true; try { notifyCopyStart(destinationFile); destinationFile.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destinationFile); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { result = false; handleException("\n Error in method: copy!\n", e, errorLog); } finally { notifyCopyEnd(destinationFile); } return result; }
11
Code Sample 1: private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; } Code Sample 2: public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("Utils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
00
Code Sample 1: private boolean doDelete(String identifier) throws IOException, MalformedURLException { URL url = new URL(baseurl.toString() + "/" + identifier); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); huc.setRequestMethod("DELETE"); huc.connect(); if (huc.getResponseCode() == 200) { return true; } else return false; } Code Sample 2: private static String getHashString(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException { AssertUtility.notNull(text); AssertUtility.notNullAndNotSpace(algorithm); MessageDigest md; md = MessageDigest.getInstance(algorithm); md.update(text.getBytes("UTF-8"), 0, text.length()); byte[] hash = md.digest(); return convertToHex(hash); }
00
Code Sample 1: private void checkRoundtrip(byte[] content) throws Exception { InputStream in = new ByteArrayInputStream(content); ByteArrayOutputStream out = new ByteArrayOutputStream(); CodecUtil.encodeQuotedPrintableBinary(in, out); in = new QuotedPrintableInputStream(new ByteArrayInputStream(out.toByteArray())); out = new ByteArrayOutputStream(); IOUtils.copy(in, out); assertEquals(content, out.toByteArray()); } Code Sample 2: @Override public HostRecord addressForHost(String domainName) throws Exception { String fullUrl = requestUrlStub + domainName; URL url = new URL(fullUrl); HttpURLConnection connection = null; connection = null; connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setReadTimeout(10000); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; HostRecord result = new HostRecord(domainName); byte parts[] = new byte[4]; while ((inputLine = in.readLine()) != null) { String pat1 = "<span class='orange'>"; String pat2 = "</span>"; int index1 = inputLine.indexOf(pat1); int index2 = inputLine.indexOf(pat2); if ((index1 > 0) && (index2 > 0)) { String ipStr = inputLine.substring(index1 + pat1.length(), index2); String[] s = ipStr.split("\\."); for (int i = 0; i < s.length; i++) parts[i] = (byte) Integer.parseInt(s[i]); } } IPAddress ipAddress = new IPAddress(parts); result.addIpAddress(ipAddress); in.close(); return result; }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public static void copyFile(File in, File outDir) throws IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); File out = new File(outDir, in.getName()); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { if (sourceChannel != null) { sourceChannel.close(); } } finally { if (destinationChannel != null) { destinationChannel.close(); } } } }
00
Code Sample 1: public void afficherMetar(String oaci) { if (oaci.length() != 4) { System.out.println("un code METAR est composé de 4 caracteres"); } oaci.toUpperCase(); try { URL url = new URL("http://weather.noaa.gov/pub/data/observations/metar/stations/" + oaci + ".TXT"); System.out.println(url.toString()); Proxy acReunion = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.ac-reunion.fr", 8080)); HttpURLConnection con = (HttpURLConnection) url.openConnection(acReunion); InputStreamReader isr = new InputStreamReader(con.getInputStream()); BufferedReader in = new BufferedReader(isr); Vector vListe = new Vector(); String line; System.out.println("Affichage METAR"); System.out.println("--------"); while ((line = in.readLine()) != null) { System.out.println(line); vListe.add(line); } System.out.println("--------"); in.close(); } catch (java.io.FileNotFoundException e) { System.out.println("Impossible de trouver le METAR"); System.out.println(e); } catch (Exception e) { System.out.println(e.toString()); } } Code Sample 2: private void loadInitialDbState() throws IOException { InputStream in = SchemaAndDataPopulator.class.getClassLoader().getResourceAsStream(resourceName); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer); for (String statement : writer.toString().split(SQL_STATEMENT_DELIMITER)) { logger.info("Executing SQL Statement {}", statement); template.execute(statement); } }
11
Code Sample 1: public static int my_rename(String source, String dest) { logger.debug("RENAME " + source + " to " + dest); if (source == null || dest == null) return -1; { logger.debug("\tMoving file across file systems."); FileChannel srcChannel = null; FileChannel dstChannel = null; FileLock lock = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); lock = dstChannel.lock(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); dstChannel.force(true); } catch (IOException e) { logger.fatal("Error while copying file '" + source + "' to file '" + dest + "'. " + e.getMessage(), e); return common_h.ERROR; } finally { try { lock.release(); } catch (Throwable t) { logger.fatal("Error releasing file lock - " + dest); } try { srcChannel.close(); } catch (Throwable t) { } try { dstChannel.close(); } catch (Throwable t) { } } } return common_h.OK; } Code Sample 2: private void initFiles() throws IOException { if (!tempDir.exists()) { if (!tempDir.mkdir()) throw new IOException("Temp dir '' can not be created"); } File tmp = new File(tempDir, TORRENT_FILENAME); if (!tmp.exists()) { FileChannel in = new FileInputStream(torrentFile).getChannel(); FileChannel out = new FileOutputStream(tmp).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } torrentFile = tmp; if (!stateFile.exists()) { FileChannel out = new FileOutputStream(stateFile).getChannel(); int numChunks = metadata.getPieceHashes().size(); ByteBuffer zero = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0 }); for (int i = 0; i < numChunks; i++) { out.write(zero); zero.clear(); } out.close(); } }
00
Code Sample 1: private static boolean isXmlApplicationFile(URL url) throws java.io.IOException { if (DEBUG) { System.out.println("Checking whether file is xml"); } String firstLine; BufferedReader fileReader = null; try { fileReader = new BomStrippingInputStreamReader(url.openStream()); firstLine = fileReader.readLine(); } finally { if (fileReader != null) fileReader.close(); } if (firstLine == null) { return false; } for (String startOfXml : STARTOFXMLAPPLICATIONFILES) { if (firstLine.length() >= startOfXml.length() && firstLine.substring(0, startOfXml.length()).equals(startOfXml)) { if (DEBUG) { System.out.println("isXMLApplicationFile = true"); } return true; } } if (DEBUG) { System.out.println("isXMLApplicationFile = false"); } return false; } Code Sample 2: public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }