label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception { String project = request.getParameter("project"); String line; response.setContentType("text/html"); PrintWriter out = response.getWriter(); htmlHeader(out, "Project Status", ""); try { synchronized (Class.forName("com.sun.gep.SunTCP")) { Vector list = new Vector(); String directory = home; Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project); FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute"); File listfile = new File(directory + SUNTCP_LIST); BufferedReader read = new BufferedReader(new FileReader(listfile)); while ((line = read.readLine()) != null) { if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) { list.addElement(line); } } read.close(); if (list.size() > 0) { PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile))); for (int i = 0; i < list.size(); i++) { write.println((String) list.get(i)); } write.close(); } else { listfile.delete(); } out.println("The project was successfully deleted."); } } catch (Exception e) { out.println("Error accessing this project."); } out.println("<center><form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form></center>"); htmlFooter(out); }
|
00
|
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:
protected static String getInitialUUID() { if (myRand == null) { myRand = new Random(); } long rand = myRand.nextLong(); String sid; try { sid = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { sid = Thread.currentThread().getName(); } StringBuffer sb = new StringBuffer(); sb.append(sid); sb.append(":"); sb.append(Long.toString(rand)); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new OMException(e); } md5.update(sb.toString().getBytes()); byte[] array = md5.digest(); StringBuffer sb2 = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; sb2.append(Integer.toHexString(b)); } int begin = myRand.nextInt(); if (begin < 0) begin = begin * -1; begin = begin % 8; return sb2.toString().substring(begin, begin + 18).toUpperCase(); }
|
11
|
Code Sample 1:
public void newGuidSeed(boolean secure) { SecureRandom sr = new SecureRandom(); long secureInitializer = sr.nextLong(); Random rand = new Random(secureInitializer); String host_ip = ""; try { host_ip = InetAddress.getLocalHost().toString(); } catch (UnknownHostException err) { err.printStackTrace(); } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException err) { err.printStackTrace(); } try { long time = System.currentTimeMillis(); long randNumber = 0; if (secure) { randNumber = sr.nextLong(); } else { randNumber = rand.nextLong(); } sbBeforeMd5.append(host_ip); sbBeforeMd5.append(":"); sbBeforeMd5.append(Long.toString(time)); sbBeforeMd5.append(":"); sbBeforeMd5.append(Long.toString(randNumber)); seed = sbBeforeMd5.toString(); md5.update(seed.getBytes()); byte[] array = md5.digest(); StringBuffer temp_sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x10) temp_sb.append('0'); temp_sb.append(Integer.toHexString(b)); } rawGUID = temp_sb.toString(); } catch (Exception err) { err.printStackTrace(); } }
Code Sample 2:
private String hashmd5(String suppliedPassword) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(suppliedPassword.getBytes()); String encriptedPassword = null; try { encriptedPassword = new String(Base64.encode(md.digest()), "ASCII"); } catch (UnsupportedEncodingException e) { } return encriptedPassword; }
|
11
|
Code Sample 1:
private void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
private static boolean genMovieRatingFile(String completePath, String masterFile, String CustLocationsFileName, String MovieRatingFileName) { try { File inFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC1 = new FileInputStream(inFile1).getChannel(); int fileSize1 = (int) inC1.size(); int totalNoDataRows = fileSize1 / 7; ByteBuffer mappedBuffer = inC1.map(FileChannel.MapMode.READ_ONLY, 0, fileSize1); System.out.println("Loaded master binary file"); File inFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel inC2 = new FileInputStream(inFile2).getChannel(); int fileSize2 = (int) inC2.size(); System.out.println(fileSize2); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieRatingFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); for (int i = 0; i < 1; i++) { ByteBuffer locBuffer = inC2.map(FileChannel.MapMode.READ_ONLY, i * fileSize2, fileSize2); System.out.println("Loaded cust location file chunk: " + i); while (locBuffer.hasRemaining()) { int locationToRead = locBuffer.getInt(); mappedBuffer.position((locationToRead - 1) * 7); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); ByteBuffer outBuf = ByteBuffer.allocate(3); outBuf.putShort(movieName); outBuf.put(rating); outBuf.flip(); outC.write(outBuf); } } mappedBuffer.clear(); inC1.close(); inC2.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
|
11
|
Code Sample 1:
private String hashString(String key) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); byte[] hash = digest.digest(); BigInteger bi = new BigInteger(1, hash); return String.format("%0" + (hash.length << 1) + "X", bi) + KERNEL_VERSION; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "" + key.hashCode(); } }
Code Sample 2:
private boolean verifyPassword(String password, byte[] hash) { boolean returnValue = false; try { MessageDigest msgDigest = MessageDigest.getInstance("SHA-1"); msgDigest.update(password.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); returnValue = Arrays.equals(hash, digest); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AuthentificationState.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AuthentificationState.class.getName()).log(Level.SEVERE, null, ex); } return returnValue; }
|
11
|
Code Sample 1:
private File sendQuery(String query) throws MusicBrainzException { File xmlServerResponse = null; try { xmlServerResponse = new File(SERVER_RESPONSE_FILE); long start = Calendar.getInstance().getTimeInMillis(); System.out.println("\n\n++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(" consulta de busqueda -> " + query); URL url = new URL(query); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String line = ""; System.out.println(" Respuesta del servidor: \n"); while ((line = in.readLine()) != null) { response += line; } xmlServerResponse = new File(SERVER_RESPONSE_FILE); System.out.println(" Ruta del archivo XML -> " + xmlServerResponse.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(xmlServerResponse)); out.write(response); out.close(); System.out.println("Tamanho del xmlFile -> " + xmlServerResponse.length()); long ahora = (Calendar.getInstance().getTimeInMillis() - start); System.out.println(" Tiempo transcurrido en la consulta (en milesimas) -> " + ahora); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); } catch (IOException e) { e.printStackTrace(); String msg = e.getMessage(); if (e instanceof FileNotFoundException) { msg = "ERROR: MusicBrainz URL used is not found:\n" + msg; } else { } throw new MusicBrainzException(msg); } return xmlServerResponse; }
Code Sample 2:
public String getHtmlCode(String urlString) { StringBuffer result = new StringBuffer(); BufferedReader in = null; try { URL url = new URL((urlString)); URLConnection con = url.openConnection(); in = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); String line = null; while ((line = in.readLine()) != null) { result.append(line + "\r\n"); } in.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } finally { if (in != null) { try { in.close(); } catch (Exception ex) { System.out.println("Exception throws at finally close reader when connecting to URL: " + urlString); } } } return result.toString(); }
|
11
|
Code Sample 1:
public FileInputStream execute() { FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().getResponse(); String pdfPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf"); try { FileOutputStream outputStream = new FileOutputStream(pdfPath + "/driveTogether.pdf"); PdfWriter writer = PdfWriter.getInstance(doc, outputStream); doc.open(); String pfad = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/pdf/template.pdf"); logger.info("Loading PDF-Template: " + pfad); PdfReader reader = new PdfReader(pfad); PdfImportedPage page = writer.getImportedPage(reader, 1); PdfContentByte cb = writer.getDirectContent(); cb.addTemplate(page, 0, 0); doHeader(); doParagraph(trip, forUser); doc.close(); fis = new FileInputStream(pdfPath + "/driveTogether.pdf"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return fis; }
Code Sample 2:
public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } }
|
00
|
Code Sample 1:
public static URLConnection createConnection(URL url) throws java.io.IOException { URLConnection urlConn = url.openConnection(); if (urlConn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setRequestMethod("POST"); } urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setDefaultUseCaches(false); return urlConn; }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
|
11
|
Code Sample 1:
private void copyFile(File f) throws IOException { File newFile = new File(destdir + "/" + f.getName()); newFile.createNewFile(); FileInputStream fin = new FileInputStream(f); FileOutputStream fout = new FileOutputStream(newFile); int c; while ((c = fin.read()) != -1) fout.write(c); fin.close(); fout.close(); }
Code Sample 2:
private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) { String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old"; String backupName = createUniqueFileName(candidateBackupName); MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE); String message = format.format(new String[] { backupName }); boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message); if (ok) { File orig = new File(archiveAccessor.getArchiveFileName()); try { IOUtils.copyFiles(orig, new File(backupName)); DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory()); dram.writeRepository(); } catch (IOException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } catch (RepositoryException e) { EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e); } } return ok; }
|
11
|
Code Sample 1:
public static Hashtable DefaultLoginValues(String firstName, String lastName, String password, String mac, String startLocation, int major, int minor, int patch, int build, String platform, String viewerDigest, String userAgent, String author) throws Exception { Hashtable values = new Hashtable(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes("ASCII"), 0, password.length()); byte[] raw_digest = md5.digest(); String passwordDigest = Helpers.toHexText(raw_digest); values.put("first", firstName); values.put("last", lastName); values.put("passwd", "" + password); values.put("start", startLocation); values.put("major", major); values.put("minor", minor); values.put("patch", patch); values.put("build", build); values.put("platform", platform); values.put("mac", mac); values.put("agree_to_tos", "true"); values.put("viewer_digest", viewerDigest); values.put("user-agent", userAgent + " (" + Helpers.VERSION + ")"); values.put("author", author); Vector optionsArray = new Vector(); optionsArray.addElement("inventory-root"); optionsArray.addElement("inventory-skeleton"); optionsArray.addElement("inventory-lib-root"); optionsArray.addElement("inventory-lib-owner"); optionsArray.addElement("inventory-skel-lib"); optionsArray.addElement("initial-outfit"); optionsArray.addElement("gestures"); optionsArray.addElement("event_categories"); optionsArray.addElement("event_notifications"); optionsArray.addElement("classified_categories"); optionsArray.addElement("buddy-list"); optionsArray.addElement("ui-config"); optionsArray.addElement("login-flags"); optionsArray.addElement("global-textures"); values.put("options", optionsArray); return values; }
Code Sample 2:
public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); }
|
00
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (e.getSource() == cancel) { email.setText(""); name.setText(""); category.setSelectedIndex(0); subject.setText(""); message.setText(""); setVisible(false); } else { StringBuffer errors = new StringBuffer(); if (email.getText().trim().equals("")) errors.append("El campo 'Email' es obligatorio<br/>"); if (name.getText().trim().equals("")) errors.append("El campo 'Nombre' es obligatorio<br/>"); if (subject.getText().trim().equals("")) errors.append("El campo 'T�tulo' es obligatorio<br/>"); if (message.getText().trim().equals("")) errors.append("No hay conrtenido en el mensaje<br/>"); if (errors.length() > 0) { JOptionPane.showMessageDialog(this, "<html><b>Error</b><br/>" + errors.toString() + "</html>", "Error", JOptionPane.ERROR_MESSAGE); } else { try { StringBuffer params = new StringBuffer(); params.append("name=").append(URLEncoder.encode(name.getText(), "UTF-8")).append("&category=").append(URLEncoder.encode((String) category.getSelectedItem(), "UTF-8")).append("&title=").append(URLEncoder.encode(subject.getText(), "UTF-8")).append("&email=").append(URLEncoder.encode(email.getText(), "UTF-8")).append("&id=").append(URLEncoder.encode(MainWindow.getUserPreferences().getUniqueId() + "", "UTF-8")).append("&body=").append(URLEncoder.encode(message.getText(), "UTF-8")); URL url = new URL("http://www.cronopista.com/diccionario2/sendMessage.php"); URLConnection connection = url.openConnection(); Utils.setupProxy(connection); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(params.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close(); email.setText(""); name.setText(""); category.setSelectedIndex(0); subject.setText(""); message.setText(""); setVisible(false); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "<html><b>Error</b><br/>Ha ocurrido un error enviando tu mensaje.<br/>" + "Por favor, int�ntalo m�s tarde o ponte en contacto conmigo a trav�s de www.cronopista.com</html>", "Error", JOptionPane.ERROR_MESSAGE); } } } }
Code Sample 2:
private boolean copyAvecProgressNIO(File sRC2, File dEST2, JProgressBar progressEnCours) throws IOException { boolean resultat = false; FileInputStream fis = new FileInputStream(sRC2); FileOutputStream fos = new FileOutputStream(dEST2); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); progressEnCours.setValue(0); progressEnCours.setString(sRC2 + " : 0 %"); channelSrc.transferTo(0, channelSrc.size(), channelDest); progressEnCours.setValue(100); progressEnCours.setString(sRC2 + " : 100 %"); if (channelSrc.size() == channelDest.size()) { resultat = true; } else { resultat = false; } fis.close(); fos.close(); return (resultat); }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
private boolean exportPKC(String keystoreLocation, String pw) { boolean created = false; KeyStore ks = null; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new BufferedInputStream(new FileInputStream(keystoreLocation)), pw.toCharArray()); } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading keystore file when exporting PKC: " + e.getMessage()); } return false; } Certificate cert = null; try { cert = ks.getCertificate("saws"); } catch (KeyStoreException e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error reading certificate from keystore file when exporting PKC: " + e.getMessage()); } return false; } try { StringBuffer sb = new StringBuffer("-----BEGIN CERTIFICATE-----\n"); sb.append(new String(Base64.encode(cert.getEncoded()))); sb.append("\n-----END CERTIFICATE-----\n"); OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream("sawsSigningPKC.crt")); wr.write(new String(sb)); wr.flush(); wr.close(); created = true; } catch (Exception e) { if (this.debugLevel >= SAWSConstant.ErrorInfo) { this.sawsDebugLog.write("Error exporting PKC file: " + e.getMessage()); } return false; } return created; }
|
00
|
Code Sample 1:
public static String getDeclaredXMLEncoding(URL url) throws IOException { InputStream stream = url.openStream(); BufferedReader buffReader = new BufferedReader(new InputStreamReader(stream)); String firstLine = buffReader.readLine(); if (firstLine == null) { return SYSTEM_ENCODING; } int piStart = firstLine.indexOf("<?xml version=\"1.0\""); if (piStart != -1) { int attributeStart = firstLine.indexOf("encoding=\""); if (attributeStart >= 0) { int nextQuote = firstLine.indexOf('"', attributeStart + 10); if (nextQuote >= 0) { String encoding = firstLine.substring(attributeStart + 10, nextQuote); return encoding.trim(); } } } stream.close(); return SYSTEM_ENCODING; }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
|
00
|
Code Sample 1:
public IContentExtension[] getContentExtensions(String locale) { if (RemoteHelp.isEnabled()) { List contributions = new ArrayList(); PreferenceFileHandler handler = new PreferenceFileHandler(); String isEnabled[] = handler.isEnabled(); for (int ic = 0; ic < handler.getTotalRemoteInfocenters(); ic++) { if (isEnabled[ic].equalsIgnoreCase("true")) { InputStream in = null; try { URL url = RemoteHelp.getURL(ic, PATH_EXTENSIONS); in = url.openStream(); if (reader == null) { reader = new DocumentReader(); } UAElement element = reader.read(in); IContentExtension[] children = (IContentExtension[]) element.getChildren(IContentExtension.class); for (int contrib = 0; contrib < children.length; contrib++) { contributions.add(children[contrib]); } } catch (IOException e) { String msg = "I/O error while trying to contact the remote help server"; HelpBasePlugin.logError(msg, e); } catch (Throwable t) { String msg = "Internal error while reading topic extensions from remote server"; HelpBasePlugin.logError(msg, t); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } } return (IContentExtension[]) contributions.toArray(new IContentExtension[contributions.size()]); } return new IContentExtension[0]; }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { logger.error(Logger.SECURITY_FAILURE, "Problem encoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String CFDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = movieAverages.get(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, CFDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictPearsonWeightedSlopeOneRating(knn, movieToProcess, customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else { finalPrediction = movieAverages.get(movieToProcess); System.out.println("NaN Prediction"); } buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = null; ServletOutputStream outstream = null; try { String action = req.getParameter("nmrshiftdbaction"); String relativepath = ServletUtils.expandRelative(this.getServletConfig(), "/WEB-INF"); TurbineConfig tc = new TurbineConfig(relativepath + "..", relativepath + getServletConfig().getInitParameter("properties")); tc.init(); int spectrumId = -1; DBSpectrum spectrum = null; Export export = null; String format = req.getParameter("format"); if (action.equals("test")) { try { res.setContentType("text/plain"); out = res.getWriter(); List l = DBSpectrumPeer.executeQuery("select SPECTRUM_ID from SPECTRUM limit 1"); if (l.size() > 0) spectrumId = ((Record) l.get(0)).getValue(1).asInt(); out.write("success"); } catch (Exception ex) { out.write("failure"); } } else if (action.equals("rss")) { int numbertoexport = 10; out = res.getWriter(); if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } res.setContentType("text/xml"); RssWriter rssWriter = new RssWriter(); rssWriter.setWriter(res.getWriter()); AtomContainerSet soac = new AtomContainerSet(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" order by MOLECULE.DATE desc;"; List l = NmrshiftdbUserPeer.executeQuery(query); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); IMolecule cdkmol = mol.getAsCDKMoleculeAsEntered(1); soac.addAtomContainer(cdkmol); rssWriter.getLinkmap().put(cdkmol, mol.getEasylink(req)); rssWriter.getDatemap().put(cdkmol, mol.getDate()); rssWriter.getTitlemap().put(cdkmol, mol.getChemicalNamesAsOneStringWithFallback()); rssWriter.getCreatormap().put(cdkmol, mol.getNmrshiftdbUser().getUserName()); rssWriter.setCreator(GeneralUtils.getAdminEmail(getServletConfig())); Vector v = mol.getDBCanonicalNames(); for (int k = 0; k < v.size(); k++) { DBCanonicalName canonName = (DBCanonicalName) v.get(k); if (canonName.getDBCanonicalNameType().getCanonicalNameType() == "INChI") { rssWriter.getInchimap().put(cdkmol, canonName.getName()); break; } } rssWriter.setTitle("NMRShiftDB"); rssWriter.setLink("http://www.nmrshiftdb.org"); rssWriter.setDescription("NMRShiftDB is an open-source, open-access, open-submission, open-content web database for chemical structures and their nuclear magnetic resonance data"); rssWriter.setPublisher("NMRShiftDB.org"); rssWriter.setImagelink("http://www.nmrshiftdb.org/images/nmrshift-logo.gif"); rssWriter.setAbout("http://www.nmrshiftdb.org/NmrshiftdbServlet?nmrshiftdbaction=rss"); Collection coll = new ArrayList(); Vector spectra = mol.selectSpectra(null); for (int k = 0; k < spectra.size(); k++) { Element el = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Element el2 = el.getChildElements().get(0); el.removeChild(el2); coll.add(el2); } rssWriter.getMultiMap().put(cdkmol, coll); } rssWriter.write(soac); } else if (action.equals("getattachment")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); DBSample sample = DBSamplePeer.retrieveByPK(new NumberKey(req.getParameter("sampleid"))); outstream.write(sample.getAttachment()); } else if (action.equals("createreport")) { res.setContentType("application/pdf"); outstream = res.getOutputStream(); boolean yearly = req.getParameter("style").equals("yearly"); int yearstart = Integer.parseInt(req.getParameter("yearstart")); int yearend = Integer.parseInt(req.getParameter("yearend")); int monthstart = 0; int monthend = 0; if (!yearly) { monthstart = Integer.parseInt(req.getParameter("monthstart")); monthend = Integer.parseInt(req.getParameter("monthend")); } int type = Integer.parseInt(req.getParameter("type")); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relativepath + "/reports/" + (yearly ? "yearly" : "monthly") + "_report_" + type + ".jasper"); Map parameters = new HashMap(); if (yearly) parameters.put("HEADER", "Report for years " + yearstart + " - " + yearend); else parameters.put("HEADER", "Report for " + monthstart + "/" + yearstart + " - " + monthend + "/" + yearend); DBConnection dbconn = TurbineDB.getConnection(); Connection conn = dbconn.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = null; if (type == 1) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE where YEAR(DATE)>=" + yearstart + " and YEAR(DATE)<=" + yearend + " and LOGIN_NAME<>'testuser' group by YEAR, " + (yearly ? "" : "MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME"); } else if (type == 2) { rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE group by YEAR, " + (yearly ? "" : "MONTH, ") + "MACHINE.NAME"); } JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(rs)); JasperExportManager.exportReportToPdfStream(jasperPrint, outstream); dbconn.close(); } else if (action.equals("exportcmlbyinchi")) { res.setContentType("text/xml"); out = res.getWriter(); String inchi = req.getParameter("inchi"); String spectrumtype = req.getParameter("spectrumtype"); Criteria crit = new Criteria(); crit.add(DBCanonicalNamePeer.NAME, inchi); crit.addJoin(DBCanonicalNamePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.addJoin(DBSpectrumPeer.SPECTRUM_TYPE_ID, DBSpectrumTypePeer.SPECTRUM_TYPE_ID); crit.add(DBSpectrumTypePeer.NAME, spectrumtype); try { GeneralUtils.logToSql(crit.toString(), null); } catch (Exception ex) { } Vector spectra = DBSpectrumPeer.doSelect(crit); if (spectra.size() == 0) { out.write("No such molecule or spectrum"); } else { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = ((DBSpectrum) spectra.get(0)).getDBMolecule().getCML(1); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); for (int k = 0; k < spectra.size(); k++) { Element parentspec = ((DBSpectrum) spectra.get(k)).getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); } out.write(cmlElement.toXML()); } } else if (action.equals("namelist")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); Criteria crit = new Criteria(); crit.addJoin(DBMoleculePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID); crit.add(DBSpectrumPeer.REVIEW_FLAG, "true"); Vector v = DBMoleculePeer.doSelect(crit); for (int i = 0; i < v.size(); i++) { if (i % 500 == 0) { if (i != 0) { zipout.write(new String("<p>The list is continued <a href=\"nmrshiftdb.names." + i + ".html\">here</a></p></body></html>").getBytes()); zipout.closeEntry(); } zipout.putNextEntry(new ZipEntry("nmrshiftdb.names." + i + ".html")); zipout.write(new String("<html><body><h1>This is a list of strcutures in <a href=\"http://www.nmrshiftdb.org\">NMRShiftDB</a>, starting at " + i + ", Its main purpose is to be found by search engines</h1>").getBytes()); } DBMolecule mol = (DBMolecule) v.get(i); zipout.write(new String("<p><a href=\"" + mol.getEasylink(req) + "\">").getBytes()); Vector cannames = mol.getDBCanonicalNames(); for (int k = 0; k < cannames.size(); k++) { zipout.write(new String(((DBCanonicalName) cannames.get(k)).getName() + " ").getBytes()); } Vector chemnames = mol.getDBChemicalNames(); for (int k = 0; k < chemnames.size(); k++) { zipout.write(new String(((DBChemicalName) chemnames.get(k)).getName() + " ").getBytes()); } zipout.write(new String("</a>. Information we have got: NMR spectra").getBytes()); Vector spectra = mol.selectSpectra(); for (int k = 0; k < spectra.size(); k++) { zipout.write(new String(((DBSpectrum) spectra.get(k)).getDBSpectrumType().getName() + ", ").getBytes()); } if (mol.hasAny3d()) zipout.write(new String("3D coordinates, ").getBytes()); zipout.write(new String("File formats: CML, mol, png, jpeg").getBytes()); zipout.write(new String("</p>").getBytes()); } zipout.write(new String("</body></html>").getBytes()); zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("predictor")) { if (req.getParameter("symbol") == null) { res.setContentType("text/plain"); out = res.getWriter(); out.write("please give the symbol to create the predictor for in the request with symbol=X (e. g. symbol=C"); } res.setContentType("application/zip"); outstream = res.getOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipout = new ZipOutputStream(baos); String filename = "org/openscience/nmrshiftdb/PredictionTool.class"; zipout.putNextEntry(new ZipEntry(filename)); JarInputStream jip = new JarInputStream(new FileInputStream(ServletUtils.expandRelative(getServletConfig(), "/WEB-INF/lib/nmrshiftdb-lib.jar"))); JarEntry entry = jip.getNextJarEntry(); while (entry.getName().indexOf("PredictionTool.class") == -1) { entry = jip.getNextJarEntry(); } for (int i = 0; i < entry.getSize(); i++) { zipout.write(jip.read()); } zipout.closeEntry(); zipout.putNextEntry(new ZipEntry("nmrshiftdb.csv")); int i = 0; org.apache.turbine.util.db.pool.DBConnection conn = TurbineDB.getConnection(); HashMap mapsmap = new HashMap(); while (true) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select HOSE_CODE, VALUE, SYMBOL from HOSE_CODES where CONDITION_TYPE='m' and WITH_RINGS=0 and SYMBOL='" + req.getParameter("symbol") + "' limit " + (i * 1000) + ", 1000"); int m = 0; while (rs.next()) { String code = rs.getString(1); Double value = new Double(rs.getString(2)); String symbol = rs.getString(3); if (mapsmap.get(symbol) == null) { mapsmap.put(symbol, new HashMap()); } for (int spheres = 6; spheres > 0; spheres--) { StringBuffer hoseCodeBuffer = new StringBuffer(); StringTokenizer st = new StringTokenizer(code, "()/"); for (int k = 0; k < spheres; k++) { if (st.hasMoreTokens()) { String partcode = st.nextToken(); hoseCodeBuffer.append(partcode); } if (k == 0) { hoseCodeBuffer.append("("); } else if (k == 3) { hoseCodeBuffer.append(")"); } else { hoseCodeBuffer.append("/"); } } String hoseCode = hoseCodeBuffer.toString(); if (((HashMap) mapsmap.get(symbol)).get(hoseCode) == null) { ((HashMap) mapsmap.get(symbol)).put(hoseCode, new ArrayList()); } ((ArrayList) ((HashMap) mapsmap.get(symbol)).get(hoseCode)).add(value); } m++; } i++; stmt.close(); if (m == 0) break; } Set keySet = mapsmap.keySet(); Iterator it = keySet.iterator(); while (it.hasNext()) { String symbol = (String) it.next(); HashMap hosemap = ((HashMap) mapsmap.get(symbol)); Set keySet2 = hosemap.keySet(); Iterator it2 = keySet2.iterator(); while (it2.hasNext()) { String hoseCode = (String) it2.next(); ArrayList list = ((ArrayList) hosemap.get(hoseCode)); double[] values = new double[list.size()]; for (int k = 0; k < list.size(); k++) { values[k] = ((Double) list.get(k)).doubleValue(); } zipout.write(new String(symbol + "|" + hoseCode + "|" + Statistics.minimum(values) + "|" + Statistics.average(values) + "|" + Statistics.maximum(values) + "\r\n").getBytes()); } } zipout.closeEntry(); zipout.close(); InputStream is = new ByteArrayInputStream(baos.toByteArray()); byte[] buf = new byte[32 * 1024]; int nRead = 0; i = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } else if (action.equals("exportspec") || action.equals("exportmol")) { if (spectrumId > -1) spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(spectrumId)); else spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(req.getParameter("spectrumid"))); export = new Export(spectrum); } else if (action.equals("exportmdl")) { res.setContentType("text/plain"); outstream = res.getOutputStream(); DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(req.getParameter("moleculeid"))); outstream.write(mol.getStructureFile(Integer.parseInt(req.getParameter("coordsetid")), false).getBytes()); } else if (action.equals("exportlastinputs")) { format = action; } else if (action.equals("printpredict")) { res.setContentType("text/html"); out = res.getWriter(); HttpSession session = req.getSession(); VelocityContext context = PredictPortlet.getContext(session, true, true, new StringBuffer(), getServletConfig(), req, true); StringWriter w = new StringWriter(); Velocity.mergeTemplate("predictprint.vm", "ISO-8859-1", context, w); out.println(w.toString()); } else { res.setContentType("text/html"); out = res.getWriter(); out.println("No valid action"); } if (format == null) format = ""; if (format.equals("pdf") || format.equals("rtf")) { res.setContentType("application/" + format); out = res.getWriter(); } if (format.equals("docbook")) { res.setContentType("application/zip"); outstream = res.getOutputStream(); } if (format.equals("svg")) { res.setContentType("image/x-svg"); out = res.getWriter(); } if (format.equals("tiff")) { res.setContentType("image/tiff"); outstream = res.getOutputStream(); } if (format.equals("jpeg")) { res.setContentType("image/jpeg"); outstream = res.getOutputStream(); } if (format.equals("png")) { res.setContentType("image/png"); outstream = res.getOutputStream(); } if (format.equals("mdl") || format.equals("txt") || format.equals("cml") || format.equals("cmlboth") || format.indexOf("exsection") == 0) { res.setContentType("text/plain"); out = res.getWriter(); } if (format.equals("simplehtml") || format.equals("exportlastinputs")) { res.setContentType("text/html"); out = res.getWriter(); } if (action.equals("exportlastinputs")) { int numbertoexport = 4; if (req.getParameter("numbertoexport") != null) { try { numbertoexport = Integer.parseInt(req.getParameter("numbertoexport")); if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large"); } catch (NumberFormatException ex) { out.println("The parameter <code>numbertoexport</code>must be an integer from 1 to 20"); } } NmrshiftdbUser user = null; try { user = NmrshiftdbUserPeer.getByName(req.getParameter("username")); } catch (NmrshiftdbException ex) { out.println("Seems <code>username</code> is not OK: " + ex.getMessage()); } if (user != null) { List l = NmrshiftdbUserPeer.executeQuery("SELECT LAST_DOWNLOAD_DATE FROM TURBINE_USER where LOGIN_NAME=\"" + user.getUserName() + "\";"); Date lastDownloadDate = ((Record) l.get(0)).getValue(1).asDate(); if (((new Date().getTime() - lastDownloadDate.getTime()) / 3600000) < 24) { out.println("Your last download was at " + lastDownloadDate + ". You may download your last inputs only once a day. Sorry for this, but we need to be carefull with resources. If you want to put your last inputs on your homepage best use some sort of cache (e. g. use wget for downlaod with crond and link to this static resource))!"); } else { NmrshiftdbUserPeer.executeStatement("UPDATE TURBINE_USER SET LAST_DOWNLOAD_DATE=NOW() where LOGIN_NAME=\"" + user.getUserName() + "\";"); Vector<String> parameters = new Vector<String>(); String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" and SPECTRUM.USER_ID=" + user.getUserId() + " order by MOLECULE.DATE desc;"; l = NmrshiftdbUserPeer.executeQuery(query); String url = javax.servlet.http.HttpUtils.getRequestURL(req).toString(); url = url.substring(0, url.length() - 17); for (int i = 0; i < numbertoexport; i++) { if (i == l.size()) break; DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt())); parameters.add(new String("<a href=\"" + url + "/portal/pane0/Results?nmrshiftdbaction=showDetailsFromHome&molNumber=" + mol.getMoleculeId() + "\"><img src=\"" + javax.servlet.http.HttpUtils.getRequestURL(req).toString() + "?nmrshiftdbaction=exportmol&spectrumid=" + ((DBSpectrum) mol.getDBSpectrums().get(0)).getSpectrumId() + "&format=jpeg&size=150x150&backcolor=12632256\"></a>")); } VelocityContext context = new VelocityContext(); context.put("results", parameters); StringWriter w = new StringWriter(); Velocity.mergeTemplate("lateststructures.vm", "ISO-8859-1", context, w); out.println(w.toString()); } } } if (action.equals("exportspec")) { if (format.equals("txt")) { String lastsearchtype = req.getParameter("lastsearchtype"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { List l = ParseUtils.parseSpectrumFromSpecFile(req.getParameter("lastsearchvalues")); spectrum.initSimilarity(l, lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)); } Vector v = spectrum.getOptions(); DBMolecule mol = spectrum.getDBMolecule(); out.print(mol.getChemicalNamesAsOneString(false) + mol.getMolecularFormula(false) + "; " + mol.getMolecularWeight() + " Dalton\n\r"); out.print("\n\rAtom\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("Mult.\t"); out.print("Meas."); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tInput\tDiff"); } out.print("\n\r"); out.print("No.\t"); if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("\t"); out.print("Shift"); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\tShift\tM-I"); } out.print("\n\r"); for (int i = 0; i < v.size(); i++) { out.print(((ValuesForVelocityBean) v.get(i)).getDisplayText() + "\t" + ((ValuesForVelocityBean) v.get(i)).getRange()); if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) { out.print("\t" + ((ValuesForVelocityBean) v.get(i)).getNameForElements() + "\t" + ((ValuesForVelocityBean) v.get(i)).getDelta()); } out.print("\n\r"); } } if (format.equals("simplehtml")) { String i1 = export.getImage(false, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[0] = new File(i1).getName(); String i2 = export.getImage(true, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true); export.pictures[1] = new File(i2).getName(); String docbook = export.getHtml(); out.print(docbook); } if (format.equals("pdf") || format.equals("rtf")) { String svgSpec = export.getSpecSvg(400, 200); String svgspecfile = relativepath + "/tmp/" + System.currentTimeMillis() + "s.svg"; new FileOutputStream(svgspecfile).write(svgSpec.getBytes()); export.pictures[1] = svgspecfile; String molSvg = export.getMolSvg(true); String svgmolfile = relativepath + "/tmp/" + System.currentTimeMillis() + "m.svg"; new FileOutputStream(svgmolfile).write(molSvg.getBytes()); export.pictures[0] = svgmolfile; String docbook = export.getDocbook("pdf", "SVG"); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource("file:" + GeneralUtils.getNmrshiftdbProperty("docbookxslpath", getServletConfig()) + "/fo/docbook.xsl")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new StreamSource(new StringReader(docbook)), new StreamResult(baos)); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); OutputStream out2 = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(format.equals("rtf") ? MimeConstants.MIME_RTF : MimeConstants.MIME_PDF, foUserAgent, out2); TransformerFactory factory = TransformerFactory.newInstance(); transformer = factory.newTransformer(); Source src = new StreamSource(new StringReader(baos.toString())); Result res2 = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res2); out.print(out2.toString()); } if (format.equals("docbook")) { String i1 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i1).write(export.getSpecSvg(300, 200).getBytes()); export.pictures[0] = new File(i1).getName(); String i2 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg"; new FileOutputStream(i2).write(export.getMolSvg(true).getBytes()); export.pictures[1] = new File(i2).getName(); String docbook = export.getDocbook("pdf", "SVG"); String docbookfile = relativepath + "/tmp/" + System.currentTimeMillis() + ".xml"; new FileOutputStream(docbookfile).write(docbook.getBytes()); ByteArrayOutputStream baos = export.makeZip(new String[] { docbookfile, i1, i2 }); outstream.write(baos.toByteArray()); } if (format.equals("svg")) { out.print(export.getSpecSvg(400, 200)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(false, format, relativepath + "/tmp/" + System.currentTimeMillis(), true)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("cml")) { out.print(spectrum.getCmlSpect().toXML()); } if (format.equals("cmlboth")) { Element cmlElement = new Element("cml"); cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention")); cmlElement.setNamespaceURI("http://www.xml-cml.org/schema"); Element parent = spectrum.getDBMolecule().getCML(1, spectrum.getDBSpectrumType().getName().equals("1H")); nu.xom.Node cmldoc = parent.getChild(0); ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema"); parent.removeChildren(); cmlElement.appendChild(cmldoc); Element parentspec = spectrum.getCmlSpect(); Node spectrumel = parentspec.getChild(0); parentspec.removeChildren(); cmlElement.appendChild(spectrumel); ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema"); out.write(cmlElement.toXML()); } if (format.indexOf("exsection") == 0) { StringTokenizer st = new StringTokenizer(format, "-"); st.nextToken(); String template = st.nextToken(); Criteria crit = new Criteria(); crit.add(DBSpectrumPeer.USER_ID, spectrum.getUserId()); Vector v = spectrum.getDBMolecule().getDBSpectrums(crit); VelocityContext context = new VelocityContext(); context.put("spectra", v); context.put("molecule", spectrum.getDBMolecule()); StringWriter w = new StringWriter(); Velocity.mergeTemplate("exporttemplates/" + template, "ISO-8859-1", context, w); out.write(w.toString()); } } if (action.equals("exportmol")) { int width = -1; int height = -1; if (req.getParameter("size") != null) { StringTokenizer st = new StringTokenizer(req.getParameter("size"), "x"); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } boolean shownumbers = true; if (req.getParameter("shownumbers") != null && req.getParameter("shownumbers").equals("false")) { shownumbers = false; } if (req.getParameter("backcolor") != null) { export.backColor = new Color(Integer.parseInt(req.getParameter("backcolor"))); } if (req.getParameter("markatom") != null) { export.selected = Integer.parseInt(req.getParameter("markatom")) - 1; } if (format.equals("svg")) { out.print(export.getMolSvg(true)); } if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) { InputStream is = new FileInputStream(export.getImage(true, format, relativepath + "/tmp/" + System.currentTimeMillis(), width, height, shownumbers, null)); byte[] buf = new byte[32 * 1024]; int nRead = 0; while ((nRead = is.read(buf)) != -1) { outstream.write(buf, 0, nRead); } } if (format.equals("mdl")) { out.println(spectrum.getDBMolecule().getStructureFile(1, false)); } if (format.equals("cml")) { out.println(spectrum.getDBMolecule().getCMLString(1)); } } if (out != null) out.flush(); else outstream.flush(); } catch (Exception ex) { ex.printStackTrace(); out.print(GeneralUtils.logError(ex, "NmrshiftdbServlet", null, true)); out.flush(); } }
|
11
|
Code Sample 1:
private static void copySmallFile(final File sourceFile, final File targetFile) throws PtException { LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'."); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(sourceFile).getChannel(); outChannel = new FileOutputStream(targetFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new PtException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(inChannel, outChannel); } }
Code Sample 2:
static void linkBlocks(File from, File to, int oldLV) throws IOException { if (!from.isDirectory()) { if (from.getName().startsWith(COPY_FILE_PREFIX)) { IOUtils.copyBytes(new FileInputStream(from), new FileOutputStream(to), 16 * 1024, true); } else { if (oldLV >= PRE_GENERATIONSTAMP_LAYOUT_VERSION) { to = new File(convertMetatadataFileName(to.getAbsolutePath())); } HardLink.createHardLink(from, to); } return; } if (!to.mkdir()) throw new IOException("Cannot create directory " + to); String[] blockNames = from.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(BLOCK_SUBDIR_PREFIX) || name.startsWith(BLOCK_FILE_PREFIX) || name.startsWith(COPY_FILE_PREFIX); } }); for (int i = 0; i < blockNames.length; i++) linkBlocks(new File(from, blockNames[i]), new File(to, blockNames[i]), oldLV); }
|
11
|
Code Sample 1:
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); } }
Code Sample 2:
protected void copy(URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { in = url.openStream(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } }
|
00
|
Code Sample 1:
@SuppressWarnings({ "ProhibitedExceptionDeclared" }) public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; if (args.size() == 0) { log(Level.SEVERE, "noarguments"); returnCode++; } final byte[] buf = new byte[BUF_SIZE]; for (final String arg : args) { try { final URL url = new URL(arg); final URLConnection con = url.openConnection(); final InputStream in = con.getInputStream(); try { final String location = con.getHeaderField("Content-Location"); final String outputFilename = new File((location != null ? new URL(url, location) : url).getFile()).getName(); log(Level.INFO, "writing", arg, outputFilename); final OutputStream out = new FileOutputStream(outputFilename); try { for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) { out.write(buf, 0, bytesRead); } } finally { out.close(); } } finally { in.close(); } } catch (final IOException e) { log(Level.WARNING, "cannotopen", arg, e); returnCode++; } } return returnCode; }
Code Sample 2:
public static String createMD5(String str) { String sig = null; String strSalt = str + sSalt; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(strSalt.getBytes(), 0, strSalt.length()); byte byteData[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } sig = sb.toString(); } catch (NoSuchAlgorithmException e) { System.err.println("Can not use md5 algorithm"); } return sig; }
|
00
|
Code Sample 1:
public HttpURLConnection openConnection(String url) throws IOException { if (isDebugMode()) System.out.println("open: " + url); URL u = new URL(url); HttpURLConnection urlConnection; if (proxy != null) urlConnection = (HttpURLConnection) u.openConnection(proxy); else urlConnection = (HttpURLConnection) u.openConnection(); urlConnection.setRequestProperty("User-Agent", userAgent); return urlConnection; }
Code Sample 2:
private static void serveHTML() throws Exception { Bus bus = BusFactory.getDefaultBus(); DestinationFactoryManager dfm = bus.getExtension(DestinationFactoryManager.class); DestinationFactory df = dfm.getDestinationFactory("http://cxf.apache.org/transports/http/configuration"); EndpointInfo ei = new EndpointInfo(); ei.setAddress("http://localhost:8080/test.html"); Destination d = df.getDestination(ei); d.setMessageObserver(new MessageObserver() { public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } } }); }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException(className + "Cannot overwrite existing file: " + dest.getAbsolutePath()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } }
Code Sample 2:
public static void fileCopy(String from_name, String to_name) throws IOException { File fromFile = new File(from_name); File toFile = new File(to_name); if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name); if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name); if (!fromFile.isFile()) abort("can't copy directory: " + from_name); if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name); } else { String parent = toFile.getParent(); if (parent == null) abort("destination directory doesn't exist: " + parent); File dir = new File(parent); if (!dir.exists()) abort("destination directory doesn't exist: " + parent); if (dir.isFile()) abort("destination is not a directory: " + parent); if (!dir.canWrite()) abort("destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
public static boolean verify(final String password, final String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } final byte[] data = Base64.decode(base64.toCharArray()); final byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); }
Code Sample 2:
public static String MD5(String text) { byte[] md5hash = new byte[32]; try { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); } catch (Exception e) { e.printStackTrace(); } return convertToHex(md5hash); }
|
00
|
Code Sample 1:
public static InputStream sendReq(String url, String content, ConnectData data) { try { URLConnection con = new URL(url).openConnection(); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); con.setUseCaches(false); setUA(con); con.setRequestProperty("Accept-Charset", "utf-8"); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (data.cookie != null) con.setRequestProperty("Cookie", data.cookie); HttpURLConnection httpurl = (HttpURLConnection) con; httpurl.setRequestMethod("POST"); Writer wr = new OutputStreamWriter(con.getOutputStream()); wr.write(content); wr.flush(); con.connect(); InputStream is = con.getInputStream(); is = new BufferedInputStream(is); wr.close(); parseCookie(con, data); return is; } catch (IOException ioe) { Log.except("failed to send request " + url, ioe); } return null; }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String cacheName = req.getParameter("cacheName"); if (cacheName == null || cacheName.equals("")) { resp.getWriter().println("parameter cacheName required"); return; } else { StringBuffer urlStr = new StringBuffer(); urlStr.append(BASE_URL); urlStr.append("?"); urlStr.append("cacheName="); urlStr.append("rpcwc.bo.cache."); urlStr.append(cacheName); URL url = new URL(urlStr.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; StringBuffer output = new StringBuffer(); while ((line = reader.readLine()) != null) { output.append(line); output.append(System.getProperty("line.separator")); } reader.close(); resp.getWriter().println(output.toString()); } }
|
11
|
Code Sample 1:
private boolean copy_to_file_io(File src, File dst) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); is = new BufferedInputStream(is); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); byte buffer[] = new byte[1024 * 64]; int read; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } return true; } finally { try { if (is != null) is.close(); } catch (IOException e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (IOException e) { Debug.debug(e); } } }
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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </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 void setPage(String url) { System.out.println("SetPage(" + url + ")"); if (url != null) { if (!url.startsWith("http://")) { url = "http://" + url; } boolean exists = false; for (int i = 0; i < urlComboBox.getItemCount(); i++) { if (((String) urlComboBox.getItemAt(i)).equals(url)) { exists = true; urlComboBox.setSelectedItem(url); } } if (!exists) { int i = urlComboBox.getSelectedIndex(); if (i == -1 || urlComboBox.getItemCount() == 0) { i = 0; } else { i++; } urlComboBox.insertItemAt(url, i); urlComboBox.setSelectedItem(url); } boolean image = false; for (final String element : imageExtensions) { if (url.endsWith(element)) { image = true; } } try { if (image) { final String html = "<html><img src=\"" + url + "\"></html>"; } else { final String furl = url; Runnable loadPage = new Runnable() { public void run() { try { System.out.println("Setting page on Cobra"); SimpleHtmlRendererContext rendererContext = new SimpleHtmlRendererContext(htmlPanel, new SimpleUserAgentContext()); int nodeBaseEnd = furl.indexOf("/", 10); if (nodeBaseEnd == -1) nodeBaseEnd = furl.length(); String nodeBase = furl.substring(0, nodeBaseEnd); InputStream pageStream = new URL(furl).openStream(); BufferedReader pageStreamReader = new BufferedReader(new InputStreamReader(pageStream)); String pageContent = ""; String line; while ((line = pageStreamReader.readLine()) != null) pageContent += line; pageContent = borderImages(pageContent, nodeBase); htmlPanel.setHtml(pageContent, furl, rendererContext); } catch (Exception e) { System.out.println("Error loading page " + furl + " : " + e); } } }; new Thread(loadPage).start(); } } catch (final Throwable exception) { System.out.println("Error in Browser.setPage(): " + exception); } } }
Code Sample 2:
private boolean readRemoteFile() { InputStream inputstream; Concept concept = new Concept(); try { inputstream = url.openStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputStreamReader); String s4; while ((s4 = bufferedreader.readLine()) != null && s4.length() > 0) { if (!parseLine(s4, concept)) { return false; } } } catch (MalformedURLException e) { logger.fatal("malformed URL, trying to read local file"); return readLocalFile(); } catch (IOException e1) { logger.fatal("Error reading URL file, trying to read local file"); return readLocalFile(); } catch (Exception x) { logger.fatal("Failed to readRemoteFile " + x.getMessage() + ", trying to read local file"); return readLocalFile(); } return true; }
|
00
|
Code Sample 1:
public boolean save(String trxName) { if (m_value == null || (!(m_value instanceof String || m_value instanceof byte[])) || (m_value instanceof String && m_value.toString().length() == 0) || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) { StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=null WHERE ").append(m_whereClause); int no = DB.executeUpdate(sql.toString(), trxName); log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value); if (no == 0) log.warning("[" + trxName + "] - not updated - " + sql); return true; } StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=? WHERE ").append(m_whereClause); boolean success = true; if (DB.isRemoteObjects()) { log.fine("[" + trxName + "] - Remote - " + m_value); Server server = CConnection.get().getServer(); try { if (server != null) { success = server.updateLOB(sql.toString(), m_displayType, m_value, trxName, SecurityToken.getInstance()); if (CLogMgt.isLevelFinest()) log.fine("server.updateLOB => " + success); return success; } log.log(Level.SEVERE, "AppsServer not found"); } catch (RemoteException ex) { log.log(Level.SEVERE, "AppsServer error", ex); } return false; } log.fine("[" + trxName + "] - Local - " + m_value); Trx trx = null; if (trxName != null) trx = Trx.get(trxName, false); Connection con = null; if (trx != null) con = trx.getConnection(); if (con == null) con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); if (con == null) { log.log(Level.SEVERE, "Could not get Connection"); return false; } PreparedStatement pstmt = null; success = true; try { pstmt = con.prepareStatement(sql.toString()); if (m_displayType == DisplayType.TextLong) pstmt.setString(1, (String) m_value); else pstmt.setBytes(1, (byte[]) m_value); int no = pstmt.executeUpdate(); if (no != 1) { log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql); success = false; } } catch (Throwable e) { log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e); success = false; } finally { DB.close(pstmt); pstmt = null; } if (success) { if (trx != null) { trx = null; con = null; } else { try { con.commit(); } catch (Exception e) { log.log(Level.SEVERE, "[" + trxName + "] - commit ", e); success = false; } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } if (!success) { log.severe("[" + trxName + "] - rollback"); if (trx != null) { trx.rollback(); trx = null; con = null; } else { try { con.rollback(); } catch (Exception ee) { log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee); } finally { try { con.close(); } catch (SQLException e) { } con = null; } } } return success; }
Code Sample 2:
@Test public void testRegisterOwnJceProvider() throws Exception { MyTestProvider provider = new MyTestProvider(); assertTrue(-1 != Security.addProvider(provider)); MessageDigest messageDigest = MessageDigest.getInstance("SHA-1", MyTestProvider.NAME); assertEquals(MyTestProvider.NAME, messageDigest.getProvider().getName()); messageDigest.update("hello world".getBytes()); byte[] result = messageDigest.digest(); Assert.assertArrayEquals("hello world".getBytes(), result); Security.removeProvider(MyTestProvider.NAME); }
|
11
|
Code Sample 1:
public static void copy(String sourceName, String destName) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); for (int i = 0; i < files.length; i++) { targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath()); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
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:
boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; }
Code Sample 2:
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() + ")"); } } }
|
11
|
Code Sample 1:
public static String getMD5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes("ISO8859_1")); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; }
Code Sample 2:
private byte[] szyfrujKlucz(byte[] kluczSesyjny) { byte[] zaszyfrowanyKlucz = null; byte[] klucz = null; try { MessageDigest skrot = MessageDigest.getInstance("SHA-1"); skrot.update(haslo.getBytes()); byte[] skrotHasla = skrot.digest(); Object kluczDoKlucza = MARS_Algorithm.makeKey(skrotHasla); int resztaKlucza = this.dlugoscKlucza % ROZMIAR_BLOKU; if (resztaKlucza == 0) { klucz = kluczSesyjny; zaszyfrowanyKlucz = new byte[this.dlugoscKlucza]; } else { int liczbaBlokow = this.dlugoscKlucza / ROZMIAR_BLOKU + 1; int nowyRozmiar = liczbaBlokow * ROZMIAR_BLOKU; zaszyfrowanyKlucz = new byte[nowyRozmiar]; klucz = new byte[nowyRozmiar]; byte roznica = (byte) (ROZMIAR_BLOKU - resztaKlucza); System.arraycopy(kluczSesyjny, 0, klucz, 0, kluczSesyjny.length); for (int i = kluczSesyjny.length; i < nowyRozmiar; i++) klucz[i] = (byte) roznica; } byte[] szyfrogram = null; int liczbaBlokow = klucz.length / ROZMIAR_BLOKU; int offset = 0; for (offset = 0; offset < liczbaBlokow; offset++) { szyfrogram = MARS_Algorithm.blockEncrypt(klucz, offset * ROZMIAR_BLOKU, kluczDoKlucza); System.arraycopy(szyfrogram, 0, zaszyfrowanyKlucz, offset * ROZMIAR_BLOKU, szyfrogram.length); } } catch (InvalidKeyException ex) { Logger.getLogger(SzyfrowaniePliku.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return zaszyfrowanyKlucz; }
|
11
|
Code Sample 1:
private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); }
Code Sample 2:
public void trimAndWriteNewSff(OutputStream out) throws IOException { TrimParser trimmer = new TrimParser(); SffParser.parseSFF(untrimmedSffFile, trimmer); tempOut.close(); headerBuilder.withNoIndex().numberOfReads(numberOfTrimmedReads); SffWriter.writeCommonHeader(headerBuilder.build(), out); InputStream in = null; try { in = new FileInputStream(tempReadDataFile); IOUtils.copyLarge(in, out); } finally { IOUtil.closeAndIgnoreErrors(in); } }
|
00
|
Code Sample 1:
@Override protected void copy(InputStream inputs, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException(); } if (inputs == null) { throw new NullPointerException(); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream(outputs); zipoutputs.putNextEntry(new ZipEntry("default")); IOUtils.copy(inputs, zipoutputs); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (zipoutputs != null) { zipoutputs.close(); } if (inputs != null) { inputs.close(); } } }
Code Sample 2:
@Override public void setOntology1Document(URL url1) throws IllegalArgumentException { if (url1 == null) throw new IllegalArgumentException("Input parameter URL for ontology 1 is null."); try { ont1 = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(url1.openStream()); } catch (IOException e) { throw new IllegalArgumentException("Cannot open stream for ontology 1 from given URL."); } catch (OWLOntologyCreationException e) { throw new IllegalArgumentException("Cannot load ontology 1 from given URL."); } }
|
11
|
Code Sample 1:
private static String deviceIdFromCombined_Device_ID(Context context) { StringBuilder builder = new StringBuilder(); builder.append(deviceIdFromIMEI(context)); builder.append(deviceIdFromPseudo_Unique_Id()); builder.append(deviceIdFromAndroidId(context)); builder.append(deviceIdFromWLAN_MAC_Address(context)); builder.append(deviceIdFromBT_MAC_Address(context)); String m_szLongID = builder.toString(); MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(m_szLongID.getBytes(), 0, m_szLongID.length()); byte p_md5Data[] = m.digest(); String m_szUniqueID = new String(); for (int i = 0; i < p_md5Data.length; i++) { int b = (0xFF & p_md5Data[i]); if (b <= 0xF) m_szUniqueID += "0"; m_szUniqueID += Integer.toHexString(b); } return m_szUniqueID; }
Code Sample 2:
public static byte[] hash(final byte[] saltBefore, final String content, final byte[] saltAfter, final int repeatedHashingCount) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (content == null) return null; final MessageDigest digest = MessageDigest.getInstance(DIGEST); if (digestLength == -1) digestLength = digest.getDigestLength(); for (int i = 0; i < repeatedHashingCount; i++) { if (i > 0) digest.update(digest.digest()); digest.update(saltBefore); digest.update(content.getBytes(WebCastellumParameter.DEFAULT_CHARACTER_ENCODING.getValue())); digest.update(saltAfter); } return digest.digest(); }
|
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:
private void saveFile(File destination) { InputStream in = null; OutputStream out = null; try { if (fileScheme) in = new BufferedInputStream(new FileInputStream(source.getPath())); else in = new BufferedInputStream(getContentResolver().openInputStream(source)); out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) out.write(buffer); Toast.makeText(this, R.string.saveas_file_saved, Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } }
Code Sample 2:
private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; }
|
00
|
Code Sample 1:
private void copyFile(File sourcefile, File targetfile) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(sourcefile)); out = new BufferedOutputStream(new FileOutputStream(targetfile)); byte[] buffer = new byte[4096]; int bytesread = 0; while ((bytesread = in.read(buffer)) >= 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); String line = reader.readLine(); reader.close(); urlcon.disconnect(); return line; }
|
11
|
Code Sample 1:
public static String translate(String s, String type) { try { String result = null; URL url = new URL("http://www.excite.co.jp/world/english/"); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("before=" + URLEncoder.encode(s, "SJIS") + "&wb_lp="); out.print(type); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "SJIS")); String inputLine; while ((inputLine = in.readLine()) != null) { int textPos = inputLine.indexOf("name=\"after\""); if (textPos >= 0) { int ltrPos = inputLine.indexOf(">", textPos + 11); if (ltrPos >= 0) { int closePos = inputLine.indexOf("<", ltrPos + 1); if (closePos >= 0) { result = inputLine.substring(ltrPos + 1, closePos); break; } else { result = inputLine.substring(ltrPos + 1); break; } } } } in.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
private String getShaderIncludeSource(String path) throws Exception { URL url = this.getClass().getResource(path); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); boolean run = true; String str; String ret = new String(); while (run) { str = in.readLine(); if (str != null) ret += str + "\n"; else run = false; } in.close(); return ret; }
|
00
|
Code Sample 1:
private InputStream getInputStream(final String pUrlStr) throws IOException { URL url; int responseCode; String encoding; url = new URL(pUrlStr); myActiveConnection = (HttpURLConnection) url.openConnection(); myActiveConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); responseCode = myActiveConnection.getResponseCode(); if (responseCode != RESPONSECODE_OK) { String message; String apiErrorMessage; apiErrorMessage = myActiveConnection.getHeaderField("Error"); if (apiErrorMessage != null) { message = "Received API HTTP response code " + responseCode + " with message \"" + apiErrorMessage + "\" for URL \"" + pUrlStr + "\"."; } else { message = "Received API HTTP response code " + responseCode + " for URL \"" + pUrlStr + "\"."; } throw new OsmosisRuntimeException(message); } myActiveConnection.setConnectTimeout(TIMEOUT); encoding = myActiveConnection.getContentEncoding(); responseStream = myActiveConnection.getInputStream(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { responseStream = new GZIPInputStream(responseStream); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { responseStream = new InflaterInputStream(responseStream, new Inflater(true)); } return responseStream; }
Code Sample 2:
public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } }
Code Sample 2:
private void updateService(int nodeID, String interfaceIP, int serviceID, String notifyFlag) throws ServletException { Connection connection = null; final DBUtils d = new DBUtils(getClass()); try { connection = Vault.getDbConnection(); d.watch(connection); PreparedStatement stmt = connection.prepareStatement(UPDATE_SERVICE); d.watch(stmt); stmt.setString(1, notifyFlag); stmt.setInt(2, nodeID); stmt.setString(3, interfaceIP); stmt.setInt(4, serviceID); stmt.executeUpdate(); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException sqlEx) { throw new ServletException("Couldn't roll back update to service " + serviceID + " on interface " + interfaceIP + " notify as " + notifyFlag + " in the database.", sqlEx); } throw new ServletException("Error when updating to service " + serviceID + " on interface " + interfaceIP + " notify as " + notifyFlag + " in the database.", e); } finally { d.cleanUp(); } }
|
00
|
Code Sample 1:
public void delUser(User user) throws SQLException, IOException, ClassNotFoundException { String dbUserID; String stockSymbol; Statement stmt = con.createStatement(); try { con.setAutoCommit(false); dbUserID = user.getUserID(); if (getUser(dbUserID) != null) { ResultSet rs1 = stmt.executeQuery("SELECT userID, symbol " + "FROM UserStocks WHERE userID = '" + dbUserID + "'"); while (rs1.next()) { try { stockSymbol = rs1.getString("symbol"); delUserStocks(dbUserID, stockSymbol); } catch (SQLException ex) { throw new SQLException("Deletion of user stock holding failed: " + ex.getMessage()); } } try { stmt.executeUpdate("DELETE FROM Users WHERE " + "userID = '" + dbUserID + "'"); } catch (SQLException ex) { throw new SQLException("User deletion failed: " + ex.getMessage()); } } else throw new IOException("User not found in database - cannot delete."); try { con.commit(); } catch (SQLException ex) { throw new SQLException("Transaction commit failed: " + ex.getMessage()); } } catch (SQLException ex) { try { con.rollback(); } catch (SQLException sqx) { throw new SQLException("Transaction failed then rollback failed: " + sqx.getMessage()); } throw new SQLException("Transaction failed; was rolled back: " + ex.getMessage()); } stmt.close(); }
Code Sample 2:
protected static void writeFileToStream(FileWrapper file, String filename, ZipOutputStream zipStream) throws CausedIOException, IOException { InputStream in; try { in = file.getInputStream(); } catch (Exception e) { throw new CausedIOException("Could not obtain InputStream for " + filename, e); } try { IOUtils.copy(in, zipStream); } finally { IOUtils.closeQuietly(in); } }
|
00
|
Code Sample 1:
public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); System.out.println("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { System.out.println("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); return UTType.Item; } if (contentType != null) { System.out.println("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; System.out.println("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; }
Code Sample 2:
public int doEndTag() throws JspException { HttpSession session = pageContext.getSession(); try { IntactUserI user = (IntactUserI) session.getAttribute(Constants.USER_KEY); String urlStr = user.getSourceURL(); if (urlStr == null) { return EVAL_PAGE; } URL url = null; try { url = new URL(urlStr); } catch (MalformedURLException me) { String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("The source is malformed : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } StringBuffer httpContent = new StringBuffer(); httpContent.append("<!-- URL : " + urlStr + "-->"); String tmpLine; try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((tmpLine = reader.readLine()) != null) { httpContent.append(tmpLine); } reader.close(); } catch (IOException ioe) { user.resetSourceURL(); String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); pageContext.getOut().write("Unable to display the source at : <a href=\"" + decodedUrl + "\" target=\"_blank\">" + decodedUrl + "</a>"); return EVAL_PAGE; } pageContext.getOut().write(httpContent.toString()); } catch (Exception e) { e.printStackTrace(); throw new JspException("Error when trying to get HTTP content"); } return EVAL_PAGE; }
|
11
|
Code Sample 1:
private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } }
Code Sample 2:
private static String retrieveVersion(InputStream is) throws RepositoryException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { IOUtils.copy(is, buffer); } catch (IOException e) { throw new RepositoryException(exceptionLocalizer.format("device-repository-file-missing", DeviceRepositoryConstants.VERSION_FILENAME), e); } return buffer.toString().trim(); }
|
00
|
Code Sample 1:
private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; }
Code Sample 2:
private ProgramYek getYek(String keyFilename) { File f = new File(keyFilename); InputStream is = null; try { is = new FileInputStream(f); } catch (java.io.FileNotFoundException ee) { } catch (Exception e) { System.out.println("** Exception reading key: " + e); } if (is == null) { try { URL url = ChiselResources.getResourceByName(ProgramYek.getVidSys(), ChiselResources.LOADFROMCLASSPATH); if (url == null) { } else { is = url.openStream(); } } catch (Exception e) { System.out.println("** Exception reading key: " + e); } } ProgramYek y = null; if (is != null) { try { y = ProgramYek.read(is); } catch (Exception e) { System.out.println("** Exception reading key: " + e); } } else { File chk = new File(checkFilename); if (chk.exists()) { System.out.println("This is the evaluation version of " + appname); y = new ProgramYek(appname, "Evaluation", "", 15); ProgramYek.serialize(y, keyFilename); } } return y; }
|
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:
protected File downloadFile(String href) { Map<String, File> currentDownloadDirMap = downloadedFiles.get(downloadDir); if (currentDownloadDirMap != null) { File downloadedFile = currentDownloadDirMap.get(href); if (downloadedFile != null) { return downloadedFile; } } else { downloadedFiles.put(downloadDir, new HashMap<String, File>()); currentDownloadDirMap = downloadedFiles.get(downloadDir); } URL url; File result; try { FilesystemUtils.forceMkdirIfNotExists(downloadDir); url = generateUrl(href); result = createUniqueFile(downloadDir, href); } catch (IOException e) { LOG.warn("Failed to create file for download", e); return null; } currentDownloadDirMap.put(href, result); LOG.info("Downloading " + url); try { IOUtils.copy(url.openStream(), new FileOutputStream(result)); } catch (IOException e) { LOG.warn("Failed to download file " + url); } return result; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { String urltext = "http://www.vogella.de"; URL url = new URL(urltext); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); }
Code Sample 2:
private static List retrieveQuotes(Report report, Symbol symbol, String suffix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, suffix, startDate, endDate); EODQuoteFilter filter = new YahooEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("YAHOO_DISPLAY_URL") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
|
00
|
Code Sample 1:
protected void doRestoreOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_TABLE + " " + "(parent_organize_type,child_organize_type) " + "VALUES (?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("parent_organize_type")); ps.setString(2, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException while committing or rollback"); } }
Code Sample 2:
private String hashPassword(String password) { if (password != null && password.trim().length() > 0) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.trim().getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } } return null; }
|
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 void transform(CommandLine commandLine) throws IOException { Reader reader; if (commandLine.hasOption('i')) { reader = createFileReader(commandLine.getOptionValue('i')); } else { reader = createStandardInputReader(); } Writer writer; if (commandLine.hasOption('o')) { writer = createFileWriter(commandLine.getOptionValue('o')); } else { writer = createStandardOutputWriter(); } String mapRule = commandLine.getOptionValue("m"); try { SrxTransformer transformer = new SrxAnyTransformer(); Map<String, Object> parameterMap = new HashMap<String, Object>(); if (mapRule != null) { parameterMap.put(Srx1Transformer.MAP_RULE_NAME, mapRule); } transformer.transform(reader, writer, parameterMap); } finally { cleanupReader(reader); cleanupWriter(writer); } }
|
11
|
Code Sample 1:
public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
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); } }
|
11
|
Code Sample 1:
static void linkBlocks(File from, File to, int oldLV) throws IOException { if (!from.isDirectory()) { if (from.getName().startsWith(COPY_FILE_PREFIX)) { IOUtils.copyBytes(new FileInputStream(from), new FileOutputStream(to), 16 * 1024, true); } else { if (oldLV >= PRE_GENERATIONSTAMP_LAYOUT_VERSION) { to = new File(convertMetatadataFileName(to.getAbsolutePath())); } HardLink.createHardLink(from, to); } return; } if (!to.mkdir()) throw new IOException("Cannot create directory " + to); String[] blockNames = from.list(new java.io.FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith(BLOCK_SUBDIR_PREFIX) || name.startsWith(BLOCK_FILE_PREFIX) || name.startsWith(COPY_FILE_PREFIX); } }); for (int i = 0; i < blockNames.length; i++) linkBlocks(new File(from, blockNames[i]), new File(to, blockNames[i]), oldLV); }
Code Sample 2:
public void adjustPadding(File file, int paddingSize, long audioStart) throws FileNotFoundException, IOException { logger.finer("Need to move audio file to accomodate tag"); FileChannel fcIn = null; FileChannel fcOut; ByteBuffer paddingBuffer = ByteBuffer.wrap(new byte[paddingSize]); File paddedFile; try { paddedFile = File.createTempFile(Utils.getMinBaseFilenameAllowedForTempFile(file), ".new", file.getParentFile()); logger.finest("Created temp file:" + paddedFile.getName() + " for " + file.getName()); } catch (IOException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); if (ioe.getMessage().equals(FileSystemMessage.ACCESS_IS_DENIED.getMsg())) { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } else { logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToCreateFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_CREATE_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } } try { fcOut = new FileOutputStream(paddedFile).getChannel(); } catch (FileNotFoundException ioe) { logger.log(Level.SEVERE, ioe.getMessage(), ioe); logger.severe(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); throw new UnableToModifyFileException(ErrorMessage.GENERAL_WRITE_FAILED_TO_MODIFY_TEMPORARY_FILE_IN_FOLDER.getMsg(file.getName(), file.getParentFile().getPath())); } try { fcIn = new FileInputStream(file).getChannel(); long written = fcOut.write(paddingBuffer); logger.finer("Copying:" + (file.length() - audioStart) + "bytes"); long audiolength = file.length() - audioStart; if (audiolength <= MAXIMUM_WRITABLE_CHUNK_SIZE) { long written2 = fcIn.transferTo(audioStart, audiolength, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } else { long noOfChunks = audiolength / MAXIMUM_WRITABLE_CHUNK_SIZE; long lastChunkSize = audiolength % MAXIMUM_WRITABLE_CHUNK_SIZE; long written2 = 0; for (int i = 0; i < noOfChunks; i++) { written2 += fcIn.transferTo(audioStart + (i * MAXIMUM_WRITABLE_CHUNK_SIZE), MAXIMUM_WRITABLE_CHUNK_SIZE, fcOut); } written2 += fcIn.transferTo(audioStart + (noOfChunks * MAXIMUM_WRITABLE_CHUNK_SIZE), lastChunkSize, fcOut); logger.finer("Written padding:" + written + " Data:" + written2); if (written2 != audiolength) { throw new RuntimeException(ErrorMessage.MP3_UNABLE_TO_ADJUST_PADDING.getMsg(audiolength, written2)); } } long lastModified = file.lastModified(); if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } replaceFile(file, paddedFile); paddedFile.setLastModified(lastModified); } finally { try { if (fcIn != null) { if (fcIn.isOpen()) { fcIn.close(); } } if (fcOut != null) { if (fcOut.isOpen()) { fcOut.close(); } } } catch (Exception e) { logger.log(Level.WARNING, "Problem closing channels and locks:" + e.getMessage(), e); } } }
|
11
|
Code Sample 1:
private void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); }
Code Sample 2:
public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
|
11
|
Code Sample 1:
public void fileCopy2(File inFile, File outFile) throws Exception { try { FileChannel srcChannel = new FileInputStream(inFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { throw new Exception("Could not copy file: " + inFile.getName()); } }
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 retrieveFiles() throws DataSyncException { try { ftp.connect(hostname, port); boolean success = ftp.login(username, password); log.info("FTP Login:" + success); if (success) { System.out.println(directory); ftp.changeWorkingDirectory(directory); ftp.setFileType(FTP.ASCII_FILE_TYPE); ftp.enterLocalPassiveMode(); ftp.setRemoteVerificationEnabled(false); FTPFile[] files = ftp.listFiles(); for (FTPFile file : files) { ftp.setFileType(file.getType()); log.debug(file.getName() + "," + file.getSize()); FileOutputStream output = new FileOutputStream(localDirectory + file.getName()); try { ftp.retrieveFile(file.getName(), output); } finally { IOUtils.closeQuietly(output); } } } } catch (Exception e) { throw new DataSyncException(e); } finally { try { ftp.disconnect(); } catch (IOException e) { } } }
Code Sample 2:
public String getWeather(String cityName, String fileAddr) { try { URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather=" + cityName); InputStream inputstream = url.openStream(); String s, str; BufferedReader in = new BufferedReader(new InputStreamReader(inputstream)); StringBuffer stringbuffer = new StringBuffer(); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileAddr), "utf-8")); while ((s = in.readLine()) != null) { stringbuffer.append(s); } str = new String(stringbuffer); out.write(str); out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } File file = new File(fileAddr); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String str = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); NodeList nodelist1 = (NodeList) doc.getElementsByTagName("forecast_conditions"); NodeList nodelist2 = nodelist1.item(0).getChildNodes(); str = nodelist2.item(4).getAttributes().item(0).getNodeValue() + ",temperature:" + nodelist2.item(1).getAttributes().item(0).getNodeValue() + "℃-" + nodelist2.item(2).getAttributes().item(0).getNodeValue() + "℃"; } catch (Exception e) { e.printStackTrace(); } return str; }
|
00
|
Code Sample 1:
private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; }
Code Sample 2:
private static long writeVMDKFile(String absoluteFile, String urlString) throws Exception { URL urlCon = new URL(urlString); HttpsURLConnection conn = (HttpsURLConnection) urlCon.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setAllowUserInteraction(true); List cookies = (List) headers.get("Set-cookie"); cookieValue = (String) cookies.get(0); StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); String path = "$" + tokenizer.nextToken(); String cookie = "$Version=\"1\"; " + cookieValue + "; " + path; Map map = new HashMap(); map.put("Cookie", Collections.singletonList(cookie)); ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map); conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Expect", "100-continue"); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Length", "1024"); InputStream in = conn.getInputStream(); String localpath = localPath + "/" + absoluteFile; OutputStream out = new FileOutputStream(new File(localpath)); byte[] buf = new byte[102400]; int len = 0; long written = 0; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); written = written + len; } System.out.println(" Exported File " + absoluteFile + " : " + written); in.close(); out.close(); return written; }
|
00
|
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 static Collection<Class<? extends Page>> loadPages() throws IOException { ClassLoader ldr = Thread.currentThread().getContextClassLoader(); Collection<Class<? extends Page>> pages = new ArrayList<Class<? extends Page>>(); Enumeration<URL> e = ldr.getResources("META-INF/services/" + Page.class.getName()); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); ; try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int comment = line.indexOf('#'); if (comment >= 0) line = line.substring(0, comment); String name = line.trim(); if (name.length() == 0) continue; Class<?> clz = Class.forName(name, true, ldr); Class<? extends Page> impl = clz.asSubclass(Page.class); pages.add(impl); } } catch (Exception ex) { System.out.println(ex); } finally { try { is.close(); } catch (Exception ex) { } } } return pages; }
|
11
|
Code Sample 1:
public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } }
Code Sample 2:
public byte[] loadResource(String name) throws IOException { ClassPathResource cpr = new ClassPathResource(name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(cpr.getInputStream(), baos); return baos.toByteArray(); }
|
00
|
Code Sample 1:
public static String upload_file(String sessionid, String localFilePath, String remoteTagPath) { String jsonstring = "If you see this message, there is some problem inside the function:upload_file()"; String srcPath = localFilePath; String uploadUrl = "https://s2.cloud.cm/rpc/json/?session_id=" + sessionid + "&c=Storage&m=upload_file&tag=" + remoteTagPath; String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(srcPath); byte[] buffer = new byte[8192]; int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); jsonstring = br.readLine(); dos.close(); is.close(); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
Code Sample 2:
File exportCommunityData(Community community) throws CommunityNotActiveException, FileNotFoundException, IOException, CommunityNotFoundException { try { String communityId = community.getId(); if (!community.isActive()) { log.error("The community with id " + communityId + " is inactive"); throw new CommunityNotActiveException("The community with id " + communityId + " is inactive"); } new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH).mkdirs(); String communityName = community.getName(); String communityType = community.getType(); String communityTitle = I18NUtils.localize(community.getTitle()); File zipOutFilename; if (community.isPersonalCommunity()) { zipOutFilename = new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH + communityName + ".zip"); } else { zipOutFilename = new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH + MANUAL_EXPORTED_COMMUNITY_PREFIX + communityTitle + ".zip"); } ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipOutFilename)); File file = File.createTempFile("exported-community", null); TemporaryFilesHandler.register(null, file); FileOutputStream fos = new FileOutputStream(file); String contentPath = JCRUtil.getNodeById(communityId).getPath(); JCRUtil.currentSession().exportSystemView(contentPath, fos, false, false); fos.close(); File propertiesFile = File.createTempFile("exported-community-properties", null); TemporaryFilesHandler.register(null, propertiesFile); FileOutputStream fosProperties = new FileOutputStream(propertiesFile); fosProperties.write(("communityId=" + communityId).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("externalId=" + community.getExternalId()).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("title=" + communityTitle).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("communityType=" + communityType).getBytes()); fosProperties.write(";".getBytes()); fosProperties.write(("communityName=" + communityName).getBytes()); fosProperties.close(); FileInputStream finProperties = new FileInputStream(propertiesFile); byte[] bufferProperties = new byte[4096]; out.putNextEntry(new ZipEntry("properties")); int readProperties = 0; while ((readProperties = finProperties.read(bufferProperties)) > 0) { out.write(bufferProperties, 0, readProperties); } finProperties.close(); FileInputStream fin = new FileInputStream(file); byte[] buffer = new byte[4096]; out.putNextEntry(new ZipEntry("xmlData")); int read = 0; while ((read = fin.read(buffer)) > 0) { out.write(buffer, 0, read); } fin.close(); out.close(); community.setActive(Boolean.FALSE); communityPersister.saveCommunity(community); Collection<Community> duplicatedPersonalCommunities = communityPersister.searchCommunitiesByName(communityName); if (CommunityManager.PERSONAL_COMMUNITY_TYPE.equals(communityType)) { for (Community currentCommunity : duplicatedPersonalCommunities) { if (currentCommunity.isActive()) { currentCommunity.setActive(Boolean.FALSE); communityPersister.saveCommunity(currentCommunity); } } } return zipOutFilename; } catch (RepositoryException e) { log.error("Error getting community with id " + community.getId()); throw new GroupwareRuntimeException("Error getting community with id " + community.getId(), e.getCause()); } }
|
00
|
Code Sample 1:
public void aprovarCandidato(Atividade atividade) throws SQLException { Connection conn = null; String insert = "update Atividade_has_recurso_humano set ativo='true' " + "where atividade_idatividade=" + atividade.getIdAtividade() + " and " + " usuario_idusuario=" + atividade.getRecursoHumano().getIdUsuario(); try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } }
Code Sample 2:
private static HttpURLConnection getConnection(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Accept", "application/zip;text/html"); return conn; }
|
11
|
Code Sample 1:
public void copyServer(int id) throws Exception { File in = new File("servers" + File.separatorChar + "server_" + id); File serversDir = new File("servers" + File.separatorChar); int newNumber = serversDir.listFiles().length + 1; System.out.println("New File Number: " + newNumber); File out = new File("servers" + File.separatorChar + "server_" + newNumber); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { e.printStackTrace(); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } getServer(newNumber - 1); }
Code Sample 2:
private byte[] digestFile(File file, MessageDigest digest) throws IOException { DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest); IOUtils.copy(in, new NullOutputStream()); in.close(); return in.getMessageDigest().digest(); }
|
00
|
Code Sample 1:
public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
public void testDigest() { try { String myinfo = "我的测试信息"; MessageDigest alga = MessageDigest.getInstance("SHA-1"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); System.out.println("本信息摘要是:" + byte2hex(digesta)); MessageDigest algb = MessageDigest.getInstance("SHA-1"); algb.update(myinfo.getBytes()); if (MessageDigest.isEqual(digesta, algb.digest())) { System.out.println("信息检查正常"); } else { System.out.println("摘要不相同"); } } catch (NoSuchAlgorithmException ex) { System.out.println("非法摘要算法"); } }
|
11
|
Code Sample 1:
HTTPValuePatternComponent(final String url, final long seed) throws IOException { seedRandom = new Random(seed); random = new ThreadLocal<Random>(); final ArrayList<String> lineList = new ArrayList<String>(100); final URL parsedURL = new URL(url); final HttpURLConnection urlConnection = (HttpURLConnection) parsedURL.openConnection(); final BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); try { while (true) { final String line = reader.readLine(); if (line == null) { break; } lineList.add(line); } } finally { reader.close(); } if (lineList.isEmpty()) { throw new IOException(ERR_VALUE_PATTERN_COMPONENT_EMPTY_FILE.get()); } lines = new String[lineList.size()]; lineList.toArray(lines); }
Code Sample 2:
public static String checkPublicIP() { String ipAddress = null; try { URL url; url = new URL("http://checkip.dyndns.org/"); InputStreamReader in = new InputStreamReader(url.openStream()); BufferedReader buffer = new BufferedReader(in); String line; Pattern p = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b"); while ((line = buffer.readLine()) != null) { if (line.indexOf("IP Address:") != -1) { Matcher m = p.matcher(line); if (m.find()) { ipAddress = m.group(); break; } } } buffer.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ipAddress; }
|
00
|
Code Sample 1:
public static String upLoadImg(File pic, String uid) throws Throwable { System.out.println("开始上传======================================================="); HttpPost post = getHttpPost(getUploadUrl(uid), uid); FileBody file = new FileBody(pic, "image/jpg"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("pic1", file); post.setEntity(reqEntity); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); post.abort(); if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_MOVED_PERMANENTLY) { String newuri = response.getHeaders("location")[0].getValue(); System.out.println(newuri); return newuri.substring(newuri.indexOf("pid=") + 4, newuri.indexOf("&token=")); } return null; }
Code Sample 2:
public boolean getAuth(String content) throws IOException { String resp_remote; try { URL url = new URL(remoteurl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("md5sum=" + content); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); resp_remote = response.toString(); wd.del(); wd.setKey(resp_remote); return true; } else { return false; } } catch (MalformedURLException e) { } catch (IOException e) { } return false; }
|
00
|
Code Sample 1:
public List<String[]> getCSV(String name) { return new ResourceLoader<List<String[]>>(name) { @Override protected List<String[]> get(URL url) throws Exception { CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(url.openStream())); return reader.readAll(); } finally { IOUtils.closeQuietly(reader); } } }.get(); }
Code Sample 2:
public static byte[] hash(String plainTextValue) { MessageDigest msgDigest; try { msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(plainTextValue.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); return digest; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } }
|
11
|
Code Sample 1:
public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; }
Code Sample 2:
public static String getStringFromInputStream(InputStream in) throws Exception { CachedOutputStream bos = new CachedOutputStream(); IOUtils.copy(in, bos); in.close(); bos.close(); return bos.getOut().toString(); }
|
00
|
Code Sample 1:
public static void copyAll(URL url, StringBuilder ret) { Reader in = null; try { in = new InputStreamReader(new BufferedInputStream(url.openStream())); copyAll(in, ret); } catch (IOException e) { throw new RuntimeException(e); } finally { close(in); } }
Code Sample 2:
private void copyDirContent(String fromDir, String toDir) throws Exception { String fs = System.getProperty("file.separator"); File[] files = new File(fromDir).listFiles(); if (files == null) { throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!"); } for (int i = 0; i < files.length; i++) { File dir = new File(toDir); dir.mkdirs(); if (files[i].isFile()) { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { Logger.ERROR("Error during file copy: " + e.getMessage()); throw e; } } } }
|
11
|
Code Sample 1:
@Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } }
Code Sample 2:
public static void translateTableMetaData(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table", nsDefinition); String filename = baseDir + "table.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + ".xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + ".json", baseDir + tableName + ".xsl"); }
|
11
|
Code Sample 1:
public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
Code Sample 2:
public static void createModelZip(String filename, String tempdir, boolean overwrite) throws Exception { FileTools.checkOutput(filename, overwrite); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); }
|
11
|
Code Sample 1:
public static byte[] ComputeForBinary(String ThisString) throws Exception { byte[] Result; MessageDigest MD5Hasher; MD5Hasher = MessageDigest.getInstance("MD5"); MD5Hasher.update(ThisString.getBytes("iso-8859-1")); Result = MD5Hasher.digest(); return Result; }
Code Sample 2:
private ContactModel convertJajahContactToContact(com.funambol.jajah.www.Contact jajahContact) throws JajahException { String temp; if (log.isTraceEnabled()) { log.trace("Converting Jajah contact to Foundation contact: Name:" + jajahContact.getName() + " Email:" + jajahContact.getEmail()); } try { ContactModel contactModel; Contact contact = new Contact(); if (jajahContact.getName() != null && jajahContact.getName().equals("") == false) { if (log.isDebugEnabled()) { log.debug("NAME: " + jajahContact.getName()); } contact.getName().getFirstName().setPropertyValue(jajahContact.getName()); } if (jajahContact.getEmail() != null && jajahContact.getEmail().equals("") == false) { if (log.isDebugEnabled()) { log.debug("EMAIL1_ADDRESS: " + jajahContact.getEmail()); } Email email1 = new Email(); email1.setEmailType(SIFC.EMAIL1_ADDRESS); email1.setPropertyValue(jajahContact.getEmail()); contact.getPersonalDetail().addEmail(email1); } if (jajahContact.getMobile() != null && jajahContact.getMobile().equals("") == false) { if (log.isDebugEnabled()) { log.debug("MOBILE_TELEPHONE_NUMBER: " + jajahContact.getMobile()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.MOBILE_TELEPHONE_NUMBER); temp = jajahContact.getMobile().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getPersonalDetail().addPhone(phone); } if (jajahContact.getLandline() != null && jajahContact.getLandline().equals("") == false) { if (log.isDebugEnabled()) { log.debug("HOME_TELEPHONE_NUMBER: " + jajahContact.getLandline()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.HOME_TELEPHONE_NUMBER); temp = jajahContact.getLandline().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getPersonalDetail().addPhone(phone); } if (jajahContact.getOffice() != null && jajahContact.getOffice().equals("") == false) { if (log.isDebugEnabled()) { log.debug("BUSINESS_TELEPHONE_NUMBER: " + jajahContact.getOffice()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.BUSINESS_TELEPHONE_NUMBER); temp = jajahContact.getOffice().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getBusinessDetail().addPhone(phone); } if (log.isDebugEnabled()) { log.debug("CONTACT_ID: " + jajahContact.getId()); } contactModel = new ContactModel(String.valueOf(jajahContact.getId()), contact); ContactToSIFC convert = new ContactToSIFC(null, null); String sifObject = convert.convert(contactModel); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(sifObject.getBytes()); String md5Hash = (new BigInteger(m.digest())).toString(); contactModel.setMd5Hash(md5Hash); return contactModel; } catch (Exception e) { throw new JajahException("JAJAH - convertJajahContactToContact error: " + e.getMessage()); } }
|
11
|
Code Sample 1:
public Object mapRow(ResultSet rs, int i) throws SQLException { Blob blob = rs.getBlob(1); if (rs.wasNull()) return null; try { InputStream inputStream = blob.getBinaryStream(); if (length > 0) IOUtils.copy(inputStream, outputStream, offset, length); else IOUtils.copy(inputStream, outputStream); inputStream.close(); } catch (IOException e) { } return null; }
Code Sample 2:
public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
|
00
|
Code Sample 1:
public static List<PluginInfo> getPluginInfos(String urlRepo) throws MalformedURLException, IOException { XStream xStream = new XStream(); xStream.alias("plugin", PluginInfo.class); xStream.alias("plugins", List.class); List<PluginInfo> infos = null; URL url; BufferedReader in = null; StringBuilder buffer = new StringBuilder(); try { url = new URL(urlRepo); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { buffer.append(inputLine); } } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { Logger.getLogger(RemotePluginsManager.class.getName()).log(Level.SEVERE, null, ex); } } infos = (List<PluginInfo>) xStream.fromXML(buffer.toString()); return infos; }
Code Sample 2:
public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } }
|
11
|
Code Sample 1:
public void copyFile(File sourceFile, File destFile) throws IOException { Log.level3("Copying " + sourceFile.getPath() + " to " + destFile.getPath()); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } } if (destination != null) { destination.close(); } }
Code Sample 2:
public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); System.out.println("test"); URL url = new URL(addr); System.out.println("test2"); IOUtils.copy(url.openStream(), output); return output.toString(); }
|
00
|
Code Sample 1:
public static boolean isLinkHtmlContent(String address) { boolean isHtml = false; URLConnection conn = null; try { if (!address.startsWith("http://")) { address = "http://" + address; } URL url = new URL(address); conn = url.openConnection(); if (conn.getContentType().equals("text/html") && !conn.getHeaderField(0).contains("404")) { isHtml = true; } } catch (Exception e) { logger.error("Address attempted: " + conn.getURL()); logger.error("Error Message: " + e.getMessage()); } return isHtml; }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
00
|
Code Sample 1:
protected Class findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (this.extensionJars != null) { for (int i = 0; i < this.extensionJars.length; i++) { JarFile extensionJar = this.extensionJars[i]; JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } }
Code Sample 2:
@Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { File result = new File(parent, doc.getName()); if (doc instanceof XMLDOMDocument) { new PlainXMLDocumentWriter(result).writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { IOUtils.copy(bin.getContent().getInputStream(), new FileOutputStream(result)); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
|
11
|
Code Sample 1:
protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } }
Code Sample 2:
public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); }
|
11
|
Code Sample 1:
public boolean setCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) { boolean inserto = false; try { stm = conexion.prepareStatement("insert into clientes values( '" + IDcliente + "' , '" + nombre.toUpperCase() + "' , '" + paterno.toUpperCase() + "' , '" + materno.toUpperCase() + "' , '" + ocupacion.toUpperCase() + "' , '" + rfc + "' )"); stm.executeUpdate(); conexion.commit(); inserto = true; } catch (SQLException e) { System.out.println("error al insertar registro en la tabla clientes general " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return inserto = false; } return inserto; }
Code Sample 2:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
|
00
|
Code Sample 1:
public void deleteSynchrnServerFile(SynchrnServerVO synchrnServerVO) throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(synchrnServerVO.getServerIp())) { throw new RuntimeException("IP is needed. (" + synchrnServerVO.getServerIp() + ")"); } InetAddress host = InetAddress.getByName(synchrnServerVO.getServerIp()); ftpClient.connect(host, Integer.parseInt(synchrnServerVO.getServerPort())); ftpClient.login(synchrnServerVO.getFtpId(), synchrnServerVO.getFtpPassword()); FTPFile[] fTPFile = null; try { ftpClient.changeWorkingDirectory(synchrnServerVO.getSynchrnLc()); fTPFile = ftpClient.listFiles(synchrnServerVO.getSynchrnLc()); for (int i = 0; i < fTPFile.length; i++) { if (synchrnServerVO.getDeleteFileNm().equals(fTPFile[i].getName())) ftpClient.deleteFile(fTPFile[i].getName()); } SynchrnServer synchrnServer = new SynchrnServer(); synchrnServer.setServerId(synchrnServerVO.getServerId()); synchrnServer.setReflctAt("N"); synchrnServerDAO.processSynchrn(synchrnServer); } catch (Exception e) { System.out.println(e); } finally { ftpClient.logout(); } }
Code Sample 2:
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && wanted.containsKey(name)) { FileOutputStream out = new FileOutputStream(wanted.get(name)); IOUtils.copy(stream, out); out.close(); } else { if (downstreamParser != null) { downstreamParser.parse(stream, handler, metadata, context); } } }
|
00
|
Code Sample 1:
public static InputStreamReader getInputStreamReader(String name) throws java.io.IOException { URL url = getURL(name); if (url != null) { return new InputStreamReader(url.openStream()); } throw new FileNotFoundException("UniverseData: Resource \"" + name + "\" not found."); }
Code Sample 2:
private static void exportConfigResource(ClassLoader classLoader, String resourceName, String targetFileName) throws Exception { InputStream is = classLoader.getResourceAsStream(resourceName); FileOutputStream fos = new FileOutputStream(targetFileName, false); IOUtils.copy(is, fos); fos.close(); is.close(); }
|
11
|
Code Sample 1:
char[] DigestCalcResponse(char[] HA1, String serverNonce, String nonceCount, String clientNonce, String qop, String method, String digestUri, boolean clientResponseFlag) throws SaslException { byte[] HA2; byte[] respHash; char[] HA2Hex; try { MessageDigest md = MessageDigest.getInstance("MD5"); if (clientResponseFlag) md.update(method.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(digestUri.getBytes("UTF-8")); if ("auth-int".equals(qop)) { md.update(":".getBytes("UTF-8")); md.update("00000000000000000000000000000000".getBytes("UTF-8")); } HA2 = md.digest(); HA2Hex = convertToHex(HA2); md.update(new String(HA1).getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(serverNonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); if (qop.length() > 0) { md.update(nonceCount.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(clientNonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(qop.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); } md.update(new String(HA2Hex).getBytes("UTF-8")); respHash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new SaslException("No provider found for MD5 hash", e); } catch (UnsupportedEncodingException e) { throw new SaslException("UTF-8 encoding not supported by platform.", e); } return convertToHex(respHash); }
Code Sample 2:
public String hasheMotDePasse(String mdp) { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { } sha.reset(); sha.update(mdp.getBytes()); byte[] digest = sha.digest(); String pass = new String(Base64.encode(digest)); pass = "{SHA}" + pass; return pass; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { FileOutputStream f = new FileOutputStream("test.zip"); CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32()); ZipOutputStream zos = new ZipOutputStream(csum); BufferedOutputStream out = new BufferedOutputStream(zos); zos.setComment("A test of Java Zipping"); for (String arg : args) { print("Writing file " + arg); BufferedReader in = new BufferedReader(new FileReader(arg)); zos.putNextEntry(new ZipEntry(arg)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.flush(); } out.close(); print("Checksum: " + csum.getChecksum().getValue()); print("Reading file"); FileInputStream fi = new FileInputStream("test.zip"); CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32()); ZipInputStream in2 = new ZipInputStream(csumi); BufferedInputStream bis = new BufferedInputStream(in2); ZipEntry ze; while ((ze = in2.getNextEntry()) != null) { print("Reading file " + ze); int x; while ((x = bis.read()) != -1) { System.out.write(x); } if (args.length == 1) { print("Checksum: " + csumi.getChecksum().getValue()); } bis.close(); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public void zipUp() throws PersistenceException { ZipOutputStream out = null; try { if (!backup.exists()) backup.createNewFile(); out = new ZipOutputStream(new FileOutputStream(backup)); out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String file : backupDirectory.list()) { logger.debug("Deflating: " + file); FileInputStream in = null; try { in = new FileInputStream(new File(backupDirectory, file)); out.putNextEntry(new ZipEntry(file)); IOUtils.copy(in, out); } finally { out.closeEntry(); if (null != in) in.close(); } } FileUtils.deleteDirectory(backupDirectory); } catch (Exception ex) { logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex); throw new PersistenceException(ex); } finally { try { if (null != out) out.close(); } catch (IOException e) { logger.error("Unable to close ZIP output stream.", e); } } }
Code Sample 2:
public void serviceDocument(final TranslationRequest request, final TranslationResponse response, final Document document) throws Exception { response.addHeaders(document.getResponseHeaders()); try { IOUtils.copy(document.getInputStream(), response.getOutputStream()); response.setEndState(ResponseStateOk.getInstance()); } catch (Exception e) { response.setEndState(new ResponseStateException(e)); log.warn("Error parsing XML of " + document, e); } }
|
00
|
Code Sample 1:
@Override public boolean delete(String consulta, boolean autocommit, int transactionIsolation, Connection cx) throws SQLException { filasDelete = 0; if (!consulta.contains(";")) { this.tipoConsulta = new Scanner(consulta); if (this.tipoConsulta.hasNext()) { execConsulta = this.tipoConsulta.next(); if (execConsulta.equalsIgnoreCase("delete")) { Connection conexion = cx; Statement st = null; try { conexion.setAutoCommit(autocommit); if (transactionIsolation == 1 || transactionIsolation == 2 || transactionIsolation == 4 || transactionIsolation == 8) { conexion.setTransactionIsolation(transactionIsolation); } else { throw new IllegalArgumentException("Valor invalido sobre TransactionIsolation,\n TRANSACTION_NONE no es soportado por MySQL"); } st = (Statement) conexion.createStatement(ResultSetImpl.TYPE_SCROLL_SENSITIVE, ResultSetImpl.CONCUR_UPDATABLE); conexion.setReadOnly(false); filasDelete = st.executeUpdate(consulta.trim(), Statement.RETURN_GENERATED_KEYS); if (filasDelete > -1) { if (autocommit == false) { conexion.commit(); } return true; } else { return false; } } catch (MySQLIntegrityConstraintViolationException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLNonTransientConnectionException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } catch (MySQLDataException e) { System.out.println("Datos incorrectos"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (MySQLSyntaxErrorException e) { System.out.println("Error en la sintaxis de la Consulta en MySQL"); if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } return false; } catch (SQLException e) { if (autocommit == false) { try { conexion.rollback(); System.out.println("Se ejecuto un Rollback"); } catch (MySQLTransactionRollbackException sqlE) { System.out.println("No se ejecuto un Rollback"); sqlE.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } } e.printStackTrace(); return false; } finally { try { if (st != null) { if (!st.isClosed()) { st.close(); } } if (!conexion.isClosed()) { conexion.close(); } } catch (NullPointerException ne) { ne.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } else { throw new IllegalArgumentException("No es una instruccion Delete"); } } else { try { throw new JMySQLException("Error Grave , notifique al departamento de Soporte Tecnico \n" + email); } catch (JMySQLException ex) { Logger.getLogger(JMySQL.class.getName()).log(Level.SEVERE, null, ex); return false; } } } else { throw new IllegalArgumentException("No estan permitidas las MultiConsultas en este metodo"); } }
Code Sample 2:
public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
|
00
|
Code Sample 1:
protected void sort(int a) { int[] masiv = new int[a + 1]; Random fff = new Random(); for (int i = 0; i <= a; i++) { masiv[i] = fff.nextInt(9); } int d; for (int j = 0; j < a; j++) { for (int i = 0; i < a; i++) { if (masiv[i] < masiv[i + 1]) { } else { d = masiv[i]; masiv[i] = masiv[i + 1]; masiv[i + 1] = d; } } } while (a != 0) { System.out.println("sort: " + masiv[a]); a--; } }
Code Sample 2:
@Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnRegister) { Error.log(6002, "Bot�o cadastrar pressionado por " + login + "."); if (nameUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo nome requerido"); nameUser.setFocusable(true); return; } if (loginUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo login requerido"); loginUser.setFocusable(true); return; } String group = ""; if (groupUser.getSelectedIndex() == 0) group = "admin"; else if (groupUser.getSelectedIndex() == 1) group = "user"; else { JOptionPane.showMessageDialog(null, "Campo grupo n�o selecionado"); return; } if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int i = 1; for (i = 1; i < password1.length(); i++) { if (passwordUser1.getPassword()[i] != c) { break; } c = passwordUser1.getPassword()[i]; } if (i == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } ResultSet rs; Statement stmt; String sql; String result = ""; sql = "select login from Usuarios where login='" + loginUser.getText() + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("login"); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (result.compareTo("") != 0) { JOptionPane.showMessageDialog(null, "Login " + result + " j� existe"); loginUser.setText(""); loginUser.setFocusable(true); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } sql = "insert into Usuarios (login,password,tries_personal,tries_one_use," + "grupo,description) values " + "('" + loginUser.getText() + "','" + outputDigest + "',0,0,'" + group + "','" + nameUser.getText() + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(loginUser.getText() + ".txt", false)); for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + loginUser.getText() + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + loginUser.getText() + " foi cadastrado com sucesso."); dispose(); } if (e.getSource() == btnCancel) { Error.log(6003, "Bot�o voltar de cadastrar para o menu principal pressionado por " + login + "."); dispose(); } }
|
11
|
Code Sample 1:
public void doInsertImage() { logger.debug(">>> Inserting image..."); logger.debug(" fullFileName : #0", uploadedFileName); String fileName = uploadedFileName.substring(uploadedFileName.lastIndexOf(File.separator) + 1); logger.debug(" fileName : #0", fileName); String newFileName = System.currentTimeMillis() + "_" + fileName; String filePath = ImageResource.getResourceDirectory() + File.separator + newFileName; logger.debug(" filePath : #0", filePath); try { File file = new File(filePath); file.createNewFile(); FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(uploadedFile).getChannel(); dstChannel = new FileOutputStream(file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { closeChannel(srcChannel); closeChannel(dstChannel); } StringBuilder imageTag = new StringBuilder(); imageTag.append("<img src=\""); imageTag.append(getRequest().getContextPath()); imageTag.append("/seam/resource"); imageTag.append(ImageResource.RESOURCE_PATH); imageTag.append("/"); imageTag.append(newFileName); imageTag.append("\"/>"); if (getQuestionDefinition().getDescription() == null) { getQuestionDefinition().setDescription(""); } getQuestionDefinition().setDescription(getQuestionDefinition().getDescription() + imageTag); } catch (IOException e) { logger.error("Error during saving image file", e); } uploadedFile = null; uploadedFileName = null; logger.debug("<<< Inserting image...Ok"); }
Code Sample 2:
@Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
|
00
|
Code Sample 1:
public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
public boolean createProject(String projectName, String export) { IProgressMonitor progressMonitor = new NullProgressMonitor(); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IProject project = root.getProject(projectName); try { if (!project.exists()) { project.create(progressMonitor); } project.open(progressMonitor); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, progressMonitor); IJavaProject javaProject = JavaCore.create(project); IFolder binFolder = project.getFolder("bin"); IFolder outputFolder = project.getFolder(export); if (!binFolder.exists()) { binFolder.create(false, true, null); } javaProject.setOutputLocation(outputFolder.getFullPath(), progressMonitor); List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(); IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall(); LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall); for (LibraryLocation element : locations) { entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null)); } javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null); IFolder sourceFolder = project.getFolder("src"); if (!sourceFolder.exists()) { sourceFolder.create(false, true, null); } IPackageFragmentRoot rootfolder = javaProject.getPackageFragmentRoot(sourceFolder); IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1]; System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length); newEntries[oldEntries.length] = JavaCore.newSourceEntry(rootfolder.getPath()); javaProject.setRawClasspath(newEntries, null); IPackageFragment pack; if (rootfolder.getPackageFragment("") == null) { pack = rootfolder.createPackageFragment("", true, progressMonitor); } else { pack = rootfolder.getPackageFragment(""); } StringBuffer buffer = new StringBuffer(); buffer.append("\n"); buffer.append(source); ICompilationUnit cu = pack.createCompilationUnit("ProcessingApplet.java", buffer.toString(), false, null); return true; } catch (CoreException e) { e.printStackTrace(); } return false; }
|
00
|
Code Sample 1:
public void zip_compressFiles() throws Exception { FileInputStream in = null; File f1 = new File("C:\\WINDOWS\\regedit.exe"); File f2 = new File("C:\\WINDOWS\\win.ini"); File file = new File("C:\\" + NTUtil.class.getName() + ".zip"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.putNextEntry(new ZipEntry("regedit.exe")); in = new FileInputStream(f1); while (in.available() > 0) { out.write(in.read()); } in.close(); out.closeEntry(); out.putNextEntry(new ZipEntry("win.ini")); in = new FileInputStream(f2); while (in.available() > 0) { out.write(in.read()); } in.close(); out.closeEntry(); out.close(); }
Code Sample 2:
public void sendBinaryFile(String filename) throws IOException { Checker.checkEmpty(filename, "filename"); URL url = _getFile(filename); OutputStream out = getOutputStream(); Streams.copy(url.openStream(), out); out.close(); }
|
00
|
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:
private static String readURL(URL url) throws IOException { BufferedReader in = null; StringBuffer s = new StringBuffer(); try { in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s.append(str); } } finally { if (in != null) in.close(); } return s.toString(); }
|
00
|
Code Sample 1:
private static String getProviderName(URL url, PrintStream err) { InputStream in = null; try { in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String result = null; while (true) { String line = reader.readLine(); if (line == null) { break; } int commentPos = line.indexOf('#'); if (commentPos >= 0) { line = line.substring(0, commentPos); } line = line.trim(); int len = line.length(); if (len != 0) { if (result != null) { print(err, "checkconfig.multiproviders", url.toString()); return null; } result = line; } } if (result == null) { print(err, "checkconfig.missingprovider", url.toString()); return null; } return result; } catch (IOException e) { print(err, "configconfig.read", url.toString(), e); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
Code Sample 2:
private GenomicSequence fetch(Chromosome k, int start, int end) throws IOException { try { String chr = k.toString(); if (chr.toLowerCase().startsWith("chr")) chr = chr.substring(3); SAXParserFactory f = SAXParserFactory.newInstance(); f.setNamespaceAware(false); f.setValidating(false); SAXParser parser = f.newSAXParser(); URL url = new URL("http://genome.ucsc.edu/cgi-bin/das/" + genomeVersion + "/dna?segment=" + URLEncoder.encode(chr, "UTF-8") + ":" + (start + 1) + "," + (end)); DASHandler handler = new DASHandler(); InputStream in = url.openStream(); parser.parse(in, handler); in.close(); GenomicSequence seq = new GenomicSequence(); seq.sequence = handler.bytes.toByteArray(); seq.start = start; seq.end = end; if (seq.sequence.length != seq.length()) throw new IOException("bad bound " + seq + " " + seq.sequence.length + " " + seq.length()); return seq; } catch (IOException err) { throw err; } catch (Exception e) { throw new IOException(e); } }
|
11
|
Code Sample 1:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } }
Code Sample 2:
public void configureKerberos(boolean overwriteExistingSetup) throws Exception { OutputStream keyTabOut = null; InputStream keyTabIn = null; OutputStream krb5ConfOut = null; try { keyTabIn = loadKeyTabResource(keyTabResource); File file = new File(keyTabRepository + keyTabResource); if (!file.exists() || overwriteExistingSetup) { keyTabOut = new FileOutputStream(file, false); if (logger.isDebugEnabled()) logger.debug("Installing keytab file to : " + file.getAbsolutePath()); IOUtils.copy(keyTabIn, keyTabOut); } File krb5ConfFile = new File(System.getProperty("java.security.krb5.conf", defaultKrb5Config)); if (logger.isDebugEnabled()) logger.debug("Using Kerberos config file : " + krb5ConfFile.getAbsolutePath()); if (!krb5ConfFile.exists()) throw new Exception("Kerberos config file not found : " + krb5ConfFile.getAbsolutePath()); FileInputStream fis = new FileInputStream(krb5ConfFile); Wini krb5Conf = new Wini(KerberosConfigUtil.toIni(fis)); Ini.Section krb5Realms = krb5Conf.get("realms"); String windowsDomainSetup = krb5Realms.get(kerberosRealm); if (kerberosRealm == null || overwriteExistingSetup) { windowsDomainSetup = "{ kdc = " + keyDistributionCenter + ":88 admin_server = " + keyDistributionCenter + ":749 default_domain = " + kerberosRealm.toLowerCase() + " }"; krb5Realms.put(kerberosRealm, windowsDomainSetup); } Ini.Section krb5DomainRealms = krb5Conf.get("domain_realm"); String domainRealmSetup = krb5DomainRealms.get(kerberosRealm.toLowerCase()); if (domainRealmSetup == null || overwriteExistingSetup) { krb5DomainRealms.put(kerberosRealm.toLowerCase(), kerberosRealm); krb5DomainRealms.put("." + kerberosRealm.toLowerCase(), kerberosRealm); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); krb5Conf.store(baos); InputStream bios = new ByteArrayInputStream(baos.toByteArray()); bios = KerberosConfigUtil.toKrb5(bios); krb5ConfOut = new FileOutputStream(krb5ConfFile, false); IOUtils.copy(bios, krb5ConfOut); } catch (Exception e) { logger.error("Error while configuring Kerberos :" + e.getMessage(), e); throw e; } finally { IOUtils.closeQuietly(keyTabOut); IOUtils.closeQuietly(keyTabIn); IOUtils.closeQuietly(krb5ConfOut); } }
|
11
|
Code Sample 1:
public void testConvert() throws IOException, ConverterException { InputStreamReader reader = new InputStreamReader(new FileInputStream("test" + File.separator + "input" + File.separator + "A0851ohneex.dat"), CharsetUtil.forName("x-PICA")); FileWriter writer = new FileWriter("test" + File.separator + "output" + File.separator + "ddbInterToMarcxmlTest.out"); Converter c = context.getConverter("ddb-intern", "MARC21-xml", "x-PICA", "UTF-8"); ConversionParameters params = new ConversionParameters(); params.setSourceCharset("x-PICA"); params.setTargetCharset("UTF-8"); params.setAddCollectionHeader(true); params.setAddCollectionFooter(true); c.convert(reader, writer, params); }
Code Sample 2:
@SuppressWarnings("finally") private void compress(File src) throws IOException { if (this.switches.contains(Switch.test)) return; checkSourceFile(src); if (src.getPath().endsWith(".bz2")) { this.log.println("WARNING: skipping file because it already has .bz2 suffix:").println(src); return; } final File dst = new File(src.getPath() + ".bz2").getAbsoluteFile(); if (!checkDestFile(dst)) return; FileChannel inChannel = null; FileChannel outChannel = null; FileOutputStream fileOut = null; BZip2OutputStream bzOut = null; FileLock inLock = null; FileLock outLock = null; try { inChannel = new FileInputStream(src).getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); fileOut = new FileOutputStream(dst); outChannel = fileOut.getChannel(); bzOut = new BZip2OutputStream( new BufferedXOutputStream(fileOut, 8192), Math.min( (this.blockSize == -1) ? BZip2OutputStream.MAX_BLOCK_SIZE : this.blockSize, BZip2OutputStream.chooseBlockSize(inSize) ) ); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); final boolean showProgress = this.switches.contains(Switch.showProgress); long pos = 0; int progress = 0; if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } while (true) { final long maxStep = showProgress ? Math.max(8192, (inSize - pos) / MAX_PROGRESS) : (inSize - pos); if (maxStep <= 0) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } else { final long step = inChannel.transferTo(pos, maxStep, bzOut); if ((step == 0) && (inChannel.size() != inSize)) throw error("file " + src + " has been modified concurrently by another process"); pos += step; if (showProgress) { final double p = (double) pos / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } inLock.release(); inChannel.close(); bzOut.closeInstance(); final long outSize = outChannel.position(); outChannel.truncate(outSize); outLock.release(); fileOut.close(); if (this.verbose) { final double ratio = (inSize == 0) ? (outSize * 100) : ((double) outSize / (double) inSize); this.log.print("raw size: ").print(inSize) .print("; compressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } } catch (final IOException ex) { IO.tryClose(inChannel); IO.tryClose(bzOut); IO.tryClose(fileOut); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } }
|
00
|
Code Sample 1:
public HSSFWorkbook callRules(URL urlOfExcelDataFile, RuleSource ruleSource, String excelLogSheet) throws DroolsParserException, IOException, ClassNotFoundException { InputStream inputFromExcel = null; try { log.info("Looking for url:" + urlOfExcelDataFile); inputFromExcel = urlOfExcelDataFile.openStream(); log.info("found url:" + urlOfExcelDataFile); } catch (MalformedURLException e) { log.log(Level.SEVERE, "Malformed URL Exception Loading rules", e); throw e; } catch (IOException e) { log.log(Level.SEVERE, "IO Exception Loading rules", e); throw e; } return callRules(inputFromExcel, ruleSource, excelLogSheet); }
Code Sample 2:
public String plainStringToMD5(String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.throwing(getClass().getName(), "plainStringToMD5", e); } md.reset(); try { md.update(input.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xF0 & byteHash[i]).charAt(0)); resultString.append(Integer.toHexString(0x0F & byteHash[i])); } return (resultString.toString()); }
|
11
|
Code Sample 1:
@SuppressWarnings("null") public static void copyFile(File src, File dst) throws IOException { if (!dst.getParentFile().exists()) { dst.getParentFile().mkdirs(); } dst.createNewFile(); FileChannel srcC = null; FileChannel dstC = null; try { srcC = new FileInputStream(src).getChannel(); dstC = new FileOutputStream(dst).getChannel(); dstC.transferFrom(srcC, 0, srcC.size()); } finally { try { if (dst != null) { dstC.close(); } } catch (Exception e) { e.printStackTrace(); } try { if (src != null) { srcC.close(); } } catch (Exception e) { e.printStackTrace(); } } }
Code Sample 2:
private 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(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
protected void find(final String pckgname, final boolean recursive) { URL url; String name = pckgname; name = name.replace('.', '/'); url = ResourceLocatorTool.getClassPathResource(ExampleRunner.class, name); File directory; try { directory = new File(URLDecoder.decode(url.getFile(), "UTF-8")); } catch (final UnsupportedEncodingException e) { throw new RuntimeException(e); } if (directory.exists()) { logger.info("Searching for examples in \"" + directory.getPath() + "\"."); addAllFilesInDirectory(directory, pckgname, recursive); } else { try { logger.info("Searching for Demo classes in \"" + url + "\"."); final URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof JarURLConnection) { final JarURLConnection conn = (JarURLConnection) urlConnection; final JarFile jfile = conn.getJarFile(); final Enumeration<JarEntry> e = jfile.entries(); while (e.hasMoreElements()) { final ZipEntry entry = e.nextElement(); final Class<?> result = load(entry.getName()); if (result != null) { addClassForPackage(result); } } } } catch (final IOException e) { logger.logp(Level.SEVERE, this.getClass().toString(), "find(pckgname, recursive, classes)", "Exception", e); } catch (final Exception e) { logger.logp(Level.SEVERE, this.getClass().toString(), "find(pckgname, recursive, classes)", "Exception", e); } } }
Code Sample 2:
public static byte[] readUrl(URL url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = url.openStream(); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } }
|
00
|
Code Sample 1:
private File magiaImagen(String titulo) throws MalformedURLException, IOException { titulo = URLEncoder.encode("\"" + titulo + "\"", "UTF-8"); setMessage("Buscando portada en google..."); URL url = new URL("http://images.google.com/images?q=" + titulo + "&imgsz=small|medium|large|xlarge"); setMessage("Buscando portada en google: conectando..."); URLConnection urlCon = url.openConnection(); urlCon.setRequestProperty("User-Agent", "MyBNavigator"); BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), Charset.forName("ISO-8859-1"))); String inputLine; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } inputLine = sb.toString(); String busqueda = "<a href=/imgres?imgurl="; setMessage("Buscando portada en google: analizando..."); while (inputLine.indexOf(busqueda) != -1) { int posBusqueda = inputLine.indexOf(busqueda) + busqueda.length(); int posFinal = inputLine.indexOf("&", posBusqueda); String urlImagen = inputLine.substring(posBusqueda, posFinal); switch(confirmarImagen(urlImagen)) { case JOptionPane.YES_OPTION: setMessage("Descargando imagen..."); URL urlImg = new URL(urlImagen); String ext = urlImagen.substring(urlImagen.lastIndexOf(".") + 1); File f = File.createTempFile("Ignotus", "." + ext); BufferedImage image = ImageIO.read(urlImg); FileOutputStream outer = new FileOutputStream(f); ImageIO.write(image, ext, outer); outer.close(); in.close(); return f; case JOptionPane.CANCEL_OPTION: in.close(); return null; default: inputLine = inputLine.substring(posBusqueda + busqueda.length()); } } return null; }
Code Sample 2:
public static void getGroupsImage(String username) { try { URL url = new URL("http://www.lastfm.de/user/" + username + "/groups/"); URLConnection con = url.openConnection(); HashMap hm = new HashMap(); Parser parser = new Parser(con); NodeList images = parser.parse(new TagNameFilter("IMG")); System.out.println(images.size()); for (int i = 0; i < images.size(); i++) { Node bild = images.elementAt(i); String bilder = bild.getText(); if (bilder.contains("http://panther1.last.fm/groupava")) { String bildurl = bilder.substring(9, 81); StringTokenizer st = new StringTokenizer(bilder.substring(88), "\""); String groupname = st.nextToken(); hm.put(groupname, bildurl); } } DB_Groups.addGroupImage(hm); System.out.println("log3"); } catch (ParserException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
protected InputStream openInputStream(String filename) throws FileNotFoundException { InputStream in = null; try { URL url = new URL(filename); in = url.openConnection().getInputStream(); logger.info("Opening file " + filename); } catch (FileNotFoundException e) { logger.error("Resource file not found: " + filename); throw e; } catch (IOException e) { logger.error("Resource file can not be readed: " + filename); throw new FileNotFoundException("Resource file can not be readed: " + filename); } if (in == null) { logger.error("Resource file not found: " + filename); throw new FileNotFoundException(filename); } return in; }
Code Sample 2:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (doAuth(request, response)) { Connection conn = null; try { int UID = icsm.getIntChatSession(request).getUID(); conn = getJDBCConnection(icsm.getHeavyDatabaseConnectionPool(), request, response, HttpServletResponse.SC_SERVICE_UNAVAILABLE); if (conn == null) return; ResultSet rs = IntChatDatabaseOperations.executeQuery(conn, "SELECT id FROM ic_messagetypes WHERE templatename='" + IntChatConstants.MessageTemplates.IC_FILES + "' LIMIT 1"); if (rs.next()) { int fileTypeID = rs.getInt("id"); String recipients = request.getHeader(IntChatConstants.HEADER_FILERECIPIENTS); rs.getStatement().close(); rs = null; if (recipients != null) { HashMap<String, String> hm = Tools.parseMultiparamLine(request.getHeader("Content-Disposition")); String fileName = URLDecoder.decode(hm.get("filename"), IntChatServerDefaults.ENCODING); long fileLength = (request.getHeader("Content-Length") != null ? Long.parseLong(request.getHeader("Content-Length")) : -1); fileLength = (request.getHeader(IntChatConstants.HEADER_FILELENGTH) != null ? Long.parseLong(request.getHeader(IntChatConstants.HEADER_FILELENGTH)) : fileLength); long maxFileSize = RuntimeParameters.getIntValue(ParameterNames.MAX_FILE_SIZE) * 1048576; if (maxFileSize > 0 && fileLength > maxFileSize) { request.getInputStream().close(); response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } long now = System.currentTimeMillis(); long nextid = ic_messages_id_seq.nextval(); IntChatServletInputStream in = new IntChatServletInputStream(request); IntChatMessage icm = null; conn.setAutoCommit(false); try { PreparedStatement ps = conn.prepareStatement("INSERT INTO ic_messages (id, tid, mhead, mbody, mdate, sid) VALUES (?, ?, ?, ?, ?, ?)"); ps.setLong(1, nextid); ps.setInt(2, fileTypeID); ps.setString(3, fileName); ps.setString(4, Long.toString(fileLength)); ps.setLong(5, now); ps.setInt(6, UID); ps.executeUpdate(); ps.close(); if (!insertBLOB(conn, in, fileLength, nextid, maxFileSize)) { conn.rollback(); return; } icm = new IntChatMessage(false, fileTypeID, null, null); String[] id = recipients.split(","); int id1; for (int i = 0; i < id.length; i++) { id1 = Integer.parseInt(id[i].trim()); IntChatDatabaseOperations.executeUpdate(conn, "INSERT INTO ic_recipients (mid, rid) VALUES ('" + nextid + "', '" + id1 + "')"); icm.addTo(id1); } conn.commit(); } catch (Exception e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } if (icm != null) { icm.setID(nextid); icm.setDate(new Timestamp(now - TimeZone.getDefault().getOffset(now))); icm.setFrom(UID); icm.setHeadText(fileName); icm.setBodyText(Long.toString(fileLength)); icsm.onClientSentMessage(icm); } response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } if (rs != null) { rs.getStatement().close(); rs = null; } } catch (RetryRequest rr) { throw rr; } catch (Exception e) { Tools.makeErrorResponse(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { try { if (conn != null) icsm.getHeavyDatabaseConnectionPool().releaseConnection(conn); } catch (Exception e) { } } } }
|
11
|
Code Sample 1:
protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; }
Code Sample 2:
public static String getMD5Hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); String hexChar = ""; for (int i = 0; i < hash.length; i++) { hexChar = Integer.toHexString(0xFF & hash[i]); if (hexChar.length() < 2) { hexChar = "0" + hexChar; } hexString.append(hexChar); } return hexString.toString(); } catch (NoSuchAlgorithmException ex) { return null; } }
|
00
|
Code Sample 1:
public static <T extends Comparable<T>> void BubbleSortComparable2(T[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j].compareTo(num[j + 1]) > 0) { T temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); }
Code Sample 2:
public void doRecurringPayment(Subscription subscription) { int amount = Math.round(subscription.getTotalCostWithDiscounts() * 100.0f); String currency = subscription.getCurrency(); String aliasCC = subscription.getAliasCC(); String expm = subscription.getLastCardExpm(); String expy = subscription.getLastCardExpy(); String subscriptionId = String.valueOf(subscription.getSubscriptionId()); StringBuffer xmlSB = new StringBuffer(""); xmlSB.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); xmlSB.append("<authorizationService version=\"1\">\n"); xmlSB.append(" <body merchantId=\"" + getMerchantId() + "\" testOnly=\"" + getTestOnly() + "\">\n"); xmlSB.append(" <transaction refno=\"" + REF_NO + "\">\n"); xmlSB.append(" <request>\n"); xmlSB.append(" <amount>" + amount + "</amount>\n"); xmlSB.append(" <currency>" + currency + "</currency>\n"); xmlSB.append(" <aliasCC>" + aliasCC + "</aliasCC>\n"); xmlSB.append(" <expm>" + expm + "</expm>\n"); xmlSB.append(" <expy>" + expy + "</expy>\n"); xmlSB.append(" <subscriptionId>" + subscriptionId + "</subscriptionId>\n"); xmlSB.append(" </request>\n"); xmlSB.append(" </transaction>\n"); xmlSB.append(" </body>\n"); xmlSB.append("</authorizationService>\n"); String xmlS = xmlSB.toString(); try { java.net.URL murl = new java.net.URL(getRecurringPaymentUrl()); java.net.HttpURLConnection mcon = (java.net.HttpURLConnection) murl.openConnection(); mcon.setRequestMethod("POST"); mcon.setRequestProperty("encoding", "UTF-8"); mcon.setRequestProperty("Content-Type", "text/xml"); mcon.setRequestProperty("Content-length", String.valueOf(xmlS.length())); mcon.setDoOutput(true); java.io.OutputStream outs = mcon.getOutputStream(); outs.write(xmlS.getBytes("UTF-8")); outs.close(); java.io.BufferedReader inps = new java.io.BufferedReader(new java.io.InputStreamReader(mcon.getInputStream())); StringBuffer respSB = new StringBuffer(""); String s = null; while ((s = inps.readLine()) != null) { respSB.append(s); } inps.close(); String respXML = respSB.toString(); processReccurentPaymentResponce(respXML); } catch (Exception ex) { throw new SecurusException(ex); } }
|
11
|
Code Sample 1:
public static boolean copy(String source, String dest) { int bytes; byte array[] = new byte[BUFFER_LEN]; try { InputStream is = new FileInputStream(source); OutputStream os = new FileOutputStream(dest); while ((bytes = is.read(array, 0, BUFFER_LEN)) > 0) os.write(array, 0, bytes); is.close(); os.close(); return true; } catch (IOException e) { return false; } }
Code Sample 2:
private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
|
00
|
Code Sample 1:
public boolean connect() { if (connectStatus > -1) return (connectStatus == 1); connectStatus = 0; try { URL url = new URL(getURL()); m_connection = (HttpURLConnection) url.openConnection(); m_connection.connect(); processHeaders(); m_inputStream = m_connection.getInputStream(); } catch (MalformedURLException e) { newError("connect failed", e, true); } catch (IOException e) { newError("connect failed", e, true); } return (connectStatus == 1); }
Code Sample 2:
public void generateHtmlPage(String real_filename, String url_filename) { String str_content = ""; URL m_url = null; URLConnection m_urlcon = null; try { m_url = new URL(url_filename); m_urlcon = m_url.openConnection(); InputStream in_stream = m_urlcon.getInputStream(); byte[] bytes = new byte[1]; Vector v_bytes = new Vector(); while (in_stream.read(bytes) != -1) { v_bytes.add(bytes); bytes = new byte[1]; } byte[] all_bytes = new byte[v_bytes.size()]; for (int i = 0; i < v_bytes.size(); i++) all_bytes[i] = ((byte[]) v_bytes.get(i))[0]; str_content = new String(all_bytes, "GBK"); } catch (Exception urle) { } try { oaFileOperation file_control = new oaFileOperation(); file_control.writeFile(str_content, real_filename, true); String strPath = url_filename.substring(0, url_filename.lastIndexOf("/") + 1); String strUrlFileName = url_filename.substring(url_filename.lastIndexOf("/") + 1); if (strUrlFileName.indexOf(".jsp") > 0) { strUrlFileName = strUrlFileName.substring(0, strUrlFileName.indexOf(".jsp")) + "_1.jsp"; m_url = new URL(strPath + strUrlFileName); m_url.openConnection(); } intWriteFileCount++; intWriteFileCount = (intWriteFileCount > 100000) ? 0 : intWriteFileCount; } catch (Exception e) { } m_urlcon = null; }
|
11
|
Code Sample 1:
public static void main(String[] args) { File directory = new File(args[0]); File[] files = directory.listFiles(); try { PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(args[1]))); for (int i = 0; i < files.length; i++) { BufferedReader reader = new BufferedReader(new FileReader(files[i])); while (reader.ready()) writer.println(reader.readLine()); reader.close(); } writer.flush(); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void copyResourceFileTo(String destFileName, String resourceFileName) { if (destFileName == null || resourceFileName == null) throw new IllegalArgumentException("Argument cannot be null."); try { FileInputStream in = null; FileOutputStream out = null; URL url = HelperMethods.class.getResource(resourceFileName); if (url == null) { System.out.println("URL " + resourceFileName + " cannot be created."); return; } String fileName = url.getFile(); fileName = fileName.replaceAll("%20", " "); File resourceFile = new File(fileName); if (!resourceFile.isFile()) { System.out.println(fileName + " cannot be opened."); return; } in = new FileInputStream(resourceFile); out = new FileOutputStream(new File(destFileName)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } }
|
00
|
Code Sample 1:
@Override public CelShadingModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); CelShadingModel model = loadModel(url.openStream(), skin); if (baseURLWasNull) { popBaseURL(); } return (model); }
Code Sample 2:
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
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 Graph<N, E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } }
|
00
|
Code Sample 1:
public static IProject createEMFProject(IPath javaSource, URI projectLocationURI, List<IProject> referencedProjects, Monitor monitor, int style, List<?> pluginVariables) { IProgressMonitor progressMonitor = BasicMonitor.toIProgressMonitor(monitor); String projectName = javaSource.segment(0); IProject project = null; try { List<IClasspathEntry> classpathEntries = new UniqueEList<IClasspathEntry>(); progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenEcorePlugin.INSTANCE.getString("_UI_CreatingEMFProject_message", new Object[] { projectName, projectLocationURI != null ? projectLocationURI.toString() : projectName })); IWorkspace workspace = ResourcesPlugin.getWorkspace(); project = workspace.getRoot().getProject(projectName); if (!project.exists()) { URI location = projectLocationURI; if (location == null) { location = URI.createFileURI(workspace.getRoot().getLocation().append(projectName).toOSString()); } location = location.appendSegment(".project"); File projectFile = new File(location.toString()); if (projectFile.exists()) { projectFile.renameTo(new File(location.toString() + ".old")); } } IJavaProject javaProject = JavaCore.create(project); IProjectDescription projectDescription = null; if (!project.exists()) { projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectName); if (projectLocationURI != null) { projectDescription.setLocationURI(new java.net.URI(projectLocationURI.toString())); } project.create(projectDescription, new SubProgressMonitor(progressMonitor, 1)); project.open(new SubProgressMonitor(progressMonitor, 1)); } else { projectDescription = project.getDescription(); project.open(new SubProgressMonitor(progressMonitor, 1)); if (project.hasNature(JavaCore.NATURE_ID)) { classpathEntries.addAll(Arrays.asList(javaProject.getRawClasspath())); } } boolean isInitiallyEmpty = classpathEntries.isEmpty(); { if (referencedProjects.size() != 0 && (style & (EMF_PLUGIN_PROJECT_STYLE | EMF_EMPTY_PROJECT_STYLE)) == 0) { projectDescription.setReferencedProjects(referencedProjects.toArray(new IProject[referencedProjects.size()])); for (IProject referencedProject : referencedProjects) { IClasspathEntry referencedProjectClasspathEntry = JavaCore.newProjectEntry(referencedProject.getFullPath()); classpathEntries.add(referencedProjectClasspathEntry); } } String[] natureIds = projectDescription.getNatureIds(); if (natureIds == null) { natureIds = new String[] { JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature" }; } else { if (!project.hasNature(JavaCore.NATURE_ID)) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = JavaCore.NATURE_ID; } if (!project.hasNature("org.eclipse.pde.PluginNature")) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = "org.eclipse.pde.PluginNature"; } } projectDescription.setNatureIds(natureIds); ICommand[] builders = projectDescription.getBuildSpec(); if (builders == null) { builders = new ICommand[0]; } boolean hasManifestBuilder = false; boolean hasSchemaBuilder = false; for (int i = 0; i < builders.length; ++i) { if ("org.eclipse.pde.ManifestBuilder".equals(builders[i].getBuilderName())) { hasManifestBuilder = true; } if ("org.eclipse.pde.SchemaBuilder".equals(builders[i].getBuilderName())) { hasSchemaBuilder = true; } } if (!hasManifestBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.ManifestBuilder"); } if (!hasSchemaBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.SchemaBuilder"); } projectDescription.setBuildSpec(builders); project.setDescription(projectDescription, new SubProgressMonitor(progressMonitor, 1)); IContainer sourceContainer = project; if (javaSource.segmentCount() > 1) { IPath sourceContainerPath = javaSource.removeFirstSegments(1).makeAbsolute(); sourceContainer = project.getFolder(sourceContainerPath); if (!sourceContainer.exists()) { for (int i = sourceContainerPath.segmentCount() - 1; i >= 0; i--) { sourceContainer = project.getFolder(sourceContainerPath.removeLastSegments(i)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(progressMonitor, 1)); } } } IClasspathEntry sourceClasspathEntry = JavaCore.newSourceEntry(javaSource); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getPath().isPrefixOf(javaSource)) { i.remove(); } } classpathEntries.add(0, sourceClasspathEntry); } if (isInitiallyEmpty) { IClasspathEntry jreClasspathEntry = JavaCore.newVariableEntry(new Path(JavaRuntime.JRELIB_VARIABLE), new Path(JavaRuntime.JRESRC_VARIABLE), new Path(JavaRuntime.JRESRCROOT_VARIABLE)); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getPath().isPrefixOf(jreClasspathEntry.getPath())) { i.remove(); } } String jreContainer = JavaRuntime.JRE_CONTAINER; String complianceLevel = CodeGenUtil.EclipseUtil.getJavaComplianceLevel(project); if ("1.5".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"; } else if ("1.6".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"; } classpathEntries.add(JavaCore.newContainerEntry(new Path(jreContainer))); } if ((style & EMF_EMPTY_PROJECT_STYLE) == 0) { if ((style & EMF_PLUGIN_PROJECT_STYLE) != 0) { classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); for (Iterator<IClasspathEntry> i = classpathEntries.iterator(); i.hasNext(); ) { IClasspathEntry classpathEntry = i.next(); if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE && !JavaRuntime.JRELIB_VARIABLE.equals(classpathEntry.getPath().toString()) || classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { i.remove(); } } } else { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_CORE_RUNTIME", "org.eclipse.core.runtime"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_CORE_RESOURCES", "org.eclipse.core.resources"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_COMMON", "org.eclipse.emf.common"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE", "org.eclipse.emf.ecore"); if ((style & EMF_XML_PROJECT_STYLE) != 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE_XMI", "org.eclipse.emf.ecore.xmi"); } if ((style & EMF_MODEL_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_EDIT", "org.eclipse.emf.edit"); if ((style & EMF_EDIT_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_SWT", "org.eclipse.swt"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_JFACE", "org.eclipse.jface"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_VIEWS", "org.eclipse.ui.views"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_EDITORS", "org.eclipse.ui.editors"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_IDE", "org.eclipse.ui.ide"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "ECLIPSE_UI_WORKBENCH", "org.eclipse.ui.workbench"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_COMMON_UI", "org.eclipse.emf.common.ui"); CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_EDIT_UI", "org.eclipse.emf.edit.ui"); if ((style & EMF_XML_PROJECT_STYLE) == 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "EMF_ECORE_XMI", "org.eclipse.emf.ecore.xmi"); } } } if ((style & EMF_TESTS_PROJECT_STYLE) != 0) { CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, "JUNIT", "org.junit"); } if (pluginVariables != null) { for (Iterator<?> i = pluginVariables.iterator(); i.hasNext(); ) { Object variable = i.next(); if (variable instanceof IClasspathEntry) { classpathEntries.add((IClasspathEntry) variable); } else if (variable instanceof String) { String pluginVariable = (String) variable; String name; String id; int index = pluginVariable.indexOf("="); if (index == -1) { name = pluginVariable.replace('.', '_').toUpperCase(); id = pluginVariable; } else { name = pluginVariable.substring(0, index); id = pluginVariable.substring(index + 1); } CodeGenUtil.EclipseUtil.addClasspathEntries(classpathEntries, name, id); } } } } } javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), new SubProgressMonitor(progressMonitor, 1)); } if (isInitiallyEmpty) { javaProject.setOutputLocation(new Path("/" + javaSource.segment(0) + "/bin"), new SubProgressMonitor(progressMonitor, 1)); } } catch (Exception exception) { exception.printStackTrace(); CodeGenEcorePlugin.INSTANCE.log(exception); } finally { progressMonitor.done(); } return project; }
Code Sample 2:
protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); }
|
00
|
Code Sample 1:
public String postData(String url, List<NameValuePair> nameValuePairs) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); StringBuilder sb = new StringBuilder(); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.i(TAG, "HEADER: " + headers[i].getName() + " - " + headers[i].getValue()); } InputStream is = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = ""; while ((line = reader.readLine()) != null) { System.out.println("Parsing line... " + line); sb.append(line); if (line.contains("<html xmlns:fn")) { String gtinCode = line.substring(line.indexOf("GLN:") + 165, line.indexOf("GLN:") + 176); Log.i(TAG, "OUT: " + gtinCode); break; } } Log.i(TAG, "Post Communication OK"); } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException ", e); } catch (IOException e) { Log.e(TAG, "HTTP Not Available", e); } return sb.toString(); }
Code Sample 2:
void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.