label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
public static String encrypt(String password, String algorithm, byte[] salt) { StringBuffer buffer = new StringBuffer(); MessageDigest digest = null; int size = 0; if ("CRYPT".equalsIgnoreCase(algorithm)) { throw new InternalError("Not implemented"); } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) { size = 20; if (salt != null && salt.length > 0) { buffer.append("{SSHA}"); } else { buffer.append("{SHA}"); } try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) { size = 16; if (salt != null && salt.length > 0) { buffer.append("{SMD5}"); } else { buffer.append("{MD5}"); } try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } int outSize = size; digest.reset(); digest.update(password.getBytes()); if (salt != null && salt.length > 0) { digest.update(salt); outSize += salt.length; } byte[] out = new byte[outSize]; System.arraycopy(digest.digest(), 0, out, 0, size); if (salt != null && salt.length > 0) { System.arraycopy(salt, 0, out, size, salt.length); } buffer.append(Base64.encode(out)); return buffer.toString(); }
Code Sample 2:
public int executeUpdateJT(String sql, Object[][] paramsList) { Connection connection = null; connection = this.getConnection(); try { connection.setAutoCommit(false); } catch (SQLException e1) { e1.printStackTrace(); } PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < paramsList.length; i++) { if (connection != null && !connection.isClosed()) { InputStream is = null; if (paramsList[i].length > 0) { for (int j = 0; j < paramsList[i].length; j++) { Object obj = paramsList[i][j]; if (obj.getClass().equals(Class.forName("java.io.File"))) { File file = (File) obj; is = new FileInputStream(file); preparedStatement.setBinaryStream(j + 1, is, (int) file.length()); } else if (obj.getClass().equals(Class.forName("java.util.Date"))) { java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); preparedStatement.setString(j + 1, sdf.format((Date) obj)); } else { preparedStatement.setObject(j + 1, obj); } } } preparedStatement.executeUpdate(); if (is != null) { is.close(); } ; } } } catch (Exception e) { System.out.println("发生错误,数据回滚!"); e.printStackTrace(); try { connection.rollback(); return 0; } catch (SQLException e1) { e1.printStackTrace(); } } try { connection.commit(); return 1; } catch (SQLException e) { e.printStackTrace(); } finally { try { preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } try { connection.close(); } catch (SQLException e) { log.error("未能正确关闭数据库连接!", e); System.out.println("未能正确关闭数据库连接!"); e.printStackTrace(); } } return -1; }
|
11
|
Code Sample 1:
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; } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
public static void copy(final File src, final File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
Code Sample 2:
private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; }
|
11
|
Code Sample 1:
public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); System.out.println("test"); URL url = new URL(addr); System.out.println("test2"); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
private void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException { ZipOutputStream zipOutput = null; try { zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target))); for (File file : files) { BufferedInputStream fileInput = null; File cachePathName = new File(cacheFolder, file.getPath()); try { if (!cachePathName.exists()) { throw new CacheOperationException("Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it " + "has gone missing (cause unknown). This can indicate implementation or deployment " + "error. Aborting export operation as a safety precaution.", cachePathName.getPath(), target.getAbsolutePath(), account.getOid()); } fileInput = new BufferedInputStream(new FileInputStream(cachePathName)); ZipEntry entry = new ZipEntry(file.getPath()); entry.setSize(cachePathName.length()); entry.setTime(cachePathName.lastModified()); zipOutput.putNextEntry(entry); cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath()); int count, total = 0; int buffer = 2048; byte[] data = new byte[buffer]; while ((count = fileInput.read(data, 0, buffer)) != -1) { zipOutput.write(data, 0, count); total += count; } zipOutput.flush(); if (total != cachePathName.length()) { throw new CacheOperationException("Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). " + "This could have occured either due implementation error or file I/O error. " + "Aborting archive operation to prevent a potentially corrupt export archive to " + "be created.", total, cachePathName.length(), cachePathName.getPath(), account.getOid()); } else { cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total, cachePathName.length(), file.getPath()); } } catch (SecurityException e) { throw new ConfigurationException("Security manager has denied r/w access when attempting to read file ''{0}'' and " + "write it to archive ''{1}'' (Account : {2}) : {3}", e, cachePathName.getPath(), target, account.getOid(), e.getMessage()); } catch (IllegalArgumentException e) { throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (FileNotFoundException e) { throw new CacheOperationException("Attempted to include file ''{0}'' in export archive but it has gone missing " + "(Account : {1}). Possible implementation error in local file cache. Aborting " + "export operation as a precaution ({2})", e, cachePathName.getPath(), account.getOid(), e.getMessage()); } catch (ZipException e) { throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (IOException e) { throw new CacheOperationException("I/O error while creating export archive for account ID = {0}. " + "Operation aborted ({1})", e, account.getOid(), e.getMessage()); } finally { if (zipOutput != null) { try { zipOutput.closeEntry(); } catch (Throwable t) { cacheLog.warn("Unable to close zip entry for file ''{0}'' in export archive ''{1}'' " + "(Account : {2}) : {3}.", t, file.getPath(), target.getAbsolutePath(), account.getOid(), t.getMessage()); } } if (fileInput != null) { try { fileInput.close(); } catch (Throwable t) { cacheLog.warn("Failed to close input stream from file ''{0}'' being added " + "to export archive (Account : {1}) : {2}", t, cachePathName.getPath(), account.getOid(), t.getMessage()); } } } } } catch (FileNotFoundException e) { throw new CacheOperationException("Unable to create target export archive ''{0}'' for account {1) : {2}", e, target, account.getOid(), e.getMessage()); } finally { try { if (zipOutput != null) { zipOutput.close(); } } catch (Throwable t) { cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target, t.getMessage()); } } }
|
11
|
Code Sample 1:
public static byte[] encrypt(String x) throws NoSuchAlgorithmException { MessageDigest d = null; d = MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); return d.digest(); }
Code Sample 2:
public static byte[] decrypt(String passphrase, byte[] data) throws Exception { byte[] dataTemp; try { Security.addProvider(new com.sun.crypto.provider.SunJCE()); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes()); DESKeySpec key = new DESKeySpec(md.digest()); SecretKeySpec DESKey = new SecretKeySpec(key.getKey(), "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, DESKey); dataTemp = cipher.doFinal(data); } catch (Exception e) { throw e; } return dataTemp; }
|
00
|
Code Sample 1:
private void documentFileChooserActionPerformed(java.awt.event.ActionEvent evt) { if (evt.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { File selectedFile = documentFileChooser.getSelectedFile(); File collectionCopyFile; String newDocumentName = selectedFile.getName(); Document newDocument = new Document(newDocumentName); if (activeCollection.containsDocument(newDocument)) { int matchingFilenameDistinguisher = 1; StringBuilder distinguisherReplacer = new StringBuilder(); newDocumentName = newDocumentName.concat("(" + matchingFilenameDistinguisher + ")"); newDocument.setDocumentName(newDocumentName); while (activeCollection.containsDocument(newDocument)) { matchingFilenameDistinguisher++; newDocumentName = distinguisherReplacer.replace(newDocumentName.length() - 2, newDocumentName.length() - 1, new Integer(matchingFilenameDistinguisher).toString()).toString(); newDocument.setDocumentName(newDocumentName); } } Scanner tokenizer = null; FileChannel fileSource = null; FileChannel collectionDestination = null; HashMap<String, Integer> termHashMap = new HashMap<String, Integer>(); Index collectionIndex = activeCollection.getIndex(); int documentTermMaxFrequency = 0; int currentTermFrequency; try { tokenizer = new Scanner(new BufferedReader(new FileReader(selectedFile))); tokenizer.useDelimiter(Pattern.compile("\\p{Space}|\\p{Punct}|\\p{Cntrl}")); String nextToken; while (tokenizer.hasNext()) { nextToken = tokenizer.next().toLowerCase(); if (!nextToken.isEmpty()) if (termHashMap.containsKey(nextToken)) termHashMap.put(nextToken, termHashMap.get(nextToken) + 1); else termHashMap.put(nextToken, 1); } Term newTerm; for (String term : termHashMap.keySet()) { newTerm = new Term(term); if (!collectionIndex.termExists(newTerm)) collectionIndex.addTerm(newTerm); currentTermFrequency = termHashMap.get(term); if (currentTermFrequency > documentTermMaxFrequency) documentTermMaxFrequency = currentTermFrequency; collectionIndex.addOccurence(newTerm, newDocument, currentTermFrequency); } activeCollection.addDocument(newDocument); String userHome = System.getProperty("user.home"); String fileSeparator = System.getProperty("file.separator"); collectionCopyFile = new File(userHome + fileSeparator + "Infrared" + fileSeparator + activeCollection.getDocumentCollectionName() + fileSeparator + newDocumentName); collectionCopyFile.createNewFile(); fileSource = new FileInputStream(selectedFile).getChannel(); collectionDestination = new FileOutputStream(collectionCopyFile).getChannel(); collectionDestination.transferFrom(fileSource, 0, fileSource.size()); } catch (FileNotFoundException e) { System.err.println(e.getMessage() + " This error should never occur! The file was just selected!"); return; } catch (IOException e) { JOptionPane.showMessageDialog(this, "An I/O error occured during file transfer!", "File transfer I/O error", JOptionPane.WARNING_MESSAGE); return; } finally { try { if (tokenizer != null) tokenizer.close(); if (fileSource != null) fileSource.close(); if (collectionDestination != null) collectionDestination.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (evt.getActionCommand().equalsIgnoreCase(JFileChooser.CANCEL_SELECTION)) processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); }
Code Sample 2:
public static Version getWebRelease(String url) { InputStream is = null; try { is = new URL(url).openStream(); Reader reader = new InputStreamReader(new BufferedInputStream(is), "UTF-8"); String word = findWord(reader, "<description>Release:", "</description>").trim(); if (!isValid(word)) { word = "0"; } return new Version(word); } catch (Throwable ex) { LOGGER.log(Level.WARNING, null, ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } } return null; }
|
11
|
Code Sample 1:
private void gzip(FileHolder fileHolder) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File destFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(destFile); outStream = new GZIPOutputStream(outStream); File selectedFile = fileHolder.selectedFileList.get(0); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.close(); this.inStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error gzip'ing: " + destFile); logger.logError(errEntry); } }
Code Sample 2:
@SuppressWarnings("unchecked") protected void displayFreeMarkerResponse(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> variableMap) throws IOException { Enumeration<String> attrNameEnum = request.getSession().getAttributeNames(); String attrName; while (attrNameEnum.hasMoreElements()) { attrName = attrNameEnum.nextElement(); if (attrName != null && attrName.startsWith(ADMIN4J_SESSION_VARIABLE_PREFIX)) { variableMap.put("Session" + attrName, request.getSession().getAttribute(attrName)); } } variableMap.put("RequestAdmin4jCurrentUri", request.getRequestURI()); Template temp = FreemarkerUtils.createConfiguredTemplate(this.getClass(), templateName); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { temp.process(variableMap, new OutputStreamWriter(outStream)); response.setContentLength(outStream.size()); IOUtils.copy(new ByteArrayInputStream(outStream.toByteArray()), response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new Admin4jRuntimeException(e); } }
|
00
|
Code Sample 1:
public Object run() { if (type == GET_THEME_DIR) { String sep = File.separator; String[] dirs = new String[] { userHome + sep + ".themes", System.getProperty("swing.metacitythemedir"), "/usr/share/themes", "/usr/gnome/share/themes", "/opt/gnome2/share/themes" }; URL themeDir = null; for (int i = 0; i < dirs.length; i++) { if (dirs[i] == null) { continue; } File dir = new File(dirs[i] + sep + arg + sep + "metacity-1"); if (new File(dir, "metacity-theme-1.xml").canRead()) { try { themeDir = dir.toURL(); } catch (MalformedURLException ex) { themeDir = null; } break; } } if (themeDir == null) { String filename = "resources/metacity/" + arg + "/metacity-1/metacity-theme-1.xml"; URL url = getClass().getResource(filename); if (url != null) { String str = url.toString(); try { themeDir = new URL(str.substring(0, str.lastIndexOf('/')) + "/"); } catch (MalformedURLException ex) { themeDir = null; } } } return themeDir; } else if (type == GET_USER_THEME) { try { userHome = System.getProperty("user.home"); String theme = System.getProperty("swing.metacitythemename"); if (theme != null) { return theme; } URL url = new URL(new File(userHome).toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); Reader reader = new InputStreamReader(url.openStream(), "ISO-8859-1"); char[] buf = new char[1024]; StringBuffer strBuf = new StringBuffer(); int n; while ((n = reader.read(buf)) >= 0) { strBuf.append(buf, 0, n); } reader.close(); String str = strBuf.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); int i = strLowerCase.indexOf("<entry name=\"theme\""); if (i >= 0) { i = strLowerCase.indexOf("<stringvalue>", i); if (i > 0) { i += "<stringvalue>".length(); int i2 = str.indexOf("<", i); return str.substring(i, i2); } } } } catch (MalformedURLException ex) { } catch (IOException ex) { } return null; } else if (type == GET_IMAGE) { return new ImageIcon((URL) arg).getImage(); } else { return null; } }
Code Sample 2:
@Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < 5; i++) { if (e.getSource() == btnNumber[i]) { String password = new String((passwordField.getPassword())); passwordField.setText(password + i); } } if (e.getSource() == btnOK) { String password = new String((passwordField.getPassword())); ResultSet rs; Statement stmt; String sql; String result = ""; boolean checkPassword = false; boolean checkPassword1 = false; boolean checkPassword2 = false; sql = "select password from Usuarios where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result = rs.getString("password"); } rs.close(); stmt.close(); try { Tree tree1 = CreateTree(password, 0); Tree tree2 = CreateTree(password, 1); tree1.enumerateTree(tree1.root); tree2.enumerateTree(tree2.root); for (int i = 0; i < tree1.passwdVector.size(); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(tree1.passwdVector.get(i).getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) { checkPassword1 = true; break; } else checkPassword1 = false; } for (int i = 0; i < tree2.passwdVector.size(); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(tree2.passwdVector.get(i).getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String output = bigInt.toString(16); if (output.compareTo(result) == 0) { checkPassword2 = true; break; } else checkPassword2 = false; } if (checkPassword1 == true || checkPassword2 == true) checkPassword = true; else checkPassword = false; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } if (checkPassword == true) { JOptionPane.showMessageDialog(null, "senha correta!"); setTries(0); setVisible(false); Error.log(3003, "Senha pessoal verificada positivamente."); Error.log(3002, "Autentica��o etapa 2 encerrada."); PasswordTableWindow ptw = new PasswordTableWindow(login); ptw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } else { JOptionPane.showMessageDialog(null, "senha incorreta!"); Error.log(3004, "Senha pessoal verificada negativamente."); int tries = getTries(); if (tries == 0) { Error.log(3005, "Primeiro erro da senha pessoal contabilizado."); } else if (tries == 1) { Error.log(3006, "Segundo erro da senha pessoal contabilizado."); } else if (tries == 2) { Error.log(3007, "Terceiro erro da senha pessoal contabilizado."); Error.log(3008, "Acesso do usuario " + login + " bloqueado pela autentica��o etapa 2."); Error.log(3002, "Autentica��o etapa 2 encerrada."); Error.log(1002, "Sistema encerrado."); setTries(++tries); System.exit(1); } setTries(++tries); } } if (e.getSource() == btnClear) { passwordField.setText(""); } }
|
00
|
Code Sample 1:
private Properties loadDefaultProperties() throws IOException { Properties merged = new Properties(); try { merged.setProperty("user", System.getProperty("user.name")); } catch (java.lang.SecurityException se) { } ClassLoader cl = getClass().getClassLoader(); if (cl == null) cl = ClassLoader.getSystemClassLoader(); if (cl == null) { logger.debug("Can't find a classloader for the Driver; not loading driver configuration"); return merged; } logger.debug("Loading driver configuration via classloader " + cl); ArrayList urls = new ArrayList(); Enumeration urlEnum = cl.getResources("org/postgresql/driverconfig.properties"); while (urlEnum.hasMoreElements()) { urls.add(urlEnum.nextElement()); } for (int i = urls.size() - 1; i >= 0; i--) { URL url = (URL) urls.get(i); logger.debug("Loading driver configuration from: " + url); InputStream is = url.openStream(); merged.load(is); is.close(); } return merged; }
Code Sample 2:
protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); String line = null; try { urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); line = reader.readLine(); reader.close(); } finally { urlcon.disconnect(); } return line; }
|
00
|
Code Sample 1:
public StringBuffer get(URL url) throws IOException { StringBuffer pageContents = new StringBuffer(); PDFReader reader = new PDFReader(url.openStream()); reader.open(); int pageCount = reader.getNumberOfPages(); for (int i = 0; i < pageCount; i++) pageContents.append(new String(reader.extractTextFromPage(i).getBytes(), "UTF-8")); reader.close(); return pageContents; }
Code Sample 2:
public static String sendGetRequest(String urlStr) { String result = null; try { URL url = new URL(urlStr); System.out.println(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line = ""; System.out.println("aa" + line); while ((line = rd.readLine()) != null) { System.out.println("aa" + line); sb.append(line); } rd.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return result; }
|
00
|
Code Sample 1:
public void modifyDecisionInstruction(int id, int condition, String frameSlot, String linkName, int objectId, String attribute, int positive, int negative) throws FidoDatabaseException, ObjectNotFoundException, InstructionNotFoundException { try { Connection conn = null; Statement stmt = null; try { if ((condition == ConditionalOperatorTable.CONTAINS_LINK) || (condition == ConditionalOperatorTable.NOT_CONTAINS_LINK)) { ObjectTable ot = new ObjectTable(); if (ot.contains(objectId) == false) throw new ObjectNotFoundException(objectId); } conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, positive) == false) throw new InstructionNotFoundException(positive); if (contains(stmt, negative) == false) throw new InstructionNotFoundException(negative); String sql = "update Instructions set Operator = " + condition + ", " + " FrameSlot = '" + frameSlot + "', " + " LinkName = '" + linkName + "', " + " ObjectId = " + objectId + ", " + " AttributeName = '" + attribute + "' " + "where InstructionId = " + id; stmt.executeUpdate(sql); InstructionGroupTable groupTable = new InstructionGroupTable(); groupTable.deleteInstruction(stmt, id); if (positive != -1) groupTable.addInstructionAt(stmt, id, 1, positive); if (negative != -1) groupTable.addInstructionAt(stmt, id, 2, negative); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
Code Sample 2:
void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
00
|
Code Sample 1:
public ArrayList loadIndexes() { JSONObject job = new JSONObject(); ArrayList al = new ArrayList(); try { String req = job.put("OperationId", "1").toString(); InputStream is = null; String result = ""; JSONObject jArray = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.4:8080/newgenlibctxt/CarbonServlet"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("OperationId", "1")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } try { JSONObject jobres = new JSONObject(result); JSONArray jarr = jobres.getJSONArray("MobileIndexes"); for (int i = 0; i < jarr.length(); i++) { String indexname = jarr.getString(i); al.add(indexname); } } catch (JSONException e) { e.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } return al; }
Code Sample 2:
private ShaderProgram loadShaderProgram() { ShaderProgram sp = null; String vertexProgram = null; String fragmentProgram = null; Shader[] shaders = new Shader[2]; try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/ivory.vert"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/ivory.vert"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/ivory.vert"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); vertexProgram = new String(buffer); vertexProgram = vertexProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load ivory.vert"); e.printStackTrace(); } try { ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource("Shaders/ivory.frag"); System.out.println("url " + url); InputStream inputSteam = cl.getResourceAsStream("Shaders/ivory.frag"); Reader reader = null; if (inputSteam != null) { reader = new InputStreamReader(inputSteam); } else { File file = new File("lib"); URL url2 = new URL("jar:file:" + file.getAbsolutePath() + "/j3d-vrml97-i3mainz.jar!/Shaders/ivory.frag"); InputStream inputSteam2 = url2.openStream(); reader = new InputStreamReader(inputSteam2); } char[] buffer = new char[10000]; int len = reader.read(buffer); fragmentProgram = new String(buffer); fragmentProgram = fragmentProgram.substring(0, len); } catch (Exception e) { System.err.println("could'nt load ivory.frag"); e.printStackTrace(); } if (vertexProgram != null && fragmentProgram != null) { shaders[0] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_VERTEX, vertexProgram); shaders[1] = new SourceCodeShader(Shader.SHADING_LANGUAGE_GLSL, Shader.SHADER_TYPE_FRAGMENT, fragmentProgram); sp = new GLSLShaderProgram(); sp.setShaders(shaders); } return sp; }
|
00
|
Code Sample 1:
public QueryResult doSearch(String searchTerm, Integer searchInReceivedItems, Integer searchInSentItems, Integer searchInSupervisedItems, Integer startRow, Integer resultCount, Boolean searchArchived, Boolean searchInItemsNeededAttentionOnly) throws UnsupportedEncodingException, IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); DefaultHttpClient httpclient = new DefaultHttpClient(); QueryResult queryResult = new QueryResult(); SearchRequest request = new SearchRequest(); SearchItemsQuery query = new SearchItemsQuery(); query.setArchiveIncluded(searchArchived); log(INFO, "searchTerm=" + searchTerm); log(INFO, "search in received=" + searchInReceivedItems); log(INFO, "search in sent=" + searchInSentItems); log(INFO, "search in supervised=" + searchInSupervisedItems); List<String> filters = new ArrayList<String>(); if (searchInItemsNeededAttentionOnly == false) { if (searchInReceivedItems != null) { filters.add("ALL_RECEIVED_ITEMS"); } if (searchInSentItems != null) { filters.add("ALL_SENT_ITEMS"); } if (searchInSupervisedItems != null) { filters.add("ALL_SUPERVISED_ITEMS"); } } else { if (searchInReceivedItems != null) { filters.add("RECEIVED_ITEMS_NEEDED_ATTENTION"); } if (searchInSentItems != null) { filters.add("SENT_ITEMS_NEEDED_ATTENTION"); } } query.setFilters(filters); query.setId("1234"); query.setOwner(sessionId); query.setReferenceOnly(false); query.setSearchTerm(searchTerm); query.setUseOR(false); request.setStartRow(startRow); request.setResultCount(resultCount); request.setQuery(query); request.setSessionId(sessionId); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("SearchRequest", SearchRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("SearchResponse", SearchResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpGet httpget = new HttpGet(MewitProperties.getMewitUrl() + "/resources/search?REQUEST=" + strRequest); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); SearchResponse searchResponse = (SearchResponse) reader.fromXML(result); List<Item> items = searchResponse.getItems(); queryResult.setItems(items); queryResult.setTotal(searchResponse.getTotalResultCount()); queryResult.setStartRow(searchResponse.getStartRow()); } return queryResult; }
Code Sample 2:
public String computeMD5(String string) throws ServiceException { try { MessageDigest digest = MessageDigest.getInstance("md5"); digest.reset(); digest.update(string.getBytes(Invoker.ENCODING)); return convertToHex(digest.digest()); } catch (NoSuchAlgorithmException exception) { String message = "Could not create properly the MD5 digest"; log.error(message, exception); throw new ServiceException(message, exception); } catch (UnsupportedEncodingException exception) { String message = "Could not encode properly the MD5 digest"; log.error(message, exception); throw new ServiceException(message, exception); } }
|
00
|
Code Sample 1:
@Override public CheckAvailabilityResult execute(final CheckAvailabilityAction action, final ExecutionContext context) throws ActionException { if (LOGGER.isDebugEnabled()) { String serverName = null; if (action.getServerId() == CheckAvailability.FEDORA_ID) { serverName = "fedora"; } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) { serverName = "kramerius"; } LOGGER.debug("Processing action: CheckAvailability: " + serverName); } ServerUtils.checkExpiredSession(httpSessionProvider); boolean status = true; String url = null; String usr = ""; String pass = ""; if (action.getServerId() == CheckAvailability.FEDORA_ID) { url = configuration.getFedoraHost(); usr = configuration.getFedoraLogin(); pass = configuration.getFedoraPassword(); } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) { url = configuration.getKrameriusHost() + SOME_STATIC_KRAMERIUS_PAGE; } else { throw new ActionException("Unknown server id"); } try { URLConnection con = RESTHelper.openConnection(url, usr, pass, false); if (con instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) con; int resp = httpConnection.getResponseCode(); if (resp < 200 || resp >= 308) { status = false; LOGGER.info("Server " + url + " answered with HTTP code " + httpConnection.getResponseCode()); } } else { status = false; } } catch (MalformedURLException e) { status = false; e.printStackTrace(); } catch (IOException e) { status = false; e.printStackTrace(); } return new CheckAvailabilityResult(status, url); }
Code Sample 2:
Library(MainFrame mf, boolean newLibrary, String templateName, String newFileName) throws Exception { mainFrame = mf; trackMap = new HashMap<String, LibraryTrack>(); trackVec = new Vector<LibraryTrack>(); String propFileName = null; File propFile = null; String notExist = ""; String[] options = templateDesc; boolean isCurrent = mainFrame.library != null; int ix; if (!newLibrary) { propFileName = mainFrame.name + ".jampal"; propFile = new File(propFileName); } if (isCurrent) { options = new String[templateDesc.length + 1]; options[0] = "Copy of Current Library"; for (ix = 0; ix < templateDesc.length; ix++) { options[ix + 1] = templateDesc[ix]; } } boolean copyLibrary = false; if (newLibrary) { if (templateName == null) { Object resp = JOptionPane.showInputDialog(mainFrame.frame, "Please select a template.", "Select Type of Library", JOptionPane.WARNING_MESSAGE, null, options, null); if (resp == null) return; templateName = (String) resp; } for (ix = 0; ix < options.length && !options[ix].equals(templateName); ix++) ; if (isCurrent) ix--; boolean creatingPlaylist = false; BufferedReader in; if (ix == -1) { in = new BufferedReader(new FileReader(mainFrame.name + ".jampal")); copyLibrary = true; creatingPlaylist = (mainFrame.library.attributes.libraryType == 'P'); } else { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/" + templateNames[ix]))); creatingPlaylist = ("playlist.jampal".equals(templateNames[ix])); } if (newFileName == null) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Create New Library File"); String currentDirectory = null; if (mainFrame.name != null) { File nameFile = new File(mainFrame.name); currentDirectory = nameFile.getParent(); if (currentDirectory == null) currentDirectory = "."; } if (currentDirectory == null) currentDirectory = Jampal.jampalDirectory; if (currentDirectory != null) fileChooser.setCurrentDirectory(new File(currentDirectory)); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setMultiSelectionEnabled(false); Mp3FileFilter filter = new Mp3FileFilter(); filter.setExtension("jampal", "Jampal library files"); fileChooser.addChoosableFileFilter(filter); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(filter); fileChooser.setDialogType(JFileChooser.SAVE_DIALOG); int returnVal = fileChooser.showSaveDialog(mainFrame.frame); if (returnVal == fileChooser.APPROVE_OPTION) { propFile = fileChooser.getSelectedFile(); propFileName = propFile.getPath(); if (!propFileName.toLowerCase().endsWith(".jampal")) { propFileName = propFileName + ".jampal"; propFile = new File(propFileName); } } else return; } else { propFileName = newFileName; propFile = new File(propFileName); } if (propFile.exists()) { if (JOptionPane.showConfirmDialog(mainFrame.frame, "File " + propFileName + " already exists. Do you want to overwrite it ?", "Warning", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; } PrintWriter out = new PrintWriter(new FileOutputStream(propFile)); String libName = propFile.getName(); libName = libName.substring(0, libName.length() - 7); for (; ; ) { String line = in.readLine(); if (line == null) break; if (creatingPlaylist && line.startsWith("playlist=")) { line = "playlist=" + libName; } if (line.startsWith("libraryname=")) { line = "libraryname=" + libName + ".jmp"; } out.println(line); } in.close(); out.close(); if (!creatingPlaylist && !copyLibrary) { String playlistName = propFile.getParent() + File.separator + "playlist.jampal"; File playlistFile = new File(playlistName); if (!playlistFile.exists()) { in = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("pgbennett/jampal/playlist.jampal"))); out = new PrintWriter(new FileOutputStream(playlistFile)); for (; ; ) { String line = in.readLine(); if (line == null) break; out.println(line); } in.close(); out.close(); } } } if (propFileName != null) attributes = new LibraryAttributes(propFileName); insertBefore = -1; }
|
11
|
Code Sample 1:
public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(Options.fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
public void trimAndWriteNewSff(OutputStream out) throws IOException { TrimParser trimmer = new TrimParser(); SffParser.parseSFF(untrimmedSffFile, trimmer); tempOut.close(); headerBuilder.withNoIndex().numberOfReads(numberOfTrimmedReads); SffWriter.writeCommonHeader(headerBuilder.build(), out); InputStream in = null; try { in = new FileInputStream(tempReadDataFile); IOUtils.copyLarge(in, out); } finally { IOUtil.closeAndIgnoreErrors(in); } }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
|
11
|
Code Sample 1:
public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
private void writeData(IBaseType dataType, Writer writer) throws XMLStreamException { InputStream isData; DataType data = (DataType) baseType; if (data.isSetInputStream()) { isData = data.getInputStream(); try { IOUtils.copy(isData, writer); } catch (IOException e) { throw new XMLStreamException("DataType fail writing streaming data ", e); } } else if (data.isSetOutputStream()) { throw new XMLStreamException("DataType only can write streaming input, its an output stream (only for reading) "); } else { new CharactersEventImpl(startElement.getLocation(), String.valueOf(baseType.asData()), false).writeAsEncodedUnicode(writer); } }
|
11
|
Code Sample 1:
public static String calcHA1(String algorithm, String username, String realm, String password, String nonce, String cnonce) throws FatalException, MD5DigestException { MD5Encoder encoder = new MD5Encoder(); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new FatalException(e); } if (username == null || realm == null) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "username or realm"); } if (password == null) { System.err.println("No password has been provided"); throw new IllegalStateException(); } if (algorithm != null && algorithm.equals("MD5-sess") && (nonce == null || cnonce == null)) { throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nonce or cnonce"); } md5.update((username + ":" + realm + ":" + password).getBytes()); if (algorithm != null && algorithm.equals("MD5-sess")) { md5.update((":" + nonce + ":" + cnonce).getBytes()); } return encoder.encode(md5.digest()); }
Code Sample 2:
public static synchronized String Encrypt(String plaintextPassword) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (Exception error) { throw new Exception(error.getMessage()); } try { md.update(plaintextPassword.getBytes("UTF-8")); } catch (Exception e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
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 void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } }
|
11
|
Code Sample 1:
public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "ispyb@esrf.fr", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); }
Code Sample 2:
private 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:
private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); }
Code Sample 2:
public static void unzip2(String strZipFile, String folder) throws IOException, ArchiveException { FileUtil.fileExists(strZipFile, true); final InputStream is = new FileInputStream(strZipFile); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; OutputStream out = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { File zipPath = new File(folder); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { out = new FileOutputStream(new File(folder, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); }
|
11
|
Code Sample 1:
public static String hash(String in, String algorithm) { if (StringUtils.isBlank(algorithm)) algorithm = DEFAULT_ALGORITHM; try { md = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException nsae) { logger.error("No such algorithm exception", nsae); } md.reset(); md.update(in.getBytes()); String out = null; try { out = Base64Encoder.encode(md.digest()); } catch (IOException e) { logger.error("Error converting to Base64 ", e); } if (out.endsWith("\n")) out = out.substring(0, out.length() - 1); return out; }
Code Sample 2:
public static String encrypt(String message) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(message.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); return null; } }
|
00
|
Code Sample 1:
public void execute() { checkInput(); try { client = new FTPClient(); log("Connecting to " + ftpServer, Project.MSG_INFO); client.connect(ftpServer, ftpPort); checkFtpCode(client, "FTP server refused connection:"); log("Connected", Project.MSG_INFO); log("Logging in", Project.MSG_INFO); if (!client.login(username, password)) { log("Login failed: " + client.getReplyString(), Project.MSG_ERR); } log("Login successful", Project.MSG_INFO); client.enterLocalPassiveMode(); checkFtpCode(client, "Couldn't change connection type to passive: "); log("Changed to passive mode.", Project.MSG_VERBOSE); client.changeWorkingDirectory(remoteDir); checkFtpCode(client, "Can't change to directory: " + remoteDir); log("Listing FTP files", Project.MSG_INFO); for (int i = 0; i < remoteFileStrings.length; i++) { remoteFilePatterns = makePattern(remoteFileStrings[i]); numDir = remoteFilePatterns.length - 1; log("Setting number of directories to: " + numDir, Project.MSG_VERBOSE); FTPFile[] files = client.listFiles(remoteDir); files = followSymLink(client, files); log("# of files in " + remoteDir + " is " + files.length, Project.MSG_VERBOSE); scanDir(0, numDir, files, null); } bw.flush(); bw.close(); } catch (IOException ioe) { if (client.isConnected()) { try { client.disconnect(); } catch (IOException iof) { } } log("Could not connect to " + ftpServer + " " + ioe.getMessage(), Project.MSG_ERR); } }
Code Sample 2:
public String getShortToken(String md5Str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(md5Str.getBytes(JspRunConfig.charset)); } catch (Exception e) { e.printStackTrace(); } StringBuffer token = toHex(md5.digest()); return token.substring(8, 24); }
|
00
|
Code Sample 1:
public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
public static int ToGSML(GeoSciML_Mapping mapping, String strTemplate, String strRequest, PrintWriter sortie, String requestedSRS) throws Exception { String level = "info."; if (ConnectorServlet.debug) level = "debug."; Log log = LogFactory.getLog(level + "fr.brgm.exows.gml2gsml.Gml2Gsml"); log.debug(strRequest); String tagFeature = "FIELDS"; URL url2Request = new URL(strRequest); URLConnection conn = url2Request.openConnection(); Date dDebut = new Date(); BufferedReader buffin = new BufferedReader(new InputStreamReader(conn.getInputStream())); String strLine = null; int nbFeatures = 0; Template template = VelocityCreator.createTemplate("/fr/brgm/exows/gml2gsml/templates/" + strTemplate); while ((strLine = buffin.readLine()) != null) { if (strLine.indexOf(tagFeature) != -1) { nbFeatures++; GSMLFeatureGeneric feature = createGSMLFeatureFromGMLFeatureString(mapping, strLine); VelocityContext context = new VelocityContext(); context.put("feature", feature); String outputFeatureMember = VelocityCreator.createXMLbyContext(context, template); sortie.println(outputFeatureMember); } } buffin.close(); Date dFin = new Date(); String output = "GEOSCIML : " + nbFeatures + " features handled - time : " + (dFin.getTime() - dDebut.getTime()) / 1000 + " [" + dDebut + " // " + dFin + "]"; log.trace(output); return nbFeatures; }
|
00
|
Code Sample 1:
@Override protected void processImport() throws SudokuInvalidFormatException { importFolder(mUri.getLastPathSegment()); try { URL url = new URL(mUri.toString()); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = null; try { br = new BufferedReader(isr); String s; while ((s = br.readLine()) != null) { if (!s.equals("")) { importGame(s); } } } finally { if (br != null) br.close(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuilder hexString = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); }
|
00
|
Code Sample 1:
private static MyCookieData parseCookie(Cookie cookie) throws CookieException { String value = cookie.getValue(); System.out.println("original cookie: " + value); value = value.replace("%3A", ":"); value = value.replace("%40", "@"); System.out.println("cookie after replacement: " + value); String[] parts = value.split(":"); if (parts.length < 4) throw new CookieException("only " + parts.length + " parts in the cookie! " + value); String email = parts[0]; String nickname = parts[1]; boolean admin = Boolean.getBoolean(parts[2].toLowerCase()); String hsh = parts[3]; boolean valid_cookie = true; String cookie_secret = System.getProperty("COOKIE_SECRET"); if (cookie_secret == "") throw new CookieException("cookie secret is not set"); if (email.equals("")) { System.out.println("email is empty!"); nickname = ""; admin = false; } else { try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update((email + nickname + admin + cookie_secret).getBytes()); StringBuilder builder = new StringBuilder(); for (byte b : sha.digest()) { byte tmphigh = (byte) (b >> 4); tmphigh = (byte) (tmphigh & 0xf); builder.append(hextab.charAt(tmphigh)); byte tmplow = (byte) (b & 0xf); builder.append(hextab.charAt(tmplow)); } System.out.println(); String vhsh = builder.toString(); if (!vhsh.equals(hsh)) { System.out.println("hash not same!"); System.out.println("hash passed in: " + hsh); System.out.println("hash generated: " + vhsh); valid_cookie = false; } else System.out.println("cookie match!"); } catch (NoSuchAlgorithmException ex) { } } return new MyCookieData(email, admin, nickname, valid_cookie); }
Code Sample 2:
public static List<String> retrieveLanguages() throws Exception { List<String> result = new ArrayList<String>(); URL url = new URL("http://translatewiki.net/w/i.php?title=Special:MessageGroupStats&group=out-osm-site"); String str = StreamUtil.toString(url.openStream()); Pattern pattern = Pattern.compile(".*language=([^;\"]+).*"); Matcher m = pattern.matcher(str); while (m.find()) { String lang = m.group(1); if (!result.contains(lang)) { result.add(lang); } } return result; }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public final void saveAsCopy(String current_image, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; String source = temp_dir + key + current_image; 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"); } }
|
00
|
Code Sample 1:
public synchronized String encrypt(String plaintext) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new PasswordException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new PasswordException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new Base64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static void main(String[] args) { boolean rotateLeft = false; boolean rotateRight = false; boolean exclude = false; boolean reset = false; float quality = 0f; int thumbArea = 12000; for (int i = 0; i < args.length; i++) { if (args[i].equals("-rotl")) rotateLeft = true; else if (args[i].equals("-rotr")) rotateRight = true; else if (args[i].equals("-exclude")) exclude = true; else if (args[i].equals("-reset")) reset = true; else if (args[i].equals("-quality")) quality = Float.parseFloat(args[++i]); else if (args[i].equals("-area")) thumbArea = Integer.parseInt(args[++i]); else { File f = new File(args[i]); try { Tools t = new Tools(f); if (exclude) { URL url = t.getClass().getResource("exclude.jpg"); InputStream is = url.openStream(); File dest = t.getExcludeFile(); OutputStream os = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); t.getOutFile().delete(); t.getThumbFile().delete(); System.exit(0); } if (reset) { t.getOutFile().delete(); t.getThumbFile().delete(); t.getExcludeFile().delete(); System.exit(0); } if (quality > 0) t.setQuality(quality); if (t.getType() == Tools.THUMB || t.getType() == Tools.EXCLUDE) t.load(t.getBaseFile()); else t.load(t.getSourceFile()); File out = t.getOutFile(); if (rotateLeft) t.rotateLeft(); else if (rotateRight) t.rotateRight(); t.save(out); t.getExcludeFile().delete(); t.getThumbFile().delete(); System.exit(0); } catch (Throwable e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "The operation could not be performed", "JPhotoAlbum", JOptionPane.ERROR_MESSAGE); System.exit(1); } } } }
|
00
|
Code Sample 1:
@Test public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, null); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
Code Sample 2:
public void saveAs(File f) throws CoverException { FileOutputStream fw = null; BufferedInputStream in = null; try { HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoInput(true); in = new BufferedInputStream(httpConn.getInputStream()); f.delete(); fw = new FileOutputStream(f); int b; while ((b = in.read()) != -1) fw.write(b); fw.close(); in.close(); } catch (IOException e) { throw new CoverException(e.getMessage()); } finally { try { if (fw != null) fw.close(); if (in != null) in.close(); } catch (IOException ex) { System.err.println("Glurps this is severe: " + ex.getMessage()); } } }
|
00
|
Code Sample 1:
public static String sha1(String in) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } byte[] data = new byte[40]; try { md.update(in.getBytes("iso-8859-1"), 0, in.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } data = md.digest(); return HexidecimalUtilities.convertFromByteArrayToHex(data); }
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(); }
|
00
|
Code Sample 1:
public void getDataFiles(String server, String username, String password, String folder, String destinationFolder) { try { FTPClient ftp = new FTPClient(); ftp.connect(server); ftp.login(username, password); System.out.println("Connected to " + server + "."); System.out.print(ftp.getReplyString()); ftp.enterLocalActiveMode(); ftp.changeWorkingDirectory(folder); System.out.println("Changed to " + folder); FTPFile[] files = ftp.listFiles(); System.out.println("Number of files in dir: " + files.length); for (int i = 0; i < files.length; i++) { getFiles(ftp, files[i], destinationFolder); } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; }
|
00
|
Code Sample 1:
public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_URI); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); JSONArray result = new JSONArray(res); long[] friends = new long[result.length()]; long uid = Long.parseLong(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getLong(i)) { friends[i] = result.getLong(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
Code Sample 2:
private void _PostParser(Document document, AnnotationManager annoMan, Document htmldoc, String baseurl) { xformer = annoMan.getTransformer(); builder = annoMan.getBuilder(); String annohash = ""; if (document == null) return; NodeList ndlist = document.getElementsByTagNameNS(annoNS, "body"); if (ndlist.getLength() != 1) { System.out.println("Sorry Annotation Body was found " + ndlist.getLength() + " times"); return; } Element bodynode = (Element) ndlist.item(0); Node htmlNode = bodynode.getElementsByTagName("html").item(0); if (htmlNode == null) htmlNode = bodynode.getElementsByTagName("HTML").item(0); Document newdoc = builder.newDocument(); Element rootelem = newdoc.createElementNS(rdfNS, "r:RDF"); rootelem.setAttribute("xmlns:r", rdfNS); rootelem.setAttribute("xmlns:a", annoNS); rootelem.setAttribute("xmlns:d", dubNS); rootelem.setAttribute("xmlns:t", threadNS); newdoc.appendChild(rootelem); Element tmpelem; NodeList tmpndlist; Element annoElem = newdoc.createElementNS(annoNS, "a:Annotation"); rootelem.appendChild(annoElem); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "context").item(0); String context = tmpelem.getChildNodes().item(0).getNodeValue(); annoElem.setAttributeNS(annoNS, "a:context", context); NodeList elemcontl = tmpelem.getElementsByTagNameNS(alNS, "context-element"); Node ncontext_element = null; if (elemcontl.getLength() > 0) { Node old_context_element = elemcontl.item(0); ncontext_element = newdoc.importNode(old_context_element, true); } tmpndlist = document.getElementsByTagNameNS(dubNS, "title"); annoElem.setAttributeNS(dubNS, "d:title", tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "Default"); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "creator").item(0); annoElem.setAttributeNS(dubNS, "d:creator", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "created").item(0); annoElem.setAttributeNS(annoNS, "a:created", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "date").item(0); annoElem.setAttributeNS(dubNS, "d:date", tmpelem.getChildNodes().item(0).getNodeValue()); tmpndlist = document.getElementsByTagNameNS(dubNS, "language"); String language = (tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "en"); annoElem.setAttributeNS(dubNS, "d:language", language); Node typen = newdoc.importNode(document.getElementsByTagNameNS(rdfNS, "type").item(0), true); annoElem.appendChild(typen); Element contextn = newdoc.createElementNS(annoNS, "a:context"); contextn.setAttributeNS(rdfNS, "r:resource", context); annoElem.appendChild(contextn); Node annotatesn = newdoc.importNode(document.getElementsByTagNameNS(annoNS, "annotates").item(0), true); annoElem.appendChild(annotatesn); Element newbodynode = newdoc.createElementNS(annoNS, "a:body"); annoElem.appendChild(newbodynode); if (ncontext_element != null) { contextn.appendChild(ncontext_element); } else { System.out.println("No context element found, we create one..."); try { XPointer xptr = new XPointer(htmldoc); NodeRange xprange = xptr.getRange(context, htmldoc); Element context_elem = newdoc.createElementNS(alNS, "al:context-element"); context_elem.setAttributeNS(alNS, "al:text", xprange.getContentString()); context_elem.appendChild(newdoc.createTextNode(annoMan.generateContextString(xprange))); contextn.appendChild(context_elem); } catch (XPointerRangeException e2) { e2.printStackTrace(); } } WordFreq wf = new WordFreq(annoMan.extractTextFromNode(htmldoc)); Element docident = newdoc.createElementNS(alNS, "al:document-identifier"); annotatesn.appendChild(docident); docident.setAttributeNS(alNS, "al:orig-url", ((Element) annotatesn).getAttributeNS(rdfNS, "resource")); docident.setAttributeNS(alNS, "al:version", "1"); Iterator it = null; it = wf.getSortedWordlist(); Map.Entry ent; String word; int count; int i = 0; while (it.hasNext()) { ent = (Map.Entry) it.next(); word = ((String) ent.getKey()); count = ((Counter) ent.getValue()).count; if ((word.length() > 4) && (i < 10)) { Element wordelem = newdoc.createElementNS(alNS, "al:word"); wordelem.setAttributeNS(alNS, "al:freq", Integer.toString(count)); wordelem.appendChild(newdoc.createTextNode(word)); docident.appendChild(wordelem); i++; } } try { StringWriter strw = new StringWriter(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); xformer.transform(new DOMSource(newdoc), new StreamResult(strw)); messagedigest.update(strw.toString().getBytes()); byte[] md5bytes = messagedigest.digest(); annohash = ""; for (int b = 0; b < md5bytes.length; b++) { String s = Integer.toHexString(md5bytes[b] & 0xFF); annohash = annohash + ((s.length() == 1) ? "0" + s : s); } this.annohash = annohash; annoElem.setAttribute("xmlns:al", alNS); annoElem.setAttributeNS(alNS, "al:id", getAnnohash()); Location = (baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); newbodynode.setAttributeNS(rdfNS, "r:resource", baseurl + "/annotation/body/" + getAnnohash()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } annoMan.store(newdoc.getDocumentElement()); annoMan.createAnnoResource(newdoc.getDocumentElement(), getAnnohash()); if (htmlNode != null) annoMan.createAnnoBody(htmlNode, getAnnohash()); Location = (this.baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); this.responseDoc = newdoc; }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("arguments: sourcefile destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); }
Code Sample 2:
private static void _checkConfigFile() throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; boolean copy = false; File from = new java.io.File(filePath); if (!from.exists()) { Properties properties = new Properties(); properties.put(Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CELL_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CELL_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_VISIBILITY")); Company comp = PublicCompanyFactory.getDefaultCompany(); int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW"); for (int i = 1; i <= numberGenericVariables; i++) { properties.put(LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + i).replace(" ", "_"), Config.getStringProperty("ADDITIONAL_INFO_DEFAULT_VISIBILITY")); } try { properties.store(new java.io.FileOutputStream(filePath), null); } catch (Exception e) { Logger.error(UserManagerPropertiesFactory.class, e.getMessage(), e); } from = new java.io.File(filePath); copy = true; } String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File to = new java.io.File(tmpFilePath); if (!to.exists()) { to.createNewFile(); copy = true; } if (copy) { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "_checkLanguagesFiles:Property File Copy Failed " + e, e); } }
|
11
|
Code Sample 1:
private void createProperty(String objectID, String value, String propertyID, Long userID) throws JspTagException { ClassProperty classProperty = new ClassProperty(new Long(propertyID)); String newValue = value; if (classProperty.getName().equals("Password")) { try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(value.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } newValue = hexString.toString(); crypt.reset(); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } } Properties properties = new Properties(new Long(objectID), userID); try { Property property = properties.create(new Long(propertyID), newValue); pageContext.setAttribute(getId(), property); } catch (CreateException e) { throw new JspTagException("Could not create PropertyValue, CreateException: " + e.getMessage()); } }
Code Sample 2:
public String calculateDigest(String str) { StringBuffer s = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); for (byte d : digest) { s.append(Integer.toHexString((int) (d & 0xff))); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return s.toString(); }
|
00
|
Code Sample 1:
public byte[] authClient(String host, String user, String passwd, String realm, String serverChallenge) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream b64os = new BASE64EncoderStream(bos, Integer.MAX_VALUE); SecureRandom random; try { random = new SecureRandom(); md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { if (debugout != null) debugout.println("DEBUG DIGEST-MD5: " + ex); throw new IOException(ex.toString()); } StringBuffer result = new StringBuffer(); uri = "smtp/" + host; String nc = "00000001"; String qop = "auth"; byte[] bytes = new byte[32]; int resp; if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Begin authentication ..."); Hashtable map = tokenize(serverChallenge); if (realm == null) { String text = (String) map.get("realm"); realm = text != null ? new StringTokenizer(text, ",").nextToken() : host; } String nonce = (String) map.get("nonce"); random.nextBytes(bytes); b64os.write(bytes); b64os.flush(); String cnonce = bos.toString(); bos.reset(); md5.update(md5.digest(ASCIIUtility.getBytes(user + ":" + realm + ":" + passwd))); md5.update(ASCIIUtility.getBytes(":" + nonce + ":" + cnonce)); clientResponse = toHex(md5.digest()) + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":"; md5.update(ASCIIUtility.getBytes("AUTHENTICATE:" + uri)); md5.update(ASCIIUtility.getBytes(clientResponse + toHex(md5.digest()))); result.append("username=\"" + user + "\""); result.append(",realm=\"" + realm + "\""); result.append(",qop=" + qop); result.append(",nc=" + nc); result.append(",nonce=\"" + nonce + "\""); result.append(",cnonce=\"" + cnonce + "\""); result.append(",digest-uri=\"" + uri + "\""); result.append(",response=" + toHex(md5.digest())); if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Response => " + result.toString()); b64os.write(ASCIIUtility.getBytes(result.toString())); b64os.flush(); return bos.toByteArray(); }
Code Sample 2:
public static Vector getMetaKeywordsFromURL(String p_url) throws Exception { URL x_url = new URL(p_url); URLConnection x_conn = x_url.openConnection(); InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream()); BufferedReader x_reader = new BufferedReader(x_is_reader); String x_line = null; String x_lc_line = null; int x_body = -1; String x_keyword_list = null; int x_keywords = -1; String[] x_meta_keywords = null; while ((x_line = x_reader.readLine()) != null) { x_lc_line = x_line.toLowerCase(); x_keywords = x_lc_line.indexOf("<meta name=\"keywords\" content=\""); if (x_keywords != -1) { x_keywords = "<meta name=\"keywords\" content=\"".length(); x_keyword_list = x_line.substring(x_keywords, x_line.indexOf("\">", x_keywords)); x_keyword_list = x_keyword_list.replace(',', ' '); x_meta_keywords = Parser.extractWordsFromSpacedList(x_keyword_list); } x_body = x_lc_line.indexOf("<body"); if (x_body != -1) break; } Vector x_vector = new Vector(x_meta_keywords.length); for (int i = 0; i < x_meta_keywords.length; i++) x_vector.add(x_meta_keywords[i]); return x_vector; }
|
11
|
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 lock(String oid, String key) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setString(1, key); ps.setLong(2, System.currentTimeMillis()); ps.setString(3, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to lock object: OID = " + oid + ", KEY = " + key, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
|
11
|
Code Sample 1:
private static String format(String check) throws NoSuchAlgorithmException, UnsupportedEncodingException { check = check.replaceAll(" ", ""); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(check.getBytes("ISO-8859-1")); byte[] end = md5.digest(); String digest = ""; for (int i = 0; i < end.length; i++) { digest += ((end[i] & 0xff) < 16 ? "0" : "") + Integer.toHexString(end[i] & 0xff); } return digest; }
Code Sample 2:
public static String MD5(String str, String encoding) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } messageDigest.reset(); try { messageDigest.update(str.getBytes(encoding)); } 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])); } return md5StrBuff.toString(); }
|
11
|
Code Sample 1:
public void run() { if (getCommand() == null) throw new IllegalArgumentException("Given command is null!"); if (getSocketProvider() == null) throw new IllegalArgumentException("Given connection is not open!"); if (getCommand() instanceof ListCommand) { try { setReply(ReplyWorker.readReply(getSocketProvider(), true)); setStatus(ReplyWorker.FINISHED); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } return; } else if (getCommand() instanceof RetrieveCommand) { RetrieveCommand retrieveCommand = (RetrieveCommand) getCommand(); if (retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_I || retrieveCommand.getFromFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Download file: " + retrieveCommand.getFromFile().toString()); FileOutputStream out = null; FileChannel channel = null; if (getDownloadMethod() == RetrieveCommand.FILE_BASED) { out = new FileOutputStream(retrieveCommand.getToFile().getFile()); channel = out.getChannel(); if (retrieveCommand.getResumePosition() != -1) { try { channel.position(retrieveCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } int amount; try { while ((amount = getSocketProvider().read(buffer)) != -1) { if (amount == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); } buffer.flip(); while (buffer.hasRemaining()) { if (getDownloadMethod() == RetrieveCommand.STREAM_BASED) { int rem = buffer.remaining(); byte[] buf = new byte[rem]; buffer.get(buf, 0, rem); this.outputPipe.write(buf, 0, rem); } else if (getDownloadMethod() == RetrieveCommand.BYTEBUFFER_BASED) { } else { channel.write(buffer); } } buffer.clear(); setStatus(ReplyWorker.FINISHED); if (channel != null) channel.close(); if (this.outputPipe != null) this.outputPipe.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for download!"); return; } else if (getCommand() instanceof StoreCommand) { StoreCommand storeCommand = (StoreCommand) getCommand(); if (storeCommand.getToFile().getTransferType().intern() == Command.TYPE_I || storeCommand.getToFile().getTransferType().intern() == Command.TYPE_A) { try { log.debug("Upload file: " + storeCommand.getFromFile()); InputStream in = storeCommand.getStream(); int amount; int socketWrite; int socketAmount = 0; if (in instanceof FileInputStream) { FileChannel channel = ((FileInputStream) in).getChannel(); if (storeCommand.getResumePosition() != -1) { try { channel.position(storeCommand.getResumePosition()); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); try { channel.close(); } catch (IOException ioe2) { } return; } } try { while ((amount = channel.read(buffer)) != -1) { buffer.flip(); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount += socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); channel.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { channel.close(); getSocketProvider().close(); } catch (Exception e) { } } } else { try { while ((amount = in.read(buffer.array())) != -1) { buffer.flip(); buffer.limit(amount); socketWrite = 0; while ((socketWrite = getSocketProvider().write(buffer)) != -1) { socketAmount = socketWrite; if (amount <= socketAmount) { break; } if (socketWrite == 0) { try { Thread.sleep(4); } catch (InterruptedException e) { } } } if (socketWrite == -1) { break; } socketAmount = 0; buffer.clear(); } setStatus(ReplyWorker.FINISHED); in.close(); getSocketProvider().close(); } catch (IOException ioe) { setCaughtException(ioe); setStatus(ReplyWorker.ERROR_IO_EXCEPTION); } finally { try { in.close(); getSocketProvider().close(); } catch (Exception e) { } } } } catch (FileNotFoundException fnfe) { setCaughtException(fnfe); setStatus(ReplyWorker.ERROR_FILE_NOT_FOUND); } } else throw new IllegalArgumentException("Unknown file transfer type for upload!"); } else throw new IllegalArgumentException("Given command is not supported!"); }
Code Sample 2:
private void importSources() { InputOutput io = IOProvider.getDefault().getIO("Import Sources", false); io.select(); PrintWriter pw = new PrintWriter(io.getOut()); pw.println("Beginning transaction...."); pw.println("Processing selected files:"); String[][] selectedFiles = getSelectedFiles(pw); if (selectedFiles.length == 0) { pw.println("There are no files to process."); } else { pw.println(new StringBuilder("Importing ").append(selectedFiles.length).append(" files to ").append(group.getDisplayName()).append(" within project ").append(ProjectUtils.getInformation(project).getDisplayName()).toString()); FileObject destFO = group.getRootFolder(); try { String destRootDir = new File(destFO.getURL().toURI()).getAbsolutePath(); if (destFO.canWrite()) { for (String[] s : selectedFiles) { try { File parentDir = new File(new StringBuilder(destRootDir).append(File.separator).append(s[0]).toString()); if (!parentDir.exists()) { parentDir.mkdirs(); } File f = new File(new StringBuilder(destRootDir).append(s[0]).append(File.separator).append(s[1]).toString()); if (!f.exists()) { f.createNewFile(); } FileInputStream fin = null; FileOutputStream fout = null; byte[] b = new byte[1024]; int read = -1; try { File inputFile = new File(new StringBuilder(rootDir).append(s[0]).append(File.separator).append(s[1]).toString()); pw.print(new StringBuilder("\tImporting file:").append(inputFile.getAbsolutePath()).toString()); fin = new FileInputStream(inputFile); fout = new FileOutputStream(f); while ((read = fin.read(b)) != -1) { fout.write(b, 0, read); } pw.println(" ... done"); fin.close(); fout.close(); } catch (FileNotFoundException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } finally { if (fin != null) { try { fin.close(); } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } } if (fout != null) { try { fout.close(); } catch (IOException ex) { } } } } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } } pw.println("Import sources completed successfully."); } else { pw.println("Cannot write to the destination directory." + " Please check the priviledges and try again."); return; } } catch (FileStateInvalidException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); pw.println("Import failed!!"); } catch (URISyntaxException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); pw.println("Import failed!!"); } } }
|
11
|
Code Sample 1:
public AssessmentItemType getAssessmentItemType(String filename) { if (filename.contains(" ") && (System.getProperty("os.name").contains("Windows"))) { File source = new File(filename); String tempDir = System.getenv("TEMP"); File dest = new File(tempDir + "/temp.xml"); MQMain.logger.info("Importing from " + dest.getAbsolutePath()); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } filename = tempDir + "/temp.xml"; } } AssessmentItemType assessmentItemType = null; JAXBElement<?> jaxbe = null; try { XMLReader reader = XMLReaderFactory.createXMLReader(); ChangeNamespace convertfromv2p0tov2p1 = new ChangeNamespace(reader, "http://www.imsglobal.org/xsd/imsqti_v2p0", "http://www.imsglobal.org/xsd/imsqti_v2p1"); SAXSource source = null; try { FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = null; try { isr = new InputStreamReader(fis, "UTF-8"); } catch (UnsupportedEncodingException e) { } InputSource is = new InputSource(isr); source = new SAXSource(convertfromv2p0tov2p1, is); } catch (FileNotFoundException e) { MQMain.logger.error("SAX/getAssessmentItemType/file not found"); } jaxbe = (JAXBElement<?>) MQModel.qtiCf.unmarshal(MQModel.imsqtiUnmarshaller, source); assessmentItemType = (AssessmentItemType) jaxbe.getValue(); } catch (JAXBException e) { MQMain.logger.error("JAX/getAssessmentItemType", e); } catch (SAXException e) { MQMain.logger.error("SAX/getAssessmentItemType", e); } return assessmentItemType; }
Code Sample 2:
public static void importDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = output + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); createTablesDB(); } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); long tiempoInicio = System.currentTimeMillis(); String directoryPath = input + File.separator; File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(input + File.separator + G.imagesName); if (!fileXML.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE); } else { SAXBuilder builder = new SAXBuilder(false); Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); List<Element> globalLanguages = root.getChild("languages").getChildren("language"); Iterator<Element> langsI = globalLanguages.iterator(); HashMap<String, Integer> languageIDs = new HashMap<String, Integer>(); HashMap<String, Integer> typeIDs = new HashMap<String, Integer>(); Element e; int i = 0; int contTypes = 0; int contImages = 0; while (langsI.hasNext()) { e = langsI.next(); languageIDs.put(e.getText(), i); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)"); stmt.setInt(1, i); stmt.setString(2, e.getText()); stmt.executeUpdate(); stmt.close(); i++; } G.conn.setAutoCommit(false); while (j.hasNext()) { Element image = (Element) j.next(); String id = image.getAttributeValue("id"); List languages = image.getChildren("language"); Iterator k = languages.iterator(); if (exists(list, id)) { String pathSrc = directoryPath.concat(id); String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = output + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } while (k.hasNext()) { Element languageElement = (Element) k.next(); String language = languageElement.getAttributeValue("id"); List words = languageElement.getChildren("word"); Iterator l = words.iterator(); while (l.hasNext()) { Element wordElement = (Element) l.next(); String type = wordElement.getAttributeValue("type"); if (!typeIDs.containsKey(type)) { typeIDs.put(type, contTypes); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)"); stmt.setInt(1, contTypes); stmt.setString(2, type); stmt.executeUpdate(); stmt.close(); contTypes++; } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, wordElement.getText().toLowerCase()); stmt.setInt(2, languageIDs.get(language)); stmt.setInt(3, typeIDs.get(type)); stmt.setString(4, id); stmt.setString(5, id); stmt.executeUpdate(); stmt.close(); if (contImages == 5000) { G.conn.commit(); contImages = 0; } else contImages++; } } } else { } } G.conn.setAutoCommit(true); G.conn.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static String encrypt(String plaintext) throws NoSuchAlgorithmException { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { logger.error("unable to encrypt password" + e.getMessage()); throw new NoSuchAlgorithmException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("unable to encrypt password" + e.getMessage()); throw new NoSuchAlgorithmException(e.getMessage()); } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
|
00
|
Code Sample 1:
public static void retriveRemote(ISource source, Node[] nodes, String outDirName, boolean isBinary) throws Exception { FTPClient client = new FTPClient(); client.connect(source.getSourceDetail().getHost()); client.login(source.getSourceDetail().getUser(), source.getSourceDetail().getPassword()); if (isBinary) client.setFileType(FTPClient.BINARY_FILE_TYPE); FileOutputStream out = null; for (Node node : nodes) { if (!node.isLeaf()) { Node[] childern = source.getChildern(node); File dir = new File(outDirName + File.separator + node.getAlias()); dir.mkdir(); retriveRemote(source, childern, outDirName + File.separator + node.getAlias(), isBinary); } else { out = new FileOutputStream(outDirName + File.separator + node.getAlias()); client.retrieveFile(node.getAbsolutePath(), out); out.flush(); out.close(); } } client.disconnect(); }
Code Sample 2:
public static boolean exec_applet(String fname, VarContainer vc, ActionContainer ac, ThingTypeContainer ttc, Output OUT, InputStream IN, boolean AT, Statement state, String[] arggies) { if (!urlpath.endsWith("/")) { urlpath = urlpath + '/'; } if (!urlpath.startsWith("http://")) { urlpath = "http://" + urlpath; } String url = urlpath; if (fname.startsWith("dusty_")) { url = url + "libraries/" + fname; } else { url = url + "users/" + fname; } StringBuffer src = new StringBuffer(2400); try { String s; BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while ((s = br.readLine()) != null) { src.append(s).append('\n'); } br.close(); } catch (Exception e) { OUT.println(new DSOut(DSOut.ERR_OUT, -1, "Dustyscript failed at reading the file'" + fname + "'\n\t...for 'use' statement"), vc, AT); return false; } fork(src, vc, ac, ttc, OUT, IN, AT, state, arggies); return true; }
|
00
|
Code Sample 1:
public static void BubbleSortFloat1(float[] num) { boolean flag = true; // set flag to true to begin first pass float temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } }
Code Sample 2:
public void save(String oid, String key, Serializable obj) throws PersisterException { String lock = getLock(oid); if (lock == null) { throw new PersisterException("Object does not exist: OID = " + oid); } else if (!NULL.equals(lock) && (!lock.equals(key))) { throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key); } Connection conn = null; PreparedStatement ps = null; try { byte[] data = serialize(obj); conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("update " + _table_name + " set " + _data_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?"); ps.setBinaryStream(1, new ByteArrayInputStream(data), data.length); ps.setLong(2, System.currentTimeMillis()); ps.setString(3, oid); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to save object: OID = " + oid, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
|
11
|
Code Sample 1:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); int i; Vector images = new Vector(); images = dataBase.allImageSearch(); lengthOfTask = images.size() * 2; String directory = directoryPath + "Images" + myDirectory.separator; File newDirectoryFolder = new File(directory); newDirectoryFolder.mkdirs(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); doc = domBuilder.newDocument(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Element dbElement = doc.createElement("dataBase"); for (i = 0; ((i < images.size()) && !stop); i++) { current = i; String element = (String) images.elementAt(i); String pathSrc = "Images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(myDirectory.separator) + 1, pathSrc.length()); String pathDst = directory + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector keyWords = new Vector(); keyWords = dataBase.asociatedConceptSearch((String) images.elementAt(i)); Element imageElement = doc.createElement("image"); Element imageNameElement = doc.createElement("name"); imageNameElement.appendChild(doc.createTextNode(name)); imageElement.appendChild(imageNameElement); for (int j = 0; j < keyWords.size(); j++) { Element keyWordElement = doc.createElement("keyWord"); keyWordElement.appendChild(doc.createTextNode((String) keyWords.elementAt(j))); imageElement.appendChild(keyWordElement); } dbElement.appendChild(imageElement); } try { doc.appendChild(dbElement); File dst = new File(directory.concat("Images")); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF-8")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(bufferWriter); transformer.transform(source, result); bufferWriter.close(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } current = lengthOfTask; }
Code Sample 2:
public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new RuntimeException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); }
|
11
|
Code Sample 1:
private String encryptPassword(String password) throws NoSuchAlgorithmException { MessageDigest encript = MessageDigest.getInstance("MD5"); encript.update(password.getBytes()); byte[] b = encript.digest(); int size = b.length; StringBuffer h = new StringBuffer(size); for (int i = 0; i < size; i++) { h.append(b[i]); } return h.toString(); }
Code Sample 2:
public static boolean verify(String password, String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) { throw new InternalError("Not implemented"); } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("Invalid algorithm"); } } else { return false; } byte[] data = Base64.decode(base64.toCharArray()); byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(password.getBytes()); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); }
|
00
|
Code Sample 1:
public static void main(String arg[]) { try { URL url = new URL(tempurl); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); connect.setDoInput(true); connect.setDoOutput(true); BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream(), "gb2312")); String line = null; StringBuffer content = new StringBuffer(); while ((line = in.readLine()) != null) { content.append(line); } in.close(); url = null; String msg = content.toString(); Matcher m = p.matcher(msg); while (m.find()) { System.out.println(m.group(1) + "---" + m.group(2) + "---" + m.group(3) + "---" + m.group(4) + "---" + m.group(5) + "---"); } } catch (Exception e) { System.out.println("Error:"); System.out.println(e.getStackTrace()); } }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
public static boolean copy(File src, File dest) { boolean result = true; String files[] = null; if (src.isDirectory()) { files = src.list(); result = dest.mkdir(); } else { files = new String[1]; files[0] = ""; } if (files == null) { files = new String[0]; } for (int i = 0; (i < files.length) && result; i++) { File fileSrc = new File(src, files[i]); File fileDest = new File(dest, files[i]); if (fileSrc.isDirectory()) { result = copy(fileSrc, fileDest); } else { FileChannel ic = null; FileChannel oc = null; try { ic = (new FileInputStream(fileSrc)).getChannel(); oc = (new FileOutputStream(fileDest)).getChannel(); ic.transferTo(0, ic.size(), oc); } catch (IOException e) { log.error(sm.getString("expandWar.copy", fileSrc, fileDest), e); result = false; } finally { if (ic != null) { try { ic.close(); } catch (IOException e) { } } if (oc != null) { try { oc.close(); } catch (IOException e) { } } } } } return result; }
Code Sample 2:
public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
11
|
Code Sample 1:
public String process(URL url) throws IOException { String line, results = ""; InputStream is = url.openStream(); BufferedReader dis = new BufferedReader(new InputStreamReader(is)); while ((line = dis.readLine()) != null) { results += line + "\n"; } System.out.println(results); return results; }
Code Sample 2:
public void updateCoordinates(Address address) { String mapURL = "http://maps.google.com/maps/geo?output=csv"; String mapKey = "ABQIAAAAi__aT6y6l86JjbootR-p9xQd1nlEHNeAVGWQhS84yIVN5yGO2RQQPg9QLzy82PFlCzXtMNe6ofKjnA"; String location = address.getStreet() + " " + address.getZip() + " " + address.getCity(); if (logger.isDebugEnabled()) { logger.debug(location); } double[] coordinates = { 0.0, 0.0 }; String content = ""; try { location = URLEncoder.encode(location, "UTF-8"); String request = mapURL + "&q=" + location + "&key=" + mapKey; URL url = new URL(request); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } reader.close(); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error from google: " + e.getMessage()); } } if (logger.isDebugEnabled()) { logger.debug(content); } StringTokenizer tokenizer = new StringTokenizer(content, ","); int i = 0; while (tokenizer.hasMoreTokens()) { i++; String token = tokenizer.nextToken(); if (i == 3) { coordinates[0] = Double.parseDouble(token); } if (i == 4) { coordinates[1] = Double.parseDouble(token); } } if ((coordinates[0] != 0) || (coordinates[1] != 0)) { address.setLatitude(coordinates[0]); address.setLongitude(coordinates[1]); } else { if (logger.isDebugEnabled()) { logger.debug("Invalid coordinates for address " + address.getId()); } } }
|
00
|
Code Sample 1:
public static boolean update(String user, String pass, String channelString, String globalIP) { FTPClient ftp = new FTPClient(); int reply; try { ftp.connect("witna.co.uk", 21); ftp.login(user, pass); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { updateChannelList(ftp, channelString); if (!ipUpdated) { ipUpdated = updateMasterChannelIP(ftp, globalIP); } ftp.disconnect(); return true; } else { ftp.disconnect(); } } catch (Exception ex) { ex.printStackTrace(); } return false; }
Code Sample 2:
public void xtest7() throws Exception { System.out.println("Lowagie"); FileInputStream inputStream = new FileInputStream("C:/Temp/arquivo.pdf"); PDFBoxManager manager = new PDFBoxManager(); InputStream[] images = manager.toImage(inputStream, "jpeg"); int count = 0; for (InputStream image : images) { FileOutputStream outputStream = new FileOutputStream("C:/Temp/arquivo_" + count + ".jpg"); IOUtils.copy(image, outputStream); count++; outputStream.close(); } inputStream.close(); }
|
11
|
Code Sample 1:
public void onUploadClicked(Event event) { Media[] medias = null; try { medias = Fileupload.get("Select one or more files to upload to " + "the current directory.", "Upload Files", 5); } catch (Exception e) { log.error("An exception occurred when displaying the file " + "upload dialog", e); } if (medias == null) { return; } for (Media media : medias) { String name = media.getName(); CSPath potentialFile = model.getPathForFile(name); if (media.isBinary()) { CSPathOutputStream writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathOutputStream(potentialFile); IOUtils.copy(media.getStreamData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } else { CSPathWriter writer = null; try { potentialFile.createNewFile(); if (potentialFile.exists()) { writer = new CSPathWriter(potentialFile); IOUtils.write(media.getStringData(), writer); } } catch (IOException e) { displayError("An error occurred when uploading the file " + name + ": " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } model.fileCleanup(potentialFile); updateFileGrid(); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("utf-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final EditText eText = (EditText) findViewById(R.id.address); final Button button = (Button) findViewById(R.id.ButtonGo); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("m", "login")); nameValuePairs.add(new BasicNameValuePair("c", "User")); nameValuePairs.add(new BasicNameValuePair("password", "cloudisgreat")); nameValuePairs.add(new BasicNameValuePair("alias", "cs588")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); String result = ""; try { HttpResponse response = httpclient.execute(httppost); result = EntityUtils.toString(response.getEntity()); } catch (Exception e) { result = e.getMessage(); } LayoutInflater inflater = (LayoutInflater) WebTest.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.window1, null); final PopupWindow popup = new PopupWindowTest(layout, 100, 100); Button b = (Button) layout.findViewById(R.id.test_button); b.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d("Debug", "Button activate"); popup.dismiss(); return false; } }); popup.showAtLocation(layout, Gravity.CENTER, 0, 0); View layout2 = inflater.inflate(R.layout.window1, null); final PopupWindow popup2 = new PopupWindowTest(layout2, 100, 100); TextView tview = (TextView) layout2.findViewById(R.id.pagetext); tview.setText(result); popup2.showAtLocation(layout, Gravity.CENTER, 50, -90); } catch (Exception e) { Log.d("Debug", e.toString()); } } }); }
|
00
|
Code Sample 1:
@Transient private String md5sum(String text) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(text.getBytes()); byte messageDigest[] = md.digest(); return bufferToHex(messageDigest, 0, messageDigest.length); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
Code Sample 2:
public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); InputStream is = CheckAvailability.class.getResourceAsStream("/isbns.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String isbn = null; HttpGet get = null; while ((isbn = br.readLine().split(" ")[0]) != null) { System.out.println("Target url: \n\t" + String.format(isbnSearchUrl, isbn)); get = new HttpGet(String.format(isbnSearchUrl, isbn)); HttpResponse resp = httpclient.execute(get); Scanner s = new Scanner(resp.getEntity().getContent()); String pattern = s.findWithinHorizon("((\\d*) hold[s]? on first copy returned of (\\d*) )?[cC]opies", 0); if (pattern != null) { MatchResult match = s.match(); if (match.groupCount() == 3) { if (match.group(2) == null) { System.out.println(isbn + ": copies available"); } else { System.out.println(isbn + ": " + match.group(2) + " holds on " + match.group(3) + " copies"); } } } else { System.out.println(isbn + ": no match"); } get.abort(); } }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { closeQuietly(in); closeQuietly(out); } return success; }
Code Sample 2:
protected byte[] readGZippedBytes(TupleInput in) { final boolean is_compressed = in.readBoolean(); byte array[] = readBytes(in); if (array == null) return null; if (!is_compressed) { return array; } try { ByteArrayInputStream bais = new ByteArrayInputStream(array); GZIPInputStream gzin = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); IOUtils.copyTo(gzin, baos); gzin.close(); bais.close(); return baos.toByteArray(); } catch (IOException err) { throw new RuntimeException(err); } }
|
11
|
Code Sample 1:
public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public final void saveAsCopy(String current_image, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; String source = temp_dir + key + current_image; 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"); } }
|
00
|
Code Sample 1:
private void copyTemplate(String resource, OutputStream outputStream) throws IOException { URL url = Tools.getResource(resource); if (url == null) { throw new IOException("could not find resource"); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8"))); String line = null; do { line = reader.readLine(); if (line != null) { writer.write(line); writer.newLine(); } } while (line != null); reader.close(); writer.close(); }
Code Sample 2:
private void request() { try { connection = (HttpURLConnection) new URL(url).openConnection(); if (isCometConnection) { connection.setReadTimeout(0); } else { connection.setReadTimeout(30000); } connection.setInstanceFollowRedirects(false); connection.setDoInput(true); connection.setRequestMethod(method); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB5"); if ("post".equalsIgnoreCase(method)) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } if (user != null) { String auth = user + ":" + (password != null ? password : ""); String base64Auth = HttpRequest.Base64.byteArrayToBase64(auth.getBytes()); connection.setRequestProperty("Authorization", "Basic " + base64Auth); } for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); connection.setRequestProperty(key, (String) headers.get(key)); } connection.setUseCaches(false); if (checkAbort()) return; if ("post".equalsIgnoreCase(method)) { DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); activeOS = dos; if (content != null) { dos.writeBytes(content); } if (checkAbort()) return; dos.flush(); dos.close(); activeOS = null; } if (checkAbort()) return; InputStream is = null; try { is = connection.getInputStream(); } catch (IOException e) { if (checkAbort()) return; readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection = null; readyState = 0; return; } activeIS = is; if (readyState < 2) { readyState = 2; status = connection.getResponseCode(); statusText = connection.getResponseMessage(); if (onreadystatechange != null) { onreadystatechange.onSent(); } } receiving = initializeReceivingMonitor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buffer = new byte[10240]; int read; while (!toAbort && (read = is.read(buffer)) != -1) { if (checkAbort()) return; if (readyState != 3) { readyState = 3; if (onreadystatechange != null) { onreadystatechange.onReceiving(); } } boolean received = false; if (receiving != null) { received = receiving.receiving(baos, buffer, 0, read); } if (!received) { baos.write(buffer, 0, read); } } if (checkAbort()) return; is.close(); activeIS = null; responseText = null; String type = connection.getHeaderField("Content-Type"); if (type != null) { String charset = null; String lowerType = type.toLowerCase(); int idx = lowerType.indexOf("charset="); if (idx != -1) { charset = type.substring(idx + 8); } else { idx = lowerType.indexOf("/xml"); if (idx != -1) { String tmp = baos.toString(); Matcher matcher = Pattern.compile("<\\?.*encoding\\s*=\\s*[\'\"]([^'\"]*)[\'\"].*\\?>", Pattern.MULTILINE).matcher(tmp); if (matcher.find()) { charset = matcher.group(1); } else { responseText = tmp; } } else { idx = lowerType.indexOf("html"); if (idx != -1) { String tmp = baos.toString(); Matcher matcher = Pattern.compile("<meta.*content\\s*=\\s*[\'\"][^'\"]*charset\\s*=\\s*([^'\"]*)\\s*[\'\"].*>", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(tmp); if (matcher.find()) { charset = matcher.group(1); } else { responseText = tmp; } } } } if (charset != null) { try { responseText = baos.toString(charset); } catch (UnsupportedEncodingException e) { } } } if (responseText == null) { try { responseText = baos.toString("iso-8859-1"); } catch (UnsupportedEncodingException e) { responseText = baos.toString(); } } readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection.disconnect(); readyState = 0; } catch (Exception e) { if (checkAbort()) return; e.printStackTrace(); readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection = null; readyState = 0; } }
|
11
|
Code Sample 1:
public static String getSHADigest(String input) { if (input == null) return null; MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA-1"); } catch (java.security.NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } if (sha == null) throw new RuntimeException("No message digest"); sha.update(input.getBytes()); byte[] data = sha.digest(); StringBuffer buf = new StringBuffer(data.length * 2); for (int i = 0; i < data.length; i++) { int value = data[i] & 0xff; buf.append(hexDigit(value >> 4)); buf.append(hexDigit(value)); } return buf.toString(); }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
00
|
Code Sample 1:
public static byte[] createAuthenticator(ByteBuffer data, String secret) { assert data.isDirect() == false : "must not a direct ByteBuffer"; int pos = data.position(); if (pos < RadiusPacket.MIN_PACKET_LENGTH) { System.err.println("packet too small"); return null; } try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] arr = data.array(); md5.reset(); md5.update(arr, 0, pos); md5.update(secret.getBytes()); return md5.digest(); } catch (NoSuchAlgorithmException nsaex) { throw new RuntimeException("Could not access MD5 algorithm, fatal error"); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
private void loadMap(URI uri) throws IOException { BufferedReader reader = null; InputStream stream = null; try { URL url = uri.toURL(); stream = url.openStream(); if (url.getFile().endsWith(".gz")) { stream = new GZIPInputStream(stream); } reader = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { String[] parts = line.split(" "); if (parts.length == 2) { pinyinZhuyinMap.put(parts[0], parts[1]); zhuyinPinyinMap.put(parts[1], parts[0]); } } } } finally { if (reader != null) { reader.close(); } } }
Code Sample 2:
@Override public void parse() throws DocumentException, IOException { URL url = new URL(this.XMLAddress); URLConnection con = url.openConnection(); BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream())); String str; bStream.readLine(); while ((str = bStream.readLine()) != null) { String[] tokens = str.split("(\\s+)"); String charCode = tokens[0].replaceAll("([0-9+])", ""); Float value = Float.parseFloat(tokens[2].trim().replace(",", ".")); ResultUnit unit = new ResultUnit(charCode, value, DEFAULT_MULTIPLIER); this.set.add(unit); } }
|
00
|
Code Sample 1:
public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } }
Code Sample 2:
public static void parseRDFXML(String url, StatementHandler handler) throws IOException { ARP parser = new ARP(); parser.getHandlers().setStatementHandler(handler); URLConnection conn = new URL(url).openConnection(); String encoding = conn.getContentEncoding(); InputStream in = null; try { in = conn.getInputStream(); if (encoding == null) parser.load(in, url); else parser.load(new InputStreamReader(in, encoding), url); in.close(); } catch (org.xml.sax.SAXException e) { throw new OntopiaRuntimeException(e); } finally { if (in != null) in.close(); } }
|
00
|
Code Sample 1:
public <T extends FetionResponse> T executeAction(FetionAction<T> fetionAction) throws IOException { URL url = new URL(fetionAction.getProtocol().name().toLowerCase() + "://" + fetionUrl + fetionAction.getRequestData()); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); byte[] buffer = new byte[10240]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int read = 0; while ((read = in.read(buffer)) > 0) { bout.write(buffer, 0, read); } return fetionAction.processResponse(parseRawResponse(bout.toByteArray())); }
Code Sample 2:
public File createTemporaryFile() throws IOException { URL url = clazz.getResource(resource); if (url == null) { throw new IOException("No resource available from '" + clazz.getName() + "' for '" + resource + "'"); } String extension = getExtension(resource); String prefix = "resource-temporary-file-creator"; File file = File.createTempFile(prefix, extension); InputStream input = url.openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(file); com.volantis.synergetics.io.IOUtils.copyAndClose(input, output); return file; }
|
11
|
Code Sample 1:
public static String executePost(String urlStr, Map paramsMap) throws IOException { StringBuffer result = new StringBuffer(); HttpURLConnection connection = null; URL url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); PrintWriter out = new PrintWriter(connection.getOutputStream()); Iterator paramKeys = paramsMap.keySet().iterator(); while (paramKeys.hasNext()) { String paramName = (String) paramKeys.next(); out.print(paramName + "=" + paramsMap.get(paramName)); if (paramKeys.hasNext()) { out.print('&'); } } out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { result.append(inputLine); } in.close(); out.close(); connection.disconnect(); String msg = result.toString(); return stripOuterElement(msg); }
Code Sample 2:
private String read(URL url) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer text = new StringBuffer(); String line; while ((line = in.readLine()) != null) { text.append(line); } return text.toString(); } finally { in.close(); } }
|
11
|
Code Sample 1:
@Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
private static String retrieveVersion(InputStream is) throws RepositoryException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { IOUtils.copy(is, buffer); } catch (IOException e) { throw new RepositoryException(exceptionLocalizer.format("device-repository-file-missing", DeviceRepositoryConstants.VERSION_FILENAME), e); } return buffer.toString().trim(); }
|
11
|
Code Sample 1:
public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String encryptPassword(String originalPassword) { if (!StringUtils.hasText(originalPassword)) { originalPassword = randomPassword(); } try { MessageDigest md5 = MessageDigest.getInstance(PASSWORD_ENCRYPTION_TYPE); md5.update(originalPassword.getBytes()); byte[] bytes = md5.digest(); int value; StringBuilder buf = new StringBuilder(); for (byte aByte : bytes) { value = aByte; if (value < 0) { value += 256; } if (value < 16) { buf.append("0"); } buf.append(Integer.toHexString(value)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { log.debug("Do not encrypt password,use original password", e); return originalPassword; } }
|
00
|
Code Sample 1:
private void bubbleSort(int values[]) { PerfMonTimer timerOuter = PerfMonTimer.start("SortingTest.bubbleSort"); try { int len = values.length - 1; for (int i = 0; i < len; i++) { for (int j = 0; j < len - i; j++) { if (values[j] > values[j + 1]) { int tmp = values[j]; values[j] = values[j + 1]; values[j + 1] = tmp; } } } } finally { PerfMonTimer.stop(timerOuter); } }
Code Sample 2:
public void testDecode1000BinaryStore() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/DataStore/DataStore.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.STRICT_OPTIONS); String[] base64Values100 = { "R0lGODdhWALCov////T09M7Ozqampn19fVZWVi0tLQUFBSxYAsJAA/8Iutz+MMpJq7046827/2Ao\n", "/9j/4BBKRklGAQEBASwBLP/hGlZFeGlmTU0qF5ZOSUtPTiBDT1JQT1JBVElPTk5J", "R0lGODlhHh73KSkpOTk5QkJCSkpKUlJSWlpaY2Nja2trc3Nze3t7hISEjIyMlJSUnJycpaWlra2t\n" + "tbW1vb29xsbGzs7O1tbW3t7e5+fn7+/v//////////8=", "/9j/4BBKRklGAQEBAf/bQwYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBc=", "R0lGODlhHh73M2aZzP8zMzNmM5kzzDP/M2YzZmZmmWbM", "/9j/4BBKRklGAQEBAf/bQwYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsj\n" + "HBYWICwgIyYnKSopGR8tMC0oMCUoKSj/20M=", "R0lGODdhWAK+ov////j4+NTU1JOTk0tLSx8fHwkJCSxYAr5AA/8IMkzjrEEmahy23SpC", "R0lGODdh4QIpAncJIf4aU29mdHdhcmU6IE1pY3Jvc29mdCBPZmZpY2Us4QIpAof//////8z//5n/\n", "R0lGODdhWAK+ov////v7++fn58DAwI6Ojl5eXjExMQMDAyxYAr5AA/8Iutz+MMpJq7046827/2Ao\n" + "jmRpnmiqPsKxvg==", "R0lGODdh4QIpAncJIf4aU29mdHdhcmU6IE1pY3Jvc29mdCBPZmZpY2Us4QIpAob//////8z//5n/\nzP//zMw=" }; AlignmentType alignment = AlignmentType.bitPacked; Transmogrifier encoder = new Transmogrifier(); encoder.setEXISchema(grammarCache); encoder.setAlignmentType(alignment); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/DataStore/instance/1000BinaryStore.xml"); encoder.encode(new InputSource(url.openStream())); byte[] bts = baos.toByteArray(); Scanner scanner; int n_texts; EXIDecoder decoder = new EXIDecoder(999); decoder.setEXISchema(grammarCache); decoder.setAlignmentType(alignment); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); EXIEvent exiEvent; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (++n_texts % 100 == 0) { String expected = base64Values100[(n_texts / 100) - 1]; String val = exiEvent.getCharacters().makeString(); Assert.assertEquals(expected, val); } } } Assert.assertEquals(1000, n_texts); }
|
00
|
Code Sample 1:
public T04MixedOTSDTMUnitTestCase(String name) throws java.io.IOException { super(name); java.net.URL url = ClassLoader.getSystemResource("host0.cosnaming.jndi.properties"); jndiProps = new java.util.Properties(); jndiProps.load(url.openStream()); }
Code Sample 2:
public static void main(String[] args) { boolean rotateLeft = false; boolean rotateRight = false; boolean exclude = false; boolean reset = false; float quality = 0f; int thumbArea = 12000; for (int i = 0; i < args.length; i++) { if (args[i].equals("-rotl")) rotateLeft = true; else if (args[i].equals("-rotr")) rotateRight = true; else if (args[i].equals("-exclude")) exclude = true; else if (args[i].equals("-reset")) reset = true; else if (args[i].equals("-quality")) quality = Float.parseFloat(args[++i]); else if (args[i].equals("-area")) thumbArea = Integer.parseInt(args[++i]); else { File f = new File(args[i]); try { Tools t = new Tools(f); if (exclude) { URL url = t.getClass().getResource("exclude.jpg"); InputStream is = url.openStream(); File dest = t.getExcludeFile(); OutputStream os = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); t.getOutFile().delete(); t.getThumbFile().delete(); System.exit(0); } if (reset) { t.getOutFile().delete(); t.getThumbFile().delete(); t.getExcludeFile().delete(); System.exit(0); } if (quality > 0) t.setQuality(quality); if (t.getType() == Tools.THUMB || t.getType() == Tools.EXCLUDE) t.load(t.getBaseFile()); else t.load(t.getSourceFile()); File out = t.getOutFile(); if (rotateLeft) t.rotateLeft(); else if (rotateRight) t.rotateRight(); t.save(out); t.getExcludeFile().delete(); t.getThumbFile().delete(); System.exit(0); } catch (Throwable e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "The operation could not be performed", "JPhotoAlbum", JOptionPane.ERROR_MESSAGE); System.exit(1); } } } }
|
11
|
Code Sample 1:
public void test_digest() throws UnsupportedEncodingException { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA"); assertNotNull(sha); } catch (NoSuchAlgorithmException e) { fail("getInstance did not find algorithm"); } sha.update(MESSAGE.getBytes("UTF-8")); byte[] digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST)); sha.reset(); for (int i = 0; i < 63; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_63_As)); sha.reset(); for (int i = 0; i < 64; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_64_As)); sha.reset(); for (int i = 0; i < 65; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_65_As)); testSerializationSHA_DATA_1(sha); testSerializationSHA_DATA_2(sha); }
Code Sample 2:
public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { throw new ForumException("" + e); } return hexString.toString(); }
|
00
|
Code Sample 1:
public static void BubbleSortFloat2(float[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) { float temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); }
Code Sample 2:
private static Pair<URL, DTObject> loadRecruitersConf(URL url) throws ExternalConfigException, SyntaxException, IOException { Assert.notNullArg(url, "resourceName may not be null"); InputStream is = url.openStream(); try { Object value = ObjectParser.parse(is); if (!(value instanceof DTObject)) { throw new ExternalConfigException("The global value in " + url + " must be a DTObject"); } return new Pair<URL, DTObject>(url, (DTObject) value); } finally { is.close(); } }
|
11
|
Code Sample 1:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
@Override public void runTask(HashMap pjobParameters) throws Exception { if (hasRequiredResources(isSubTask())) { String lstrSource = getSourceFilename(); String lstrTarget = getTargetFilename(); if (getSourceDirectory() != null) { lstrSource = getSourceDirectory() + File.separator + getSourceFilename(); } if (getTargetDirectory() != null) { lstrTarget = getTargetDirectory() + File.separator + getTargetFilename(); } GZIPInputStream lgzipInput = new GZIPInputStream(new FileInputStream(lstrSource)); OutputStream lfosGUnzip = new FileOutputStream(lstrTarget); byte[] buf = new byte[1024]; int len; while ((len = lgzipInput.read(buf)) > 0) lfosGUnzip.write(buf, 0, len); lgzipInput.close(); lfosGUnzip.close(); } }
|
11
|
Code Sample 1:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Git git = Git.getCurrent(req.getSession()); GitComponentReader gitReader = git.getComponentReader("warpinjector"); String id = req.getParameter("id"); GitElement element = gitReader.getElement(id); String path = (String) element.getAttribute("targetdir"); File folder = new File(path); PrintWriter out = helper.getPrintWriter(resp); MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages"); Locale locale = req.getLocale(); helper.header(out, messageBundle, locale); if (git.getUser() == null) { helper.notLoggedIn(out, messageBundle, locale); } else { try { MultiPartRequest request = new MultiPartRequest(req); FileInfo info = request.getFileInfo("userfile"); File file = info.getFile(); out.println("tempfile found: " + file.getPath() + "<br>"); String fileName = info.getFileName(); File target = new File(folder, fileName); out.println("copying tempfile to: " + target.getPath() + "<br>"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(target); byte buf[] = new byte[1024]; int n; while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); out.println("copy successful - deleting old tempfile<br>"); out.println("deletion result. " + file.delete() + "<p>"); out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale)); out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>"); } catch (Exception ex) { out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale)); } } helper.footer(out); }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing 'file' Arg"); return; } int mfid = NumberUtils.toInt(arg); Object sageFile = MediaFileAPI.GetMediaFileForID(mfid); if (sageFile == null) { resp.sendError(404, "Sage File not found " + mfid); return; } int seconds = NumberUtils.toInt(req.getParameter("ss"), -1); long offset = NumberUtils.toLong(req.getParameter("sb"), -1); if (seconds < 0 && offset < 0) { resp.sendError(501, "Missing 'ss' or 'sb' args"); return; } int width = NumberUtils.toInt(req.getParameter("w"), 320); int height = NumberUtils.toInt(req.getParameter("h"), 320); File dir = new File(Phoenix.getInstance().getUserCacheDir(), "videothumb/" + mfid); if (!dir.exists()) { dir.mkdirs(); } String prefix = ""; if (offset > 0) { prefix = "O" + offset; } else { prefix = "S" + seconds; } File f = new File(dir, prefix + "_" + width + "_" + height + ".jpg").getCanonicalFile(); if (!f.exists()) { try { generateThumbnailNew(sageFile, f, seconds, offset, width, height); } catch (Exception e) { e.printStackTrace(); resp.sendError(503, "Failed to generate thumbnail\n " + e.getMessage()); return; } } if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } resp.setContentType("image/jpeg"); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
|
11
|
Code Sample 1:
private static void copyFile(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); FileChannel inc = in.getChannel(); FileChannel outc = out.getChannel(); inc.transferTo(0, inc.size(), outc); inc.close(); outc.close(); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
public boolean doUpload(int count) { String objFileName = Long.toString(new java.util.Date().getTime()) + Integer.toString(count); try { this.objectFileName[count] = objFileName + "_bak." + this.sourceFileExt[count]; File objFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); if (objFile.exists()) { this.doUpload(count); } else { objFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(objFile); BufferedOutputStream bos = new BufferedOutputStream(fos); int readLength = 0; int offset = 0; String str = ""; long readSize = 0L; while ((readLength = this.inStream.readLine(this.b, 0, this.b.length)) != -1) { str = new String(this.b, 0, readLength); if (str.indexOf("Content-Type:") != -1) { break; } } this.inStream.readLine(this.b, 0, this.b.length); while ((readLength = this.inStream.readLine(this.b, 0, b.length)) != -1) { str = new String(this.b, 0, readLength); if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45 && this.b[3] == 45 && this.b[4] == 45) { break; } bos.write(this.b, 0, readLength); readSize += readLength; if (readSize > this.size) { this.fileMessage[count] = "�ϴ��ļ������ļ���С�������ƣ�"; this.ok = false; break; } } if (this.ok) { bos.flush(); bos.close(); int fileLength = (int) (objFile.length()); byte[] bb = new byte[fileLength - 2]; FileInputStream fis = new FileInputStream(objFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(bb, 0, (fileLength - 2)); fis.close(); bis.close(); this.objectFileName[count] = objFileName + "." + this.sourceFileExt[count]; File ok_file = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); ok_file.createNewFile(); BufferedOutputStream bos_ok = new BufferedOutputStream(new FileOutputStream(ok_file)); bos_ok.write(bb); bos_ok.close(); objFile.delete(); this.fileMessage[count] = "OK"; return true; } else { bos.flush(); bos.close(); File delFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]); delFile.delete(); this.objectFileName[count] = "none"; return false; } } catch (Exception e) { this.objectFileName[count] = "none"; this.fileMessage[count] = e.toString(); return false; } }
|
11
|
Code Sample 1:
public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public static String read(URL url) throws Exception { String filename = Integer.toString(url.toString().hashCode()); boolean cached = false; File dir = new File(Config.CACHE_PATH); for (File file : dir.listFiles()) { if (!file.isFile()) continue; if (file.getName().equals(filename)) { filename = file.getName(); cached = true; break; } } File file = new File(Config.CACHE_PATH, filename); if (Config.USE_CACHE && cached) return read(file); System.out.println(">> CACHE HIT FAILED."); InputStream in = null; try { in = url.openStream(); } catch (Exception e) { System.out.println(">> OPEN STREAM FAILED: " + url.toString()); return null; } String content = read(in); save(file, content); return content; }
Code Sample 2:
public boolean validateZipFile(File zipFile) { String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath()); try { deleteTempFiles(); File ftempDir = new File(tempdir); ftempDir.mkdirs(); File tempZip = new File(tempdir + File.separator + zipFile.getName()); tempZip.createNewFile(); FileChannel ic = new FileInputStream(zipFile).getChannel(); FileChannel oc = new FileOutputStream(tempZip).getChannel(); for (long i = 0; i <= ic.size(); i++) { ic.transferTo(0, 1000000, oc); i = i + 999999; } ic.close(); oc.close(); if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) { ZipFile z = new ZipFile(zipFile); ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath))); } return true; } catch (Exception e) { Logger.error(this, "Error with file", e); return false; } }
|
11
|
Code Sample 1:
public boolean load() { if (getFilename() != null && getFilename().length() > 0) { try { File file = new File(PreferencesManager.loadDirectoryLocation("macros") + File.separator + getFilename()); URL url = file.toURL(); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); String macro_text = ""; while (line != null) { macro_text = macro_text.concat(line); line = br.readLine(); if (line != null) { macro_text = macro_text.concat(System.getProperty("line.separator")); } } code = macro_text; } catch (Exception e) { System.err.println("Exception at StoredMacro.load(): " + e.toString()); return false; } } return true; }
Code Sample 2:
public static String getWebpage(String url) { String content = ""; if (!url.trim().toLowerCase().startsWith("http://")) { url = "http://" + url; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } return content; }
|
00
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws WsException { String callback = para(req, JsonWriter.CALLBACK, null); String input = para(req, INPUT, null); String type = para(req, TYPE, "url"); String format = para(req, FORMAT, null); PrintWriter out = null; Reader contentReader = null; try { out = resp.getWriter(); if (StringUtils.trimToNull(input) == null) { resp.setContentType("text/html"); printHelp(out); } else { if (type.equalsIgnoreCase("url")) { HttpGet httpget = new HttpGet(input); try { HttpResponse response = client.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String charset = "UTF-8"; contentReader = new InputStreamReader(entity.getContent(), charset); if (false) { contentReader = new FilterXmlReader(contentReader); } else { contentReader = new BufferedReader(contentReader); } } } catch (RuntimeException ex) { httpget.abort(); throw ex; } } else { contentReader = new StringReader(input); } long time = System.currentTimeMillis(); TokenStream stream = nameTokenStream(contentReader); SciNameIterator iter = new SciNameIterator(stream); if (format != null && format.equalsIgnoreCase("json")) { resp.setContentType("application/json"); streamAsJSON(iter, out, callback); } else if (format != null && format.equalsIgnoreCase("xml")) { resp.setContentType("text/xml"); streamAsXML(iter, out); } else { resp.setContentType("text/plain"); streamAsText(iter, out); } log.info("Indexing finished in " + (System.currentTimeMillis() - time) + " msecs"); } } catch (IOException e1) { log.error("IOException", e1); e1.printStackTrace(); } finally { if (contentReader != null) { try { contentReader.close(); } catch (IOException e) { log.error("IOException", e); } } out.flush(); out.close(); } }
Code Sample 2:
public void fetchPublicContent(int id) throws IOException { String fileName = FILE_NAME_PREFIX + id + ".xml"; File file = new File(fileName); if (file.exists()) { System.out.println("user: " + id + " not fetched because it already exists"); return; } OutputStream out = new FileOutputStream(file, false); URL url = new URL("http://twitter.com/statuses/followers.xml?id=" + id); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); int i = 0; while ((i = in.read()) != -1) { out.write(i); } in.close(); out.close(); }
|
00
|
Code Sample 1:
public static void concatenateToDestFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IllegalArgumentException("Could not create destination file:" + destFile.getName()); } } BufferedOutputStream bufferedOutputStream = null; BufferedInputStream bufferedInputStream = null; byte[] buffer = new byte[1024]; try { bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile, true)); bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFile)); while (true) { int readByte = bufferedInputStream.read(buffer, 0, buffer.length); if (readByte == -1) { break; } bufferedOutputStream.write(buffer, 0, readByte); } } finally { if (bufferedOutputStream != null) { bufferedOutputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.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(); }
|
11
|
Code Sample 1:
public void importarHistoricoDoPIB(Andamento pAndamento) throws FileNotFoundException, SQLException, Exception { pAndamento.delimitarIntervaloDeVariacao(0, 49); PIB[] valoresPendentesDoPIB = obterValoresPendentesDoPIB(pAndamento); pAndamento.delimitarIntervaloDeVariacao(50, 100); if (valoresPendentesDoPIB != null && valoresPendentesDoPIB.length > 0) { String sql = "INSERT INTO tmp_TB_PIB(ULTIMO_DIA_DO_MES, PIB_ACUM_12MESES_REAL, PIB_ACUM_12MESES_DOLAR) VALUES(:ULTIMO_DIA_DO_MES, :PIB_ACUM_12MESES_REAL, :PIB_ACUM_12MESES_DOLAR)"; OraclePreparedStatement stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosASeremImportados = valoresPendentesDoPIB.length; try { int quantidadeDeRegistrosImportados = 0; int numeroDoRegistro = 0; final BigDecimal MILHAO = new BigDecimal("1000000"); for (PIB valorPendenteDoPIB : valoresPendentesDoPIB) { ++numeroDoRegistro; stmtDestino.clearParameters(); java.sql.Date vULTIMO_DIA_DO_MES = new java.sql.Date(obterUltimoDiaDoMes(valorPendenteDoPIB.mesEAno).getTime()); BigDecimal vPIB_ACUM_12MESES_REAL = valorPendenteDoPIB.valorDoPIBEmReais.multiply(MILHAO).setScale(0, RoundingMode.DOWN); BigDecimal vPIB_ACUM_12MESES_DOLAR = valorPendenteDoPIB.valorDoPIBEmDolares.multiply(MILHAO).setScale(0, RoundingMode.DOWN); stmtDestino.setDateAtName("ULTIMO_DIA_DO_MES", vULTIMO_DIA_DO_MES); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_REAL", vPIB_ACUM_12MESES_REAL); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_DOLAR", vPIB_ACUM_12MESES_DOLAR); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosASeremImportados * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); throw ex; } finally { if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } } pAndamento.setPercentualCompleto(100); }
Code Sample 2:
public int visitStatement(String statement) throws SQLException { mySQLLogger.info(statement); if (getConnection() == null) { throw new JdbcException("cannot exec: " + statement + ", because 'not connected to database'"); } Statement stmt = getConnection().createStatement(); try { return stmt.executeUpdate(statement); } catch (SQLException ex) { getConnection().rollback(); throw ex; } finally { stmt.close(); } }
|
00
|
Code Sample 1:
public List<String> addLine(String username, String URL, int page) { List<String> rss = new ArrayList<String>(); try { URL url = new URL(URL + page); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; System.out.println(reader.readLine()); while ((line = reader.readLine()) != null) { String string = "<text>"; String string1 = "</text>"; if (line.contains(string) && !line.contains("@") && !line.contains("http")) { String tweet = line.replace(string, "").replace(string1, "").replace("'", "").trim(); final Tweets tweets = new Tweets(username, tweet, page, false); int save = tweets.save(); tweets.setId((long) save); Thread thread = new Thread(new Runnable() { @Override public void run() { Main.addRow(tweets); } }); thread.start(); System.out.println(tweet); } } reader.close(); } catch (MalformedURLException e) { Log.put(e.toString()); System.out.println(e.toString()); } catch (IOException e) { Log.put(e.toString()); System.out.println(e.toString()); } catch (Exception e) { Log.put(e.toString()); System.out.println(e.toString()); } return rss; }
Code Sample 2:
public static void main(String[] args) throws Exception { System.out.println("Opening destination cbrout.jizz"); OutputStream out = new BufferedOutputStream(new FileOutputStream("cbrout.jizz")); System.out.println("Opening source output.jizz"); InputStream in = new CbrLiveStream(new BufferedInputStream(new FileInputStream("output.jizz")), System.currentTimeMillis() + 10000, 128); System.out.println("Starting read/write loop"); boolean started = false; int len; byte[] buf = new byte[4 * 1024]; while ((len = in.read(buf)) > -1) { if (!started) { System.out.println("Starting at " + new Date()); started = true; } out.write(buf, 0, len); } System.out.println("Finished at " + new Date()); out.close(); in.close(); }
|
00
|
Code Sample 1:
private String doUploadFile(String sessionId, File file, String originalFileName) throws UnsupportedEncodingException, IOException { log(INFO, sessionId); log(INFO, file.getPath()); DefaultHttpClient httpclient = new DefaultHttpClient(); UploadFileRequest request = new UploadFileRequest(); request.setSessionId(sessionId); request.setDirectory(UUID.randomUUID().toString()); request.setFileName(originalFileName); URL url = file.toURI().toURL(); URLConnection urlCon = url.openConnection(); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("UploadFileRequest", UploadFileRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("UploadFileResponse", UploadFileResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpPost httppost = new HttpPost(MewitProperties.getMewitUrl() + "/resources/uploadFile?REQUEST=" + strRequest); FileEntity fileEntity = new FileEntity(file, urlCon.getContentType()); httppost.setEntity(fileEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); log(INFO, result); UploadFileResponse oResponse = (UploadFileResponse) reader.fromXML(result); return oResponse.getFile(); } return null; }
Code Sample 2:
public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); }
|
00
|
Code Sample 1:
public static void main(String[] args) { LogFrame.getInstance(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.trim().startsWith(DEBUG_PARAMETER_NAME + "=")) { properties.put(DEBUG_PARAMETER_NAME, arg.trim().substring(DEBUG_PARAMETER_NAME.length() + 1).trim()); if (properties.getProperty(DEBUG_PARAMETER_NAME).toLowerCase().equals(DEBUG_TRUE)) { DEBUG = true; } } else if (arg.trim().startsWith(AUTOCONNECT_PARAMETER_NAME + "=")) { properties.put(AUTOCONNECT_PARAMETER_NAME, arg.trim().substring(AUTOCONNECT_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(SITE_CONFIG_URL_PARAMETER_NAME + "=")) { properties.put(SITE_CONFIG_URL_PARAMETER_NAME, arg.trim().substring(SITE_CONFIG_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_URL_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_URL_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_URL_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOC_ID_PARAMETER_NAME + "=")) { properties.put(DOC_ID_PARAMETER_NAME, arg.trim().substring(DOC_ID_PARAMETER_NAME.length() + 1).trim()); } else if (arg.trim().startsWith(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME + "=")) { properties.put(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME, arg.trim().substring(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME.length() + 1).trim()); RichUIUtils.setDocServiceProxyFactoryClassname(properties.getProperty(DOCSERVICE_PROXY_FACTORY_PARAMETER_NAME)); } else { System.out.println("WARNING! Unknown or undefined parameter: '" + arg.trim() + "'"); } } System.out.println("Annotation Diff GUI startup parameters:"); System.out.println("------------------------------"); for (Object propName : properties.keySet()) { System.out.println(propName.toString() + "=" + properties.getProperty((String) propName)); } System.out.println("------------------------------"); if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) == null || properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() == 0) { String err = "Mandatory parameter '" + SITE_CONFIG_URL_PARAMETER_NAME + "' is missing.\n\nApplication will exit."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); System.exit(-1); } try { String context = System.getProperty(CONTEXT); if (context == null || "".equals(context)) { context = DEFAULT_CONTEXT; } String s = System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { File f = File.createTempFile("foo", ""); String gateHome = f.getParent().toString() + context; f.delete(); System.setProperty(GateConstants.GATE_HOME_PROPERTY_NAME, gateHome); f = new File(System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/plugins"); File f = new File(System.getProperty(GateConstants.PLUGINS_HOME_PROPERTY_NAME)); if (!f.exists()) { f.mkdirs(); } } s = System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME); if (s == null || s.length() == 0) { System.setProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME, System.getProperty(GateConstants.GATE_HOME_PROPERTY_NAME) + "/gate.xml"); } if (properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME) != null && properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME).length() > 0) { File f = new File(System.getProperty(GateConstants.GATE_SITE_CONFIG_PROPERTY_NAME)); if (f.exists()) { f.delete(); } f.getParentFile().mkdirs(); f.createNewFile(); URL url = new URL(properties.getProperty(SITE_CONFIG_URL_PARAMETER_NAME)); InputStream is = url.openStream(); FileOutputStream fos = new FileOutputStream(f); int i = is.read(); while (i != -1) { fos.write(i); i = is.read(); } fos.close(); is.close(); } try { Gate.init(); gate.Main.applyUserPreferences(); } catch (Exception e) { e.printStackTrace(); } } catch (Throwable e) { e.printStackTrace(); } MainFrame.getInstance().setVisible(true); MainFrame.getInstance().pack(); if (properties.getProperty(AUTOCONNECT_PARAMETER_NAME, "").toLowerCase().equals(AUTOCONNECT_TRUE)) { if (properties.getProperty(DOC_ID_PARAMETER_NAME) == null || properties.getProperty(DOC_ID_PARAMETER_NAME).length() == 0) { String err = "Can't autoconnect. A parameter '" + DOC_ID_PARAMETER_NAME + "' is missing."; System.out.println(err); JOptionPane.showMessageDialog(new JFrame(), err, "Error!", JOptionPane.ERROR_MESSAGE); ActionShowAnnDiffConnectDialog.getInstance().actionPerformed(null); } else { ActionConnectToAnnDiffGUI.getInstance().actionPerformed(null); } } else { ActionShowAnnDiffConnectDialog.getInstance().actionPerformed(null); } }
Code Sample 2:
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); 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[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
00
|
Code Sample 1:
private void readCard() { try { final String urlString = createURLStringExistRESTGetXQuery("//scheda[cata = \"" + cata + "\"]"); InputStream inputStream = new URL(urlString).openStream(); uiSchedaXml.read(inputStream); inputStream.close(); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } }
Code Sample 2:
public static boolean copy(File src, File dest) { boolean result = true; String files[] = null; if (src.isDirectory()) { files = src.list(); result = dest.mkdir(); } else { files = new String[1]; files[0] = ""; } if (files == null) { files = new String[0]; } for (int i = 0; (i < files.length) && result; i++) { File fileSrc = new File(src, files[i]); File fileDest = new File(dest, files[i]); if (fileSrc.isDirectory()) { result = copy(fileSrc, fileDest); } else { FileChannel ic = null; FileChannel oc = null; try { ic = (new FileInputStream(fileSrc)).getChannel(); oc = (new FileOutputStream(fileDest)).getChannel(); ic.transferTo(0, ic.size(), oc); } catch (IOException e) { log.error(sm.getString("expandWar.copy", fileSrc, fileDest), e); result = false; } finally { if (ic != null) { try { ic.close(); } catch (IOException e) { } } if (oc != null) { try { oc.close(); } catch (IOException e) { } } } } } return result; }
|
00
|
Code Sample 1:
public boolean setDeleteCliente(int IDcliente) { boolean delete = false; try { stm = conexion.prepareStatement("delete clientes where IDcliente='" + IDcliente + "'"); stm.executeUpdate(); conexion.commit(); delete = true; } catch (SQLException e) { System.out.println("Error en la eliminacion del registro en tabla clientes " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return delete = false; } return delete; }
Code Sample 2:
public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url = l.getResource("weka/core/parser/JFlex/skeleton.default"); if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } }
|
00
|
Code Sample 1:
public static String encrypt(String plaintext) throws EncryptionException { if (plaintext == null) { throw new EncryptionException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); return Base64.encodeBytes(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } }
Code Sample 2:
private ResourceZoneRulesDataProvider(URL url) throws ClassNotFoundException, IOException { boolean throwing = false; InputStream in = null; try { in = url.openStream(); DataInputStream dis = new DataInputStream(in); if (dis.readByte() != 1) { throw new StreamCorruptedException("File format not recognised"); } this.groupID = dis.readUTF(); int versionCount = dis.readShort(); String[] versionArray = new String[versionCount]; for (int i = 0; i < versionCount; i++) { versionArray[i] = dis.readUTF(); } int regionCount = dis.readShort(); String[] regionArray = new String[regionCount]; for (int i = 0; i < regionCount; i++) { regionArray[i] = dis.readUTF(); } this.regions = new HashSet<String>(Arrays.asList(regionArray)); Set<ZoneRulesVersion> versionSet = new HashSet<ZoneRulesVersion>(versionCount); for (int i = 0; i < versionCount; i++) { int versionRegionCount = dis.readShort(); String[] versionRegionArray = new String[versionRegionCount]; short[] versionRulesArray = new short[versionRegionCount]; for (int j = 0; j < versionRegionCount; j++) { versionRegionArray[j] = regionArray[dis.readShort()]; versionRulesArray[j] = dis.readShort(); } versionSet.add(new ResourceZoneRulesVersion(this, versionArray[i], versionRegionArray, versionRulesArray)); } this.versions = versionSet; int ruleCount = dis.readShort(); this.rules = new AtomicReferenceArray<Object>(ruleCount); for (int i = 0; i < ruleCount; i++) { byte[] bytes = new byte[dis.readShort()]; dis.readFully(bytes); rules.set(i, bytes); } } catch (IOException ex) { throwing = true; throw ex; } finally { if (in != null) { try { in.close(); } catch (IOException ex) { if (throwing == false) { throw ex; } } } } }
|
11
|
Code Sample 1:
public void run() { StringBuffer xml; String tabName; Element guiElement; setBold(monitor.getReading()); setBold(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Working"); HttpMethod method = null; xml = new StringBuffer(); File tempfile = new File(url); if (tempfile.exists()) { try { InputStream in = new FileInputStream(tempfile); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading XML file from local file"); e.printStackTrace(System.err); return; } } else { try { HttpClient client = new HttpClient(); method = new GetMethod(url); int response = client.executeMethod(method); if (response == 200) { InputStream in = method.getResponseBodyAsStream(); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } else { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response); return; } } catch (IOException e) { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server"); e.printStackTrace(System.err); return; } } setPlain(monitor.getReading()); setPlain(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Done"); setBold(monitor.getValidating()); setBold(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Working"); DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl(); try { DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes())); if (method != null) { method.releaseConnection(); } Element root = document.getDocumentElement(); NodeList temp = root.getElementsByTagName("resource"); for (int j = 0; j < temp.getLength(); j++) { Element resource = (Element) temp.item(j); resources.add(new URL(resource.getAttribute("url"))); } NodeList connections = root.getElementsByTagName("jmxserver"); for (int j = 0; j < connections.getLength(); j++) { Element connection = (Element) connections.item(j); String name = connection.getAttribute("name"); String tempUrl = connection.getAttribute("url"); String auth = connection.getAttribute("auth"); if (tempUrl.indexOf("${host}") != -1) { HostDialog dialog = new HostDialog(Config.getHosts()); String host = dialog.showDialog(); if (host == null) { System.out.println("Host can not be null, unable to create panel."); return; } tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host); Config.addHost(host); } JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl); JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false)); if (auth != null && auth.equalsIgnoreCase("true")) { LoginTrueService loginService = new LoginTrueService(); JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService); if (status != JXLoginPanel.Status.SUCCEEDED) { return; } server.setUsername(loginService.getName()); server.setPassword(loginService.getPassword()); } servers.put(name, server); NodeList listeners = connection.getElementsByTagName("listener"); for (int i = 0; i < listeners.getLength(); i++) { Element attribute = (Element) listeners.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String filtertype = attribute.getAttribute("filterType"); TaskNotificationListener listener = new TaskNotificationListener(); NotificationFilterSupport filter = new NotificationFilterSupport(); if (filtertype == null || "".equals(filtertype)) { filter = null; } else { filter.enableType(filtertype); } Task task = new Task(-1, Task.LISTEN, server); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); } NodeList attributes = connection.getElementsByTagName("attribute"); for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String attributename = attribute.getAttribute("attributename"); String frequency = attribute.getAttribute("frequency"); String onEvent = attribute.getAttribute("onEvent"); if (frequency.equalsIgnoreCase("onchange")) { TaskNotificationListener listener = new TaskNotificationListener(); AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(attributename); Task task = new Task(-1, Task.LISTEN, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server); task2.setAttribute(att); task2.setMbean(mbean); server.getWorker().addTask(task2); List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); hashTempList.add(task2); tasks.put(taskname, hashTempList); } else { int frequency2 = Integer.parseInt(frequency); Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); TaskNotificationListener listener = null; if (onEvent != null && !"".equals(onEvent)) { Task tempTask = tasks.get(onEvent).get(0); if (tempTask == null) { System.out.println(onEvent + " was not found."); return; } else { listener = (TaskNotificationListener) tempTask.getListener(); } } if (listener == null) { server.getWorker().addTask(task); } else { listener.addTask(task); } } } } NodeList guiTemp = root.getElementsByTagName("gui"); guiElement = (Element) guiTemp.item(0); tabName = guiElement.getAttribute("name"); if (MonitorServer.contains(tabName)) { JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setTitleAt(i, tabName); break; } } NodeList tempBindings = root.getElementsByTagName("binding"); for (int i = 0; i < tempBindings.getLength(); i++) { Element binding = (Element) tempBindings.item(i); String guiname = binding.getAttribute("guiname"); String tmethod = binding.getAttribute("method"); String taskname = binding.getAttribute("taskname"); String formater = binding.getAttribute("formater"); BindingContainer tempBinding; if (formater == null || (formater != null && formater.equals(""))) { tempBinding = new BindingContainer(guiname, tmethod, taskname); } else { tempBinding = new BindingContainer(guiname, tmethod, taskname, formater); } bindings.add(tempBinding); } } catch (Exception e) { System.err.println("Exception message: " + e.getMessage()); System.out.println("Loading Monitor Failed, couldnt parse XML file."); e.printStackTrace(System.err); return; } setPlain(monitor.getValidating()); setPlain(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Done"); setBold(monitor.getDownload()); setBold(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Working"); List<File> jarFiles = new ArrayList<File>(); File cacheDir = new File(Config.getCacheDir()); if (!cacheDir.exists()) { cacheDir.mkdir(); } for (URL resUrl : resources) { try { HttpClient client = new HttpClient(); HttpMethod methodRes = new GetMethod(resUrl.toString()); int response = client.executeMethod(methodRes); if (response == 200) { int index = resUrl.toString().lastIndexOf("/") + 1; File file = new File(Config.getCacheDir() + resUrl.toString().substring(index)); FileOutputStream out = new FileOutputStream(file); InputStream in = methodRes.getResponseBodyAsStream(); int readTemp = 0; while ((readTemp = in.read()) != -1) { out.write(readTemp); } System.out.println(file.getName() + " downloaded."); methodRes.releaseConnection(); if (file.getName().endsWith(".jar")) { jarFiles.add(file); } } else { methodRes.releaseConnection(); System.out.println("Loading Monitor Failed. Unable to get resource " + url); return; } } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server"); e.printStackTrace(System.err); return; } } URL[] urls = new URL[jarFiles.size()]; try { for (int i = 0; i < jarFiles.size(); i++) { File file = jarFiles.get(i); File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName()); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newFile); int n = 0; byte[] buf = new byte[1024]; while ((n = in.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); out.close(); in.close(); urls[i] = new URL("file:" + newFile.getAbsolutePath()); } } catch (Exception e1) { System.out.println("Unable to load jar files."); e1.printStackTrace(); } URLClassLoader loader = new URLClassLoader(urls); engine.setClassLoader(loader); setPlain(monitor.getDownload()); setPlain(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Done"); setBold(monitor.getGui()); setBold(monitor.getGuiStatus()); monitor.getGuiStatus().setText(" Working"); Container container; try { String tempXml = xml.toString(); int start = tempXml.indexOf("<gui"); start = tempXml.indexOf('>', start) + 1; int end = tempXml.indexOf("</gui>"); container = engine.render(new StringReader(tempXml.substring(start, end))); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Exception msg: " + e.getMessage()); System.out.println("Loading Monitor Failed, error creating gui."); return; } for (BindingContainer bcon : bindings) { List<Task> temp = tasks.get(bcon.getTask()); if (temp == null) { System.out.println("Task with name " + bcon.getTask() + " doesnt exist."); } else { for (Task task : temp) { if (task != null) { Object comp = engine.find(bcon.getComponent()); if (comp != null) { if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) { TaskNotificationListener listener = (TaskNotificationListener) task.getListener(); if (bcon.getFormater() == null) { listener.addResultListener(new Binding(comp, bcon.getMethod())); } else { listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } else { if (bcon.getFormater() == null) { task.addResultListener(new Binding(comp, bcon.getMethod())); } else { task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } } else { System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor."); return; } } else { System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor."); return; } } } } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this)); break; } } System.out.println("Connecting to server(s)."); Enumeration e = servers.keys(); List<JmxWorker> list = new ArrayList<JmxWorker>(); while (e.hasMoreElements()) { JmxWorker worker = servers.get(e.nextElement()).getWorker(); worker.setRunning(true); worker.start(); list.add(worker); } MonitorServer.add(tabName, list); Config.addUrl(url); }
Code Sample 2:
public void importCertFile(File file) throws IOException { File kd; File cd; synchronized (this) { kd = keysDir; cd = certsDir; } if (!cd.isDirectory()) { kd.mkdirs(); cd.mkdirs(); } String newName = file.getName(); File dest = new File(cd, newName); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(file).getChannel(); destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException e) { } } } }
|
11
|
Code Sample 1:
protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; }
Code Sample 2:
public static String digest(String ha1, String ha2, String nonce) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(ha1, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(nonce, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(ha2, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
|
11
|
Code Sample 1:
public static Drawable fetchCachedDrawable(String url) throws MalformedURLException, IOException { Log.d(LOG_TAG, "Fetching cached : " + url); String cacheName = md5(url); checkAndCreateDirectoryIfNeeded(); File r = new File(CACHELOCATION + cacheName); if (!r.exists()) { InputStream is = (InputStream) fetch(url); FileOutputStream fos = new FileOutputStream(CACHELOCATION + cacheName); int nextChar; while ((nextChar = is.read()) != -1) fos.write((char) nextChar); fos.flush(); } FileInputStream fis = new FileInputStream(CACHELOCATION + cacheName); Drawable d = Drawable.createFromStream(fis, "src"); return d; }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
00
|
Code Sample 1:
public Request call() { InputStream is = null; try { if (DEBUG) Log.d(TAG, "Requesting: " + request.uri); HttpGet httpGet = new HttpGet(request.uri.toString()); httpGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = mHttpClient.execute(httpGet); String mimeType = response.getHeaders("Content-Type")[0].getValue(); if (DEBUG) Log.d(TAG, "mimeType:" + mimeType); if (mimeType.startsWith("image")) { HttpEntity entity = response.getEntity(); is = getUngzippedContent(entity); Bitmap bitmap = BitmapFactory.decodeStream(is); if (mResourceCache.store(request.hash, bitmap)) { mCache.put(request.uri.toString(), new SoftReference<Bitmap>(bitmap)); if (DEBUG) Log.d(TAG, "Request successful: " + request.uri); } else { mResourceCache.invalidate(request.hash); } } } catch (IOException e) { if (DEBUG) Log.d(TAG, "IOException", e); } finally { if (DEBUG) Log.e(TAG, "Request finished: " + request.uri); mActiveRequestsMap.remove(request); if (is != null) { notifyObservers(request.uri); } try { if (is != null) { is.close(); } } catch (IOException e) { if (DEBUG) e.printStackTrace(); } } return request; }
Code Sample 2:
public static String getWebpage(String url) { String content = ""; if (!url.trim().toLowerCase().startsWith("http://")) { url = "http://" + url; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } return content; }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[1024]; int count = 0; while ((count = is.read(buf, 0, 1024)) != -1) os.write(buf, 0, count); is.close(); os.close(); }
Code Sample 2:
@Override public Class<?> loadClass(final String name) throws ClassNotFoundException { final String baseName = StringUtils.substringBefore(name, "$"); if (baseName.startsWith("java") && !whitelist.contains(baseName) && !additionalWhitelist.contains(baseName)) { throw new NoClassDefFoundError(name + " is a restricted class for GAE"); } if (!name.startsWith("com.gargoylesoftware")) { return super.loadClass(name); } super.loadClass(name); final InputStream is = getResourceAsStream(name.replaceAll("\\.", "/") + ".class"); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { IOUtils.copy(is, bos); final byte[] bytes = bos.toByteArray(); return defineClass(name, bytes, 0, bytes.length); } catch (final IOException e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
private String getPage(String urlString) throws Exception { if (pageBuffer.containsKey(urlString)) return pageBuffer.get(urlString); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = null; StringBuilder page = new StringBuilder(); try { in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException ioe) { logger.warn("Failed to read web page"); } finally { if (in != null) { in.close(); } } return page.toString(); }
Code Sample 2:
private Component createLicensePane(String propertyKey) { if (licesePane == null) { String licenseText = ""; BufferedReader in = null; try { String filename = "conf/LICENSE.txt"; java.net.URL url = FileUtil.toURL(filename); in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while (true) { line = in.readLine(); if (line == null) break; licenseText += line; } } catch (Exception e) { log.error(e); } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } licenseText = StringUtils.replace(licenseText, "<br>", "\n"); licenseText = StringUtils.replace(licenseText, "<p>", "\n\n"); StyleContext context = new StyleContext(); StyledDocument document = new DefaultStyledDocument(context); Style style = context.getStyle(StyleContext.DEFAULT_STYLE); StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER); StyleConstants.setSpaceAbove(style, 4); StyleConstants.setSpaceBelow(style, 4); StyleConstants.setFontSize(style, 14); try { document.insertString(document.getLength(), licenseText, style); } catch (BadLocationException e) { log.error(e); } JTextPane textPane = new JTextPane(document); textPane.setEditable(false); licesePane = new JScrollPane(textPane); } return licesePane; }
|
11
|
Code Sample 1:
public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream contentIn2 = getClass().getResourceAsStream(CONTENT2_FILE); sourceOut = emptySource.getOutputStream(); try { IOUtils.copy(contentIn2, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn2.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT2_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
Code Sample 2:
public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); FileResourceManager frm = CommonsTransactionContext.configure(new File("C:/tmp")); try { frm.start(); } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } FileInputStream is = new FileInputStream("C:/Alfresco/WCM_Eval_Guide2.0.pdf"); CommonsTransactionOutputStream os = new CommonsTransactionOutputStream(new Ownerr()); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); try { frm.stop(FileResourceManager.SHUTDOWN_MODE_NORMAL); } catch (ResourceManagerSystemException e) { throw new RuntimeException(e); } System.out.println(System.currentTimeMillis() - start); }
|
11
|
Code Sample 1:
private String transferWSDL(String usernameAndPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (this.password != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(usernameAndPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { logger.error("Failed to download wsdl from URL : " + wsdlURL); throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
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:
private static boolean genCustomerLocationsFileAndCustomerIndexFile(String completePath, String masterFile, String CustLocationsFileName, String CustIndexFileName) { try { TIntObjectHashMap CustInfoHash = new TIntObjectHashMap(480189, 1); File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC = new FileInputStream(inFile).getChannel(); File outFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel outC1 = new FileOutputStream(outFile1, true).getChannel(); File outFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel outC2 = new FileOutputStream(outFile2, true).getChannel(); int fileSize = (int) inC.size(); int totalNoDataRows = fileSize / 7; for (int i = 1; i <= totalNoDataRows; i++) { ByteBuffer mappedBuffer = ByteBuffer.allocate(7); inC.read(mappedBuffer); mappedBuffer.position(0); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); mappedBuffer.clear(); if (CustInfoHash.containsKey(customer)) { TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); locations.add(i); CustInfoHash.put(customer, locations); } else { TIntArrayList locations = new TIntArrayList(); locations.add(i); CustInfoHash.put(customer, locations); } } int[] customers = CustInfoHash.keys(); Arrays.sort(customers); int count = 1; for (int i = 0; i < customers.length; i++) { int customer = customers[i]; TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); int noRatingsForCust = locations.size(); ByteBuffer outBuf1 = ByteBuffer.allocate(12); outBuf1.putInt(customer); outBuf1.putInt(count); outBuf1.putInt(count + noRatingsForCust - 1); outBuf1.flip(); outC1.write(outBuf1); count += noRatingsForCust; for (int j = 0; j < locations.size(); j++) { ByteBuffer outBuf2 = ByteBuffer.allocate(4); outBuf2.putInt(locations.get(j)); outBuf2.flip(); outC2.write(outBuf2); } } inC.close(); outC1.close(); outC2.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
Code Sample 2:
protected File getFile(NameCategory category) throws IOException { File home = new File(System.getProperty("user.dir")); String fileName = String.format("%s.txt", category); File file = new File(home, fileName); if (file.exists()) { return file; } else { URL url = DefaultNameGenerator.class.getResource("/sc/common/" + fileName); if (url == null) { throw new IllegalStateException(String.format("Cannot find resource at %s", fileName)); } else { InputStream in = url.openStream(); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { IOUtils.copy(in, out); } finally { out.close(); } } finally { in.close(); } return file; } } }
|
00
|
Code Sample 1:
public static void copia(File nombreFuente, File nombreDestino) throws IOException { FileInputStream fis = new FileInputStream(nombreFuente); FileOutputStream fos = new FileOutputStream(nombreDestino); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); }
Code Sample 2:
public final void run() { active = true; String s = findcachedir(); uid = getuid(s); try { File file = new File(s + "main_file_cache.dat"); if (file.exists() && file.length() > 0x3200000L) file.delete(); cache_dat = new RandomAccessFile(s + "main_file_cache.dat", "rw"); for (int j = 0; j < 5; j++) cache_idx[j] = new RandomAccessFile(s + "main_file_cache.idx" + j, "rw"); } catch (Exception exception) { exception.printStackTrace(); } for (int i = threadliveid; threadliveid == i; ) { if (socketreq != 0) { try { socket = new Socket(socketip, socketreq); } catch (Exception _ex) { socket = null; } socketreq = 0; } else if (threadreq != null) { Thread thread = new Thread(threadreq); thread.setDaemon(true); thread.start(); thread.setPriority(threadreqpri); threadreq = null; } else if (dnsreq != null) { try { dns = InetAddress.getByName(dnsreq).getHostName(); } catch (Exception _ex) { dns = "unknown"; } dnsreq = null; } else if (savereq != null) { if (savebuf != null) try { FileOutputStream fileoutputstream = new FileOutputStream(s + savereq); fileoutputstream.write(savebuf, 0, savelen); fileoutputstream.close(); } catch (Exception _ex) { } if (waveplay) { wave = s + savereq; waveplay = false; } if (midiplay) { midi = s + savereq; midiplay = false; } savereq = null; } else if (urlreq != null) { try { urlstream = new DataInputStream((new URL(mainapp.getCodeBase(), urlreq)).openStream()); } catch (Exception _ex) { urlstream = null; } urlreq = null; } try { Thread.sleep(50L); } catch (Exception _ex) { } } }
|
00
|
Code Sample 1:
public LogoutHandler(String username, String token) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=LogOut&username=" + username + "&authentication_token=" + token); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return; } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void getDirectories() throws IOException { if (user == null || ukey == null) { System.out.println("user and or ukey null"); } if (directories != null) { if (directories.length != 0) { System.out.println("directories already present"); return; } } HttpPost requestdirectories = new HttpPost(GET_DIRECTORIES_KEY_URL + "?ukey=" + ukey.getValue() + "&user=" + user.getValue()); HttpResponse dirResponse = getHttpClient().execute(requestdirectories); String ds = EntityUtils.toString(dirResponse.getEntity()); dirResponse.getEntity().consumeContent(); getDirectories(ds); }
|
00
|
Code Sample 1:
public static String getDocumentAsString(URL url) throws IOException { StringBuffer result = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8")); String line = ""; while (line != null) { result.append(line); line = in.readLine(); } return result.toString(); }
Code Sample 2:
private void getViolationsReportBySLATIdYearMonth() throws IOException { String xmlFile10Send = System.getenv("SLASOI_HOME") + System.getProperty("file.separator") + "Integration" + System.getProperty("file.separator") + "soap" + System.getProperty("file.separator") + "getViolationsReportBySLATIdYearMonth.xml"; URL url10; url10 = new URL(bmReportingWSUrl); URLConnection connection10 = url10.openConnection(); HttpURLConnection httpConn10 = (HttpURLConnection) connection10; FileInputStream fin10 = new FileInputStream(xmlFile10Send); ByteArrayOutputStream bout10 = new ByteArrayOutputStream(); SOAPClient4XG.copy(fin10, bout10); fin10.close(); byte[] b10 = bout10.toByteArray(); httpConn10.setRequestProperty("Content-Length", String.valueOf(b10.length)); httpConn10.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8"); httpConn10.setRequestProperty("SOAPAction", soapAction); httpConn10.setRequestMethod("POST"); httpConn10.setDoOutput(true); httpConn10.setDoInput(true); OutputStream out10 = httpConn10.getOutputStream(); out10.write(b10); out10.close(); InputStreamReader isr10 = new InputStreamReader(httpConn10.getInputStream()); BufferedReader in10 = new BufferedReader(isr10); String inputLine10; StringBuffer response10 = new StringBuffer(); while ((inputLine10 = in10.readLine()) != null) { response10.append(inputLine10); } in10.close(); System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "Component Name: Business Manager\n" + "Interface Name: getReport\n" + "Operation Name: getViolationsReportBySLATIdYearMonth\n" + "Input" + "ProductOfferID-1\n" + "PartyID-1\n" + "\n" + "####################################################" + "#################################################\n" + "####################################################" + "#################################################\n" + "######################################## RESPONSE" + "############################################\n\n"); System.out.println("--------------------------------"); System.out.println("Response\n" + response10.toString()); }
|
11
|
Code Sample 1:
public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); }
Code Sample 2:
public static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
|
11
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("Copy: no such source file: " + fromFileName); if (!fromFile.canRead()) throw new IOException("Copy: source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("Copy: destination file is unwriteable: " + toFileName); if (JOptionPane.showConfirmDialog(null, "Overwrite File ?", "Overwrite File", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) return; } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("Copy: destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("Copy: destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("Copy: 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 static void writeBinaryFile(String filename, String target) throws IOException { File outputFile = new File(target); AgentFilesystem.forceDir(outputFile.getParent()); FileOutputStream output = new FileOutputStream(new File(target)); FileInputStream inputStream = new FileInputStream(filename); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > -1) output.write(buffer, 0, bytesRead); inputStream.close(); output.close(); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
|
11
|
Code Sample 1:
public void copyFilesIntoProject(HashMap<String, String> files) { Set<String> filenames = files.keySet(); for (String key : filenames) { String realPath = files.get(key); if (key.equals("fw4ex.xml")) { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + bundle.getString("Stem") + STEM_FILE_EXETENSION)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } else { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + key)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } } }
Code Sample 2:
public File convert(URI uri) throws DjatokaException { processing.add(uri.toString()); File urlLocal = null; try { logger.info("processingRemoteURI: " + uri.toURL()); boolean isJp2 = false; InputStream src = IOUtils.getInputStream(uri.toURL()); String ext = uri.toURL().toString().substring(uri.toURL().toString().lastIndexOf(".") + 1).toLowerCase(); if (ext.equals(FORMAT_ID_TIF) || ext.equals(FORMAT_ID_TIFF)) { urlLocal = File.createTempFile("convert" + uri.hashCode(), "." + FORMAT_ID_TIF); } else if (formatMap.containsKey(ext) && (formatMap.get(ext).equals(FORMAT_MIMEYPE_JP2) || formatMap.get(ext).equals(FORMAT_MIMEYPE_JPX))) { urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + ext); isJp2 = true; } else { if (src.markSupported()) src.mark(15); if (ImageProcessingUtils.checkIfJp2(src)) urlLocal = File.createTempFile("cache" + uri.hashCode(), "." + FORMAT_ID_JP2); if (src.markSupported()) src.reset(); else { src.close(); src = IOUtils.getInputStream(uri.toURL()); } } if (urlLocal == null) { urlLocal = File.createTempFile("convert" + uri.hashCode(), ".img"); } urlLocal.deleteOnExit(); FileOutputStream dest = new FileOutputStream(urlLocal); IOUtils.copyStream(src, dest); if (!isJp2) urlLocal = processImage(urlLocal, uri); src.close(); dest.close(); return urlLocal; } catch (Exception e) { urlLocal.delete(); throw new DjatokaException(e); } finally { if (processing.contains(uri.toString())) processing.remove(uri.toString()); } }
|
11
|
Code Sample 1:
public Logging() throws Exception { File home = new File(System.getProperty("user.home"), ".jorgan"); if (!home.exists()) { home.mkdirs(); } File logging = new File(home, "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } finally { IOUtils.closeQuietly(input); } }
Code Sample 2:
private void createWar() throws IOException, XMLStreamException { String appName = this.fileout.getName(); int i = appName.indexOf("."); if (i != -1) appName = appName.substring(0, i); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(this.fileout)); { ZipEntry entry = new ZipEntry("WEB-INF/web.xml"); zout.putNextEntry(entry); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter w = factory.createXMLStreamWriter(zout, "ASCII"); w.writeStartDocument("ASCII", "1.0"); w.writeStartElement("web-app"); w.writeAttribute("xsi", XSI, "schemaLocation", "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml /ns/javaee/web-app_2_5.xsd"); w.writeAttribute("version", "2.5"); w.writeAttribute("xmlns", J2EE); w.writeAttribute("xmlns:xsi", XSI); w.writeStartElement("description"); w.writeCharacters("Site maintenance for " + appName); w.writeEndElement(); w.writeStartElement("display-name"); w.writeCharacters(appName); w.writeEndElement(); w.writeStartElement("servlet"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("jsp-file"); w.writeCharacters("/WEB-INF/jsp/down.jsp"); w.writeEndElement(); w.writeEndElement(); w.writeStartElement("servlet-mapping"); w.writeStartElement("servlet-name"); w.writeCharacters("down"); w.writeEndElement(); w.writeStartElement("url-pattern"); w.writeCharacters("/*"); w.writeEndElement(); w.writeEndElement(); w.writeEndElement(); w.writeEndDocument(); w.flush(); zout.closeEntry(); } { ZipEntry entry = new ZipEntry("WEB-INF/jsp/down.jsp"); zout.putNextEntry(entry); PrintWriter w = new PrintWriter(zout); if (this.messageFile != null) { IOUtils.copyTo(new FileReader(this.messageFile), w); } else if (this.messageString != null) { w.print("<html><body>" + this.messageString + "</body></html>"); } else { w.print("<html><body><div style='text-align:center;font-size:500%;'>Oh No !<br/><b>" + appName + "</b><br/>is down for maintenance!</div></body></html>"); } w.flush(); zout.closeEntry(); } zout.finish(); zout.flush(); zout.close(); }
|
00
|
Code Sample 1:
public void run(IAction action) { int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle(); Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
Code Sample 2:
public static boolean exec_applet(String fname, VarContainer vc, ActionContainer ac, ThingTypeContainer ttc, Output OUT, InputStream IN, boolean AT, Statement state, String[] arggies) { if (!urlpath.endsWith("/")) { urlpath = urlpath + '/'; } if (!urlpath.startsWith("http://")) { urlpath = "http://" + urlpath; } String url = urlpath; if (fname.startsWith("dusty_")) { url = url + "libraries/" + fname; } else { url = url + "users/" + fname; } StringBuffer src = new StringBuffer(2400); try { String s; BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while ((s = br.readLine()) != null) { src.append(s).append('\n'); } br.close(); } catch (Exception e) { OUT.println(new DSOut(DSOut.ERR_OUT, -1, "Dustyscript failed at reading the file'" + fname + "'\n\t...for 'use' statement"), vc, AT); return false; } fork(src, vc, ac, ttc, OUT, IN, AT, state, arggies); return true; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.