label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void copyFile(File in, File out) throws Exception { Permissions before = getFilePermissons(in); FileChannel inFile = new FileInputStream(in).getChannel(); FileChannel outFile = new FileOutputStream(out).getChannel(); inFile.transferTo(0, inFile.size(), outFile); inFile.close(); outFile.close(); setFilePermissions(out, before); }
|
00
|
Code Sample 1:
public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); }
Code Sample 2:
@Override public final boolean delete() throws RecordException { if (frozen) { throw new RecordException("The object is frozen."); } Connection conn = ConnectionManager.getConnection(); LoggableStatement pStat = null; Class<? extends Record> actualClass = this.getClass(); StatementBuilder builder = null; try { builder = new StatementBuilder("delete from " + TableNameResolver.getTableName(actualClass) + " where id = :id"); Field f = FieldHandler.findField(this.getClass(), "id"); builder.set("id", FieldHandler.getValue(f, this)); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); return i == 1; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { throw new RecordException("Error executing rollback"); } throw new RecordException(e); } finally { try { if (pStat != null) { pStat.close(); } conn.commit(); conn.close(); } catch (SQLException e) { throw new RecordException("Error closing connection"); } } }
|
00
|
Code Sample 1:
protected static boolean checkVersion(String address) { Scanner scanner = null; try { URL url = new URL(address); InputStream iS = url.openStream(); scanner = new Scanner(iS); if (scanner == null && DEBUG) System.out.println("SCANNER NULL"); String firstLine = scanner.nextLine(); double latestVersion = Double.valueOf(firstLine.trim()); double thisVersion = JCards.VERSION; if (thisVersion >= latestVersion) { JCards.latestVersion = true; } else { displaySimpleAlert(null, JCards.VERSION_PREFIX + latestVersion + " is available online!\n" + "Look under the file menu for a link to the download site."); } } catch (Exception e) { if (VERBOSE || DEBUG) { System.out.println("Can't decide latest version"); e.printStackTrace(); } return false; } return true; }
Code Sample 2:
public boolean isPasswordCorrect(String attempt) { try { MessageDigest digest = MessageDigest.getInstance(attempt); digest.update(salt); digest.update(attempt.getBytes("UTF-8")); byte[] attemptHash = digest.digest(); return attemptHash.equals(hash); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void copyResource(final String resourceName, final File file) throws IOException { assertTrue(resourceName.startsWith("/")); InputStream in = null; boolean suppressExceptionOnClose = true; try { in = this.getClass().getResourceAsStream(resourceName); assertNotNull("Resource '" + resourceName + "' not found.", in); OutputStream out = null; try { out = new FileOutputStream(file); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
|
11
|
Code Sample 1:
public static String encode(String username, String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(username.getBytes()); digest.update(password.getBytes()); return new String(digest.digest()); } catch (Exception e) { Log.error("Error encrypting credentials", e); } return null; }
Code Sample 2:
private String generaHashMD5(String plainText) throws Exception { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes(FirmaUtil.CHARSET)); byte[] digest = mdAlgorithm.digest(); return toHex(digest); }
|
11
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } }
Code Sample 2:
public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
|
00
|
Code Sample 1:
@Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } return status > 199 && status < 400; }
Code Sample 2:
public static void copyFiles(String strPath, String trgPath) { File src = new File(strPath); File trg = new File(trgPath); if (src.isDirectory()) { if (trg.exists() != true) trg.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String strPath_1 = src.getAbsolutePath() + SEPARATOR + list[i]; String trgPath_1 = trg.getAbsolutePath() + SEPARATOR + list[i]; copyFiles(strPath_1, trgPath_1); } } else { try { FileChannel srcChannel = new FileInputStream(strPath).getChannel(); FileChannel dstChannel = new FileOutputStream(trgPath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (FileNotFoundException e) { System.out.println("[Error] File not found: " + e.getMessage()); } catch (IOException e) { System.out.println("[Error] " + e.getMessage()); } } }
|
00
|
Code Sample 1:
byte[] loadUrlByteArray(String szName, int offset, int size) { byte[] baBuffer = new byte[size]; try { URL url = new URL(waba.applet.Applet.currentApplet.getCodeBase(), szName); try { InputStream file = url.openStream(); if (size == 0) { int n = file.available(); baBuffer = new byte[n - offset]; } DataInputStream dataFile = new DataInputStream(file); try { dataFile.skip(offset); dataFile.readFully(baBuffer); } catch (EOFException e) { System.err.print(e.getMessage()); } file.close(); } catch (IOException e) { System.err.print(e.getMessage()); } } catch (MalformedURLException e) { System.err.print(e.getMessage()); } return baBuffer; }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(sid); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { } }
|
11
|
Code Sample 1:
public void encryptPassword() { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.out.print(e); } try { digest.update(passwordIn.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.out.println("cannot find char set for getBytes"); } byte digestBytes[] = digest.digest(); passwordHash = (new BASE64Encoder()).encode(digestBytes); }
Code Sample 2:
public static String hash(String password) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(password.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(Hex.encodeHex(rawHash)); } catch (Exception e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
@Test public void testWriteModel() { Model model = new Model(); model.setName("MY_MODEL1"); Stereotype st1 = new Stereotype(); st1.setName("Pirulito1"); PackageObject p1 = new PackageObject("p1"); ClassType type1 = new ClassType("Class1"); type1.setStereotype(st1); type1.addMethod(new Method("doSomething")); p1.add(type1); ClassType type2 = new ClassType("Class2"); Method m2 = new Method("doSomethingElse"); m2.setType(type1); type2.addMethod(m2); p1.add(type2); Generalization g = new Generalization(); g.setSource(type1); g.setTarget(type1); p1.add(g); model.add(p1); ModelWriter writer = new ModelWriter(); try { File modelFile = new File("target", "test.model"); writer.write(model, modelFile); File xmlFile = new File("target", "test.xml"); xmlFile.createNewFile(); IOUtils.copy(new GZIPInputStream(new FileInputStream(modelFile)), new FileOutputStream(xmlFile)); } catch (IOException e) { log.error(e.getMessage(), e); Assert.fail(e.getMessage()); } }
Code Sample 2:
private void copyFile(String file) { FileChannel inChannel = null; FileChannel outChannel = null; try { Date dt = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss "); File in = new File(file); String[] name = file.split("\\\\"); File out = new File(".\\xml_archiv\\" + df.format(dt) + name[name.length - 1]); inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { System.err.println("Copy error!"); System.err.println("Error: " + e.getMessage()); } finally { if (inChannel != null) { try { inChannel.close(); } catch (IOException ex) { Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex); } } if (outChannel != null) { try { outChannel.close(); } catch (IOException ex) { Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex); } } } }
|
11
|
Code Sample 1:
public static void zipFile(String file, String entry) throws IOException { FileInputStream in = new FileInputStream(file); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file + ".zip")); out.putNextEntry(new ZipEntry(entry)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.closeEntry(); out.close(); File fin = new File(file); fin.delete(); }
Code Sample 2:
protected void zipDirectory(File dir, File zipfile) throws IOException, IllegalArgumentException { if (!dir.isDirectory()) throw new IllegalArgumentException("Compress: not a directory: " + dir); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytes_read; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); } out.close(); }
|
00
|
Code Sample 1:
private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); System.exit(1); } return null; }
Code Sample 2:
private Document getDocument(URL url) throws SAXException, IOException { InputStream is; try { is = url.openStream(); } catch (IOException io) { System.out.println("parameter error : The specified reading data is mistaken."); System.out.println(" Request URL is " + sourceUri); throw new IOException("\t" + io.toString()); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.out.println("error : The error of DocumentBuilder instance generation"); throw new RuntimeException(pce.toString()); } Document doc; try { doc = builder.parse(is); } catch (Exception e) { System.out.println("error : parse of reading data went wrong."); System.out.println(" Request URL is " + sourceUri); throw new RuntimeException(e.toString()); } return doc; }
|
11
|
Code Sample 1:
private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: destination file is unwriteable: " + toFileName); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: existing file was not overwritten."); } else { 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) { ; } } }
Code Sample 2:
private void copia(FileInputStream input, FileOutputStream output) throws ErrorException { if (input == null || output == null) { throw new ErrorException("Param null"); } FileChannel inChannel = input.getChannel(); FileChannel outChannel = output.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (IOException e) { throw new ErrorException("Casino nella copia del file"); } }
|
11
|
Code Sample 1:
private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
Code Sample 2:
public static void copy(File srcDir, File dstDir) throws IOException { if (srcDir.isDirectory()) { if (!dstDir.exists()) dstDir.mkdir(); String[] children = srcDir.list(); for (int i = 0; i < children.length; i++) copy(new File(srcDir, children[i]), new File(dstDir, children[i])); } else { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcDir); out = new FileOutputStream(dstDir); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } } }
|
00
|
Code Sample 1:
private void scanURL(String packagePath, Collection<String> componentClassNames, URL url) throws IOException { URLConnection connection = url.openConnection(); JarFile jarFile; if (connection instanceof JarURLConnection) { jarFile = ((JarURLConnection) connection).getJarFile(); } else { jarFile = getAlternativeJarFile(url); } if (jarFile != null) { scanJarFile(packagePath, componentClassNames, jarFile); } else if (supportsDirStream(url)) { Stack<Queued> queue = new Stack<Queued>(); queue.push(new Queued(url, packagePath)); while (!queue.isEmpty()) { Queued queued = queue.pop(); scanDirStream(queued.packagePath, queued.packageURL, componentClassNames, queue); } } else { String packageName = packagePath.replace("/", "."); if (packageName.endsWith(".")) { packageName = packageName.substring(0, packageName.length() - 1); } scanDir(packageName, new File(url.getFile()), componentClassNames); } }
Code Sample 2:
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."); }
|
00
|
Code Sample 1:
private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
00
|
Code Sample 1:
public XMLResourceBundle() throws MissingResourceException { String systemId = getShortName() + ".xml"; URL url; if ((url = getClass().getResource(systemId)) != null) { InputStream is = null; try { is = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); xmlReader.setContentHandler(new MessageContentHandler()); xmlReader.parse(new InputSource(is)); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } catch (SAXException se) { System.err.println(se.getMessage()); se.printStackTrace(); } catch (ParserConfigurationException pce) { System.err.println(pce.getMessage()); pce.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } } } else { throw new MissingResourceException("Resource file '" + systemId + "' could not be found.", systemId, null); } }
Code Sample 2:
public void delete(Connection conn, boolean commit) throws SQLException { PreparedStatement stmt = null; if (isNew()) { String errorMessage = "Unable to delete non-persistent DAO '" + getClass().getName() + "'"; if (log.isErrorEnabled()) { log.error(errorMessage); } throw new SQLException(errorMessage); } try { stmt = conn.prepareStatement(getDeleteSql()); stmt.setObject(1, getPrimaryKey()); int rowCount = stmt.executeUpdate(); if (rowCount != 1) { if (commit) { conn.rollback(); } String errorMessage = "Invalid number of rows changed!"; if (log.isErrorEnabled()) { log.error(errorMessage); } throw new SQLException(errorMessage); } else if (commit) { conn.commit(); } } finally { OvJdbcUtils.closeStatement(stmt); } }
|
00
|
Code Sample 1:
public void addUser(String strUserName, String strPass) { String datetime = Function.getSysTime().toString(); String time = datetime.substring(0, 4) + datetime.substring(5, 7) + datetime.substring(8, 10) + datetime.substring(11, 13) + datetime.substring(14, 16) + datetime.substring(17, 19) + datetime.substring(20, 22) + "0"; Connection con = null; PreparedStatement pstmt = null; try { con = DbForumFactory.getConnection(); con.setAutoCommit(false); int userID = DbSequenceManager.nextID(DbSequenceManager.USER); pstmt = con.prepareStatement(INSERT_USER); pstmt.setString(1, strUserName); pstmt.setString(2, SecurityUtil.md5ByHex(strPass)); pstmt.setString(3, time); pstmt.setString(4, ""); pstmt.setString(5, ""); pstmt.setString(6, ""); pstmt.setString(7, ""); pstmt.setInt(8, userID); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = con.prepareStatement(INSERT_USERPROPS); pstmt.setString(1, ""); pstmt.setString(2, ""); pstmt.setString(3, ""); pstmt.setInt(4, 0); pstmt.setString(5, ""); pstmt.setInt(6, 0); pstmt.setInt(7, 0); pstmt.setString(8, ""); pstmt.setString(9, ""); pstmt.setString(10, ""); pstmt.setInt(11, 0); pstmt.setInt(12, 0); pstmt.setInt(13, 0); pstmt.setInt(14, 0); pstmt.setString(15, ""); pstmt.setString(16, ""); pstmt.setString(17, ""); pstmt.setString(18, ""); pstmt.setString(19, ""); pstmt.setString(20, ""); pstmt.setString(21, ""); pstmt.setString(22, ""); pstmt.setString(23, ""); pstmt.setInt(24, 0); pstmt.setInt(25, 0); pstmt.setInt(26, userID); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = con.prepareStatement(INSTER_USERGROUP); pstmt.setInt(1, 4); pstmt.setInt(2, userID); pstmt.setInt(3, 0); pstmt.executeUpdate(); con.commit(); } catch (Exception e) { try { con.rollback(); } catch (SQLException e1) { } log.error("insert user Error: " + e.toString()); } finally { DbForumFactory.closeDB(null, pstmt, null, con); } }
Code Sample 2:
public void logout(String cookieString) throws NetworkException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_LOGOUT); if (cookieString != null && cookieString.length() != 0) get.setHeader("Cookie", cookieString); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
|
00
|
Code Sample 1:
private void storeFieldMap(Content c, Connection conn) throws SQLException { SQLDialect dialect = getDatabase().getSQLDialect(); if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(false); } try { Object thisKey = c.getPrimaryKey(); deleteFieldContent(thisKey, conn); PreparedStatement ps = null; StructureItem nextItem; Map fieldMap = c.getFieldMap(); String type; Object value, siKey; for (Iterator i = c.getStructure().getStructureItems().iterator(); i.hasNext(); ) { nextItem = (StructureItem) i.next(); type = nextItem.getDataType().toUpperCase(); siKey = nextItem.getPrimaryKey(); value = fieldMap.get(nextItem.getName()); if (type.equals(StructureItem.DATE)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_DATE_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); dialect.setDate(ps, 3, (java.util.Date) value); ps.executeUpdate(); } else if (type.equals(StructureItem.INT) || type.equals(StructureItem.FLOAT) || type.equals(StructureItem.VARCHAR)) { ps = conn.prepareStatement(sqlConstants.get("INSERT_" + type + "_FIELD")); ps.setObject(1, thisKey); ps.setObject(2, siKey); if (value != null) { ps.setObject(3, value); } else { int sqlType = Types.INTEGER; if (type.equals(StructureItem.FLOAT)) { sqlType = Types.FLOAT; } else if (type.equals(StructureItem.VARCHAR)) { sqlType = Types.VARCHAR; } ps.setNull(3, sqlType); } ps.executeUpdate(); } else if (type.equals(StructureItem.TEXT)) { setTextField(c, siKey, (String) value, conn); } if (ps != null) { ps.close(); ps = null; } } if (TRANSACTIONS_ENABLED) { conn.commit(); } } catch (SQLException e) { if (TRANSACTIONS_ENABLED) { conn.rollback(); } throw e; } finally { if (TRANSACTIONS_ENABLED) { conn.setAutoCommit(true); } } }
Code Sample 2:
public static String getFurigana(String sentence) throws Exception { Log.d("--VOA--", "getFurigana START"); sbFurigana = new StringBuffer(); String urlStr = getYahooApiURL(); urlStr = addSentence(urlStr, sentence); URL url = new URL(urlStr); URLConnection uc = url.openConnection(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Log.d("--VOA--", uc.getURL().toString()); InputStream is = uc.getInputStream(); doc = db.parse(is); walkThrough(); Log.d("--VOA--", "getFurigana END"); return sbFurigana.toString(); }
|
11
|
Code Sample 1:
private static void copierScriptChargement(File webInfDir, String initialDataChoice) { File chargementInitialDir = new File(webInfDir, "chargementInitial"); File fichierChargement = new File(chargementInitialDir, "ScriptChargementInitial.sql"); File fichierChargementAll = new File(chargementInitialDir, "ScriptChargementInitial-All.sql"); File fichierChargementTypesDocument = new File(chargementInitialDir, "ScriptChargementInitial-TypesDocument.sql"); File fichierChargementVide = new File(chargementInitialDir, "ScriptChargementInitial-Vide.sql"); if (fichierChargement.exists()) { fichierChargement.delete(); } File fichierUtilise = null; if ("all".equals(initialDataChoice)) { fichierUtilise = fichierChargementAll; } else if ("typesDocument".equals(initialDataChoice)) { fichierUtilise = fichierChargementTypesDocument; } else if ("empty".equals(initialDataChoice)) { fichierUtilise = fichierChargementVide; } if (fichierUtilise != null && fichierUtilise.exists()) { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(fichierUtilise).getChannel(); destination = new FileOutputStream(fichierChargement).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (source != null) { try { source.close(); } catch (Exception e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (Exception e) { e.printStackTrace(); } } } } }
Code Sample 2:
public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
|
11
|
Code Sample 1:
public static void loadPages() throws IOException { ClassLoader ldr = Thread.currentThread().getContextClassLoader(); Collection<Class<? extends BasePage>> pages = new ArrayList<Class<? extends BasePage>>(); 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); if (BasePage.class.isAssignableFrom(clz)) { pages.add(clz.asSubclass(BasePage.class)); } } } catch (Exception ex) { ex.printStackTrace(); } finally { try { is.close(); } catch (Exception ex) { } } } pageTypes = pages; }
Code Sample 2:
protected BufferedReader getDataReader() { BufferedReader in = null; PrintWriter out = null; try { String line; URL url = new URL(this.catalog.getCatalogURL()); Debug.output("Catalog URL:" + url.toString()); in = new BufferedReader(new InputStreamReader(url.openStream())); File dir = (File) SessionHandler.getServletContext().getAttribute("javax.servlet.context.tempdir"); File temp = new File(dir, TEMP); Debug.output("Temp file:" + temp.toString()); out = new PrintWriter(new BufferedWriter(new FileWriter(temp))); while ((line = in.readLine()) != null) { out.println(line); } Debug.output("Temp file size:" + temp.length()); return new BufferedReader(new FileReader(temp)); } catch (IOException e) { throw new SeismoException(e); } finally { Util.close(in); Util.close(out); } }
|
00
|
Code Sample 1:
public static void initialize(Monitor monitor, final JETEmitter jetEmitter) throws JETException { IProgressMonitor progressMonitor = BasicMonitor.toIProgressMonitor(monitor); progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_GeneratingJETEmitterFor_message", new Object[] { jetEmitter.templateURI })); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { final JETCompiler jetCompiler = jetEmitter.templateURIPath == null ? new MyBaseJETCompiler(jetEmitter.templateURI, jetEmitter.encoding, jetEmitter.classLoader) : new MyBaseJETCompiler(jetEmitter.templateURIPath, jetEmitter.templateURI, jetEmitter.encoding, jetEmitter.classLoader); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETParsing_message", new Object[] { jetCompiler.getResolvedTemplateURI() })); jetCompiler.parse(); progressMonitor.worked(1); String packageName = jetCompiler.getSkeleton().getPackageName(); if (jetEmitter.templateURIPath != null) { URI templateURI = URI.createURI(jetEmitter.templateURIPath[0]); URLClassLoader theClassLoader = null; if (templateURI.isPlatformResource()) { IProject project = workspace.getRoot().getProject(templateURI.segment(1)); if (JETNature.getRuntime(project) != null) { List<URL> urls = new ArrayList<URL>(); IJavaProject javaProject = JavaCore.create(project); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); for (IClasspathEntry classpathEntry : javaProject.getResolvedClasspath(true)) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = classpathEntry.getPath(); IProject otherProject = workspace.getRoot().getProject(projectPath.segment(0)); IJavaProject otherJavaProject = JavaCore.create(otherProject); urls.add(new File(otherProject.getLocation() + "/" + otherJavaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); } } theClassLoader = new URLClassLoader(urls.toArray(new URL[0])) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return super.loadClass(className); } catch (ClassNotFoundException classNotFoundException) { return jetEmitter.classLoader.loadClass(className); } } }; } } else if (templateURI.isPlatformPlugin()) { final Bundle bundle = Platform.getBundle(templateURI.segment(1)); if (bundle != null) { theClassLoader = new URLClassLoader(new URL[0], jetEmitter.classLoader) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return bundle.loadClass(className); } catch (ClassNotFoundException classNotFoundException) { return super.loadClass(className); } } }; } } if (theClassLoader != null) { String className = (packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName(); if (className.endsWith("_")) { className = className.substring(0, className.length() - 1); } try { Class<?> theClass = theClassLoader.loadClass(className); Class<?> theOtherClass = null; try { theOtherClass = jetEmitter.classLoader.loadClass(className); } catch (ClassNotFoundException exception) { } if (theClass != theOtherClass) { String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } return; } } catch (ClassNotFoundException exception) { } } } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jetCompiler.generate(outputStream); final InputStream contents = new ByteArrayInputStream(outputStream.toByteArray()); if (!javaModel.isOpen()) { javaModel.open(new SubProgressMonitor(progressMonitor, 1)); } else { progressMonitor.worked(1); } final IProject project = workspace.getRoot().getProject(jetEmitter.getProjectName()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETPreparingProject_message", new Object[] { project.getName() })); IJavaProject javaProject; if (!project.exists()) { progressMonitor.subTask("JET creating project " + project.getName()); project.create(new SubProgressMonitor(progressMonitor, 1)); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreatingProject_message", new Object[] { project.getName() })); IProjectDescription description = workspace.newProjectDescription(project.getName()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); description.setLocation(null); project.open(new SubProgressMonitor(progressMonitor, 1)); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); javaProject = JavaCore.create(project); for (Map.Entry<String, String> option : jetEmitter.getJavaOptions().entrySet()) { javaProject.setOption(option.getKey(), option.getValue()); } } else { project.open(new SubProgressMonitor(progressMonitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); javaProject = JavaCore.create(project); } List<IClasspathEntry> classpath = new UniqueEList<IClasspathEntry>(Arrays.asList(javaProject.getRawClasspath())); for (int i = 0, len = classpath.size(); i < len; i++) { IClasspathEntry entry = classpath.get(i); if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && ("/" + project.getName()).equals(entry.getPath().toString())) { classpath.remove(i); } } progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETInitializingProject_message", new Object[] { project.getName() })); IClasspathEntry classpathEntry = JavaCore.newSourceEntry(new Path("/" + project.getName() + "/src")); IClasspathEntry jreClasspathEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); classpath.add(classpathEntry); classpath.add(jreClasspathEntry); classpath.addAll(jetEmitter.classpathEntries); IFolder sourceFolder = project.getFolder(new Path("src")); if (!sourceFolder.exists()) { sourceFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } IFolder runtimeFolder = project.getFolder(new Path("bin")); if (!runtimeFolder.exists()) { runtimeFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), new SubProgressMonitor(progressMonitor, 1)); javaProject.setOutputLocation(new Path("/" + project.getName() + "/bin"), new SubProgressMonitor(progressMonitor, 1)); javaProject.close(); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETOpeningJavaProject_message", new Object[] { project.getName() })); javaProject.open(new SubProgressMonitor(progressMonitor, 1)); IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots(); IPackageFragmentRoot sourcePackageFragmentRoot = null; for (int j = 0; j < packageFragmentRoots.length; ++j) { IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[j]; if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { sourcePackageFragmentRoot = packageFragmentRoot; break; } } StringTokenizer stringTokenizer = new StringTokenizer(packageName, "."); IProgressMonitor subProgressMonitor = new SubProgressMonitor(progressMonitor, 1); subProgressMonitor.beginTask("", stringTokenizer.countTokens() + 4); subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_CreateTargetFile_message")); IContainer sourceContainer = sourcePackageFragmentRoot == null ? project : (IContainer) sourcePackageFragmentRoot.getCorrespondingResource(); while (stringTokenizer.hasMoreElements()) { String folderName = stringTokenizer.nextToken(); sourceContainer = sourceContainer.getFolder(new Path(folderName)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(subProgressMonitor, 1)); } } IFile targetFile = sourceContainer.getFile(new Path(jetCompiler.getSkeleton().getClassName() + ".java")); if (!targetFile.exists()) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreating_message", new Object[] { targetFile.getFullPath() })); targetFile.create(contents, true, new SubProgressMonitor(subProgressMonitor, 1)); } else { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETUpdating_message", new Object[] { targetFile.getFullPath() })); targetFile.setContents(contents, true, true, new SubProgressMonitor(subProgressMonitor, 1)); } subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETBuilding_message", new Object[] { project.getName() })); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(subProgressMonitor, 1)); IMarker[] markers = targetFile.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE); boolean errors = false; for (int i = 0; i < markers.length; ++i) { IMarker marker = markers[i]; if (marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO) == IMarker.SEVERITY_ERROR) { errors = true; subProgressMonitor.subTask(marker.getAttribute(IMarker.MESSAGE) + " : " + (CodeGenPlugin.getPlugin().getString("jet.mark.file.line", new Object[] { targetFile.getLocation(), marker.getAttribute(IMarker.LINE_NUMBER) }))); } } if (!errors) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETLoadingClass_message", new Object[] { jetCompiler.getSkeleton().getClassName() + ".class" })); List<URL> urls = new ArrayList<URL>(); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); final Set<Bundle> bundles = new HashSet<Bundle>(); LOOP: for (IClasspathEntry jetEmitterClasspathEntry : jetEmitter.getClasspathEntries()) { IClasspathAttribute[] classpathAttributes = jetEmitterClasspathEntry.getExtraAttributes(); if (classpathAttributes != null) { for (IClasspathAttribute classpathAttribute : classpathAttributes) { if (classpathAttribute.getName().equals(CodeGenUtil.EclipseUtil.PLUGIN_ID_CLASSPATH_ATTRIBUTE_NAME)) { Bundle bundle = Platform.getBundle(classpathAttribute.getValue()); if (bundle != null) { bundles.add(bundle); continue LOOP; } } } } urls.add(new URL("platform:/resource" + jetEmitterClasspathEntry.getPath() + "/")); } URLClassLoader theClassLoader = new URLClassLoader(urls.toArray(new URL[0]), jetEmitter.classLoader) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return super.loadClass(className); } catch (ClassNotFoundException exception) { for (Bundle bundle : bundles) { try { return bundle.loadClass(className); } catch (ClassNotFoundException exception2) { } } throw exception; } } }; Class<?> theClass = theClassLoader.loadClass((packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName()); String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } } subProgressMonitor.done(); } catch (CoreException exception) { throw new JETException(exception); } catch (Exception exception) { throw new JETException(exception); } finally { progressMonitor.done(); } }
Code Sample 2:
public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("camel/exec-context.xml"); CamelContext context = appContext.getBean(CamelContext.class); Exchange exchange = new DefaultExchange(context); List<String> arg = new ArrayList<String>(); arg.add("/home/sumit/derby.log"); arg.add("helios:cameltesting/"); exchange.getIn().setHeader(ExecBinding.EXEC_COMMAND_ARGS, arg); Exchange res = context.createProducerTemplate().send("direct:input", exchange); ExecResult result = (ExecResult) res.getIn().getBody(); System.out.println(result.getExitValue()); System.out.println(result.getCommand()); if (result.getStderr() != null) { IOUtils.copy(result.getStderr(), new FileOutputStream(new File("/home/sumit/error.log"))); } if (result.getStdout() != null) { IOUtils.copy(result.getStdout(), new FileOutputStream(new File("/home/sumit/out.log"))); } appContext.close(); }
|
11
|
Code Sample 1:
protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); }
Code Sample 2:
public static void main(String[] argv) { if (1 < argv.length) { File[] sources = Source(argv[0]); if (null != sources) { for (File src : sources) { File[] targets = Target(src, argv); if (null != targets) { final long srclen = src.length(); try { FileChannel source = new FileInputStream(src).getChannel(); try { for (File tgt : targets) { FileChannel target = new FileOutputStream(tgt).getChannel(); try { source.transferTo(0L, srclen, target); } finally { target.close(); } System.out.printf("Updated %s\n", tgt.getPath()); File[] deletes = Delete(src, tgt); if (null != deletes) { for (File del : deletes) { if (SVN) { if (SvnDelete(del)) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } else if (del.delete()) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } } if (SVN) SvnAdd(tgt); } } finally { source.close(); } } catch (Exception exc) { exc.printStackTrace(); System.exit(1); } } } System.exit(0); } else { System.err.printf("Source file(s) not found in '%s'\n", argv[0]); System.exit(1); } } else { usage(); System.exit(1); } }
|
00
|
Code Sample 1:
public static boolean changeCredentials() { boolean passed = false; boolean credentials = false; HashMap info = null; Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write the credentials to file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { System.out.println(ex.toString()); if (ex.getMessage().toLowerCase().contains("unable")) { JOptionPane.showMessageDialog(null, "Database problem occured, please try again later", "Error", JOptionPane.ERROR_MESSAGE); passed = true; testVar = false; } else { passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed until you enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } while (!passed) { Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write credentials to local xml file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { Debug.log("Main.changeCredentials", "credential validation failed"); passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed untill u enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } } return credentials; }
Code Sample 2:
public String retrieve(String url) { HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); if (getResponseEntity != null) { return EntityUtils.toString(getResponseEntity); } } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null; }
|
11
|
Code Sample 1:
private void makeDailyBackup() throws CacheOperationException, ConfigurationException { final int MAX_DAILY_BACKUPS = 5; File cacheFolder = getBackupFolder(); cacheLog.debug("Making a daily backup of current Beehive archive..."); try { File oldestDaily = new File(DAILY_BACKUP_PREFIX + "." + MAX_DAILY_BACKUPS); if (oldestDaily.exists()) { moveToWeeklyBackup(oldestDaily); } for (int index = MAX_DAILY_BACKUPS - 1; index > 0; index--) { File daily = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + index); File target = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + (index + 1)); if (!daily.exists()) { cacheLog.debug("Daily backup file ''{0}'' was not present. Skipping...", daily.getAbsolutePath()); continue; } if (!daily.renameTo(target)) { sortBackups(); throw new CacheOperationException("There was an error moving ''{0}'' to ''{1}''.", daily.getAbsolutePath(), target.getAbsolutePath()); } else { cacheLog.debug("Moved " + daily.getAbsolutePath() + " to " + target.getAbsolutePath()); } } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied read/write access to daily backup files in ''{0}'' : {1}" + e, cacheFolder.getAbsolutePath(), e.getMessage()); } File beehiveArchive = getCachedArchive(); File tempBackupArchive = new File(cacheFolder, BEEHIVE_ARCHIVE_NAME + ".tmp"); BufferedInputStream archiveReader = null; BufferedOutputStream tempBackupWriter = null; try { archiveReader = new BufferedInputStream(new FileInputStream(beehiveArchive)); tempBackupWriter = new BufferedOutputStream(new FileOutputStream(tempBackupArchive)); int len, bytecount = 0; final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = archiveReader.read(buffer, 0, BUFFER_SIZE)) != -1) { tempBackupWriter.write(buffer, 0, len); bytecount += len; } tempBackupWriter.flush(); long originalFileSize = beehiveArchive.length(); if (originalFileSize != bytecount) { throw new CacheOperationException("Original archive size was {0} bytes but only {1} were copied.", originalFileSize, bytecount); } cacheLog.debug("Finished copying ''{0}'' to ''{1}''.", beehiveArchive.getAbsolutePath(), tempBackupArchive.getAbsolutePath()); } catch (FileNotFoundException e) { throw new CacheOperationException("Files required for copying a backup of Beehive archive could not be found, opened " + "or created : {1}", e, e.getMessage()); } catch (IOException e) { throw new CacheOperationException("Error while making a copy of the Beehive archive : {0}", e, e.getMessage()); } finally { if (archiveReader != null) { try { archiveReader.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, beehiveArchive.getAbsolutePath(), t.getMessage()); } } if (tempBackupWriter != null) { try { tempBackupWriter.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, tempBackupArchive.getAbsolutePath(), t.getMessage()); } } } validateArchive(tempBackupArchive); File newestDaily = getNewestDailyBackupFile(); try { if (!tempBackupArchive.renameTo(newestDaily)) { throw new CacheOperationException("Error moving ''{0}'' to ''{1}''.", tempBackupArchive.getAbsolutePath(), newestDaily.getAbsolutePath()); } else { cacheLog.info("Backup complete. Saved in ''{0}''", newestDaily.getAbsolutePath()); } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied write access to ''{0}'' : {1}", e, newestDaily.getAbsolutePath(), e.getMessage()); } }
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()); } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest); } } byte[] buffer = new byte[1]; 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:
private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
|
00
|
Code Sample 1:
private static void userAuth(String challenge) throws IOException { try { MessageDigest md = MessageDigest.getInstance("BrokenMD4"); String passwd = null; if (System.getProperty("jarsync.password.gui") != null) { JPasswordField pass = new JPasswordField(); JPanel panel = new JPanel(new GridLayout(2, 1)); panel.add(new JLabel("Password:")); panel.add(pass); JOptionPane.showMessageDialog(null, panel, remoteUser + '@' + remoteHost + "'s Password", JOptionPane.QUESTION_MESSAGE); passwd = new String(pass.getPassword()); } else { System.out.print(remoteUser + '@' + remoteHost + "'s password: "); passwd = Util.readLine(System.in); System.out.println(); } md.update(new byte[4]); md.update(passwd.getBytes("US-ASCII")); md.update(challenge.getBytes("US-ASCII")); byte[] response = md.digest(); Util.writeASCII(out, remoteUser + " " + Util.base64(response) + '\n'); out.flush(); } catch (NoSuchAlgorithmException nsae) { throw new IOException("could not create message digest."); } }
Code Sample 2:
public void close() { try { if (writer != null) { BufferedReader reader; writer.close(); writer = new BufferedWriter(new FileWriter(fileName)); for (int i = 0; i < headers.size(); i++) writer.write(headers.get(i) + ","); writer.write("\n"); reader = new BufferedReader(new FileReader(file)); while (reader.ready()) writer.write(reader.readLine() + "\n"); reader.close(); writer.close(); file.delete(); } } catch (java.io.IOException e) { throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
Code Sample 2:
private void initJarURL() { try { URL url = getKwantuJarURLInMavenRepo(artifactId, version); File tempJarFile = File.createTempFile(artifactId + "-" + version, ".jar"); OutputStream out = new FileOutputStream(tempJarFile); InputStream in = url.openStream(); int length = 0; byte[] bytes = new byte[2048]; while ((length = in.read(bytes)) > 0) { out.write(bytes, 0, length); } in.close(); out.close(); jarURL = tempJarFile.toURI().toURL(); } catch (IOException ex) { throw new KwantuFaultException(ex); } }
|
11
|
Code Sample 1:
public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private static void copyFile(File source, File dest, boolean visibleFilesOnly) throws IOException { if (visibleFilesOnly && isHiddenOrDotFile(source)) { return; } if (dest.exists()) { System.err.println("Destination File Already Exists: " + dest); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
|
00
|
Code Sample 1:
static String getMD5Sum(String source) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(source.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); return bigInt.toString(16); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 algorithm seems to not be supported. This is a requirement!"); } }
Code Sample 2:
private void gerarFaturamento() { int opt = Funcoes.mensagemConfirma(null, "Confirma o faturamento?"); if (opt == JOptionPane.OK_OPTION) { StringBuilder insert = new StringBuilder(); insert.append("INSERT INTO RPFATURAMENTO "); insert.append("(CODEMP, CODFILIAL, CODPED, CODITPED, "); insert.append("QTDFATURADO, VLRFATURADO, QTDPENDENTE, "); insert.append("PERCCOMISFAT, VLRCOMISFAT, DTFATURADO ) "); insert.append("VALUES"); insert.append("(?,?,?,?,?,?,?,?,?,?)"); PreparedStatement ps; int parameterIndex; try { for (int i = 0; i < tab.getNumLinhas(); i++) { parameterIndex = 1; ps = con.prepareStatement(insert.toString()); ps.setInt(parameterIndex++, AplicativoRep.iCodEmp); ps.setInt(parameterIndex++, ListaCampos.getMasterFilial("RPFATURAMENTO")); ps.setInt(parameterIndex++, txtCodPed.getVlrInteger()); ps.setInt(parameterIndex++, (Integer) tab.getValor(i, ETabNota.ITEM.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.QTDFATURADA.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRFATURADO.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.QDTPENDENTE.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.PERCCOMIS.ordinal())); ps.setBigDecimal(parameterIndex++, (BigDecimal) tab.getValor(i, ETabNota.VLRCOMIS.ordinal())); ps.setDate(parameterIndex++, Funcoes.dateToSQLDate(Calendar.getInstance().getTime())); ps.executeUpdate(); } gerarFaturamento.setEnabled(false); gerarComissao.setEnabled(true); Funcoes.mensagemInforma(null, "Faturamento criado para pedido " + txtCodPed.getVlrInteger()); con.commit(); } catch (Exception e) { e.printStackTrace(); Funcoes.mensagemErro(this, "Erro ao gerar faturamento!\n" + e.getMessage()); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } }
|
00
|
Code Sample 1:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UsuarioBll usuarioBll = new UsuarioBll(); String senha = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(request.getParameter("Senha").getBytes(), 0, request.getParameter("Senha").length()); senha = new BigInteger(1, messageDigest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } String[] data = request.getParameter("Nascimento").split("/"); Calendar calendar = Calendar.getInstance(); calendar.set(Integer.parseInt(data[2]), Integer.parseInt(data[1]) - 1, Integer.parseInt(data[0])); Telefone telefone = new Telefone(); Usuario usuario = new Usuario(); usuario.setNome(request.getParameter("Nome")); telefone.setTelefone(request.getParameter("Telefone").replaceAll("\\D", "")); telefone.setTelefoneTipo(TelefoneTipoBll.getTelefoneTipoByTelefoneTipoID(Integer.parseInt(request.getParameter("TipoTelefone")))); usuario.setTelefone(telefone); usuario.setEmail(request.getParameter("Email")); usuario.setCpf(request.getParameter("CPF").replaceAll("\\D", "")); usuario.setNascimento(calendar); Endereco endereco = new Endereco(); endereco.setCep(Integer.parseInt(request.getParameter("CEP").replaceAll("\\D", ""))); endereco.setNumero(request.getParameter("Numero")); endereco.setComplemento(request.getParameter("Complemento")); usuario.setEndereco(endereco); usuario.setSenha(senha); String msg = "?msg=0"; if (usuarioBll.addNewUsuario(usuario)) { msg = "?msg=1"; Usuario usuarioAutenticado = UsuarioBll.getUsuarioByEmailAndSenha(usuario.getEmail(), usuario.getSenha()); HttpSession session = request.getSession(); session.setAttribute("usuario", usuarioAutenticado); } response.sendRedirect("templates/verde-rosa/cadastro.jsp" + msg); }
Code Sample 2:
@Override protected Set<DataRecord> retrieveRecords(DataTemplate template) { String query = template.getQuery(); if (query == null) { query = topic; } String select = prefix + " SELECT ?resource WHERE { { ?resource rdf:type " + "<http://dbpedia.org/class/yago/" + StringUtils.toCamelCase(query) + "> } UNION { ?resource skos:subject <http://dbpedia.org/resource/Category:" + query.replaceAll(" ", "_") + "> } }"; Document doc = null; HashSet<DataRecord> recs = new HashSet<DataRecord>(); try { URL url = new URL(queryBase + URLEncoder.encode(select, "UTF-8")); InputStream inStream = url.openStream(); doc = docBuild.parse(inStream); HashSet<String> resourceNames = new HashSet<String>(); Element table = doc.getDocumentElement(); NodeList rows = table.getElementsByTagName("tr"); for (int i = 0; i < rows.getLength(); i++) { Element row = (Element) rows.item(i); NodeList cols = row.getElementsByTagName("td"); if (cols.getLength() > 0) { Element elem = (Element) cols.item(0); String resource = ((Text) elem.getFirstChild()).getData(); resourceNames.add(resource); } } inStream.close(); for (String resource : resourceNames) { MultiValueMap<String> resRecord = queryResource(resource); if (resource != null) { DataRecord rec = parseResource(resRecord, template); if (rec != null) { recs.add(rec); } } } } catch (IOException exc) { exc.printStackTrace(); } catch (SAXException exc) { exc.printStackTrace(); } return recs; }
|
00
|
Code Sample 1:
protected Source resolveRepositoryURI(String path) throws TransformerException { Source resolvedSource = null; try { if (path != null) { URL url = new URL(path); InputStream in = url.openStream(); if (in != null) { resolvedSource = new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible."); } } catch (MalformedURLException mfue) { throw new TransformerException("Error accessing resource using servlet context: " + path, mfue); } catch (IOException ioe) { throw new TransformerException("Unable to access resource at: " + path, ioe); } return resolvedSource; }
Code Sample 2:
public static InputStream getResourceAsStream(String resourceName) { try { URL url = getEmbeddedFileUrl(WS_SEP + resourceName); if (url != null) { return url.openStream(); } } catch (MalformedURLException e) { GdtAndroidPlugin.getLogger().logError(e, "Failed to read stream '%s'", resourceName); } catch (IOException e) { GdtAndroidPlugin.getLogger().logError(e, "Failed to read stream '%s'", resourceName); } return null; }
|
11
|
Code Sample 1:
public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } this.currentGafFilePath = this.url; try { if (this.httpURL != null) { LOG.info("Reading URL :" + httpURL); InputStream is = this.httpURL.openStream(); int index = this.httpURL.toString().lastIndexOf('/'); String file = this.httpURL.toString().substring(index + 1); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), "tmp-" + file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); is = new FileInputStream(downloadLocation); if (url.endsWith(".gz")) { is = new GZIPInputStream(is); } this.currentGafFile = this.currentGafFilePath.substring(this.currentGafFilePath.lastIndexOf("/") + 1); this.httpURL = null; return is; } else { String file = files[counter++].getName(); this.currentGafFile = file; if (!this.currentGafFilePath.endsWith(file)) currentGafFilePath += file; LOG.info("Returning input stream for the file: " + file); _connect(); ftpClient.changeWorkingDirectory(path); InputStream is = ftpClient.retrieveFileStream(file); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); System.out.println("Download complete....."); is = new FileInputStream(downloadLocation); if (file.endsWith(".gz")) { is = new GZIPInputStream(is); } return is; } } catch (IOException ex) { throw new RuntimeException(ex); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
11
|
Code Sample 1:
public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); }
Code Sample 2:
public static String SHA1(String string) throws XLWrapException { MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new XLWrapException("SHA-1 message digest is not available."); } byte[] data = new byte[40]; md.update(string.getBytes()); data = md.digest(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); }
|
00
|
Code Sample 1:
@Override public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("getAudioFileFormat(URL url)"); } InputStream inputStream = url.openStream(); try { return getAudioFileFormat(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } }
Code Sample 2:
private HttpURLConnection sendData(URL url, String user, String password) throws IOException, IllegalArgumentException { String tmpAuthUserName = ""; if (user != null) { tmpAuthUserName = user; } final String anAuthUserName = tmpAuthUserName; String tmpAuthPasswd = ""; if (password != null) { tmpAuthPasswd = password; } final String anAuthPasswd = tmpAuthPasswd; Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(anAuthUserName, anAuthPasswd.toCharArray()); } }); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(1000); conn.connect(); return conn; }
|
00
|
Code Sample 1:
public String getMD5Str(String str) { MessageDigest messageDigest = null; String mdStr = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } mdStr = md5StrBuff.toString(); return mdStr; }
Code Sample 2:
public byte[] loadClassFirst(final String className) { if (className.startsWith("com.sun.sgs.impl.service.transaction.TransactionCoordinatorImpl")) { String resource = null; if (className.equals("com.sun.sgs.impl.service.transaction.TransactionCoordinatorImpl")) { resource = "com/sun/sgs/impl/service/transaction/TransactionCoordinatorImpl.class.bin"; } if (resource != null) { final URL url = Thread.currentThread().getContextClassLoader().getResource(resource); if (url != null) { try { return StreamUtil.read(url.openStream()); } catch (final IOException e) { } } throw new IllegalStateException("Unable to load binary class"); } } return null; }
|
00
|
Code Sample 1:
public static void main(String args[]) { String midletClass = null; ; File appletInputFile = null; File deviceInputFile = null; File midletInputFile = null; File htmlOutputFile = null; File appletOutputFile = null; File deviceOutputFile = null; File midletOutputFile = null; List params = new ArrayList(); for (int i = 0; i < args.length; i++) { params.add(args[i]); } Iterator argsIterator = params.iterator(); while (argsIterator.hasNext()) { String arg = (String) argsIterator.next(); argsIterator.remove(); if ((arg.equals("--help")) || (arg.equals("-help"))) { System.out.println(usage()); System.exit(0); } else if (arg.equals("--midletClass")) { midletClass = (String) argsIterator.next(); argsIterator.remove(); } else if (arg.equals("--appletInput")) { appletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceInput")) { deviceInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletInput")) { midletInputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--htmlOutput")) { htmlOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--appletOutput")) { appletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--deviceOutput")) { deviceOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } else if (arg.equals("--midletOutput")) { midletOutputFile = new File((String) argsIterator.next()); argsIterator.remove(); } } if (midletClass == null || appletInputFile == null || deviceInputFile == null || midletInputFile == null || htmlOutputFile == null || appletOutputFile == null || deviceOutputFile == null || midletOutputFile == null) { System.out.println(usage()); System.exit(0); } try { DeviceImpl device = null; String descriptorLocation = null; JarFile jar = new JarFile(deviceInputFile); for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorLocation = entry; break; } } if (descriptorLocation != null) { EmulatorContext context = new EmulatorContext() { private DisplayComponent displayComponent = new NoUiDisplayComponent(); private InputMethod inputMethod = new J2SEInputMethod(); private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay(this); private FontManager fontManager = new J2SEFontManager(); private DeviceComponent deviceComponent = new SwingDeviceComponent(true); public DisplayComponent getDisplayComponent() { return displayComponent; } public InputMethod getDeviceInputMethod() { return inputMethod; } public DeviceDisplay getDeviceDisplay() { return deviceDisplay; } public FontManager getDeviceFontManager() { return fontManager; } public InputStream getResourceAsStream(String name) { return MIDletBridge.getCurrentMIDlet().getClass().getResourceAsStream(name); } public DeviceComponent getDeviceComponent() { return deviceComponent; } }; URL[] urls = new URL[1]; urls[0] = deviceInputFile.toURI().toURL(); ClassLoader classLoader = new ExtensionsClassLoader(urls, urls.getClass().getClassLoader()); device = DeviceImpl.create(context, classLoader, descriptorLocation, J2SEDevice.class); } if (device == null) { System.out.println("Error parsing device package: " + descriptorLocation); System.exit(0); } createHtml(htmlOutputFile, device, midletClass, midletOutputFile, appletOutputFile, deviceOutputFile); createMidlet(midletInputFile.toURI().toURL(), midletOutputFile); IOUtils.copyFile(appletInputFile, appletOutputFile); IOUtils.copyFile(deviceInputFile, deviceOutputFile); } catch (IOException ex) { ex.printStackTrace(); } System.exit(0); }
Code Sample 2:
private String postData(String requestUrl, String atom) throws AuthenticationException, IOException { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String header; try { header = oauthAuthenticator.getHttpAuthorizationHeader(url.toString(), "POST", profile.getOAuthToken(), profile.getOAuthTokenSecret()); } catch (OAuthException e) { throw new AuthenticationException(e); } conn.setRequestProperty("Authorization", header); conn.setRequestProperty("Content-Type", "application/atom+xml"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); writer.write(atom); writer.close(); if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthenticationException(); } InputStreamReader reader = new InputStreamReader(conn.getInputStream()); char[] buffer = new char[1024]; int bytesRead = 0; StringBuilder data = new StringBuilder(); while ((bytesRead = reader.read(buffer)) != -1) { data.append(buffer, 0, bytesRead); } reader.close(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new IOException(conn.getResponseCode() + " " + conn.getResponseMessage() + "\n" + data); } return data.toString(); }
|
00
|
Code Sample 1:
public String getSummaryText() { if (summaryText == null) { for (Iterator iter = xdcSources.values().iterator(); iter.hasNext(); ) { XdcSource source = (XdcSource) iter.next(); File packageFile = new File(source.getFile().getParentFile(), "xdc-package.html"); if (packageFile.exists()) { Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { summaryText = buf.substring(pos1 + 6, pos2); } else { summaryText = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); summaryText = ""; } catch (IOException e) { LOG.error(e.getMessage(), e); summaryText = ""; } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } break; } else { summaryText = ""; } } } return summaryText; }
Code Sample 2:
protected InputStream getInputStream() throws IOException { if (source instanceof URL) { URL url = (URL) source; location = url.toString(); return url.openStream(); } else if (source instanceof File) { location = ((File) source).getAbsolutePath(); return new FileInputStream((File) source); } else if (source instanceof String) { location = (String) source; return new FileInputStream((String) source); } else if (source instanceof InputStream) { return (InputStream) source; } return null; }
|
00
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true); IOUtils.copy(reader, out, null); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
Code Sample 2:
private boolean authenticateWithServer(String user, String password) { Object o; String response; byte[] dataKey; try { o = objectIn.readObject(); if (o instanceof String) { response = (String) o; Debug.netMsg("Connected to JFritz Server: " + response); if (!response.equals("JFRITZ SERVER 1.1")) { Debug.netMsg("Unkown Server version, newer JFritz protocoll version?"); Debug.netMsg("Canceling login attempt!"); } objectOut.writeObject(user); objectOut.flush(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); DESKeySpec desKeySpec = new DESKeySpec(md.digest()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.DECRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(desCipher); if (o instanceof byte[]) { dataKey = (byte[]) o; desKeySpec = new DESKeySpec(dataKey); secretKey = keyFactory.generateSecret(desKeySpec); inCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); outCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); inCipher.init(Cipher.DECRYPT_MODE, secretKey); outCipher.init(Cipher.ENCRYPT_MODE, secretKey); SealedObject sealed_ok = new SealedObject("OK", outCipher); objectOut.writeObject(sealed_ok); SealedObject sealed_response = (SealedObject) objectIn.readObject(); o = sealed_response.getObject(inCipher); if (o instanceof String) { if (o.equals("OK")) { return true; } else { Debug.netMsg("Server sent wrong string as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong object as response to authentication challenge!"); } } else { Debug.netMsg("Server sent wrong type for data key!"); } } } catch (ClassNotFoundException e) { Debug.error("Server authentication response invalid!"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { Debug.netMsg("MD5 Algorithm not present in this JVM!"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeySpecException e) { Debug.netMsg("Error generating cipher, problems with key spec?"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeyException e) { Debug.netMsg("Error genertating cipher, problems with key?"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchPaddingException e) { Debug.netMsg("Error generating cipher, problems with padding?"); Debug.error(e.toString()); e.printStackTrace(); } catch (EOFException e) { Debug.error("Server closed Stream unexpectedly!"); Debug.error(e.toString()); e.printStackTrace(); } catch (SocketTimeoutException e) { Debug.error("Read timeout while authenticating with server!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.error("Error reading response during authentication!"); Debug.error(e.toString()); e.printStackTrace(); } catch (IllegalBlockSizeException e) { Debug.error("Illegal block size exception!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.error("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return false; }
|
00
|
Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { log.info("Copying file '" + sourceFile + "' to '" + destFile + "'"); if (!sourceFile.isFile()) { throw new IllegalArgumentException("The sourceFile '" + sourceFile + "' does not exist or is not a normal file."); } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); long numberOfBytes = destination.transferFrom(source, 0, source.size()); log.debug("Transferred " + numberOfBytes + " bytes from '" + sourceFile + "' to '" + destFile + "'."); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public String getDocumentAt(String urlString) { StringBuffer document = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) document.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } return document.toString(); }
|
11
|
Code Sample 1:
public static FileChannel newFileChannel(File file, String rw, boolean enableException) throws IOException { if (file == null) return null; if (rw == null || rw.length() == 0) { return null; } rw = rw.toLowerCase(); if (rw.equals(MODE_READ)) { if (FileUtil.exists(file, enableException)) { FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel(); setObjectMap(ch.hashCode(), fis, FIS); return ch; } } else if (rw.equals(MODE_WRITE)) { FileOutputStream fos = new FileOutputStream(file); FileChannel ch = fos.getChannel(); setObjectMap(ch.hashCode(), fos, FOS_W); return ch; } else if (rw.equals(MODE_APPEND)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel ch = raf.getChannel(); ch.position(ch.size()); setObjectMap(ch.hashCode(), raf, FOS_A); return ch; } } else if (rw.equals(MODE_READ_WRITE)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, rw); FileChannel ch = raf.getChannel(); setObjectMap(ch.hashCode(), raf, RAF); return ch; } } else { throw new IllegalArgumentException("Illegal read/write type : [" + rw + "]\n" + "You can use following types for: \n" + " (1) Read Only = \"r\"\n" + " (2) Write Only = \"w\"\n" + " (3) Read/Write = \"rw\"\n" + " (4) Append = \"a\""); } return null; }
Code Sample 2:
public void guardarRecordatorio() { try { if (espaciosLlenos()) { guardarCantidad(); String dat = ""; String filenametxt = String.valueOf("recordatorio" + cantidadArchivos + ".txt"); String filenamezip = String.valueOf("recordatorio" + cantidadArchivos + ".zip"); cantidadArchivos++; dat += identificarDato(datoSeleccionado) + "\n"; dat += String.valueOf(mesTemporal) + "\n"; dat += String.valueOf(anoTemporal) + "\n"; dat += horaT.getText() + "\n"; dat += lugarT.getText() + "\n"; dat += actividadT.getText() + "\n"; File archivo = new File(filenametxt); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(dat); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filenamezip); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File(filenametxt); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry(filenametxt); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); JOptionPane.showMessageDialog(null, "El recordatorio ha sido guardado con exito", "Recordatorio Guardado", JOptionPane.INFORMATION_MESSAGE); marco.hide(); marco.dispose(); establecerMarca(); table.clearSelection(); } else JOptionPane.showMessageDialog(null, "Debe llenar los espacios de Hora, Lugar y Actividad", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
00
|
Code Sample 1:
public static String createRecoveryContent(String password) { try { password = encryptGeneral1(password); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recovery_file"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String textContent = root.getTextContent(); return textContent; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
Code Sample 2:
void copyFile(File src, File dst) throws IOException { FileInputStream fis = new FileInputStream(src); byte[] buf = new byte[10000]; int n; FileOutputStream fos = new FileOutputStream(dst); while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); copied++; }
|
00
|
Code Sample 1:
public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public static File copyFile(File file) { File src = file; File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
|
11
|
Code Sample 1:
public boolean renameTo(File dest) throws IOException { if (dest == null) { throw new NullPointerException("dest"); } if (!file.renameTo(dest)) { FileInputStream inputStream = new FileInputStream(file); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel in = inputStream.getChannel(); FileChannel out = outputStream.getChannel(); long destsize = in.transferTo(0, size, out); in.close(); out.close(); if (destsize == size) { file.delete(); file = dest; isRenamed = true; return true; } else { dest.delete(); return false; } } file = dest; isRenamed = true; return true; }
Code Sample 2:
public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
|
11
|
Code Sample 1:
public void delete(Channel channel) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(channel.getPath(), "1", connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); String sqlStr = "delete from t_ip_channel where channel_path=?"; preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); sqlStr = "delete from t_ip_channel_order where channel_order_site = ?"; preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException ex) { connection.rollback(); log.error("ɾ��Ƶ��ʧ�ܣ�channelPath=" + channel.getPath(), ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } }
Code Sample 2:
public 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(); }
|
11
|
Code Sample 1:
public void genCreateSchema(DiagramModel diagramModel, String source) { try { con.setAutoCommit(false); stmt = con.createStatement(); Collection boxes = diagramModel.getBoxes(); BoxModel box; ItemModel item; String sqlQuery; int counter = 0; for (Iterator x = boxes.iterator(); x.hasNext(); ) { box = (BoxModel) x.next(); if (!box.isAbstractDef()) { sqlQuery = sqlCreateTableBegin(box); Collection items = box.getItems(); for (Iterator y = items.iterator(); y.hasNext(); ) { item = (ItemModel) y.next(); sqlQuery = sqlQuery + sqlColumn(item); } sqlQuery = sqlQuery + sqlForeignKeyColumns(box); sqlQuery = sqlQuery + sqlPrimaryKey(box); sqlQuery = sqlQuery + sqlUniqueKey(box); sqlQuery = sqlQuery + sqlCreateTableEnd(box, source); System.out.println(sqlQuery); try { stmt.executeUpdate(sqlQuery); counter++; } catch (SQLException e) { String tableName = box.getName(); System.out.println("// Problem while creating table " + tableName + " : " + e.getMessage()); String msg = Para.getPara().getText("tableNotCreated") + " -- " + tableName; this.informUser(msg); } } } this.genCreateForeignKeys(diagramModel); con.commit(); if (counter > 0) { String msg = Para.getPara().getText("schemaCreated") + " -- " + counter + " " + Para.getPara().getText("tables"); this.informUser(msg); } else { this.informUser(Para.getPara().getText("schemaNotCreated")); } } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the JDBC schema generation! "); try { con.rollback(); this.informUser(Para.getPara().getText("schemaNotCreated")); } catch (SQLException e1) { System.out.println(e1.getMessage() + " // Problem with the connection rollback! "); } } finally { try { con.setAutoCommit(true); stmt.close(); } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the statement closing! "); } } }
Code Sample 2:
public void processSaveHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_HOLDING " + "SET " + " full_name_HOLDING=?, " + " NAME_HOLDING=? " + "WHERE ID_HOLDING = ? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); RsetTools.setLong(ps, num++, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); processInsertRelatedCompany(dbDyn, holdingBean, authSession); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
00
|
Code Sample 1:
public static String stringToHash(String text) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Should not happened: SHA-1 algorithm is missing."); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Should not happened: Could not encode text bytes '" + text + "' to iso-8859-1."); } return new String(Base64.encodeBase64(md.digest())); }
Code Sample 2:
public String sendRequest(HTTPHandler.RequestData requestData) throws HTTPHandlerException { try { final String urlString = requestData.getURLString(); final URL url = new URL(urlString); final String postString = requestData.getPostString(); m_pluginThreadContext.startTimer(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); final Iterator headersIterator = requestData.getHeaders().entrySet().iterator(); while (headersIterator.hasNext()) { final Map.Entry entry = (Map.Entry) headersIterator.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } final AuthorizationData authorizationData = requestData.getAuthorizationData(); if (authorizationData != null && authorizationData instanceof HTTPHandler.BasicAuthorizationData) { final HTTPHandler.BasicAuthorizationData basicAuthorizationData = (HTTPHandler.BasicAuthorizationData) authorizationData; connection.setRequestProperty("Authorization", "Basic " + Codecs.base64Encode(basicAuthorizationData.getUser() + ":" + basicAuthorizationData.getPassword())); } connection.setInstanceFollowRedirects(m_followRedirects); if (m_useCookies) { final String cookieString = m_cookieHandler.getCookieString(url, m_useCookiesVersionString); if (cookieString != null) { connection.setRequestProperty("Cookie", cookieString); } } connection.setUseCaches(false); if (postString != null) { connection.setRequestMethod("POST"); connection.setDoOutput(true); final BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream()); final PrintWriter out = new PrintWriter(bos); out.write(postString); out.close(); } connection.connect(); final int responseCode = connection.getResponseCode(); if (m_timeToFirstByteIndex != null) { m_pluginThreadContext.getCurrentTestStatistics().addValue(m_timeToFirstByteIndex, System.currentTimeMillis() - m_pluginThreadContext.getStartTime()); } if (m_useCookies) { int headerIndex = 1; String headerKey = null; String headerValue = connection.getHeaderField(headerIndex); while (headerValue != null) { headerKey = connection.getHeaderFieldKey(headerIndex); if (headerKey != null && "Set-Cookie".equals(headerKey)) { m_cookieHandler.setCookies(headerValue, url); } headerValue = connection.getHeaderField(++headerIndex); } } if (responseCode == HttpURLConnection.HTTP_OK) { final InputStreamReader isr = new InputStreamReader(connection.getInputStream()); final BufferedReader in = new BufferedReader(isr); final StringWriter stringWriter = new StringWriter(512); char[] buffer = new char[512]; int charsRead = 0; if (!m_dontReadBody) { while ((charsRead = in.read(buffer, 0, buffer.length)) > 0) { stringWriter.write(buffer, 0, charsRead); } } in.close(); stringWriter.close(); m_pluginThreadContext.logMessage(urlString + " OK"); return stringWriter.toString(); } else if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { m_pluginThreadContext.logMessage(urlString + " was not modified"); } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == 307) { m_pluginThreadContext.logMessage(urlString + " returned a redirect (" + responseCode + "). " + "Ensure the next URL is " + connection.getHeaderField("Location")); return null; } else { m_pluginThreadContext.logError("Unknown response code: " + responseCode + " for " + urlString); } return null; } catch (Exception e) { throw new HTTPHandlerException(e.getMessage(), e); } finally { m_pluginThreadContext.stopTimer(); } }
|
00
|
Code Sample 1:
public static String getMD5(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] digest = md.digest(); String out = ""; for (int i = 0; i < digest.length; i++) { out += digest[i]; } return out; } catch (NoSuchAlgorithmException e) { System.err.println("Manca l'MD5 (piuttosto strano)"); } return ""; }
Code Sample 2:
private void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public static boolean insereCapitulo(final Connection con, Capitulo cap, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodCapitulo(con, cap); String text = desc.getTexto().replaceAll("[']", "\""); String titulo = cap.getTitulo().replaceAll("['\"]", ""); String coment = cap.getComentario().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + text + "')"); smt.executeUpdate("INSERT INTO capitulo VALUES(" + cap.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO cap_aut VALUES(" + cap.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "CAPITULO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } }
Code Sample 2:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
|
00
|
Code Sample 1:
private void saveAttachment(long messageId, Part attachment, boolean saveAsNew) throws IOException, MessagingException { long attachmentId = -1; Uri contentUri = null; int size = -1; File tempAttachmentFile = null; if ((!saveAsNew) && (attachment instanceof LocalAttachmentBodyPart)) { attachmentId = ((LocalAttachmentBodyPart) attachment).getAttachmentId(); } if (attachment.getBody() != null) { Body body = attachment.getBody(); if (body instanceof LocalAttachmentBody) { contentUri = ((LocalAttachmentBody) body).getContentUri(); } else { InputStream in = attachment.getBody().getInputStream(); tempAttachmentFile = File.createTempFile("att", null, mAttachmentsDir); FileOutputStream out = new FileOutputStream(tempAttachmentFile); size = IOUtils.copy(in, out); in.close(); out.close(); } } if (size == -1) { String disposition = attachment.getDisposition(); if (disposition != null) { String s = MimeUtility.getHeaderParameter(disposition, "size"); if (s != null) { size = Integer.parseInt(s); } } } if (size == -1) { size = 0; } String storeData = Utility.combine(attachment.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA), ','); String name = MimeUtility.getHeaderParameter(attachment.getContentType(), "name"); String contentId = attachment.getContentId(); if (attachmentId == -1) { ContentValues cv = new ContentValues(); cv.put("message_id", messageId); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("store_data", storeData); cv.put("size", size); cv.put("name", name); cv.put("mime_type", attachment.getMimeType()); cv.put("content_id", contentId); attachmentId = mDb.insert("attachments", "message_id", cv); } else { ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); cv.put("size", size); cv.put("content_id", contentId); cv.put("message_id", messageId); mDb.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (tempAttachmentFile != null) { File attachmentFile = new File(mAttachmentsDir, Long.toString(attachmentId)); tempAttachmentFile.renameTo(attachmentFile); attachment.setBody(new LocalAttachmentBody(contentUri, mContext)); ContentValues cv = new ContentValues(); cv.put("content_uri", contentUri != null ? contentUri.toString() : null); mDb.update("attachments", cv, "id = ?", new String[] { Long.toString(attachmentId) }); } if (attachment instanceof LocalAttachmentBodyPart) { ((LocalAttachmentBodyPart) attachment).setAttachmentId(attachmentId); } }
Code Sample 2:
public boolean GetExternalLanguage() { String thisURL, newURL, TheLine; boolean ReadOK = true; int SlashPos = -1; thisURL = getDocumentBase().toString(); SlashPos = thisURL.lastIndexOf("/"); newURL = thisURL.substring(0, (SlashPos + 1)) + "language.txt"; try { URL url = new URL(newURL); try { InputStream TheFile = url.openStream(); try { DataInputStream MyData = new DataInputStream(TheFile); try { while ((TheLine = MyData.readLine()) != null) { if (TheLine.substring(0, 1).compareTo("*") == 0) { if (!ExternalLanguageVariable(TheLine)) { ReadOK = false; break; } } } } catch (Exception e) { System.out.println("Error " + e.toString()); ReadOK = false; } } catch (Exception e) { System.out.println("Error " + e.toString()); ReadOK = false; } } catch (Exception f) { System.out.println("Error " + f.toString()); ReadOK = false; } } catch (Exception g) { System.out.println("Error " + g.toString()); ReadOK = false; } return ReadOK; }
|
00
|
Code Sample 1:
public Object invoke(Invocation invocation) throws Throwable { SmartRef smartRef = (SmartRef) invocation.getValue(Invocation.SMARTREF); HttpURLConnection connection = null; ObjectOutputStream out = null; URL url = null; try { url = new URL(smartRef.getProperties().getProperty("org.smartcc.connector.url")); url = new URL(url, smartRef.getLookup()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); out = new ObjectOutputStream(connection.getOutputStream()); out.writeObject(invocation); out.flush(); } catch (ObjectStreamException e) { System.err.println("error: during serialization"); throw new EJBException("error: during serialization", e); } catch (IOException e) { System.err.println("error: could not connect to " + url); throw new ConnectIOException("could not connect to " + url, e); } finally { try { out.close(); } catch (Exception e) { } } boolean isThrowable = false; Object result = null; ObjectInputStream in = null; try { in = new ObjectInputStream(connection.getInputStream()); isThrowable = in.readBoolean(); if (isThrowable || !invocation.getMethod().getReturnType().equals(void.class)) result = in.readObject(); } catch (ObjectStreamException e) { System.err.println("error: during deserialization"); throw new EJBException("error: during deserialization", e); } catch (IOException e) { System.err.println("error: could not connect to " + url); throw new ConnectIOException("could not connect to " + url, e); } finally { try { in.close(); } catch (Exception e) { } } if (isThrowable) throw (Throwable) result; return result; }
Code Sample 2:
public static String getETag(final String uri, final long lastModified) { try { final MessageDigest dg = MessageDigest.getInstance("MD5"); dg.update(uri.getBytes("utf-8")); dg.update(new byte[] { (byte) ((lastModified >> 24) & 0xFF), (byte) ((lastModified >> 16) & 0xFF), (byte) ((lastModified >> 8) & 0xFF), (byte) (lastModified & 0xFF) }); return CBASE64Codec.encode(dg.digest()); } catch (final Exception ignore) { return uri + lastModified; } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; }
|
11
|
Code Sample 1:
public static void decryptFile(String input, String output, String pwd) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(input), cipher); out = new FileOutputStream(output); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
Code Sample 2:
private final int copyFiles(File[] list, String dest, boolean dest_is_full_name) throws InterruptedException { Context c = ctx; File file = null; for (int i = 0; i < list.length; i++) { boolean existed = false; FileChannel in = null; FileChannel out = null; File outFile = null; file = list[i]; if (file == null) { error(c.getString(R.string.unkn_err)); break; } String uri = file.getAbsolutePath(); try { if (isStopReq()) { error(c.getString(R.string.canceled)); break; } long last_modified = file.lastModified(); String fn = file.getName(); outFile = dest_is_full_name ? new File(dest) : new File(dest, fn); if (file.isDirectory()) { if (depth++ > 40) { error(ctx.getString(R.string.too_deep_hierarchy)); break; } else if (outFile.exists() || outFile.mkdir()) { copyFiles(file.listFiles(), outFile.getAbsolutePath(), false); if (errMsg != null) break; } else error(c.getString(R.string.cant_md, outFile.getAbsolutePath())); depth--; } else { if (existed = outFile.exists()) { int res = askOnFileExist(c.getString(R.string.file_exist, outFile.getAbsolutePath()), commander); if (res == Commander.SKIP) continue; if (res == Commander.REPLACE) { if (outFile.equals(file)) continue; else outFile.delete(); } if (res == Commander.ABORT) break; } if (move) { long len = file.length(); if (file.renameTo(outFile)) { counter++; totalBytes += len; int so_far = (int) (totalBytes * conv); sendProgress(outFile.getName() + " " + c.getString(R.string.moved), so_far, 0); continue; } } in = new FileInputStream(file).getChannel(); out = new FileOutputStream(outFile).getChannel(); long size = in.size(); final long max_chunk = 524288; long pos = 0; long chunk = size > max_chunk ? max_chunk : size; long t_chunk = 0; long start_time = 0; int speed = 0; int so_far = (int) (totalBytes * conv); String sz_s = Utils.getHumanSize(size); String rep_s = c.getString(R.string.copying, fn); for (pos = 0; pos < size; ) { if (t_chunk == 0) start_time = System.currentTimeMillis(); sendProgress(rep_s + sizeOfsize(pos, sz_s), so_far, (int) (totalBytes * conv), speed); long transferred = in.transferTo(pos, chunk, out); pos += transferred; t_chunk += transferred; totalBytes += transferred; if (isStopReq()) { Log.d(TAG, "Interrupted!"); error(c.getString(R.string.canceled)); return counter; } long time_delta = System.currentTimeMillis() - start_time; if (time_delta > 0) { speed = (int) (1000 * t_chunk / time_delta); t_chunk = 0; } } in.close(); out.close(); in = null; out = null; if (i >= list.length - 1) sendProgress(c.getString(R.string.copied_f, fn) + sizeOfsize(pos, sz_s), (int) (totalBytes * conv)); counter++; } if (move) file.delete(); outFile.setLastModified(last_modified); final int GINGERBREAD = 9; if (android.os.Build.VERSION.SDK_INT >= GINGERBREAD) ForwardCompat.setFullPermissions(outFile); } catch (SecurityException e) { error(c.getString(R.string.sec_err, e.getMessage())); } catch (FileNotFoundException e) { error(c.getString(R.string.not_accs, e.getMessage())); } catch (ClosedByInterruptException e) { error(c.getString(R.string.canceled)); } catch (IOException e) { String msg = e.getMessage(); error(c.getString(R.string.acc_err, uri, msg != null ? msg : "")); } catch (RuntimeException e) { error(c.getString(R.string.rtexcept, uri, e.getMessage())); } finally { try { if (in != null) in.close(); if (out != null) out.close(); if (!move && errMsg != null && outFile != null && !existed) { Log.i(TAG, "Deleting failed output file"); outFile.delete(); } } catch (IOException e) { error(c.getString(R.string.acc_err, uri, e.getMessage())); } } } return counter; }
|
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 boolean connentServer() { boolean result = false; try { ftpClient = new FTPClient(); ftpClient.setDefaultPort(port); ftpClient.setControlEncoding("GBK"); strOut = strOut + "Connecting to host " + host + "\r\n"; ftpClient.connect(host); if (!ftpClient.login(user, password)) return false; FTPClientConfig conf = new FTPClientConfig(getSystemKey(ftpClient.getSystemName())); conf.setServerLanguageCode("zh"); ftpClient.configure(conf); strOut = strOut + "User " + user + " login OK.\r\n"; if (!ftpClient.changeWorkingDirectory(sDir)) { ftpClient.makeDirectory(sDir); ftpClient.changeWorkingDirectory(sDir); } strOut = strOut + "Directory: " + sDir + "\r\n"; ftpClient.setFileType(FTP.BINARY_FILE_TYPE); strOut = strOut + "Connect Success.\r\n"; result = true; } catch (Exception e) { e.printStackTrace(); result = false; } return result; }
|
00
|
Code Sample 1:
public static ContextInfo login(Context pContext, String pUsername, String pPwd, String pDeviceid) { HttpClient lClient = new DefaultHttpClient(); StringBuilder lBuilder = new StringBuilder(); ContextInfo lContextInfo = null; HttpPost lHttpPost = new HttpPost(new StringBuilder().append("http://").append(LoginActivity.mIpAddress.getText().toString()).append("/ZJWHServiceTest/GIS_Duty.asmx/PDALoginCheck").toString()); List<NameValuePair> lNameValuePairs = new ArrayList<NameValuePair>(2); lNameValuePairs.add(new BasicNameValuePair("username", pUsername)); lNameValuePairs.add(new BasicNameValuePair("password", pPwd)); lNameValuePairs.add(new BasicNameValuePair("deviceid", pDeviceid)); try { lHttpPost.setEntity(new UrlEncodedFormEntity(lNameValuePairs)); HttpResponse lResponse = lClient.execute(lHttpPost); BufferedReader lHeader = new BufferedReader(new InputStreamReader(lResponse.getEntity().getContent())); for (String s = lHeader.readLine(); s != null; s = lHeader.readLine()) { lBuilder.append(s); } String lResult = lBuilder.toString(); lResult = DataParseUtil.handleResponse(lResult); lContextInfo = LoginParseUtil.onlineParse(lResult); lContextInfo.setDeviceid(pDeviceid); if (0 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(0); } else if (1 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(1); updateUserInfo(pContext, lContextInfo); } else if (2 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(2); } else if (3 == lContextInfo.getLoginFlag()) { lContextInfo.setLoginFlag(3); } } catch (Exception e) { return lContextInfo; } return lContextInfo; }
Code Sample 2:
private static String createBoundary(int number) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } digest.update(String.valueOf(Math.random()).getBytes()); digest.update(String.valueOf(System.currentTimeMillis()).getBytes()); digest.update(String.valueOf(digest.hashCode()).getBytes()); byte[] bytes = digest.digest(); String paddedNumber = Integer.toString(number); paddedNumber = ("0000000000".substring(0, 10 - paddedNumber.length()) + paddedNumber); StringBuffer buffer = new StringBuffer(); buffer.append("---------------------------------=__"); for (int i = 0; i < 8; i++) { String hex = Integer.toHexString((bytes[i] & 0xff) + 0x100).substring(1); buffer.append(hex); } buffer.append('_'); buffer.append(paddedNumber); return buffer.toString(); }
|
00
|
Code Sample 1:
@Test public void testValidLogConfiguration() throws IOException, IllegalArgumentException { URL url = ClassLoader.getSystemResource(PROPERTIES_FILE_NAME); if (url == null) { throw new IOException("Could not find configuration file " + PROPERTIES_FILE_NAME + " in class path"); } Properties properties = new Properties(); properties.load(url.openStream()); LogLevel logLevel = LogLevel.valueOf((String) properties.get(PROPERTY_KEY_LOGLEVEL)); if (logLevel == null) { throw new IOException("Invalid configuration file " + PROPERTIES_FILE_NAME + ": no entry for " + PROPERTY_KEY_LOGLEVEL); } String loggerIdentifier = "Test logger"; Logger logger = LoggerFactory.getLogger(loggerIdentifier); assertEquals("Logger has wrong log level", logLevel, logger.getLogLevel()); }
Code Sample 2:
public void putFullDirectory(final String ftpURL, final String remoteDir, final String userId, final String pwd, final String localDir) throws Exception { if (!Strings.isPopulated(ftpURL)) { Util.dspmsg("Need an FTP url."); return; } if (!Strings.isPopulated(remoteDir)) { Util.dspmsg("Need a remote directory."); return; } if (!Strings.isPopulated(userId)) { Util.dspmsg("Need a user ID."); return; } if (!Strings.isPopulated(pwd)) { Util.dspmsg("Need a password."); return; } if (!Strings.isPopulated(localDir)) { Util.dspmsg("Need a local directory."); return; } FTPClient c = new FTPClient(); c.connect(ftpURL); int replyCode = c.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { Util.dspmsg("Could not connect, code: " + replyCode); c.disconnect(); return; } if (!c.login(userId, pwd)) { Util.dspmsg("Could not log on, userId: " + userId + " pwd: " + pwd); return; } StringTokenizer st = new StringTokenizer(remoteDir, "/"); while (st.hasMoreElements()) { if (!chgDir(c, st.nextToken())) { return; } } c.setFileType(FTP.BINARY_FILE_TYPE); File file = new File(localDir); if (file.isDirectory()) { FOR: for (File f : file.listFiles()) { if (!put(c, f)) { break FOR; } } } else { put(c, file); } c.logout(); c.disconnect(); }
|
00
|
Code Sample 1:
public String uploadVideo(String ticketId, String filePath) { TreeMap<String, String> uploadParams = new TreeMap<String, String>(); String url = "http://www.vimeo.com/services/upload/"; uploadParams.put("api_key", apiKey); uploadParams.put("auth_token", this.TEMP_AUTH_TOKEN); uploadParams.put("ticket_id", ticketId); uploadParams.put("format", "json"); String signature = this.generateAppSignature(uploadParams); uploadParams.put("api_sig", signature); ClientHttpRequest request = null; try { request = new ClientHttpRequest(new URL(url).openConnection()); } catch (IOException e) { e.printStackTrace(); } for (Entry<String, String> param : uploadParams.entrySet()) { try { request.setParameter(param.getKey(), param.getValue()); } catch (IOException e) { e.printStackTrace(); } } InputStream videoInput = null; try { videoInput = new FileInputStream(filePath); } catch (FileNotFoundException e) { e.printStackTrace(); } try { request.setParameter("video", filePath, videoInput); } catch (IOException e) { e.printStackTrace(); } InputStream response = null; try { response = request.post(); } catch (IOException e) { e.printStackTrace(); } try { InputStreamReader inR = new InputStreamReader(response); BufferedReader buf = new BufferedReader(inR); String line; try { while ((line = buf.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return "hey"; }
Code Sample 2:
@Override public void render(Output output) throws IOException { output.setStatus(headersFile.getStatusCode(), headersFile.getStatusMessage()); for (Entry<String, Set<String>> header : headersFile.getHeadersMap().entrySet()) { Set<String> values = header.getValue(); for (String value : values) { output.addHeader(header.getKey(), value); } } if (file != null) { InputStream inputStream = new FileInputStream(file); try { output.open(); OutputStream out = output.getOutputStream(); IOUtils.copy(inputStream, out); } finally { inputStream.close(); output.close(); } } }
|
11
|
Code Sample 1:
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.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
Code Sample 2:
public void process(Group group, List resourcesName, List excludeResources, ServletContext servletContext, Writer out, String location) throws IOException { LOG.debug("Merging content of group : " + group.getName()); for (Iterator iterator = group.getSubgroups().iterator(); iterator.hasNext(); ) { Group subGroup = (Group) iterator.next(); String subLocation = subGroup.getBestLocation(location); ResourcesProcessor subGroupProcessor = null; if (subGroup.isMinimize() == null) subGroupProcessor = this; else subGroupProcessor = subGroup.getJSProcessor(); subGroupProcessor.process(subGroup, subGroup.getJsNames(), excludeResources, servletContext, out, subLocation); } for (Iterator it = resourcesName.iterator(); it.hasNext(); ) { URL url = null; String path = (String) it.next(); if (!excludeResources.contains(path)) { url = URLUtils.getLocalURL(path, servletContext); if (url == null) { String webPath = URLUtils.concatUrlWithSlaches(group.getBestLocation(location), path); url = URLUtils.getWebUrlResource(webPath); } if (url == null) { throw new IOException("The resources '" + path + "' could not be found neither in the webapp folder nor in a jar"); } InputStream in = null; try { in = url.openStream(); IOUtils.copy(in, out, URLUtils.DEFAULT_ENCODING); out.write("\n\n"); } catch (Exception e) { LOG.error("Merge failed for file " + path, e); } finally { if (in != null) in.close(); } excludeResources.add(path); } } }
|
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 static String hashToMD5(String sig) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(sig.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032X", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } }
|
00
|
Code Sample 1:
public static void copy(File source, File dest) throws BuildException { dest = new File(dest, source.getName()); if (source.isFile()) { byte[] buffer = new byte[4096]; FileInputStream fin = null; FileOutputStream fout = null; try { fin = new FileInputStream(source); fout = new FileOutputStream(dest); int count = 0; while ((count = fin.read(buffer)) > 0) fout.write(buffer, 0, count); fin.close(); fout.close(); } catch (IOException ex) { throw new BuildException(ex); } finally { try { if (fin != null) fin.close(); } catch (IOException ex) { } try { if (fout != null) fout.close(); } catch (IOException ex) { } } } else { dest.mkdirs(); File[] children = source.listFiles(); for (File child : children) copy(child, dest); } }
Code Sample 2:
private InputStream getInputStream(URI uri) throws IOException { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Loading ACL : " + uri.toString()); } URL url = uri.toURL(); URLConnection connection = url.openConnection(); connection.setDoInput(true); return connection.getInputStream(); }
|
11
|
Code Sample 1:
public void testStorageByteArray() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { OutputStream output = r.getOutputStream(); output.write("This is an example".getBytes("UTF-8")); output.write(" and another one.".getBytes("UTF-8")); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and even more."); assertEquals("This is an example and another one. and another line and write some more and even more.", r.getText()); } assertFalse(r.hasEnded()); r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
Code Sample 2:
public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } }
|
11
|
Code Sample 1:
public void covertFile(File file) throws IOException { if (!file.isFile()) { return; } Reader reader = null; OutputStream os = null; File newfile = null; String filename = file.getName(); boolean succeed = false; try { newfile = new File(file.getParentFile(), filename + ".bak"); reader = new InputStreamReader(new FileInputStream(file), fromEncoding); os = new FileOutputStream(newfile); IOUtils.copy(reader, os, toEncoding); } catch (Exception e) { e.printStackTrace(); throw new IOException("Encoding error for file [" + file.getAbsolutePath() + "]"); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } try { file.delete(); succeed = newfile.renameTo(file); } catch (Exception e) { throw new IOException("Clear bak error for file [" + file.getAbsolutePath() + "]"); } if (succeed) { System.out.println("Changed encoding for file [" + file.getAbsolutePath() + "]"); } }
Code Sample 2:
public void objectParserAssesmentItem(int file, int currentquestion, Resource resTemp) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int indexLastSeparator; String sOldPath = ""; try { if (file == 1) { nl = doc.getElementsByTagName("object"); } else { nl = doc_[currentquestion].getElementsByTagName("object"); } for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem("data"); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getFile(); sOldPath = sOldPath.replace('/', File.separatorChar); indexLastSeparator = sOldPath.lastIndexOf(File.separatorChar); String sSourcePath = sOldPath; sFilename = sOldPath.substring(indexLastSeparator + 1); sNewPath = this.sTempLocation + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } if (file == 1) { sXml = sXml.replace(nsrc.getTextContent(), sFilename); } else { sXml_[currentquestion] = sXml_[currentquestion].replace(nsrc.getTextContent(), sFilename); } lsImages.add(sFilename); resTemp.addFile(sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
@SuppressWarnings("unchecked") public static void unzip(String input, String output) { try { if (!output.endsWith("/")) output = output + "/"; ZipFile zip = new ZipFile(input); Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { FileUtils.forceMkdir(new File(output + entry.getName())); } else { FileOutputStream out = new FileOutputStream(output + entry.getName()); IOUtils.copy(zip.getInputStream(entry), out); IOUtils.closeQuietly(out); } } } catch (Exception e) { log.error("�����ҵ��ļ�:" + output, e); throw new RuntimeException("�����ҵ��ļ�:" + output, e); } }
Code Sample 2:
public boolean open(String mode) { if (source instanceof String) return false; else if (mode == null) mode = ""; else mode = mode.toLowerCase(); boolean toread = false, towrite = false; if (mode.indexOf("r") >= 0) toread = true; if (mode.indexOf("w") >= 0) towrite = true; if (!toread && !towrite) toread = towrite = true; try { if (toread && input == null) { if (isDirectory()) return true; else if (reader != null) return true; else if (source instanceof File) input = new FileInputStream((File) source); else if (source instanceof Socket) input = ((Socket) source).getInputStream(); else if (source instanceof URL) return getUrlInfo(toread, towrite); else return false; } if (towrite && output == null) { if (isDirectory()) return false; else if (writer != null) return true; else if (source instanceof File) output = new FileOutputStream((File) source); else if (source instanceof Socket) output = ((Socket) source).getOutputStream(); else if (source instanceof URL) return getUrlInfo(toread, towrite); else return false; } return true; } catch (Exception e) { return false; } }
|
11
|
Code Sample 1:
public static void decryptFile(String input, String output, String pwd) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(input), cipher); out = new FileOutputStream(output); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.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!"); }
|
00
|
Code Sample 1:
public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException { boolean bMatch = false; try { String strSalt = (String) salt; byte[] baSalt = Hex.decodeHex(strSalt.toCharArray()); MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(rawPass.getBytes(CHAR_ENCODING)); md.update(baSalt); byte[] baCalculatedHash = md.digest(); byte[] baStoredHash = Hex.decodeHex(encPass.toCharArray()); bMatch = MessageDigest.isEqual(baCalculatedHash, baStoredHash); } catch (Exception e) { e.printStackTrace(); } return bMatch; }
Code Sample 2:
public static String submitURLRequest(String url) throws HttpException, IOException, URISyntaxException { HttpClient httpclient = new DefaultHttpClient(); InputStream stream = null; user_agents = new LinkedList<String>(); user_agents.add("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); String response_text = ""; URI uri = new URI(url); HttpGet post = new HttpGet(uri); int MAX = user_agents.size() - 1; int index = (int) Math.round(((double) Math.random() * (MAX))); String agent = user_agents.get(index); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, agent); httpclient.getParams().setParameter("User-Agent", agent); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.ACCEPT_NONE); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { stream = entity.getContent(); response_text = convertStreamToString(stream); } httpclient.getConnectionManager().shutdown(); if (stream != null) { stream.close(); } return response_text; }
|
11
|
Code Sample 1:
public String digestResponse() { String digest = null; if (null == nonce) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] d = md.digest(); if (null != algorithm && -1 != (algorithm.toLowerCase()).indexOf("md5-sess")) { md = MessageDigest.getInstance("MD5"); md.update(d); md.update(":".getBytes()); md.update(nonce.getBytes()); md.update(":".getBytes()); md.update(cnonce.getBytes()); d = md.digest(); } byte[] a1 = bytesToHex(d); md = MessageDigest.getInstance("MD5"); md.update(method.getBytes()); md.update(":".getBytes()); md.update(uri.getBytes()); d = md.digest(); byte[] a2 = bytesToHex(d); md = MessageDigest.getInstance("MD5"); md.update(a1); md.update(":".getBytes()); md.update(nonce.getBytes()); md.update(":".getBytes()); if (null != qop) { md.update(nonceCount.getBytes()); md.update(":".getBytes()); md.update(cnonce.getBytes()); md.update(":".getBytes()); md.update(qop.getBytes()); md.update(":".getBytes()); } md.update(a2); d = md.digest(); byte[] r = bytesToHex(d); digest = new String(r); } catch (Exception e) { e.printStackTrace(); } return digest; }
Code Sample 2:
public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; }
|
00
|
Code Sample 1:
public static String getHash(String input) { MessageDigest m; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } m.update(input.getBytes(), 0, input.length()); return new BigInteger(1, m.digest()).toString(16); }
Code Sample 2:
public static String getDocumentAsString(URL url) throws IOException { StringBuffer result = new StringBuffer(); InputStream inStream = url.openStream(); int character; while ((character = inStream.read()) != -1) { result.append((char) character); } return result.toString(); }
|
00
|
Code Sample 1:
public RemotePolicyMigrator createRemotePolicyMigrator() { return new RemotePolicyMigrator() { public String migratePolicy(InputStream stream, String url) throws ResourceMigrationException, IOException { ByteArrayOutputCreator oc = new ByteArrayOutputCreator(); IOUtils.copyAndClose(stream, oc.getOutputStream()); return oc.getOutputStream().toString(); } }; }
Code Sample 2:
protected String readUrl(String urlString) throws IOException { URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String response = ""; String inputLine; while ((inputLine = in.readLine()) != null) response += inputLine; in.close(); return response; }
|
00
|
Code Sample 1:
public static byte[] post(String path, Map<String, String> params, String encode) throws Exception { StringBuilder parambuilder = new StringBuilder(""); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { parambuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&"); } parambuilder.deleteCharAt(parambuilder.length() - 1); } byte[] data = parambuilder.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(5 * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); conn.setRequestProperty("Accept-Language", "zh-CN"); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); conn.setRequestProperty("Connection", "Keep-Alive"); DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { return StreamTool.readInputStream(conn.getInputStream()); } return null; }
Code Sample 2:
public static String getMD5(String password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] b = md.digest(); StringBuffer sb = new StringBuffer(); for (byte aB : b) { sb.append((Integer.toHexString((aB & 0xFF) | 0x100)).substring(1, 3)); } return sb.toString(); }
|
00
|
Code Sample 1:
@Override public void alterar(QuestaoMultiplaEscolha q) throws Exception { PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoMultiplaEscolha(q); } catch (SQLException e) { conexao.rollback(); throw e; } }
Code Sample 2:
public static void copyFile(String input, String output) { try { File inputFile = new File(input); File outputFile = new File(output); FileReader in; in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
|
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:
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:
private String unzip(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
Code Sample 2:
public static double getPrice(final String ticker) { try { final URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + ticker); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); reader.readLine(); final String data = reader.readLine(); System.out.println("Results of data: " + data); final String[] dataItems = data.split(","); return Double.parseDouble(dataItems[dataItems.length - 1]); } catch (Exception ex) { throw new RuntimeException(ex); } }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { if (args.length == 0) { System.out.println("Usage: \nGZIPcompress file\n" + "\tUses GZIP compression to compress " + "the file to test.gz"); System.exit(1); } BufferedReader in = new BufferedReader(new FileReader(args[0])); BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("test.gz"))); System.out.println("Writing file"); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); System.out.println("Reading file"); BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("test.gz")))); String s; while ((s = in2.readLine()) != null) System.out.println(s); }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
11
|
Code Sample 1:
public String merge(int width, int height) throws Exception { htErrors.clear(); sendGetImageRequests(width, height); Vector files = new Vector(); ConcurrentHTTPTransactionHandler c = new ConcurrentHTTPTransactionHandler(); c.setCache(cache); c.checkIfModified(false); for (int i = 0; i < vImageUrls.size(); i++) { if ((String) vImageUrls.get(i) != null) { c.register((String) vImageUrls.get(i)); } else { } } c.doTransactions(); vTransparency = new Vector(); for (int i = 0; i < vImageUrls.size(); i++) { if (vImageUrls.get(i) != null) { String path = c.getResponseFilePath((String) vImageUrls.get(i)); if (path != null) { String contentType = c.getHeaderValue((String) vImageUrls.get(i), "content-type"); if (contentType.startsWith("image")) { files.add(path); vTransparency.add(htTransparency.get(vRank.get(i))); } } } } if (files.size() > 1) { File output = TempFiles.getFile(); String path = output.getPath(); ImageMerger.mergeAndSave(files, vTransparency, path, ImageMerger.GIF); imageName = output.getName(); imagePath = output.getPath(); return (imageName); } else if (files.size() == 1) { File f = new File((String) files.get(0)); File out = TempFiles.getFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out)); byte buf[] = new byte[1024]; for (int nRead; (nRead = is.read(buf, 0, 1024)) > 0; os.write(buf, 0, nRead)) ; os.flush(); os.close(); is.close(); imageName = out.getName(); return imageName; } else return ""; }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public static void main(String[] args) { String command = "java -jar "; String linkerJarPath = ""; String path = ""; String osName = System.getProperty("os.name"); String temp = Launcher.class.getResource("").toString(); int index = temp.indexOf(".jar"); int start = index - 1; while (Character.isLetter(temp.charAt(start))) { start--; } String jarName = temp.substring(start + 1, index + 4); System.out.println(jarName); if (osName.startsWith("Linux")) { temp = temp.substring(temp.indexOf("/"), temp.indexOf(jarName)); } else if (osName.startsWith("Windows")) { temp = temp.substring(temp.indexOf("file:") + 5, temp.indexOf(jarName)); } else { System.exit(0); } path = path + temp; try { path = java.net.URLDecoder.decode(path, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File dir = new File(path); File[] files = dir.listFiles(); String exeJarName = null; for (File f : files) { if (f.getName().endsWith(".jar") && !f.getName().startsWith(jarName)) { exeJarName = f.getName(); break; } } if (exeJarName == null) { System.out.println("no exefile"); System.exit(0); } linkerJarPath = path + exeJarName; String pluginDirPath = path + "plugin" + File.separator; File[] plugins = new File(pluginDirPath).listFiles(); StringBuffer pluginNames = new StringBuffer(""); for (File plugin : plugins) { if (plugin.getAbsolutePath().endsWith(".jar")) { pluginNames.append("plugin/" + plugin.getName() + " "); } } String libDirPath = path + "lib" + File.separator; File[] libs = new File(libDirPath).listFiles(); StringBuffer libNames = new StringBuffer(""); for (File lib : libs) { if (lib.getAbsolutePath().endsWith(".jar")) { libNames.append("lib/" + lib.getName() + " "); } } try { JarFile jarFile = new JarFile(linkerJarPath); Manifest manifest = jarFile.getManifest(); if (manifest == null) { manifest = new Manifest(); } Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Class-Path", pluginNames.toString() + libNames.toString()); String backupFile = linkerJarPath + "back"; FileInputStream copyInput = new FileInputStream(linkerJarPath); FileOutputStream copyOutput = new FileOutputStream(backupFile); byte[] buffer = new byte[4096]; int s; while ((s = copyInput.read(buffer)) > -1) { copyOutput.write(buffer, 0, s); } copyOutput.flush(); copyOutput.close(); copyInput.close(); JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(linkerJarPath), manifest); JarInputStream jarIn = new JarInputStream(new FileInputStream(backupFile)); byte[] buf = new byte[4096]; JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue; jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } jarOut.flush(); jarOut.close(); jarIn.close(); File file = new File(backupFile); if (file.exists()) { file.delete(); } } catch (IOException e1) { e1.printStackTrace(); } try { if (System.getProperty("os.name").startsWith("Linux")) { Runtime runtime = Runtime.getRuntime(); String[] commands = new String[] { "java", "-jar", path + exeJarName }; runtime.exec(commands); } else { path = path.substring(1); command = command + "\"" + path + exeJarName + "\""; System.out.println(command); Runtime.getRuntime().exec(command); } } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
Code Sample 2:
public void migrate(InputMetadata meta, InputStream input, OutputCreator outputCreator) throws IOException, ResourceMigrationException { RestartInputStream restartInput = new RestartInputStream(input); Match match = resourceIdentifier.identifyResource(meta, restartInput); restartInput.restart(); if (match != null) { reporter.reportNotification(notificationFactory.createLocalizedNotification(NotificationType.INFO, "migration-resource-migrating", new Object[] { meta.getURI(), match.getTypeName(), match.getVersionName() })); processMigrationSteps(match, restartInput, outputCreator); } else { reporter.reportNotification(notificationFactory.createLocalizedNotification(NotificationType.INFO, "migration-resource-copying", new Object[] { meta.getURI() })); IOUtils.copyAndClose(restartInput, outputCreator.createOutputStream()); } }
|
11
|
Code Sample 1:
private final void saveCopy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } to = null; from = null; }
Code Sample 2:
public static void uncompress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new GZIPInputStream(new FileInputStream(srcFile)); output = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
|
00
|
Code Sample 1:
public static void decompressFile(File f) throws IOException { File target = new File(f.toString().substring(0, f.toString().length() - 3)); System.out.print("Decompressing: " + f.getName() + ".. "); long initialSize = f.length(); GZIPInputStream in = new GZIPInputStream(new FileInputStream(f)); FileOutputStream fos = new FileOutputStream(target); byte[] buf = new byte[1024]; int read; while ((read = in.read(buf)) != -1) { fos.write(buf, 0, read); } System.out.println("Done."); fos.close(); in.close(); long endSize = target.length(); System.out.println("Initial size: " + initialSize + "; Decompressed size: " + endSize); }
Code Sample 2:
public int instantiate(int objectId, String description) throws FidoDatabaseException, ObjectNotFoundException, ClassLinkTypeNotFoundException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into Objects (Description) " + "values ('" + description + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, objectId) == false) throw new ObjectNotFoundException(objectId); stmt.executeUpdate(sql); int id; sql = "select currval('objects_objectid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); ObjectLinkTable objectLinkList = new ObjectLinkTable(); objectLinkList.linkObjects(stmt, id, "instance", objectId); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
|
00
|
Code Sample 1:
private synchronized void createFTPConnection() throws RemoteClientException { ftpClient = new FTPClient(); try { URL url = fileset.getHostURL(); PasswordAuthentication passwordAuthentication = fileset.getPasswordAuthentication(); if (null == passwordAuthentication) { passwordAuthentication = anonPassAuth; } InetAddress inetAddress = InetAddress.getByName(url.getHost()); if (url.getPort() == -1) { ftpClient.connect(inetAddress); } else { ftpClient.connect(inetAddress, url.getPort()); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new FTPBrowseException(ftpClient.getReplyString()); } ftpClient.login(passwordAuthentication.getUserName(), new StringBuffer().append(passwordAuthentication.getPassword()).toString()); if (url.getPath().length() > 0) { ftpClient.changeWorkingDirectory(url.getPath()); } } catch (UnknownHostException e) { throw new RemoteClientException("Host not found.", e); } catch (SocketException e) { throw new RemoteClientException("Socket cannot be opened.", e); } catch (IOException e) { throw new RemoteClientException("Socket cannot be opened.", e); } }
Code Sample 2:
public static void main(String[] args) { File file = null; try { file = File.createTempFile("TestFileChannel", ".dat"); final ByteBuffer buffer = ByteBuffer.allocateDirect(4); final ByteChannel output = new FileOutputStream(file).getChannel(); buffer.putInt(MAGIC_INT); buffer.flip(); output.write(buffer); output.close(); final ByteChannel input = new FileInputStream(file).getChannel(); buffer.clear(); while (buffer.hasRemaining()) { input.read(buffer); } input.close(); buffer.flip(); final int file_int = buffer.getInt(); if (file_int != MAGIC_INT) { System.out.println("TestFileChannel FAILURE"); System.out.println("Wrote " + Integer.toHexString(MAGIC_INT) + " but read " + Integer.toHexString(file_int)); } else { System.out.println("TestFileChannel SUCCESS"); } } catch (Exception e) { System.out.println("TestFileChannel FAILURE"); e.printStackTrace(System.out); } finally { if (null != file) { file.delete(); } } }
|
00
|
Code Sample 1:
public boolean updateLOB(String sql, int displayType, Object value, String trxName, SecurityToken token) { validateSecurityToken(token); if (sql == null || value == null) { log.fine("No sql or data"); return false; } log.fine(sql); Trx trx = null; if (trxName != null && trxName.trim().length() > 0) { trx = Trx.get(trxName, false); if (trx == null) throw new RuntimeException("Transaction lost - " + trxName); } m_updateLOBCount++; boolean success = true; Connection con = trx != null ? trx.getConnection() : DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); PreparedStatement pstmt = null; try { pstmt = con.prepareStatement(sql); if (displayType == DisplayType.TextLong) pstmt.setString(1, (String) value); else pstmt.setBytes(1, (byte[]) value); int no = pstmt.executeUpdate(); } catch (Exception e) { log.log(Level.FINE, sql, e); success = false; } finally { DB.close(pstmt); pstmt = null; } if (success && trx == null) { try { con.commit(); } catch (Exception e) { log.log(Level.SEVERE, "commit", e); success = false; } finally { try { con.close(); } catch (SQLException e) { } con = null; } } if (!success) { log.severe("rollback"); if (trx == null) { try { con.rollback(); } catch (Exception ee) { log.log(Level.SEVERE, "rollback", ee); } finally { try { con.close(); } catch (SQLException e) { } con = null; } } else { trx.rollback(); } } return success; }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
|
00
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
Code Sample 2:
public HttpResponse navigateTo(URI url) { log.debug("navigateTo: " + url.toString()); HttpGet get = new HttpGet(url); try { HttpResponse response = client.execute(get); log.debug(response.getStatusLine()); return response; } catch (ClientProtocolException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } }
|
00
|
Code Sample 1:
@Override public long insertStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); long result = statement.executeUpdate(sql.toString()); if (result == 0) log.warn(sql + " result row count is 0"); getConnection().commit(); return getInsertId(statement); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); throw new RuntimeException(); } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
Code Sample 2:
public static synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
|
00
|
Code Sample 1:
public void run() { FTPClient ftp = null; try { StarkHhDownloaderEtcProperties etcProperties = new StarkHhDownloaderEtcProperties(getUri()); StarkHhDownloaderVarProperties varProperties = new StarkHhDownloaderVarProperties(getUri()); ftp = new FTPClient(); int reply; ftp.connect(etcProperties.getHostname()); log("Connecting to ftp server at " + etcProperties.getHostname() + "."); log("Server replied with '" + ftp.getReplyString() + "'."); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw UserException.newOk("FTP server refused connection."); } log("Connected to server, now logging in."); ftp.login(etcProperties.getUsername(), etcProperties.getPassword()); log("Server replied with '" + ftp.getReplyString() + "'."); List<String> directories = etcProperties.getDirectories(); for (int i = 0; i < directories.size(); i++) { log("Checking the directory '" + directories.get(i) + "'."); boolean found = false; FTPFile[] filesArray = ftp.listFiles(directories.get(i)); List<FTPFile> files = Arrays.asList(filesArray); Collections.sort(files, new Comparator<FTPFile>() { public int compare(FTPFile file1, FTPFile file2) { if (file2.getTimestamp().getTime().equals(file1.getTimestamp().getTime())) { return file2.getName().compareTo(file1.getName()); } else { return file1.getTimestamp().getTime().compareTo(file2.getTimestamp().getTime()); } } }); for (FTPFile file : files) { if (file.getType() == FTPFile.FILE_TYPE && (varProperties.getLastImportDate(i) == null ? true : (file.getTimestamp().getTime().equals(varProperties.getLastImportDate(i).getDate()) ? file.getName().compareTo(varProperties.getLastImportName(i)) < 0 : file.getTimestamp().getTime().after(varProperties.getLastImportDate(i).getDate())))) { String fileName = directories.get(i) + "\\" + file.getName(); if (file.getSize() == 0) { log("Ignoring '" + fileName + "'because it has zero length"); } else { log("Attempting to download '" + fileName + "'."); InputStream is = ftp.retrieveFileStream(fileName); if (is == null) { reply = ftp.getReplyCode(); throw UserException.newOk("Can't download the file '" + file.getName() + "', server says: " + reply + "."); } log("File stream obtained successfully."); hhImporter = new HhDataImportProcess(getContract().getId(), new Long(0), is, fileName + ".df2", file.getSize()); hhImporter.run(); List<VFMessage> messages = hhImporter.getMessages(); hhImporter = null; if (messages.size() > 0) { for (VFMessage message : messages) { log(message.getDescription()); } throw UserException.newInvalidParameter("Problem loading file."); } } if (!ftp.completePendingCommand()) { throw UserException.newOk("Couldn't complete ftp transaction: " + ftp.getReplyString()); } varProperties.setLastImportDate(i, new MonadDate(file.getTimestamp().getTime())); varProperties.setLastImportName(i, file.getName()); found = true; } } if (!found) { log("No new files found."); } } } catch (UserException e) { try { log(e.getVFMessage().getDescription()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (IOException e) { try { log(e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (Throwable e) { try { log("Exception: " + e.getClass().getName() + " Message: " + e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } ChellowLogger.getLogger().logp(Level.SEVERE, "ContextListener", "contextInitialized", "Can't initialize context.", e); } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); log("Logged out."); } catch (IOException ioe) { } catch (ProgrammerException e) { } catch (UserException e) { } } } }
Code Sample 2:
public static synchronized String getMD5_Base64(String input) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(input.getBytes("UTF-8")); } catch (java.io.UnsupportedEncodingException ex) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] rawData = msgDigest.digest(); byte[] encoded = Base64.encodeBase64(rawData); String retValue = new String(encoded); return retValue; }
|
11
|
Code Sample 1:
private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); }
Code Sample 2:
public boolean saveLecturerecordingsXMLOnWebserver() { boolean error = false; FTPClient ftp = new FTPClient(); String lecture = ""; try { URL url = new URL("http://localhost:8080/virtPresenterVerwalter/lecturerecordings.jsp?seminarid=" + this.getSeminarID()); HttpURLConnection http = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream())); String zeile = ""; while ((zeile = in.readLine()) != null) { lecture += zeile + "\n"; } in.close(); http.disconnect(); } catch (Exception e) { System.err.println("Konnte lecturerecordings.xml nicht lesen."); } try { int reply; ftp.connect(this.getWebserver().getUrl()); System.out.println("Connected to " + this.getWebserver().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } if (!ftp.login(this.getWebserver().getFtpBenutzer(), this.getWebserver().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String tmpSeminarID = this.getSeminarID(); if (tmpSeminarID == null) tmpSeminarID = "unbekannt"; try { ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); } catch (Exception e) { ftp.makeDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ByteArrayInputStream lectureIn = new ByteArrayInputStream(lecture.getBytes()); System.err.println("FTP Verzeichnis: " + ftp.printWorkingDirectory()); ftp.storeFile("lecturerecordings.xml", lectureIn); lectureIn.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei lecturerecordings.xml konnte nicht auf Webserver kopiert werden."); error = true; e.printStackTrace(); } catch (NullPointerException e) { System.err.println("Job " + this.getId() + ": Datei lecturerecordings.xml konnte nicht auf Webserver kopiert werden. (Kein Webserver zugewiesen)"); error = true; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return error; }
|
11
|
Code Sample 1:
private static void processFile(String file) throws IOException { FileInputStream in = new FileInputStream(file); int read = 0; byte[] buf = new byte[2048]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while ((read = in.read(buf)) > 0) bout.write(buf, 0, read); in.close(); String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\""); FileOutputStream out = new FileOutputStream(file); out.write(converted.getBytes()); out.close(); }
Code Sample 2:
public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
|
00
|
Code Sample 1:
public boolean implies(Permission permission) { if (!permissionClass.isInstance(permission)) { return false; } GCFPermission perm = (GCFPermission) permission; int perm_low = perm.getMinPort(); int perm_high = perm.getMaxPort(); Enumeration search = permissions.elements(); int count = permissions.size(); int port_low[] = new int[count]; int port_high[] = new int[count]; int port_range_count = 0; while (search.hasMoreElements()) { GCFPermission cur_perm = (GCFPermission) search.nextElement(); if (cur_perm.impliesByHost(perm)) { if (cur_perm.impliesByPorts(perm)) { return true; } port_low[port_range_count] = cur_perm.getMinPort(); port_high[port_range_count] = cur_perm.getMaxPort(); port_range_count++; } } for (int i = 0; i < port_range_count; i++) { for (int j = 0; j < port_range_count - 1; j++) { if (port_low[j] > port_low[j + 1]) { int tmp = port_low[j]; port_low[j] = port_low[j + 1]; port_low[j + 1] = tmp; tmp = port_high[j]; port_high[j] = port_high[j + 1]; port_high[j + 1] = tmp; } } } int current_low = port_low[0]; int current_high = port_high[0]; for (int i = 1; i < port_range_count; i++) { if (port_low[i] > current_high + 1) { if (current_low <= perm_low && current_high >= perm_high) { return true; } if (perm_low <= current_high) { return false; } current_low = port_low[i]; current_high = port_high[i]; } else { if (current_high < port_high[i]) { current_high = port_high[i]; } } } return (current_low <= perm_low && current_high >= perm_high); }
Code Sample 2:
@Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } }
|
11
|
Code Sample 1:
private static void convertToOnline(final String filePath, final DocuBean docuBean) throws Exception { File source = new File(filePath + File.separator + docuBean.getFileName()); File dir = new File(filePath + File.separator + docuBean.getId()); if (!dir.exists()) { dir.mkdir(); } File in = source; boolean isSpace = false; if (source.getName().indexOf(" ") != -1) { in = new File(StringUtils.replace(source.getName(), " ", "")); try { IOUtils.copyFile(source, in); } catch (IOException e) { e.printStackTrace(); } isSpace = true; } File finalPdf = null; try { String outPath = dir.getAbsolutePath(); final File pdf = DocViewerConverter.toPDF(in, outPath); convertToSwf(pdf, outPath, docuBean); finalPdf = new File(outPath + File.separator + FileUtils.getFilePrefix(StringUtils.replace(source.getName(), " ", "")) + "_decrypted.pdf"); if (!finalPdf.exists()) { finalPdf = pdf; } pdfByFirstPageToJpeg(finalPdf, outPath, docuBean); if (docuBean.getSuccess() == 2 && dir.listFiles().length < 2) { docuBean.setSuccess(3); } } catch (Exception e) { throw e; } finally { if (isSpace) { IOUtils.delete(in); } } }
Code Sample 2:
public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } }
|
00
|
Code Sample 1:
public static File copyFile(File from, File to) throws IOException { FileOutputStream fos = new FileOutputStream(to); FileInputStream fis = new FileInputStream(from); FileChannel foc = fos.getChannel(); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return to; }
Code Sample 2:
public static String getMD5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); String salt = "UseTheForce4"; password = salt + password; md5.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, md5.digest()).toString(16); } catch (Exception e) { } return password; }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException, ClassNotFoundException { URL urlServlet = null; try { urlServlet = new URL("http://wofproj.appspot.com/test"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection con = null; try { con = urlServlet.openConnection(); } catch (IOException e) { e.printStackTrace(); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-java-serialized-object"); OutputStream outstream = con.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outstream); oos.writeObject("tom"); oos.flush(); oos.close(); InputStream instr = con.getInputStream(); ObjectInputStream inputFromServlet = new ObjectInputStream(instr); Object retval = inputFromServlet.readObject(); inputFromServlet.close(); instr.close(); System.out.println(retval.getClass().toString()); }
Code Sample 2:
public byte[] read(IFile input) { InputStream contents = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); contents = input.getContents(); IOUtils.copy(contents, baos); return baos.toByteArray(); } catch (IOException e) { Activator.logUnexpected(null, e); } catch (CoreException e) { Activator.logUnexpected(null, e); } finally { IOUtils.closeQuietly(contents); } return null; }
|
11
|
Code Sample 1:
public static String md5(String value) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); try { messageDigest.update(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { messageDigest.update(value.getBytes()); } byte[] bytes = messageDigest.digest(); return byteArrayToHexString(bytes); }
Code Sample 2:
private String computeHash(String str) { StringBuffer hexBuffer = new StringBuffer(); byte[] bytes; int i; try { MessageDigest hashAlgorithm = MessageDigest.getInstance(hashAlgorithmName); hashAlgorithm.reset(); hashAlgorithm.update(str.getBytes()); bytes = hashAlgorithm.digest(); } catch (NoSuchAlgorithmException e) { return null; } for (i = 0; i < bytes.length; i++) hexBuffer.append(((bytes[i] >= 0 && bytes[i] <= 15) ? "0" : "") + Integer.toHexString(bytes[i] & 0xFF)); return hexBuffer.toString(); }
|
11
|
Code Sample 1:
public void transaction() { String delPets = "delete from PETS where PERSON_ID = 1"; String delPersons = "delete from PERSONS where PERSON_ID = 1"; if (true) { System.out.println(delPets); System.out.println(delPersons); } Connection conn = null; Statement stmt = null; try { conn = ConnHelper.getConnectionByDriverManager(); conn.setAutoCommit(false); stmt = conn.createStatement(); int affectedRows = stmt.executeUpdate(delPets); System.out.println("affectedRows = " + affectedRows); if (true) { throw new SQLException("fasfdsaf"); } affectedRows = stmt.executeUpdate(delPersons); System.out.println("affectedRows = " + affectedRows); conn.commit(); conn.setAutoCommit(true); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e.printStackTrace(System.out); } e.printStackTrace(System.out); } finally { ConnHelper.close(conn, stmt, null); } }
Code Sample 2:
public void importarHistoricoDeProventos(File pArquivoXLS, boolean pFiltrarPelaDataDeCorteDoCabecalho, Andamento pAndamento) throws IOException, SQLException, InvalidFormatException { int iLinha = -1; String nomeDaColuna = ""; Statement stmtLimpezaInicialDestino = null; OraclePreparedStatement stmtDestino = null; try { Workbook arquivo = WorkbookFactory.create(new FileInputStream(pArquivoXLS)); Sheet plan1 = arquivo.getSheetAt(0); int QUANTIDADE_DE_REGISTROS_DE_METADADOS = 2; int quantidadeDeRegistrosEstimada = plan1.getPhysicalNumberOfRows() - QUANTIDADE_DE_REGISTROS_DE_METADADOS; String vNomeDePregao, vTipoDaAcao, vDataDaAprovacao, vTipoDoProvento, vDataDoUltimoPrecoCom; BigDecimal vValorDoProvento, vUltimoPrecoCom, vProventoPorPreco; int vProventoPor1Ou1000Acoes, vPrecoPor1Ou1000Acoes; java.sql.Date vUltimoDiaCom; DateFormat formatadorData = new SimpleDateFormat("yyyyMMdd"); DateFormat formatadorPadraoData = DateFormat.getDateInstance(); Row registro; Cell celula; java.util.Date dataLimite = plan1.getRow(0).getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getDateCellValue(); Cell celulaUltimoDiaCom; java.util.Date tmpUltimoDiaCom; stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_PROVENTO_EM_DINHEIRO"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "INSERT INTO TMP_TB_PROVENTO_EM_DINHEIRO(NOME_DE_PREGAO, TIPO_DA_ACAO, DATA_DA_APROVACAO, VALOR_DO_PROVENTO, PROVENTO_POR_1_OU_1000_ACOES, TIPO_DO_PROVENTO, ULTIMO_DIA_COM, DATA_DO_ULTIMO_PRECO_COM, ULTIMO_PRECO_COM, PRECO_POR_1_OU_1000_ACOES, PERC_PROVENTO_POR_PRECO) VALUES(:NOME_DE_PREGAO, :TIPO_DA_ACAO, :DATA_DA_APROVACAO, :VALOR_DO_PROVENTO, :PROVENTO_POR_1_OU_1000_ACOES, :TIPO_DO_PROVENTO, :ULTIMO_DIA_COM, :DATA_DO_ULTIMO_PRECO_COM, :ULTIMO_PRECO_COM, :PRECO_POR_1_OU_1000_ACOES, :PERC_PROVENTO_POR_PRECO)"; stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportados = 0; final int NUMERO_DA_LINHA_INICIAL = 1; for (iLinha = NUMERO_DA_LINHA_INICIAL; true; iLinha++) { registro = plan1.getRow(iLinha); if (registro != null) { nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.toString(); celulaUltimoDiaCom = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.ordinal()); if (celulaUltimoDiaCom != null) { if (celulaUltimoDiaCom.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpUltimoDiaCom = celulaUltimoDiaCom.getDateCellValue(); if (tmpUltimoDiaCom.compareTo(dataLimite) <= 0 || !pFiltrarPelaDataDeCorteDoCabecalho) { vUltimoDiaCom = new java.sql.Date(celulaUltimoDiaCom.getDateCellValue().getTime()); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.toString(); vNomeDePregao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.toString(); vTipoDaAcao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.ordinal()); try { java.util.Date tmpDataDaAprovacao; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDaAprovacao = celula.getDateCellValue(); } else { tmpDataDaAprovacao = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDaAprovacao = formatadorData.format(tmpDataDaAprovacao); } catch (ParseException ex) { vDataDaAprovacao = celula.getStringCellValue(); } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.toString(); vValorDoProvento = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.toString(); vProventoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.toString(); vTipoDoProvento = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.ordinal()); if (celula != null) { try { java.util.Date tmpDataDoUltimoPrecoCom; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDoUltimoPrecoCom = celula.getDateCellValue(); } else { tmpDataDoUltimoPrecoCom = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDoUltimoPrecoCom = formatadorData.format(tmpDataDoUltimoPrecoCom); } catch (ParseException ex) { vDataDoUltimoPrecoCom = celula.getStringCellValue().trim(); } } else { vDataDoUltimoPrecoCom = ""; } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.toString(); vUltimoPrecoCom = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.toString(); vPrecoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.ordinal()); if (celula != null && celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { vProventoPorPreco = new BigDecimal(String.valueOf(celula.getNumericCellValue())); } else { vProventoPorPreco = null; } stmtDestino.clearParameters(); stmtDestino.setStringAtName("NOME_DE_PREGAO", vNomeDePregao); stmtDestino.setStringAtName("TIPO_DA_ACAO", vTipoDaAcao); stmtDestino.setStringAtName("DATA_DA_APROVACAO", vDataDaAprovacao); stmtDestino.setBigDecimalAtName("VALOR_DO_PROVENTO", vValorDoProvento); stmtDestino.setIntAtName("PROVENTO_POR_1_OU_1000_ACOES", vProventoPor1Ou1000Acoes); stmtDestino.setStringAtName("TIPO_DO_PROVENTO", vTipoDoProvento); stmtDestino.setDateAtName("ULTIMO_DIA_COM", vUltimoDiaCom); stmtDestino.setStringAtName("DATA_DO_ULTIMO_PRECO_COM", vDataDoUltimoPrecoCom); stmtDestino.setBigDecimalAtName("ULTIMO_PRECO_COM", vUltimoPrecoCom); stmtDestino.setIntAtName("PRECO_POR_1_OU_1000_ACOES", vPrecoPor1Ou1000Acoes); stmtDestino.setBigDecimalAtName("PERC_PROVENTO_POR_PRECO", vProventoPorPreco); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; } } } else { break; } double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } else { break; } } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = pArquivoXLS.getName(); problemaDetalhado.linhaProblematicaDoArquivo = iLinha + 1; problemaDetalhado.colunaProblematicaDoArquivo = nomeDaColuna; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { pAndamento.setPercentualCompleto(100); if (stmtLimpezaInicialDestino != null && (!stmtLimpezaInicialDestino.isClosed())) { stmtLimpezaInicialDestino.close(); } if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } }
|
11
|
Code Sample 1:
private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(RuleParameter.MODIFICATION_EXCLUDES_DEFAULT.getValue()); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true, new AttackMailHandler()); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(RuleParameter.RESPONSE_MODIFICATIONS_DEFAULT.getValue()); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List<Pattern> tmpPatternsToExcludeCompleteTag = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeCompleteScript = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeLinksWithinScripts = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeLinksWithinTags = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToCaptureLinksWithinScripts = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToCaptureLinksWithinTags = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeCompleteTag = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeCompleteScript = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeLinksWithinTags = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToCaptureLinksWithinTags = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<Integer[]> tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList<Integer[]>(responseModificationDefinitions.length); final List<Integer[]> tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList<Integer[]>(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
Code Sample 2:
@Override void execute(Connection conn, Component parent, String context, ProgressMonitor progressBar, ProgressWrapper progressWrapper) throws Exception { Statement statement = null; try { conn.setAutoCommit(false); statement = conn.createStatement(); String deleteSql = getDeleteSql(m_compositionId); statement.executeUpdate(deleteSql); conn.commit(); s_compostionCache.delete(new Integer(m_compositionId)); } catch (SQLException ex) { try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } throw ex; } finally { if (statement != null) { statement.close(); } } }
|
00
|
Code Sample 1:
public void updateComponent(int id, int quantity) throws SQLException { Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(this.jdbcURL); connection.setAutoCommit(false); String query = "UPDATE components SET quantity=quantity+? WHERE comp_id=?"; ps = connection.prepareStatement(query); ps.setInt(1, quantity); ps.setInt(2, id); ps.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { connection.close(); } catch (Exception ex) { } try { ps.close(); } catch (Exception ex) { } } }
Code Sample 2:
public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
11
|
Code Sample 1:
public String hash(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { log.info("No sha-256 available"); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.fatal("sha-1 is not available", e); throw new RuntimeException("Couldn't get a hash algorithm from Java"); } } try { digest.reset(); digest.update((salt + password).getBytes("UTF-8")); byte hash[] = digest.digest(); return new String(Base64.encodeBase64(hash, false)); } catch (Throwable t) { throw new RuntimeException("Couldn't hash password"); } }
Code Sample 2:
public static String hexMD5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(value.getBytes("utf-8")); byte[] digest = messageDigest.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } }
|
00
|
Code Sample 1:
public String postXmlRequest(String url, String data) { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); StringBuffer responseStr = new StringBuffer(); try { System.out.println(data); Log4j.logger.info("Request:\n" + data); StringEntity reqEntity = new StringEntity(data, "UTF-8"); reqEntity.setContentType("text/xml"); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); this.setPostSatus(response.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { responseStr.append(line + "\n"); } if (entity != null) { entity.consumeContent(); } } catch (Exception ex) { ex.printStackTrace(); } System.out.println(responseStr); Log4j.logger.info("Response:\n" + responseStr); return responseStr.toString(); }
Code Sample 2:
public static void copyFile(String target, String source) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { ExceptionHelper.showErrorDialog(e); } }
|
11
|
Code Sample 1:
public static final void zip(final ZipOutputStream out, final File f, String base) throws Exception { if (f.isDirectory()) { final File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (final File element : fl) { zip(out, element, base + element.getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); final FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); }
Code Sample 2:
public static void copyAssetFile(Context ctx, String srcFileName, String targetFilePath) { AssetManager assetManager = ctx.getAssets(); try { InputStream is = assetManager.open(srcFileName); File out = new File(targetFilePath); if (!out.exists()) { out.getParentFile().mkdirs(); out.createNewFile(); } OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } catch (IOException e) { AIOUtils.log("error when copyAssetFile", e); } }
|
11
|
Code Sample 1:
public static String generateHash(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException { MessageDigest digest; digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(message.getBytes("iso-8859-1"), 0, message.length()); byte[] output = new byte[20]; digest.digest(output, 0, output.length); return convertToHex(output); }
Code Sample 2:
public void updateChecksum() { try { MessageDigest md = MessageDigest.getInstance("SHA"); List<Parameter> sortedKeys = new ArrayList<Parameter>(parameter_instances.keySet()); for (Parameter p : sortedKeys) { if (parameter_instances.get(p) != null && !(parameter_instances.get(p) instanceof OptionalDomain.OPTIONS) && !(parameter_instances.get(p).equals(FlagDomain.FLAGS.OFF))) { md.update(parameter_instances.get(p).toString().getBytes()); } } this.checksum = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
00
|
Code Sample 1:
public static String md5(String value) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); try { messageDigest.update(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { messageDigest.update(value.getBytes()); } byte[] bytes = messageDigest.digest(); return byteArrayToHexString(bytes); }
Code Sample 2:
public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale, Map templateContext, CmsOFBizRemoteClient remoteClient, Writer out, boolean cache) throws IOException, GeneralException { Map context = (Map) templateContext.get("context"); if (context == null) { context = FastMap.newInstance(); } String webSiteId = (String) templateContext.get("webSiteId"); if (UtilValidate.isEmpty(webSiteId)) { if (context != null) webSiteId = (String) context.get("webSiteId"); } String https = (String) templateContext.get("https"); if (UtilValidate.isEmpty(https)) { if (context != null) https = (String) context.get("https"); } Map fields = dataResource.getAllFields(); String dataResourceId = (String) fields.get("dataResourceId"); String dataResourceTypeId = (String) fields.get("dataResourceTypeId"); if (UtilValidate.isEmpty(dataResourceTypeId)) { dataResourceTypeId = "SHORT_TEXT"; } if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) { String text = (String) fields.get("objectInfo"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) { GenericValue electronicText; if (cache) { electronicText = remoteClient.findByPrimaryKeyCache("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } else { electronicText = remoteClient.findByPrimaryKey("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } fields = electronicText.getAllFields(); String text = (String) fields.get("textData"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_OBJECT")) { String text = (String) fields.get("dataResourceId"); writeText(remoteClient, dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.equals("URL_RESOURCE")) { String text = null; URL url = new URL((String) fields.get("objectInfo")); if (url.getHost() != null) { InputStream in = url.openStream(); int c; StringWriter sw = new StringWriter(); while ((c = in.read()) != -1) { sw.write(c); } sw.close(); text = sw.toString(); } else { String prefix = DataResourceWorker.buildRequestPrefix(remoteClient, locale, webSiteId, https); String sep = ""; if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { sep = "/"; } String fixedUrlStr = prefix + sep + url.toString(); URL fixedUrl = new URL(fixedUrlStr); text = (String) fixedUrl.getContent(); } out.write(text); } else if (dataResourceTypeId.endsWith("_FILE_BIN")) { writeText(remoteClient, dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_FILE")) { String dataResourceMimeTypeId = (String) fields.get("mimeTypeId"); String objectInfo = (String) fields.get("objectInfo"); String rootDir = (String) context.get("rootDir"); if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) { renderFile(dataResourceTypeId, objectInfo, rootDir, out); } else { writeText(remoteClient, dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } } else { throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in renderDataResourceAsText"); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.