label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { Logger.error(Encryptor.class, nsae.getMessage(), nsae); } catch (UnsupportedEncodingException uee) { Logger.error(Encryptor.class, uee.getMessage(), uee); } byte raw[] = mDigest.digest(); return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
public static String hash(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { } return new String(Base64.encodeBase64(md.digest())); } |
11
| Code Sample 1:
protected String getOldHash(String text) { String hash = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte[] digestedBytes = md.digest(); hash = HexUtils.convert(digestedBytes); } catch (NoSuchAlgorithmException e) { log.log(Level.SEVERE, "Error creating SHA password hash:" + e.getMessage()); hash = text; } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "UTF-8 not supported!?!"); } return hash; }
Code Sample 2:
public static String EncryptString(String method, String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); if (method.equals("SHA1") || method.equals("MD5")) { try { md = MessageDigest.getInstance(method); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); return null; } } else { return null; } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { String tmp = Integer.toHexString(0xff & byteHash[i]); if (tmp.length() < 2) tmp = "0" + tmp; resultString.append(tmp); } return (resultString.toString()); } |
11
| Code Sample 1:
public static String generate(String source) { byte[] SHA = new byte[20]; try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(source.getBytes()); SHA = digest.digest(); } catch (NoSuchAlgorithmException e) { System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage()); } CommunicationLogger.warning("SHA1 DIGEST: " + SHA); return SHA.toString(); }
Code Sample 2:
public static String descripta(String senha) throws GCIException { LOGGER.debug(INICIANDO_METODO + "descripta(String)"); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException e) { LOGGER.fatal(e.getMessage(), e); throw new GCIException(e); } finally { LOGGER.debug(FINALIZANDO_METODO + "descripta(String)"); } } |
11
| Code Sample 1:
@SuppressWarnings("unused") private String getMD5(String value) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return ""; } md5.reset(); md5.update(value.getBytes()); byte[] messageDigest = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } String hashedPassword = hexString.toString(); return hashedPassword; }
Code Sample 2:
public static String encripty(String toEncripty) { if (toEncripty != null) { try { synchronized (toEncripty) { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(toEncripty.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); 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])); } toEncripty = hexString.toString(); } } catch (Exception e) { e.getMessage(); } } return toEncripty; } |
11
| Code Sample 1:
private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; }
Code Sample 2:
public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; } |
00
| Code Sample 1:
public ResourceBundle getResources() { if (resources == null) { String lang = userProps.getProperty("language"); lang = "en"; try { URL myurl = getResource("Resources_" + lang.trim() + ".properties"); InputStream in = myurl.openStream(); resources = new PropertyResourceBundle(in); in.close(); } catch (Exception ex) { System.err.println("Error loading Resources"); return null; } } return resources; }
Code Sample 2:
public RobotList<Percentage> sort_decr_Percentage(RobotList<Percentage> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i).percent); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value < distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Percentage> sol = new RobotList<Percentage>(Percentage.class); for (int i = 0; i < length; i++) { sol.addLast(new Percentage(distri[i].value)); } return sol; } |
00
| Code Sample 1:
public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } |
00
| Code Sample 1:
@Override protected InputStream getResourceStream(String name) throws Exception { final BundleEntry entry = cpm.findLocalEntry(name); if (entry != null) return entry.getInputStream(); final URL url = cpm.getBaseData().getBundle().getResource(name); if (url != null) return url.openStream(); return null; }
Code Sample 2:
public static void main(String[] args) { URL url = Thread.currentThread().getContextClassLoader().getResource("org/jeditor/resources/jeditor.properties"); try { PropertyResourceBundle prb = new PropertyResourceBundle(url.openStream()); String version = prb.getString("version"); String date = prb.getString("date"); System.out.println("jEditor version " + version + " build on " + date); System.out.println("Distributed under GPL license"); } catch (IOException ex) { ex.printStackTrace(); } } |
11
| Code Sample 1:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; 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(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
Code Sample 2:
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("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) dir.mkdir(); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
00
| Code Sample 1:
protected BufferedImage handleRaremapsException() { if (params.uri.startsWith("http://www.raremaps.com/cgi-bin/gallery.pl/detail/")) try { params.uri = params.uri.replace("cgi-bin/gallery.pl/detail", "maps/medium"); URL url = new URL(params.uri); URLConnection connection = url.openConnection(); return processNewUri(connection); } catch (Exception e) { } return null; }
Code Sample 2:
public String useService(HashMap<String, String> input) { String output = ""; if (input.size() < 1) { return ""; } String data = ""; try { for (String key : input.keySet()) { data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(input.get(key), "UTF-8"); } data = data.substring(1); URL url = new URL(serviceUrl); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { output += line; } wr.close(); rd.close(); } catch (Exception e) { e.printStackTrace(); } return output; } |
11
| Code Sample 1:
public Object execute(Connection connection) throws JAXRException { RegistryObject registryObject = connection.getRegistryService().getBusinessQueryManager().getRegistryObject(id); if (registryObject instanceof ExtrinsicObject) { ExtrinsicObject extrinsicObject = (ExtrinsicObject) registryObject; DataHandler dataHandler = extrinsicObject.getRepositoryItem(); if (dataHandler != null) { response.setContentType("text/html"); try { PrintWriter out = response.getWriter(); InputStream is = dataHandler.getInputStream(); try { final XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("div"); xmlStreamWriter.writeStartElement("textarea"); xmlStreamWriter.writeAttribute("name", "repositoryItem"); xmlStreamWriter.writeAttribute("class", "xml"); xmlStreamWriter.writeAttribute("style", "display:none"); IOUtils.copy(new XmlInputStreamReader(is), new XmlStreamTextWriter(xmlStreamWriter)); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("script"); xmlStreamWriter.writeAttribute("class", "javascript"); xmlStreamWriter.writeCharacters("dp.SyntaxHighlighter.HighlightAll('repositoryItem');"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } finally { is.close(); } } catch (Throwable ex) { log.error("Error while trying to format repository item " + id, ex); } } else { } } else { } return null; }
Code Sample 2:
public static final boolean checkForUpdate(final String currentVersion, final String updateURL, boolean noLock) throws Exception { try { final String parentFDTConfDirName = System.getProperty("user.home") + File.separator + ".fdt"; final String fdtUpdateConfFileName = "update.properties"; final File confFile = createOrGetRWFile(parentFDTConfDirName, fdtUpdateConfFileName); if (confFile != null) { long lastCheck = 0; Properties updateProperties = new Properties(); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(confFile); updateProperties.load(fis); final String lastCheckProp = (String) updateProperties.get("LastCheck"); lastCheck = 0; if (lastCheckProp != null) { try { lastCheck = Long.parseLong(lastCheckProp); } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Got exception parsing LastCheck param", t); } lastCheck = 0; } } } catch (Throwable t) { logger.log(Level.WARNING, "Cannot load update properties file: " + confFile, t); } finally { closeIgnoringExceptions(fos); closeIgnoringExceptions(fis); } final long now = System.currentTimeMillis(); boolean bHaveUpdates = false; checkAndSetInstanceID(updateProperties); if (lastCheck + FDT.UPDATE_PERIOD < now) { lastCheck = now; try { logger.log("\n\nChecking for remote updates ... This may be disabled using -noupdates flag."); bHaveUpdates = updateFDT(currentVersion, updateURL, false, noLock); if (bHaveUpdates) { logger.log("FDT may be updated using: java -jar fdt.jar -update"); } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "No updates available"); } } } catch (Throwable t) { if (logger.isLoggable(Level.FINE)) { logger.log(Level.WARNING, "Got exception", t); } } updateProperties.put("LastCheck", "" + now); try { fos = new FileOutputStream(confFile); updateProperties.store(fos, null); } catch (Throwable t1) { logger.log(Level.WARNING, "Cannot store update properties file", t1); } finally { closeIgnoringExceptions(fos); } return bHaveUpdates; } } else { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, " [ checkForUpdate ] Cannot read or write the update conf file: " + parentFDTConfDirName + File.separator + fdtUpdateConfFileName); } return false; } } catch (Throwable t) { logger.log(Level.WARNING, "Got exception checking for updates", t); } return false; } |
00
| Code Sample 1:
private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; }
Code Sample 2:
private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } } |
11
| Code Sample 1:
public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } }
Code Sample 2:
public static void main(String[] args) { try { int encodeFlag = 0; if (args[0].equals("-e")) { encodeFlag = Base64.ENCODE; } else if (args[0].equals("-d")) { encodeFlag = Base64.DECODE; } String infile = args[1]; String outfile = args[2]; File fin = new File(infile); FileInputStream fis = new FileInputStream(fin); BufferedInputStream bis = new BufferedInputStream(fis); Base64.InputStream b64in = new Base64.InputStream(bis, encodeFlag | Base64.DO_BREAK_LINES); File fout = new File(outfile); FileOutputStream fos = new FileOutputStream(fout); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buff = new byte[1024]; int read = -1; while ((read = b64in.read(buff)) >= 0) { bos.write(buff, 0, read); } bos.close(); b64in.close(); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public HashSet<String> queryResource(String resourceName, String propertyName) { if (resourceName.startsWith("http://dbpedia.org/resource/")) { resourceName = resourceName.substring(28); } try { resourceName = resourceName.trim().replace(' ', '_'); resourceName = URLEncoder.encode(resourceName, "UTF-8"); } catch (UnsupportedEncodingException exc) { } String select = prefix + " SELECT ?hasValue WHERE { { " + "<http://dbpedia.org/resource/" + resourceName + "> " + propertyName + " ?hasValue } FILTER (lang(?hasValue) = \"" + lang + "\" || !isLiteral(?hasValue))}"; System.out.println(select); HashSet<String> values = new HashSet<String>(); try { URL url = new URL(queryBase + URLEncoder.encode(select, "UTF-8")); InputStream inStream = url.openStream(); Document doc = docBuild.parse(inStream); Element table = doc.getDocumentElement(); NodeList rows = table.getElementsByTagName("tr"); for (int i = 0; i < rows.getLength(); i++) { Element row = (Element) rows.item(i); NodeList cols = row.getElementsByTagName("td"); if (cols.getLength() > 0) { Element valElem = (Element) cols.item(0); String value = ((Text) valElem.getFirstChild()).getData(); if (value.startsWith("http://dbpedia.org/resource/")) { value = value.substring(28).replaceAll("_", " "); } else if (value.startsWith("http://dbpedia.org/ontology/")) { value = value.substring(28).replaceAll("_", " "); } else if (value.startsWith("http://dbpedia.org/class/yago/")) { value = value.substring(30); value = value.split("[\\d]+")[0]; } values.add(value); } } } catch (UnsupportedEncodingException exc) { exc.printStackTrace(); } catch (IOException exc) { System.err.println("Cannot retrieve record for " + resourceName); } catch (SAXException exc) { System.err.println("Cannot parse record for " + resourceName); } return values; }
Code Sample 2:
public void checkAndDownload(String statsUrl, RDFStatsUpdatableModelExt stats, Date lastDownload, boolean onlyIfNewer) throws DataSourceMonitorException { if (log.isInfoEnabled()) log.info("Checking if update required for statistics of " + ds + "..."); HttpURLConnection urlConnection; try { URL url = new URL(statsUrl); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(CONNECT_TIMEOUT); urlConnection.setReadTimeout(READ_TIMEOUT); int statusCode = urlConnection.getResponseCode(); if (statusCode / 100 != 2) { String msg = urlConnection.getResponseMessage(); throw new DataSourceMonitorException(statsUrl + " returned HTTP " + statusCode + (msg != null ? msg : "") + "."); } } catch (Exception e) { throw new DataSourceMonitorException("Failed to connect to " + statsUrl + ".", e); } long lastModified = urlConnection.getLastModified(); boolean newer = lastDownload == null || lastModified == 0 || lastModified - TIMING_GAP > lastDownload.getTime(); if (newer || !onlyIfNewer) { Model newStats = retrieveModelData(urlConnection, ds); Date retrievedTimestamp = Calendar.getInstance().getTime(); Date modifiedTimestamp = (urlConnection.getLastModified() > 0) ? new Date(urlConnection.getLastModified()) : null; if (log.isInfoEnabled()) log.info("Attempt to import up-to-date " + ((modifiedTimestamp != null) ? "(from " + modifiedTimestamp + ") " : "") + "statistics for " + ds + "."); try { if (stats.updateFrom(RDFStatsModelFactory.create(newStats), onlyIfNewer)) stats.setLastDownload(ds.getSPARQLEndpointURL(), retrievedTimestamp); } catch (Exception e) { throw new DataSourceMonitorException("Failed to import statistics and set last download for " + ds + ".", e); } } else { if (log.isInfoEnabled()) log.info("Statistics for " + ds + " are up-to-date" + ((lastDownload != null) ? " (" + lastDownload + ")" : "")); } } |
11
| Code Sample 1:
public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); }
Code Sample 2:
public static void unZip(String unZipfileName, String outputDirectory) throws IOException, FileNotFoundException { FileOutputStream fileOut; File file; ZipEntry zipEntry; ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)), encoder); while ((zipEntry = zipIn.getNextEntry()) != null) { file = new File(outputDirectory + File.separator + zipEntry.getName()); if (zipEntry.isDirectory()) { createDirectory(file.getPath(), ""); } else { File parent = file.getParentFile(); if (!parent.exists()) { createDirectory(parent.getPath(), ""); } fileOut = new FileOutputStream(file); int readedBytes; while ((readedBytes = zipIn.read(buf)) > 0) { fileOut.write(buf, 0, readedBytes); } fileOut.close(); } zipIn.closeEntry(); } } |
00
| Code Sample 1:
public static void executa(String arquivo, String filial, String ip) { String drive = arquivo.substring(0, 2); if (drive.indexOf(":") == -1) drive = ""; Properties p = Util.lerPropriedades(arquivo); String servidor = p.getProperty("servidor"); String impressora = p.getProperty("fila"); String arqRel = new String(drive + p.getProperty("arquivo")); String copias = p.getProperty("copias"); if (filial.equalsIgnoreCase(servidor)) { Socket s = null; int tentativas = 0; boolean conectado = false; while (!conectado) { try { tentativas++; System.out.println("Tentando conectar " + ip + " (" + tentativas + ")"); s = new Socket(ip, 7000); conectado = s.isConnected(); } catch (ConnectException ce) { System.err.println(ce.getMessage()); System.err.println(ce.getCause()); } catch (UnknownHostException uhe) { System.err.println(uhe.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } FileInputStream in = null; BufferedOutputStream out = null; try { in = new FileInputStream(new File(arqRel)); out = new BufferedOutputStream(new GZIPOutputStream(s.getOutputStream())); } catch (FileNotFoundException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } String arqtr = arqRel.substring(2); System.out.println("Proximo arquivo: " + arqRel + " ->" + arqtr); while (arqtr.length() < 30) arqtr += " "; while (impressora.length() < 30) impressora += " "; byte aux[] = new byte[30]; byte cop[] = new byte[2]; try { aux = arqtr.getBytes("UTF8"); out.write(aux); aux = impressora.getBytes("UTF8"); out.write(aux); cop = copias.getBytes("UTF8"); out.write(cop); out.flush(); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } byte b[] = new byte[1024]; int nBytes; try { while ((nBytes = in.read(b)) != -1) out.write(b, 0, nBytes); out.flush(); out.close(); in.close(); s.close(); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("Arquivo " + arqRel + " foi transmitido. \n\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } SimpleDateFormat dfArq = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat dfLog = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String arqLog = "log" + filial + dfArq.format(new Date()) + ".txt"; PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(arqLog, true)); } catch (IOException e) { e.printStackTrace(); } pw.println("Arquivo: " + arquivo + " " + dfLog.format(new Date())); pw.flush(); pw.close(); File f = new File(arquivo); while (!f.delete()) { System.out.println("Erro apagando " + arquivo); } } }
Code Sample 2:
public static void loadPlugins() { Logger.trace("Loading plugins"); Enumeration<URL> urls = null; try { urls = Play.classloader.getResources("play.plugins"); } catch (Exception e) { } while (urls != null && urls.hasMoreElements()) { URL url = urls.nextElement(); Logger.trace("Found one plugins descriptor, %s", url); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; while ((line = reader.readLine()) != null) { String[] infos = line.split(":"); PlayPlugin plugin = (PlayPlugin) Play.classloader.loadClass(infos[1].trim()).newInstance(); Logger.trace("Loaded plugin %s", plugin); plugin.index = Integer.parseInt(infos[0]); plugins.add(plugin); } } catch (Exception ex) { Logger.error(ex, "Cannot load %s", url); } } Collections.sort(plugins); for (PlayPlugin plugin : new ArrayList<PlayPlugin>(plugins)) { plugin.onLoad(); } } |
00
| Code Sample 1:
public static void copy(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(); }
Code Sample 2:
JSONResponse execute() throws ServerException, RtmApiException, IOException { HttpClient httpclient = new DefaultHttpClient(); URI uri; try { uri = new URI(this.request.getUrl()); HttpPost httppost = new HttpPost(uri); HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(is))); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } return new JSONResponse(sb.toString()); } finally { is.close(); } } catch (URISyntaxException e) { throw new RtmApiException(e.getMessage()); } catch (ClientProtocolException e) { throw new RtmApiException(e.getMessage()); } } |
11
| Code Sample 1:
@Override public byte[] read(String path) throws PersistenceException { InputStream reader = null; ByteArrayOutputStream sw = new ByteArrayOutputStream(); try { reader = new FileInputStream(path); IOUtils.copy(reader, sw); } catch (Exception e) { LOGGER.error("fail to read file - " + path, e); throw new PersistenceException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LOGGER.error("fail to close reader", e); } } } return sw.toByteArray(); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
00
| Code Sample 1:
public static String encrypt(String plainText) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static String getUploadDeleteComboBox(String fromMode, String fromFolder, String action, String object, HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); StringBuffer links = new StringBuffer(); StringBuffer folders = new StringBuffer(); String folder = ""; String server = ""; String login = ""; String password = ""; int i = 0; String liveFTPServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER") + ""; liveFTPServer = liveFTPServer.trim(); if ((liveFTPServer == null) || (liveFTPServer.equals("null")) || (liveFTPServer.equals(""))) { return ("This tool is not " + "configured and will not operate. " + "If you wish it to do so, please edit " + "this publication's properties and add correct values to " + " the Remote Server Upstreaming section."); } if (action.equals("Upload")) { server = (String) user.workingPubConfigElementsHash.get("TESTFTPSERVER"); login = (String) user.workingPubConfigElementsHash.get("TESTFTPLOGIN"); password = (String) user.workingPubConfigElementsHash.get("TESTFTPPASSWORD"); CofaxToolsUtil.log("server= " + server + " , login= " + login + " , password=" + password); if (object.equals("Media")) { folder = (String) user.workingPubConfigElementsHash.get("TESTIMAGESFOLDER"); } if (object.equals("Templates")) { folder = (String) user.workingPubConfigElementsHash.get("TESTTEMPLATEFOLDER"); CofaxToolsUtil.log("testTemplateFolder= " + folder); } } if (action.equals("Delete")) { login = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN"); password = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD"); if (object.equals("Media")) { server = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESSERVER"); folder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER"); } if (object.equals("Templates")) { server = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER"); folder = (String) user.workingPubConfigElementsHash.get("LIVETEMPLATEFOLDER"); } } ArrayList servers = splitServers(server); try { int reply; ftp.connect((String) servers.get(0)); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox connecting to server: " + (String) servers.get(0)); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox results: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP getUploadDeleteComboBox ERROR: FTP server refused connection: " + server); } else { ftp.login(login, password); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox login / pass " + login + " " + password); } try { String tempParentFolderName = folder; CofaxToolsUtil.log("fromfolder is " + fromFolder); if ((fromFolder != null) && (fromFolder.length() > folder.length())) { folder = fromFolder; tempParentFolderName = folder; int subSt = folder.lastIndexOf("/"); tempParentFolderName = tempParentFolderName.substring(0, subSt); String publicName = ""; int subStri = folder.lastIndexOf((String) user.workingPubName); if (subStri > -1) { publicName = folder.substring(subStri); } folders.append("<B><A HREF=\'/tools/?mode=" + fromMode + "&hl=templates_view_templates_images&fromFolder=" + tempParentFolderName + "\'>" + tempParentFolderName + "</A></B><BR>\n"); } else if ((fromFolder != null) && (fromFolder.length() == folder.length())) { folder = fromFolder; tempParentFolderName = folder; int subSt = folder.lastIndexOf("/"); tempParentFolderName = tempParentFolderName.substring(0, subSt); } boolean changed = ftp.changeWorkingDirectory(folder); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox changing working directory to " + folder); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox results " + changed); FTPFile[] files = null; if ((action.equals("Delete")) && (object.equals("Templates"))) { files = ftp.listFiles(new CofaxToolsNTFileListParser()); } else { files = ftp.listFiles(new CofaxToolsNTFileListParser()); } if (files == null) { CofaxToolsUtil.log("null"); } for (int ii = 0; ii < files.length; ii++) { FTPFile thisFile = (FTPFile) files[ii]; String name = thisFile.getName(); if (!thisFile.isDirectory()) { links.append("<INPUT TYPE=CHECKBOX NAME=" + i + " VALUE=" + folder + "/" + name + ">" + name + "<BR>\n"); i++; } if ((thisFile.isDirectory()) && (!name.startsWith(".")) && (!name.endsWith("."))) { int subStr = folder.lastIndexOf((String) user.workingPubName); String tempFolderName = ""; if (subStr > -1) { tempFolderName = folder.substring(subStr); } else { tempFolderName = folder; } folders.append("<LI><A HREF=\'/tools/?mode=" + fromMode + "&hl=templates_view_templates_images&fromFolder=" + folder + "/" + name + "\'>" + tempFolderName + "/" + name + "</A><BR>"); } } ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { return ("CofaxToolsFTP getUploadDeleteComboBox cannot read directory: " + folder); } } catch (IOException e) { return ("Could not connect to server: " + e); } links.append("<INPUT TYPE=HIDDEN NAME=numElements VALUE=" + i + " >\n"); links.append("<INPUT TYPE=SUBMIT VALUE=\"" + action + " " + object + "\">\n"); return (folders.toString() + links.toString()); } |
00
| Code Sample 1:
private static String genRandomGUID(boolean secure) { String valueBeforeMD5 = ""; String valueAfterMD5 = ""; MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); return valueBeforeMD5; } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); String strTemp = ""; for (int i = 0; i < array.length; i++) { strTemp = (Integer.toHexString(array[i] & 0XFF)); if (strTemp.length() == 1) { valueAfterMD5 = valueAfterMD5 + "0" + strTemp; } else { valueAfterMD5 = valueAfterMD5 + strTemp; } } return valueAfterMD5.toUpperCase(); }
Code Sample 2:
public void testCodingBeyondContentLimitFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff; and a lot more stuff"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); } |
11
| Code Sample 1:
public static void main(String[] args) throws Exception { String linesep = System.getProperty("line.separator"); FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt")); fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes()); fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes()); fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes()); fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes()); fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes()); fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes()); File[] files = new File(args[0]).listFiles(new JarFileFilter()); for (int i = 0; i < files.length; i++) { if (new File(files[i].getPath() + ".meta").exists()) { Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta")); Iterator<String> itsect = metaprops.keySet().iterator(); while (itsect.hasNext()) { String section = itsect.next(); fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes()); fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes()); fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes()); fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes()); fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes()); } } if (new File(files[i].getPath() + ".extra").exists()) { fos.write(new String("The author says:" + linesep).getBytes()); FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra")); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } fos.write(linesep.getBytes()); } fos.close(); }
Code Sample 2:
public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); } |
00
| Code Sample 1:
public void serveResource(HTTPResource resource, HttpServletRequest request, HttpServletResponse response) throws java.io.IOException { Image image = (Image) resource; log.debug("Serving: " + image); URL url = image.getResourceURL(); int idx = url.toString().lastIndexOf("."); String fn = image.getId() + url.toString().substring(idx); String cd = "filename=\"" + fn + "\""; response.setContentType(image.getContentType()); log.debug("LOADING: " + url); IOUtil.copyData(response.getOutputStream(), url.openStream()); }
Code Sample 2:
protected Object serveFile(MyServerSocket socket, String filenm, URL url) { PrintStream out = null; InputStream in = null; long len = 0; try { out = new PrintStream(socket.getOutputStream()); in = url.openStream(); len = in.available(); } catch (IOException e) { HttpHelper.httpWrap(HttpHelper.EXC, e.toString(), 0); } if (HttpHelper.isImage(filenm)) { out.print(HttpHelper.httpWrapPic(filenm, len)); } else if (filenm.endsWith(".html")) { Comms.copyStreamSED(in, out, MPRES); } else if (HttpHelper.isOtherFile(filenm)) { out.print(HttpHelper.httpWrapOtherFile(filenm, len)); } else { String type = MimeUtils.getMimeType(filenm); if (type.equals(MimeUtils.UNKNOWN_MIME_TYPE)) { out.print(HttpHelper.httpWrapMimeType(type, len)); } else { out.print(HttpHelper.httpWrapMimeType(type, len)); } } if (in == null) { Log.logThis("THE INPUT STREAM IS NULL...url=" + url); } else Files.copyStream(in, out); return null; } |
00
| Code Sample 1:
public String getResourceAsString(String name) throws IOException { String content = null; InputStream stream = aClass.getResourceAsStream(name); if (stream != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(stream, buffer); content = buffer.toString(); } else { Assert.fail("Resource not available: " + name); } return content; }
Code Sample 2:
public void sortIndexes() { int i, j, count; int t; count = m_ItemIndexes.length; for (i = 1; i < count; i++) { for (j = 0; j < count - i; j++) { if (m_ItemIndexes[j] > m_ItemIndexes[j + 1]) { t = m_ItemIndexes[j]; m_ItemIndexes[j] = m_ItemIndexes[j + 1]; m_ItemIndexes[j + 1] = t; } } } } |
11
| Code Sample 1:
@Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; }
Code Sample 2:
private void unzipData(ZipFile zipfile, ZipEntry entry) { if (entry.getName().equals("backUpExternalInfo.out")) { File outputFile = new File("temp", entry.getName()); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } try { BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException e) { throw new BackupException(e.getMessage()); } } } |
11
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
protected File 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; } } } |
11
| Code Sample 1:
public void prepareOutput(HttpServletRequest req) { EaasyStreet.logTrace(METHOD_IN + className + OUTPUT_METHOD); super.prepareOutput(req); String content = Constants.EMPTY_STRING; String rawContent = null; List parts = null; try { URL url = new URL(sourceUrl); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); buffer.append(Constants.LF); } rawContent = buffer.toString(); } catch (FileNotFoundException nf) { req.setAttribute(Constants.RAK_SYSTEM_ACTION, Constants.SYSTEM_ACTION_BACK); EaasyStreet.handleSafeEvent(req, new Event(Constants.EAA0012I, new String[] { "URL", nf.getMessage(), nf.toString() })); } catch (Exception e) { req.setAttribute(Constants.RAK_SYSTEM_ACTION, Constants.SYSTEM_ACTION_BACK); EaasyStreet.handleSafeEvent(req, new Event(Constants.EAA0012I, new String[] { "URL", e.getMessage(), e.toString() })); } if (rawContent != null) { if (startDelimiter != null) { parts = StringUtils.split(rawContent, startDelimiter); if (parts != null && parts.size() > 1) { rawContent = (String) parts.get(1); if (parts.size() > 2) { for (int x = 2; x < parts.size(); x++) { rawContent += startDelimiter; rawContent += parts.get(x); } } } else { rawContent = null; } } } if (rawContent != null) { if (endDelimiter != null) { parts = StringUtils.split(rawContent, endDelimiter); if (parts != null && parts.size() > 0) { rawContent = (String) parts.get(0); } else { rawContent = null; } } } if (rawContent != null) { if (replacementValues != null && !replacementValues.isEmpty()) { for (int x = 0; x < replacementValues.size(); x++) { LabelValueBean bean = (LabelValueBean) replacementValues.get(x); rawContent = StringUtils.replace(rawContent, bean.getLabel(), bean.getValue()); } } } if (rawContent != null) { content = rawContent; } req.setAttribute(getFormName(), content); EaasyStreet.logTrace(METHOD_OUT + className + OUTPUT_METHOD); }
Code Sample 2:
public String getMethod(String url) { logger.info("Facebook: @executing facebookGetMethod():" + url); String responseStr = null; try { HttpGet loginGet = new HttpGet(url); loginGet.addHeader("Accept-Encoding", "gzip"); HttpResponse response = httpClient.execute(loginGet); HttpEntity entity = response.getEntity(); logger.trace("Facebook: facebookGetMethod: " + response.getStatusLine()); if (entity != null) { InputStream in = response.getEntity().getContent(); if (response.getEntity().getContentEncoding().getValue().equals("gzip")) { in = new GZIPInputStream(in); } StringBuffer sb = new StringBuffer(); byte[] b = new byte[4096]; int n; while ((n = in.read(b)) != -1) { sb.append(new String(b, 0, n)); } responseStr = sb.toString(); in.close(); entity.consumeContent(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { logger.warn("Facebook: Error Occured! Status Code = " + statusCode); responseStr = null; } logger.info("Facebook: Get Method done(" + statusCode + "), response string length: " + (responseStr == null ? 0 : responseStr.length())); } catch (IOException e) { logger.warn("Facebook: ", e); } return responseStr; } |
11
| Code Sample 1:
public static void main(String args[]) throws Exception { File file = new File("D:/work/love.txt"); @SuppressWarnings("unused") ZipFile zipFile = new ZipFile("D:/work/test1.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("D:/work/test1.zip")); zos.setEncoding("GBK"); ZipEntry entry = null; if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); int readLen = 0; byte[] buf = new byte[2048]; if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 2048)) != -1) { zos.write(buf, 0, readLen); } in.close(); } zos.close(); }
Code Sample 2:
public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } |
00
| Code Sample 1:
public int openUrl(String url, String method, Bundle params) { int result = 0; try { if (method.equals("GET")) { url = url + "?" + Utility.encodeUrl(params); } String response = ""; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " RenrenAndroidSDK"); if (!method.equals("GET")) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(Utility.encodeUrl(params).getBytes("UTF-8")); } response = Utility.read(conn.getInputStream()); JSONObject json = new JSONObject(response); try { int code = json.getInt("result"); if (code > 0) result = 1; } catch (Exception e) { result = json.getInt("error_code"); errmessage = json.getString("error_msg"); } } catch (Exception e) { result = -1; } return result; }
Code Sample 2:
public static final String convertPassword(final String srcPwd) { StringBuilder out; MessageDigest md; byte[] byteValues; byte singleChar = 0; try { md = MessageDigest.getInstance("MD5"); md.update(srcPwd.getBytes()); byteValues = md.digest(); if ((byteValues == null) || (byteValues.length <= 0)) { return null; } out = new StringBuilder(byteValues.length * 2); for (byte element : byteValues) { singleChar = (byte) (element & 0xF0); singleChar = (byte) (singleChar >>> 4); singleChar = (byte) (singleChar & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); singleChar = (byte) (element & 0x0F); out.append(PasswordConverter.ENTRIES[singleChar]); } return out.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } |
11
| Code Sample 1:
public static void main(String[] args) throws IOException { String paramFileName = args[0]; BufferedReader inFile_params = new BufferedReader(new FileReader(paramFileName)); String cands_fileName = (inFile_params.readLine().split("\\s+"))[0]; String alignSrcCand_phrasal_fileName = (inFile_params.readLine().split("\\s+"))[0]; String alignSrcCand_word_fileName = (inFile_params.readLine().split("\\s+"))[0]; String source_fileName = (inFile_params.readLine().split("\\s+"))[0]; String trainSrc_fileName = (inFile_params.readLine().split("\\s+"))[0]; String trainTgt_fileName = (inFile_params.readLine().split("\\s+"))[0]; String trainAlign_fileName = (inFile_params.readLine().split("\\s+"))[0]; String alignCache_fileName = (inFile_params.readLine().split("\\s+"))[0]; String alignmentsType = "AlignmentGrids"; int maxCacheSize = 1000; inFile_params.close(); int numSentences = countLines(source_fileName); InputStream inStream_src = new FileInputStream(new File(source_fileName)); BufferedReader srcFile = new BufferedReader(new InputStreamReader(inStream_src, "utf8")); String[] srcSentences = new String[numSentences]; for (int i = 0; i < numSentences; ++i) { srcSentences[i] = srcFile.readLine(); } srcFile.close(); println("Creating src vocabulary @ " + (new Date())); srcVocab = new Vocabulary(); int[] sourceWordsSentences = Vocabulary.initializeVocabulary(trainSrc_fileName, srcVocab, true); int numSourceWords = sourceWordsSentences[0]; int numSourceSentences = sourceWordsSentences[1]; println("Reading src corpus @ " + (new Date())); srcCorpusArray = SuffixArrayFactory.createCorpusArray(trainSrc_fileName, srcVocab, numSourceWords, numSourceSentences); println("Creating src SA @ " + (new Date())); srcSA = SuffixArrayFactory.createSuffixArray(srcCorpusArray, maxCacheSize); println("Creating tgt vocabulary @ " + (new Date())); tgtVocab = new Vocabulary(); int[] targetWordsSentences = Vocabulary.initializeVocabulary(trainTgt_fileName, tgtVocab, true); int numTargetWords = targetWordsSentences[0]; int numTargetSentences = targetWordsSentences[1]; println("Reading tgt corpus @ " + (new Date())); tgtCorpusArray = SuffixArrayFactory.createCorpusArray(trainTgt_fileName, tgtVocab, numTargetWords, numTargetSentences); println("Creating tgt SA @ " + (new Date())); tgtSA = SuffixArrayFactory.createSuffixArray(tgtCorpusArray, maxCacheSize); int trainingSize = srcCorpusArray.getNumSentences(); if (trainingSize != tgtCorpusArray.getNumSentences()) { throw new RuntimeException("Source and target corpora have different number of sentences. This is bad."); } println("Reading alignment data @ " + (new Date())); alignments = null; if ("AlignmentArray".equals(alignmentsType)) { alignments = SuffixArrayFactory.createAlignments(trainAlign_fileName, srcSA, tgtSA); } else if ("AlignmentGrids".equals(alignmentsType) || "AlignmentsGrid".equals(alignmentsType)) { alignments = new AlignmentGrids(new Scanner(new File(trainAlign_fileName)), srcCorpusArray, tgtCorpusArray, trainingSize, true); } else if ("MemoryMappedAlignmentGrids".equals(alignmentsType)) { alignments = new MemoryMappedAlignmentGrids(trainAlign_fileName, srcCorpusArray, tgtCorpusArray); } if (!fileExists(alignCache_fileName)) { alreadyResolved_srcSet = new HashMap<String, TreeSet<Integer>>(); alreadyResolved_tgtSet = new HashMap<String, TreeSet<Integer>>(); } else { try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(alignCache_fileName)); alreadyResolved_srcSet = (HashMap<String, TreeSet<Integer>>) in.readObject(); alreadyResolved_tgtSet = (HashMap<String, TreeSet<Integer>>) in.readObject(); in.close(); } catch (FileNotFoundException e) { System.err.println("FileNotFoundException in AlignCandidates.main(String[]): " + e.getMessage()); System.exit(99901); } catch (IOException e) { System.err.println("IOException in AlignCandidates.main(String[]): " + e.getMessage()); System.exit(99902); } catch (ClassNotFoundException e) { System.err.println("ClassNotFoundException in AlignCandidates.main(String[]): " + e.getMessage()); System.exit(99904); } } println("Processing candidates @ " + (new Date())); PrintWriter outFile_alignSrcCand_phrasal = new PrintWriter(alignSrcCand_phrasal_fileName); PrintWriter outFile_alignSrcCand_word = new PrintWriter(alignSrcCand_word_fileName); InputStream inStream_cands = new FileInputStream(new File(cands_fileName)); BufferedReader candsFile = new BufferedReader(new InputStreamReader(inStream_cands, "utf8")); String line = ""; String cand = ""; line = candsFile.readLine(); int countSatisfied = 0; int countAll = 0; int countSatisfied_sizeOne = 0; int countAll_sizeOne = 0; int prev_i = -1; String srcSent = ""; String[] srcWords = null; int candsRead = 0; int C50count = 0; while (line != null) { ++candsRead; println("Read candidate on line #" + candsRead); int i = toInt((line.substring(0, line.indexOf("|||"))).trim()); if (i != prev_i) { srcSent = srcSentences[i]; srcWords = srcSent.split("\\s+"); prev_i = i; println("New value for i: " + i + " seen @ " + (new Date())); C50count = 0; } else { ++C50count; } line = (line.substring(line.indexOf("|||") + 3)).trim(); cand = (line.substring(0, line.indexOf("|||"))).trim(); cand = cand.substring(cand.indexOf(" ") + 1, cand.length() - 1); JoshuaDerivationTree DT = new JoshuaDerivationTree(cand, 0); String candSent = DT.toSentence(); String[] candWords = candSent.split("\\s+"); String alignSrcCand = DT.alignments(); outFile_alignSrcCand_phrasal.println(alignSrcCand); println(" i = " + i + ", alignSrcCand: " + alignSrcCand); String alignSrcCand_res = ""; String[] linksSrcCand = alignSrcCand.split("\\s+"); for (int k = 0; k < linksSrcCand.length; ++k) { String link = linksSrcCand[k]; if (link.indexOf(',') == -1) { alignSrcCand_res += " " + link.replaceFirst("--", "-"); } else { alignSrcCand_res += " " + resolve(link, srcWords, candWords); } } alignSrcCand_res = alignSrcCand_res.trim(); println(" i = " + i + ", alignSrcCand_res: " + alignSrcCand_res); outFile_alignSrcCand_word.println(alignSrcCand_res); if (C50count == 50) { println("50C @ " + (new Date())); C50count = 0; } line = candsFile.readLine(); } outFile_alignSrcCand_phrasal.close(); outFile_alignSrcCand_word.close(); candsFile.close(); println("Finished processing candidates @ " + (new Date())); try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(alignCache_fileName)); out.writeObject(alreadyResolved_srcSet); out.writeObject(alreadyResolved_tgtSet); out.flush(); out.close(); } catch (IOException e) { System.err.println("IOException in AlignCandidates.main(String[]): " + e.getMessage()); System.exit(99902); } }
Code Sample 2:
public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } |
11
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void fastBackup(File file) { FileChannel in = null; FileChannel out = null; FileInputStream fin = null; FileOutputStream fout = null; try { in = (fin = new FileInputStream(file)).getChannel(); out = (fout = new FileOutputStream(file.getAbsolutePath() + ".bak")).getChannel(); in.transferTo(0, in.size(), out); } catch (IOException e) { Logging.getErrorLog().reportError("Fast backup failure (" + file.getAbsolutePath() + "): " + e.getMessage()); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file input stream", e); } } if (fout != null) { try { fout.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file output stream", e); } } if (in != null) { try { in.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } if (out != null) { try { out.close(); } catch (IOException e) { Logging.getErrorLog().reportException("Failed to close file channel", e); } } } } |
00
| Code Sample 1:
public static String md5(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[FOUR_BYTES]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
private static void salvarArtista(Artista artista) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into artista VALUES (?,?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, artista.getNumeroInscricao()); ps.setString(2, artista.getNome()); ps.setBoolean(3, artista.isSexo()); ps.setString(4, artista.getEmail()); ps.setString(5, artista.getObs()); ps.setString(6, artista.getTelefone()); ps.setNull(7, Types.INTEGER); ps.executeUpdate(); salvarEndereco(conn, ps, artista); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } |
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 MD5_hex(String p) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(p.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); String ret = hash.toString(16); return ret; } catch (NoSuchAlgorithmException e) { logger.error("can not create confirmation key", e); throw new TechException(e); } } |
00
| Code Sample 1:
public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } catch (UnsupportedEncodingException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public void doFTP() throws BuildException { FTPClient ftp = null; try { task.log("Opening FTP connection to " + task.getServer(), Project.MSG_VERBOSE); ftp = new FTPClient(); if (task.isConfigurationSet()) { ftp = FTPConfigurator.configure(ftp, task); } ftp.setRemoteVerificationEnabled(task.getEnableRemoteVerification()); ftp.connect(task.getServer(), task.getPort()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("FTP connection failed: " + ftp.getReplyString()); } task.log("connected", Project.MSG_VERBOSE); task.log("logging in to FTP server", Project.MSG_VERBOSE); if ((task.getAccount() != null && !ftp.login(task.getUserid(), task.getPassword(), task.getAccount())) || (task.getAccount() == null && !ftp.login(task.getUserid(), task.getPassword()))) { throw new BuildException("Could not login to FTP server"); } task.log("login succeeded", Project.MSG_VERBOSE); if (task.isBinary()) { ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } else { ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not set transfer type: " + ftp.getReplyString()); } } if (task.isPassive()) { task.log("entering passive mode", Project.MSG_VERBOSE); ftp.enterLocalPassiveMode(); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString()); } } if (task.getInitialSiteCommand() != null) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, task.getInitialSiteCommand()); } }, "initial site command: " + task.getInitialSiteCommand()); } if (task.getUmask() != null) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, "umask " + task.getUmask()); } }, "umask " + task.getUmask()); } if (task.getAction() == FTPTask.MK_DIR) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { makeRemoteDir(lftp, task.getRemotedir()); } }, task.getRemotedir()); } else if (task.getAction() == FTPTask.SITE_CMD) { RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task); final FTPClient lftp = ftp; executeRetryable(h, new Retryable() { public void execute() throws IOException { doSiteCommand(lftp, task.getSiteCommand()); } }, "Site Command: " + task.getSiteCommand()); } else { if (task.getRemotedir() != null) { task.log("changing the remote directory", Project.MSG_VERBOSE); ftp.changeWorkingDirectory(task.getRemotedir()); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString()); } } if (task.isNewer() && task.isTimeDiffAuto()) { task.setTimeDiffMillis(getTimeDiff(ftp)); } task.log(FTPTask.ACTION_STRS[task.getAction()] + " " + FTPTask.ACTION_TARGET_STRS[task.getAction()]); transferFiles(ftp); } } catch (IOException ex) { throw new BuildException("error during FTP transfer: " + ex, ex); } finally { if (ftp != null && ftp.isConnected()) { try { task.log("disconnecting", Project.MSG_VERBOSE); ftp.logout(); ftp.disconnect(); } catch (IOException ex) { } } } } |
11
| Code Sample 1:
public static void copyFile(File in, File outDir) throws IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); File out = new File(outDir, in.getName()); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { if (sourceChannel != null) { sourceChannel.close(); } } finally { if (destinationChannel != null) { destinationChannel.close(); } } } }
Code Sample 2:
public Object mapRow(ResultSet rs, int i) throws SQLException { try { BLOB blob = (BLOB) rs.getBlob(1); OutputStream outputStream = blob.setBinaryStream(0L); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (Exception e) { throw new SQLException(e.getMessage()); } return null; } |
11
| Code Sample 1:
private Collection<Class<? extends Plugin>> loadFromResource(ClassLoader classLoader, String resource) throws IOException { Collection<Class<? extends Plugin>> pluginClasses = new HashSet<Class<? extends Plugin>>(); Enumeration providerFiles = classLoader.getResources(resource); if (!providerFiles.hasMoreElements()) { logger.warning("Can't find the resource: " + resource); return pluginClasses; } do { URL url = (URL) providerFiles.nextElement(); InputStream stream = url.openStream(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); } catch (IOException e) { continue; } String line; while ((line = reader.readLine()) != null) { int index = line.indexOf('#'); if (index != -1) { line = line.substring(0, index); } line = line.trim(); if (line.length() > 0) { Class pluginClass; try { pluginClass = classLoader.loadClass(line); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Can't use the Pluginclass with the name " + line + ".", e); continue; } if (Plugin.class.isAssignableFrom(pluginClass)) { pluginClasses.add((Class<? extends Plugin>) pluginClass); } else { logger.warning("The Pluginclass with the name " + line + " isn't a subclass of Plugin."); } } } reader.close(); stream.close(); } while (providerFiles.hasMoreElements()); return pluginClasses; }
Code Sample 2:
protected void doGetPost(HttpServletRequest req, HttpServletResponse resp, boolean post) throws ServletException, IOException { if (responseBufferSize > 0) resp.setBufferSize(responseBufferSize); String pathinfo = req.getPathInfo(); if (pathinfo == null) { String urlstring = req.getParameter(REMOTE_URL); if (urlstring == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.nourl")); return; } boolean allowCookieForwarding = "true".equals(req.getParameter(ALLOW_COOKIE_FORWARDING)); boolean allowFormDataForwarding = "true".equals(req.getParameter(ALLOW_FORM_DATA_FORWARDING)); String target = new JGlossURLRewriter(req.getContextPath() + req.getServletPath(), new URL(HttpUtils.getRequestURL(req).toString()), null, allowCookieForwarding, allowFormDataForwarding).rewrite(urlstring, true); resp.sendRedirect(target); return; } Set connectionAllowedProtocols; if (req.isSecure()) connectionAllowedProtocols = secureAllowedProtocols; else connectionAllowedProtocols = allowedProtocols; Object[] oa = JGlossURLRewriter.parseEncodedPath(pathinfo); if (oa == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale(), new UTF8ResourceBundleControl()).getString("error.malformedrequest"), new Object[] { pathinfo })); return; } boolean allowCookieForwarding = ((Boolean) oa[0]).booleanValue(); boolean allowFormDataForwarding = ((Boolean) oa[1]).booleanValue(); String urlstring = (String) oa[2]; getServletContext().log("received request for " + urlstring); if (urlstring.toLowerCase().indexOf(req.getServletPath().toLowerCase()) != -1) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.addressnotallowed"), new Object[] { urlstring })); return; } if (urlstring.indexOf(':') == -1) { if (req.isSecure()) { if (secureAllowedProtocols.contains("https")) urlstring = "https://" + urlstring; } else { if (allowedProtocols.contains("http")) urlstring = "http://" + urlstring; } } URL url; try { url = new URL(urlstring); } catch (MalformedURLException ex) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.malformedurl"), new Object[] { urlstring })); return; } String protocol = url.getProtocol(); if (!connectionAllowedProtocols.contains(protocol)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.protocolnotallowed"), new Object[] { protocol })); getServletContext().log("protocol not allowed accessing " + url.toString()); return; } boolean remoteIsHttp = protocol.equals("http") || protocol.equals("https"); boolean forwardCookies = remoteIsHttp && enableCookieForwarding && allowCookieForwarding; boolean forwardFormData = remoteIsHttp && enableFormDataForwarding && allowFormDataForwarding && (enableFormDataSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https")); if (forwardFormData) { String query = req.getQueryString(); if (query != null && query.length() > 0) { if (url.getQuery() == null || url.getQuery().length() == 0) url = new URL(url.toExternalForm() + "?" + query); else url = new URL(url.toExternalForm() + "&" + query); } } JGlossURLRewriter rewriter = new JGlossURLRewriter(new URL(req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath() + req.getServletPath()).toExternalForm(), url, connectionAllowedProtocols, allowCookieForwarding, allowFormDataForwarding); URLConnection connection = url.openConnection(); if (forwardFormData && post && remoteIsHttp) { getServletContext().log("using POST"); try { ((HttpURLConnection) connection).setRequestMethod("POST"); } catch (ClassCastException ex) { getServletContext().log("failed to set method POST: " + ex.getMessage()); } connection.setDoInput(true); connection.setDoOutput(true); } String acceptEncoding = buildAcceptEncoding(req.getHeader("accept-encoding")); getServletContext().log("accept-encoding: " + acceptEncoding); if (acceptEncoding != null) connection.setRequestProperty("Accept-Encoding", acceptEncoding); forwardRequestHeaders(connection, req); if (forwardCookies && (enableCookieSecureInsecureForwarding || !req.isSecure() || url.getProtocol().equals("https"))) CookieTools.addRequestCookies(connection, req.getCookies(), getServletContext()); try { connection.connect(); } catch (UnknownHostException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.unknownhost"), new Object[] { url.toExternalForm(), url.getHost() })); return; } catch (IOException ex) { resp.sendError(HttpServletResponse.SC_BAD_GATEWAY, MessageFormat.format(ResourceBundle.getBundle(MESSAGES, req.getLocale()).getString("error.connect"), new Object[] { url.toExternalForm(), ex.getClass().getName(), ex.getMessage() })); return; } if (forwardFormData && post && remoteIsHttp) { InputStream is = req.getInputStream(); OutputStream os = connection.getOutputStream(); byte[] buf = new byte[512]; int len; while ((len = is.read(buf)) != -1) os.write(buf, 0, len); is.close(); os.close(); } forwardResponseHeaders(connection, req, resp, rewriter); if (forwardCookies && (enableCookieSecureInsecureForwarding || req.isSecure() || !url.getProtocol().equals("https"))) CookieTools.addResponseCookies(connection, resp, req.getServerName(), req.getContextPath() + req.getServletPath(), req.isSecure(), getServletContext()); if (remoteIsHttp) { try { int response = ((HttpURLConnection) connection).getResponseCode(); getServletContext().log("response code " + response); resp.setStatus(response); if (response == 304) return; } catch (ClassCastException ex) { getServletContext().log("failed to read response code: " + ex.getMessage()); } } String type = connection.getContentType(); getServletContext().log("content type " + type + " url " + connection.getURL().toString()); boolean supported = false; if (type != null) { for (int i = 0; i < rewrittenContentTypes.length; i++) if (type.startsWith(rewrittenContentTypes[i])) { supported = true; break; } } if (supported) { String encoding = connection.getContentEncoding(); supported = encoding == null || encoding.endsWith("gzip") || encoding.endsWith("deflate") || encoding.equals("identity"); } if (supported) rewrite(connection, req, resp, rewriter); else tunnel(connection, req, resp); } |
00
| Code Sample 1:
private static GSP loadGSP(URL url) { try { InputStream input = url.openStream(); int c; while ((c = input.read()) != -1) { result = result + (char) c; } Unmarshaller unmarshaller = getUnmarshaller(); unmarshaller.setValidation(false); GSP gsp = (GSP) unmarshaller.unmarshal(new InputSource()); return gsp; } catch (Exception e) { System.out.println("loadGSP " + e); e.printStackTrace(); return null; } }
Code Sample 2:
public static void main(String[] args) throws Exception { String localSrc = args[0]; String dst = args[1]; InputStream in = new BufferedInputStream(new FileInputStream(localSrc)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(dst), conf); OutputStream out = fs.create(new Path(dst), new Progressable() { public void progress() { System.out.print("."); } }); IOUtils.copyBytes(in, out, 4096, true); } |
11
| Code Sample 1:
private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException { if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) { String mimeType = vds.DSMIME; if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) { try { entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { entry.setContent(vds.getContentStream(), mimeType); } } else { String dsLocation; IRI iri; if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) { dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME); try { m_zout.putNextEntry(new ZipEntry(dsLocation)); InputStream is = vds.getContentStream(); IOUtils.copy(is, m_zout); is.close(); m_zout.closeEntry(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } else { dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation); } iri = new IRI(dsLocation); entry.setSummary(vds.DSVersionID); entry.setContent(iri, vds.DSMIME); } }
Code Sample 2:
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; } |
00
| Code Sample 1:
public void importarHistoricoDeCotacoesDosPapeis(File[] pArquivosTXT, boolean pApagarDadosImportadosAnteriormente, Andamento pAndamento) throws FileNotFoundException, SQLException { if (pApagarDadosImportadosAnteriormente) { Statement stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_COTACAO_AVISTA_LOTE_PDR"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "TRUNCATE TABLE TMP_TB_COTACAO_OUTROS_MERCADOS"; stmtLimpezaInicialDestino.executeUpdate(sql); } final int TAMANHO_DO_REGISTRO = 245; long TAMANHO_DOS_METADADOS_DO_ARQUIVO = 2 * TAMANHO_DO_REGISTRO; long tamanhoDosArquivos = 0; for (File arquivoTXT : pArquivosTXT) { long tamanhoDoArquivo = arquivoTXT.length(); tamanhoDosArquivos += tamanhoDoArquivo; } int quantidadeEstimadaDeRegistros = (int) ((tamanhoDosArquivos - (pArquivosTXT.length * TAMANHO_DOS_METADADOS_DO_ARQUIVO)) / TAMANHO_DO_REGISTRO); String sqlMercadoAVistaLotePadrao = "INSERT INTO TMP_TB_COTACAO_AVISTA_LOTE_PDR(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoMercadoAVistaLotePadrao = (OraclePreparedStatement) conDestino.prepareStatement(sqlMercadoAVistaLotePadrao); stmtDestinoMercadoAVistaLotePadrao.setExecuteBatch(COMANDOS_POR_LOTE); String sqlOutrosMercados = "INSERT INTO TMP_TB_COTACAO_OUTROS_MERCADOS(DATA_PREGAO, CODBDI, CODNEG, TPMERC, NOMRES, ESPECI, PRAZOT, MODREF, PREABE, PREMAX, PREMIN, PREMED, PREULT, PREOFC, PREOFV, TOTNEG, QUATOT, VOLTOT, PREEXE, INDOPC, DATVEN, FATCOT, PTOEXE, CODISI, DISMES) VALUES(:DATA_PREGAO, :CODBDI, :CODNEG, :TPMERC, :NOMRES, :ESPECI, :PRAZOT, :MODREF, :PREABE, :PREMAX, :PREMIN, :PREMED, :PREULT, :PREOFC, :PREOFV, :TOTNEG, :QUATOT, :VOLTOT, :PREEXE, :INDOPC, :DATVEN, :FATCOT, :PTOEXE, :CODISI, :DISMES)"; OraclePreparedStatement stmtDestinoOutrosMercados = (OraclePreparedStatement) conDestino.prepareStatement(sqlOutrosMercados); stmtDestinoOutrosMercados.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportadosDosArquivos = 0; Scanner in = null; int numeroDoRegistro = -1; try { for (File arquivoTXT : pArquivosTXT) { int quantidadeDeRegistrosImportadosDoArquivoAtual = 0; int vDATA_PREGAO; try { in = new Scanner(new FileInputStream(arquivoTXT), Constantes.CONJUNTO_DE_CARACTERES_DOS_ARQUIVOS_TEXTO_DA_BOVESPA.name()); String registro; numeroDoRegistro = 0; while (in.hasNextLine()) { ++numeroDoRegistro; registro = in.nextLine(); if (registro.length() != TAMANHO_DO_REGISTRO) throw new ProblemaNaImportacaoDeArquivo(); if (registro.startsWith("01")) { stmtDestinoMercadoAVistaLotePadrao.clearParameters(); stmtDestinoOutrosMercados.clearParameters(); vDATA_PREGAO = Integer.parseInt(registro.substring(2, 10).trim()); int vCODBDI = Integer.parseInt(registro.substring(10, 12).trim()); String vCODNEG = registro.substring(12, 24).trim(); int vTPMERC = Integer.parseInt(registro.substring(24, 27).trim()); String vNOMRES = registro.substring(27, 39).trim(); String vESPECI = registro.substring(39, 49).trim(); String vPRAZOT = registro.substring(49, 52).trim(); String vMODREF = registro.substring(52, 56).trim(); BigDecimal vPREABE = obterBigDecimal(registro.substring(56, 69).trim(), 13, 2); BigDecimal vPREMAX = obterBigDecimal(registro.substring(69, 82).trim(), 13, 2); BigDecimal vPREMIN = obterBigDecimal(registro.substring(82, 95).trim(), 13, 2); BigDecimal vPREMED = obterBigDecimal(registro.substring(95, 108).trim(), 13, 2); BigDecimal vPREULT = obterBigDecimal(registro.substring(108, 121).trim(), 13, 2); BigDecimal vPREOFC = obterBigDecimal(registro.substring(121, 134).trim(), 13, 2); BigDecimal vPREOFV = obterBigDecimal(registro.substring(134, 147).trim(), 13, 2); int vTOTNEG = Integer.parseInt(registro.substring(147, 152).trim()); BigDecimal vQUATOT = new BigDecimal(registro.substring(152, 170).trim()); BigDecimal vVOLTOT = obterBigDecimal(registro.substring(170, 188).trim(), 18, 2); BigDecimal vPREEXE = obterBigDecimal(registro.substring(188, 201).trim(), 13, 2); int vINDOPC = Integer.parseInt(registro.substring(201, 202).trim()); int vDATVEN = Integer.parseInt(registro.substring(202, 210).trim()); int vFATCOT = Integer.parseInt(registro.substring(210, 217).trim()); BigDecimal vPTOEXE = obterBigDecimal(registro.substring(217, 230).trim(), 13, 6); String vCODISI = registro.substring(230, 242).trim(); int vDISMES = Integer.parseInt(registro.substring(242, 245).trim()); boolean mercadoAVistaLotePadrao = (vTPMERC == 10 && vCODBDI == 2); OraclePreparedStatement stmtDestino; if (mercadoAVistaLotePadrao) { stmtDestino = stmtDestinoMercadoAVistaLotePadrao; } else { stmtDestino = stmtDestinoOutrosMercados; } stmtDestino.setIntAtName("DATA_PREGAO", vDATA_PREGAO); stmtDestino.setIntAtName("CODBDI", vCODBDI); stmtDestino.setStringAtName("CODNEG", vCODNEG); stmtDestino.setIntAtName("TPMERC", vTPMERC); stmtDestino.setStringAtName("NOMRES", vNOMRES); stmtDestino.setStringAtName("ESPECI", vESPECI); stmtDestino.setStringAtName("PRAZOT", vPRAZOT); stmtDestino.setStringAtName("MODREF", vMODREF); stmtDestino.setBigDecimalAtName("PREABE", vPREABE); stmtDestino.setBigDecimalAtName("PREMAX", vPREMAX); stmtDestino.setBigDecimalAtName("PREMIN", vPREMIN); stmtDestino.setBigDecimalAtName("PREMED", vPREMED); stmtDestino.setBigDecimalAtName("PREULT", vPREULT); stmtDestino.setBigDecimalAtName("PREOFC", vPREOFC); stmtDestino.setBigDecimalAtName("PREOFV", vPREOFV); stmtDestino.setIntAtName("TOTNEG", vTOTNEG); stmtDestino.setBigDecimalAtName("QUATOT", vQUATOT); stmtDestino.setBigDecimalAtName("VOLTOT", vVOLTOT); stmtDestino.setBigDecimalAtName("PREEXE", vPREEXE); stmtDestino.setIntAtName("INDOPC", vINDOPC); stmtDestino.setIntAtName("DATVEN", vDATVEN); stmtDestino.setIntAtName("FATCOT", vFATCOT); stmtDestino.setBigDecimalAtName("PTOEXE", vPTOEXE); stmtDestino.setStringAtName("CODISI", vCODISI); stmtDestino.setIntAtName("DISMES", vDISMES); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportadosDoArquivoAtual++; quantidadeDeRegistrosImportadosDosArquivos++; } else if (registro.startsWith("99")) { BigDecimal totalDeRegistros = obterBigDecimal(registro.substring(31, 42).trim(), 11, 0); assert (totalDeRegistros.intValue() - 2) == quantidadeDeRegistrosImportadosDoArquivoAtual : "Quantidade de registros divergente"; break; } double percentualCompleto = (double) quantidadeDeRegistrosImportadosDosArquivos / quantidadeEstimadaDeRegistros * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = arquivoTXT.getName(); problemaDetalhado.linhaProblematicaDoArquivo = numeroDoRegistro; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { in.close(); } } } finally { pAndamento.setPercentualCompleto(100); stmtDestinoMercadoAVistaLotePadrao.close(); stmtDestinoOutrosMercados.close(); } }
Code Sample 2:
public static void decompress(final File file, final File folder, final boolean deleteZipAfter) throws IOException { final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(file.getCanonicalFile()))); ZipEntry ze; try { while (null != (ze = zis.getNextEntry())) { final File f = new File(folder.getCanonicalPath(), ze.getName()); if (f.exists()) f.delete(); if (ze.isDirectory()) { f.mkdirs(); continue; } f.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); try { try { final byte[] buf = new byte[8192]; int bytesRead; while (-1 != (bytesRead = zis.read(buf))) fos.write(buf, 0, bytesRead); } finally { fos.close(); } } catch (final IOException ioe) { f.delete(); throw ioe; } } } finally { zis.close(); } if (deleteZipAfter) file.delete(); } |
11
| Code Sample 1:
public static void copyFile(File src, File dst) throws ResourceNotFoundException, ParseErrorException, Exception { if (src.getAbsolutePath().endsWith(".vm")) { copyVMFile(src, dst.getAbsolutePath().substring(0, dst.getAbsolutePath().lastIndexOf(".vm"))); } else { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dst); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } }
Code Sample 2:
private static FileEntry writeEntry(Zip64File zip64File, FileEntry targetPath, File toWrite, boolean compress) { InputStream in = null; EntryOutputStream out = null; processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath.getName(), toWrite), compress); try { if (!compress) { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_STORED, getFileDate(toWrite)); } else { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_DEFLATED, getFileDate(toWrite)); } if (!targetPath.isDirectory()) { in = new FileInputStream(toWrite); IOUtils.copyLarge(in, out); in.close(); } out.flush(); out.close(); if (targetPath.isDirectory()) { log.info("[createZip] Written folder entry to zip: " + targetPath.getName()); } else { log.info("[createZip] Written file entry to zip: " + targetPath.getName()); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ZipException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return targetPath; } |
11
| Code Sample 1:
private static byte[] finalizeStringHash(String loginHash) throws NoSuchAlgorithmException { MessageDigest md5Hasher; md5Hasher = MessageDigest.getInstance("MD5"); md5Hasher.update(loginHash.getBytes()); md5Hasher.update(LOGIN_FINAL_SALT); return md5Hasher.digest(); }
Code Sample 2:
public static void main(String[] argv) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (Exception e) { e.printStackTrace(); } md.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes(), 0, 56); String exp = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"; String result = toString(md.digest()); System.out.println(exp); System.out.println(result); if (!exp.equals(result)) System.out.println("NOT EQUAL!"); } |
00
| Code Sample 1:
public void removeGames(List<Game> games) throws SQLException { Connection conn = ConnectionManager.getManager().getConnection(); PreparedStatement stm = null; conn.setAutoCommit(false); try { for (Game game : games) { stm = conn.prepareStatement(Statements.DELETE_GAME); stm.setInt(1, game.getGameID()); stm.executeUpdate(); } } catch (SQLException e) { conn.rollback(); throw e; } finally { if (stm != null) stm.close(); } conn.commit(); conn.setAutoCommit(true); }
Code Sample 2:
@Test public void testWriteAndReadBiggerUnbuffered() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwriteb.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwriteb.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); int b = in.read(); while (b != -1) { tmp.write(b); b = in.read(); } byte[] buffer = tmp.toByteArray(); in.close(); assertEquals(body.length(), buffer.length); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } } |
11
| Code Sample 1:
public static void main(String[] args) throws Throwable { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("cas", "cas file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("o", "output directory").longName("outputDir").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("tempDir", "temp directory").build()); options.addOption(new CommandLineOptionBuilder("prefix", "file prefix for all generated files ( default " + DEFAULT_PREFIX + " )").build()); options.addOption(new CommandLineOptionBuilder("trim", "trim file in sfffile's tab delimmed trim format").build()); options.addOption(new CommandLineOptionBuilder("trimMap", "trim map file containing tab delimited trimmed fastX file to untrimmed counterpart").build()); options.addOption(new CommandLineOptionBuilder("chromat_dir", "directory of chromatograms to be converted into phd " + "(it is assumed the read data for these chromatograms are in a fasta file which the .cas file knows about").build()); options.addOption(new CommandLineOptionBuilder("s", "cache size ( default " + DEFAULT_CACHE_SIZE + " )").longName("cache_size").build()); options.addOption(new CommandLineOptionBuilder("useIllumina", "any FASTQ files in this assembly are encoded in Illumina 1.3+ format (default is Sanger)").isFlag(true).build()); options.addOption(new CommandLineOptionBuilder("useClosureTrimming", "apply additional contig trimming based on JCVI Closure rules").isFlag(true).build()); CommandLine commandLine; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int cacheSize = commandLine.hasOption("s") ? Integer.parseInt(commandLine.getOptionValue("s")) : DEFAULT_CACHE_SIZE; File casFile = new File(commandLine.getOptionValue("cas")); File casWorkingDirectory = casFile.getParentFile(); ReadWriteDirectoryFileServer outputDir = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; TrimDataStore trimDatastore; if (commandLine.hasOption("trim")) { List<TrimDataStore> dataStores = new ArrayList<TrimDataStore>(); final String trimFiles = commandLine.getOptionValue("trim"); for (String trimFile : trimFiles.split(",")) { System.out.println("adding trim file " + trimFile); dataStores.add(new DefaultTrimFileDataStore(new File(trimFile))); } trimDatastore = MultipleDataStoreWrapper.createMultipleDataStoreWrapper(TrimDataStore.class, dataStores); } else { trimDatastore = TrimDataStoreUtil.EMPTY_DATASTORE; } CasTrimMap trimToUntrimmedMap; if (commandLine.hasOption("trimMap")) { trimToUntrimmedMap = new DefaultTrimFileCasTrimMap(new File(commandLine.getOptionValue("trimMap"))); } else { trimToUntrimmedMap = new UnTrimmedExtensionTrimMap(); } boolean useClosureTrimming = commandLine.hasOption("useClosureTrimming"); TraceDataStore<FileSangerTrace> sangerTraceDataStore = null; Map<String, File> sangerFileMap = null; ReadOnlyDirectoryFileServer sourceChromatogramFileServer = null; if (commandLine.hasOption("chromat_dir")) { sourceChromatogramFileServer = DirectoryFileServer.createReadOnlyDirectoryFileServer(new File(commandLine.getOptionValue("chromat_dir"))); sangerTraceDataStore = new SingleSangerTraceDirectoryFileDataStore(sourceChromatogramFileServer, ".scf"); sangerFileMap = new HashMap<String, File>(); Iterator<String> iter = sangerTraceDataStore.getIds(); while (iter.hasNext()) { String id = iter.next(); sangerFileMap.put(id, sangerTraceDataStore.get(id).getFile()); } } PrintWriter logOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".log")), true); PrintWriter consensusOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".consensus.fasta")), true); PrintWriter traceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".traceFiles.txt")), true); PrintWriter referenceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".referenceFiles.txt")), true); long startTime = System.currentTimeMillis(); logOut.println(System.getProperty("user.dir")); final ReadWriteDirectoryFileServer tempDir; if (!commandLine.hasOption("tempDir")) { tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(DEFAULT_TEMP_DIR); } else { File t = new File(commandLine.getOptionValue("tempDir")); IOUtil.mkdirs(t); tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(t); } try { if (!outputDir.contains("chromat_dir")) { outputDir.createNewDir("chromat_dir"); } if (sourceChromatogramFileServer != null) { for (File f : sourceChromatogramFileServer) { String name = f.getName(); OutputStream out = new FileOutputStream(outputDir.createNewFile("chromat_dir/" + name)); final FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fileInputStream); } } } FastQQualityCodec qualityCodec = commandLine.hasOption("useIllumina") ? FastQQualityCodec.ILLUMINA : FastQQualityCodec.SANGER; CasDataStoreFactory casDataStoreFactory = new MultiCasDataStoreFactory(new H2SffCasDataStoreFactory(casWorkingDirectory, tempDir, EmptyDataStoreFilter.INSTANCE), new H2FastQCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, qualityCodec, tempDir.getRootDir()), new FastaCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, cacheSize)); final SliceMapFactory sliceMapFactory = new LargeNoQualitySliceMapFactory(); CasAssembly casAssembly = new DefaultCasAssembly.Builder(casFile, casDataStoreFactory, trimDatastore, trimToUntrimmedMap, casWorkingDirectory).build(); System.out.println("finished making casAssemblies"); for (File traceFile : casAssembly.getNuceotideFiles()) { traceFilesOut.println(traceFile.getAbsolutePath()); final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!outputDir.contains("solexa_dir")) { outputDir.createNewDir("solexa_dir"); } if (outputDir.contains("solexa_dir/" + name)) { IOUtil.delete(outputDir.getFile("solexa_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!outputDir.contains("sff_dir")) { outputDir.createNewDir("sff_dir"); } if (outputDir.contains("sff_dir/" + name)) { IOUtil.delete(outputDir.getFile("sff_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } for (File traceFile : casAssembly.getReferenceFiles()) { referenceFilesOut.println(traceFile.getAbsolutePath()); } DataStore<CasContig> contigDatastore = casAssembly.getContigDataStore(); Map<String, AceContig> aceContigs = new HashMap<String, AceContig>(); CasIdLookup readIdLookup = sangerFileMap == null ? casAssembly.getReadIdLookup() : new DifferentFileCasIdLookupAdapter(casAssembly.getReadIdLookup(), sangerFileMap); Date phdDate = new Date(startTime); NextGenClosureAceContigTrimmer closureContigTrimmer = null; if (useClosureTrimming) { closureContigTrimmer = new NextGenClosureAceContigTrimmer(2, 5, 10); } for (CasContig casContig : contigDatastore) { final AceContigAdapter adpatedCasContig = new AceContigAdapter(casContig, phdDate, readIdLookup); CoverageMap<CoverageRegion<AcePlacedRead>> coverageMap = DefaultCoverageMap.buildCoverageMap(adpatedCasContig); for (AceContig aceContig : ConsedUtil.split0xContig(adpatedCasContig, coverageMap)) { if (useClosureTrimming) { AceContig trimmedAceContig = closureContigTrimmer.trimContig(aceContig); if (trimmedAceContig == null) { System.out.printf("%s was completely trimmed... skipping%n", aceContig.getId()); continue; } aceContig = trimmedAceContig; } aceContigs.put(aceContig.getId(), aceContig); consensusOut.print(new DefaultNucleotideEncodedSequenceFastaRecord(aceContig.getId(), NucleotideGlyph.convertToString(NucleotideGlyph.convertToUngapped(aceContig.getConsensus().decode())))); } } System.out.printf("finished adapting %d casAssemblies into %d ace contigs%n", contigDatastore.size(), aceContigs.size()); QualityDataStore qualityDataStore = sangerTraceDataStore == null ? casAssembly.getQualityDataStore() : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(QualityDataStore.class, TraceQualityDataStoreAdapter.adapt(sangerTraceDataStore), casAssembly.getQualityDataStore()); final DateTime phdDateTime = new DateTime(phdDate); final PhdDataStore casPhdDataStore = CachedDataStore.createCachedDataStore(PhdDataStore.class, new ArtificalPhdDataStore(casAssembly.getNucleotideDataStore(), qualityDataStore, phdDateTime), cacheSize); final PhdDataStore phdDataStore = sangerTraceDataStore == null ? casPhdDataStore : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(PhdDataStore.class, new PhdSangerTraceDataStoreAdapter<FileSangerTrace>(sangerTraceDataStore, phdDateTime), casPhdDataStore); WholeAssemblyAceTag pathToPhd = new DefaultWholeAssemblyAceTag("phdball", "cas2consed", new Date(DateTimeUtils.currentTimeMillis()), "../phd_dir/" + prefix + ".phd.ball"); AceAssembly aceAssembly = new DefaultAceAssembly<AceContig>(new SimpleDataStore<AceContig>(aceContigs), phdDataStore, Collections.<File>emptyList(), new DefaultAceTagMap(Collections.<ConsensusAceTag>emptyList(), Collections.<ReadAceTag>emptyList(), Arrays.asList(pathToPhd))); System.out.println("writing consed package..."); ConsedWriter.writeConsedPackage(aceAssembly, sliceMapFactory, outputDir.getRootDir(), prefix, false); } catch (Throwable t) { t.printStackTrace(logOut); throw t; } finally { long endTime = System.currentTimeMillis(); logOut.printf("took %s%n", new Period(endTime - startTime)); logOut.flush(); logOut.close(); outputDir.close(); consensusOut.close(); traceFilesOut.close(); referenceFilesOut.close(); trimDatastore.close(); } } catch (ParseException e) { printHelp(options); System.exit(1); } }
Code Sample 2:
private void collectImageFile(@NotNull final Progress progress, @NotNull final File collectedDirectory) throws IOException { final File file = new File(collectedDirectory, ActionBuilderUtils.getString(ACTION_BUILDER, "configSource.image.name")); final FileOutputStream fos = new FileOutputStream(file); try { final FileChannel outChannel = fos.getChannel(); try { final int numOfFaceObjects = faceObjects.size(); progress.setLabel(ActionBuilderUtils.getString(ACTION_BUILDER, "archCollectImages"), numOfFaceObjects); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); final Charset charset = Charset.forName("ISO-8859-1"); int i = 0; for (final FaceObject faceObject : faceObjects) { final String face = faceObject.getFaceName(); final String path = archFaceProvider.getFilename(face); try { final FileInputStream fin = new FileInputStream(path); try { final FileChannel inChannel = fin.getChannel(); final long imageSize = inChannel.size(); byteBuffer.clear(); byteBuffer.put(("IMAGE " + (faceObjects.isIncludeFaceNumbers() ? i + " " : "") + imageSize + " " + face + "\n").getBytes(charset)); byteBuffer.flip(); outChannel.write(byteBuffer); inChannel.transferTo(0L, imageSize, outChannel); } finally { fin.close(); } } catch (final FileNotFoundException ignored) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorFileNotFound", path); return; } catch (final IOException e) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorIOException", path, e); return; } if (i++ % 100 == 0) { progress.setValue(i); } } progress.setValue(faceObjects.size()); } finally { outChannel.close(); } } finally { fos.close(); } } |
11
| Code Sample 1:
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); }
Code Sample 2:
public PollSetMessage(String username, String question, String title, String[] choices) { this.username = username; MessageDigest m = null; try { m = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } String id = username + String.valueOf(System.nanoTime()); m.update(id.getBytes(), 0, id.length()); voteId = new BigInteger(1, m.digest()).toString(16); this.question = question; this.title = title; this.choices = choices; } |
00
| Code Sample 1:
public String getResponse(URL url) throws OAuthException { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } catch (IOException e) { throw new OAuthException("Error getting HTTP response", e); } }
Code Sample 2:
public DataSet(String name, String type, URL docBase, String plotDir) { sitename = name.toUpperCase(); data = new Vector[3]; data[0] = new Vector(); data[1] = new Vector(); data[2] = new Vector(); if (type == null) return; plottype = type.toLowerCase(); String filename; filename = plotDir + sitename + "_" + plottype + ".plt.gz"; try { double total = 0; URL dataurl = new URL(docBase, filename); BufferedReader readme = new BufferedReader(new InputStreamReader(new GZIPInputStream(dataurl.openStream()))); while (true) { String myline = readme.readLine(); if (myline == null) break; myline = myline.toLowerCase(); if (myline.startsWith("fit:")) { if (haveFit) { continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); fit = new Double[5]; String bye = (String) st.nextToken(); fit[0] = new Double((String) st.nextToken()); fit[1] = new Double((String) st.nextToken()); fit[2] = new Double((String) st.nextToken()); fit[3] = new Double((String) st.nextToken()); fit[4] = new Double((String) st.nextToken()); haveFit = true; continue; } if (myline.startsWith("decyear:")) { StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); String bye = (String) st.nextToken(); decYear = new Double((String) st.nextToken()); haveDate = true; continue; } StringTokenizer st = new StringTokenizer(myline.replace('\n', ' ')); boolean ok = true; String tmp; Double[] mydbl = new Double[3]; for (int i = 0; i < 3 && ok; i++) { if (st.hasMoreTokens()) { tmp = (String) st.nextToken(); if (tmp.startsWith("X") || tmp.startsWith("x")) { ok = false; break; } else { mydbl[i] = new Double(tmp); } } else { mydbl[i] = new Double(0.0); } } if (ok) { if (mydbl[2].doubleValue() > 100) continue; total = mydbl[1].doubleValue() + total; for (int i = 0; i < 3; i++) { data[i].addElement(mydbl[i]); } } } average = total / length(); } catch (FileNotFoundException e) { System.err.println("PlotApplet: file not found: " + e); } catch (IOException e) { System.err.println("PlotApplet: error reading input file: " + e); } } |
11
| Code Sample 1:
public FileBean create(MimeTypeBean mimeType, SanBean san) throws SQLException { long fileId = 0; DataSource ds = getDataSource(DEFAULT_DATASOURCE); Connection conn = ds.getConnection(); try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); stmt.execute(NEXT_FILE_ID); ResultSet rs = stmt.getResultSet(); while (rs.next()) { fileId = rs.getLong(NEXTVAL); } PreparedStatement pstmt = conn.prepareStatement(INSERT_FILE); pstmt.setLong(1, fileId); pstmt.setLong(2, mimeType.getId()); pstmt.setLong(3, san.getId()); pstmt.setLong(4, WORKFLOW_ATTENTE_VALIDATION); int nbrow = pstmt.executeUpdate(); if (nbrow == 0) { throw new SQLException(); } conn.commit(); closeRessources(conn, pstmt); } catch (SQLException e) { log.error("Can't FileDAOImpl.create " + e.getMessage()); conn.rollback(); throw e; } FileBean fileBean = new FileBean(); return fileBean; }
Code Sample 2:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CURRENCY")); pst.setInt(1, curr.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; } |
00
| Code Sample 1:
@Override public HostRecord addressForHost(String domainName) throws Exception { String fullUrl = requestUrlStub + domainName; URL url = new URL(fullUrl); HttpURLConnection connection = null; connection = null; connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setReadTimeout(10000); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; HostRecord result = new HostRecord(domainName); byte parts[] = new byte[4]; while ((inputLine = in.readLine()) != null) { String pat1 = "<span class='orange'>"; String pat2 = "</span>"; int index1 = inputLine.indexOf(pat1); int index2 = inputLine.indexOf(pat2); if ((index1 > 0) && (index2 > 0)) { String ipStr = inputLine.substring(index1 + pat1.length(), index2); String[] s = ipStr.split("\\."); for (int i = 0; i < s.length; i++) parts[i] = (byte) Integer.parseInt(s[i]); } } IPAddress ipAddress = new IPAddress(parts); result.addIpAddress(ipAddress); in.close(); return result; }
Code Sample 2:
protected void writeToResponse(InputStream stream, HttpServletResponse response) throws IOException { OutputStream output = response.getOutputStream(); try { IOUtils.copy(stream, output); } finally { try { stream.close(); } finally { output.close(); } } } |
11
| Code Sample 1:
public static void fileCopy(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(sourceFile); fos = new FileOutputStream(destFile); source = fis.getChannel(); destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); } finally { fis.close(); fos.close(); if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } |
11
| Code Sample 1:
public static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) { Parser p = new Parser(); javax.xml.parsers.DocumentBuilder db; try { db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("", e); throw new RuntimeException(); } Document document = db.newDocument(); InputStream is = htmlInputStream; if (log.isDebugEnabled()) { ByteArrayOutputStream baos; baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException e) { log.error("Fail to make input stream copy.", e); } IOUtils.closeQuietly(is); ByteArrayInputStream byteArrayInputStream; byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray()); try { IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8"); } catch (IOException e) { log.error("", e); } IOUtils.closeQuietly(byteArrayInputStream); is = new ByteArrayInputStream(baos.toByteArray()); } try { InputSource iSource = new InputSource(is); iSource.setEncoding(encoding); Source transformerSource = new SAXSource(p, iSource); Result result = new DOMResult(document); Transformer xslTransformer = getTransformerByName(classpathXsltResource, false); try { xslTransformer.transform(transformerSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (Exception e) { log.warn("", e); } } return document; }
Code Sample 2:
public void copy(String original, String copy) throws SQLException { try { OutputStream out = openFileOutputStream(copy, false); InputStream in = openFileInputStream(original); IOUtils.copyAndClose(in, out); } catch (IOException e) { throw Message.convertIOException(e, "Can not copy " + original + " to " + copy); } } |
11
| Code Sample 1:
public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo"); temporaryFile.deleteOnExit(); FileInputStream inputStream = new FileInputStream(file); ZipInputStream input = new ZipInputStream(inputStream); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); ZipEntry entry = input.getNextEntry(); while (entry != null) { ZipEntry zipEntry = new ZipEntry(entry); zipEntry.setCompressedSize(-1); output.putNextEntry(zipEntry); if (!entry.getName().equals(entryName)) { IOUtils.copy(input, output); } else { IOUtils.copy(stream, output); } input.closeEntry(); output.closeEntry(); entry = input.getNextEntry(); } input.close(); inputStream.close(); output.close(); System.gc(); boolean isSuccess = file.delete(); if (!isSuccess) { throw new PersistenceException(); } isSuccess = temporaryFile.renameTo(file); if (!isSuccess) { throw new PersistenceException(); } } catch (IOException e) { throw new PersistenceException(e); } }
Code Sample 2:
public static File copyFile(File file) { File src = file; File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } |
11
| Code Sample 1:
private void copy(File source, File destination) throws PackageException { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(destination); byte[] buff = new byte[1024]; int len; while ((len = in.read(buff)) > 0) out.write(buff, 0, len); in.close(); out.close(); } catch (IOException e) { throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString()); } }
Code Sample 2:
public void gzipCompress(String file) { try { File inputFile = new File(file); FileInputStream fileinput = new FileInputStream(inputFile); File outputFile = new File(file.substring(0, file.length() - 1) + "z"); FileOutputStream stream = new FileOutputStream(outputFile); GZIPOutputStream gzipstream = new GZIPOutputStream(stream); BufferedInputStream bis = new BufferedInputStream(fileinput); int bytes_read = 0; byte[] buf = new byte[READ_BUFFER_SIZE]; while ((bytes_read = bis.read(buf, 0, BLOCK_SIZE)) != -1) { gzipstream.write(buf, 0, bytes_read); } bis.close(); inputFile.delete(); gzipstream.finish(); gzipstream.close(); } catch (FileNotFoundException fnfe) { System.out.println("Compressor: Cannot find file " + fnfe.getMessage()); } catch (SecurityException se) { System.out.println("Problem saving file " + se.getMessage()); } catch (IOException ioe) { System.out.println("Problem saving file " + ioe.getMessage()); } } |
00
| Code Sample 1:
public GridDirectoryList(URL url) throws McIDASException { try { urlc = (AddeURLConnection) url.openConnection(); inputStream = new DataInputStream(new BufferedInputStream(urlc.getInputStream())); } catch (IOException e) { throw new McIDASException("Error opening URL for grids:" + e); } readDirectory(); }
Code Sample 2:
private static String getData(String myurl) throws Exception { URL url = new URL(myurl); uc = (HttpURLConnection) url.openConnection(); if (login) { uc.setRequestProperty("Cookie", logincookie + ";" + xfsscookie); } br = new BufferedReader(new InputStreamReader(uc.getInputStream())); String temp = "", k = ""; while ((temp = br.readLine()) != null) { k += temp; } br.close(); return k; } |
00
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public synchronized DASMetaData fillInDASMetaData(URL url) throws DASException { try { con = (HttpURLConnection) url.openConnection(); dasRespVersion = con.getHeaderField("X-DAS-Version"); dasSchema = con.getHeaderField("X-DAS-SchemaName"); dasSchemaVersion = con.getHeaderField("X-DAS-SchemaVersion"); String dasStatusString = con.getHeaderField("X-DAS-Status"); if (dasStatusString == null) { throw new DASException("Temporary DAS Error"); } if (dasStatusString.indexOf(" ") != -1) { dasStatusString = dasStatusString.substring(0, dasStatusString.indexOf(" ")); } dasStatus = Integer.parseInt(dasStatusString); if (dasStatus != 200) { throw new DASException("Command cannot be executed: Error was " + Integer.toString(dasStatus)); } } catch (IOException e) { throw new DASException("Cannot connect to data source"); } if (dasSchema != null && dasSchemaVersion != null) { headers.put("X-DAS-Version", dasRespVersion); headers.put("X-DAS-SchemaName", dasSchema); headers.put("X-DAS-SchemaVersion", dasSchemaVersion); dasVersion = Float.parseFloat(dasRespVersion.substring(dasRespVersion.indexOf("/") + 1, dasRespVersion.length())); theMetaData = new DASMetaDataImpl(dasVersion, Float.parseFloat(dasSchemaVersion), dasSchema); } else { dasVersion = Float.parseFloat(dasRespVersion.substring(dasRespVersion.indexOf("/") + 1, dasRespVersion.length())); headers.put("X-DAS-Version", dasRespVersion); theMetaData = new DASMetaDataImpl(dasVersion); } String lengthStr = con.getHeaderField("content-length"); if (lengthStr != null) headers.put("content-length", lengthStr); theMetaData.setDASHeaders(headers); return theMetaData; } |
11
| Code Sample 1:
public static int zipFile(File file_input, File dir_output) { File zip_output = new File(dir_output, file_input.getName() + ".zip"); ZipOutputStream zip_out_stream; try { FileOutputStream out = new FileOutputStream(zip_output); zip_out_stream = new ZipOutputStream(new BufferedOutputStream(out)); } catch (IOException e) { return STATUS_OUT_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { ZipEntry zip_entry = new ZipEntry(file_input.getName()); zip_out_stream.putNextEntry(zip_entry); FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE); while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) zip_out_stream.write(input_buffer, 0, len); in.close(); } catch (IOException e) { return STATUS_ZIP_FAIL; } try { zip_out_stream.close(); } catch (IOException e) { } return STATUS_OK; }
Code Sample 2:
private void copyResourceToDir(String ondexDir, String resource) { InputStream inputStream = OndexGraphImpl.class.getClassLoader().getResourceAsStream(resource); try { FileWriter fileWriter = new FileWriter(new File(ondexDir, resource)); IOUtils.copy(inputStream, fileWriter); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { logger.error("Unable to copy '" + resource + "' file to " + ondexDir + "'"); } } |
00
| Code Sample 1:
public static JSGFRuleGrammar newGrammarFromJSGF(URL url, JSGFRuleGrammarFactory factory) throws JSGFGrammarParseException, IOException { Reader reader; BufferedInputStream stream = new BufferedInputStream(url.openStream(), 256); JSGFEncoding encoding = getJSGFEncoding(stream); if ((encoding != null) && (encoding.encoding != null)) { System.out.println("Grammar Character Encoding \"" + encoding.encoding + "\""); reader = new InputStreamReader(stream, encoding.encoding); } else { if (encoding == null) System.out.println("WARNING: Grammar missing self identifying header"); reader = new InputStreamReader(stream); } return newGrammarFromJSGF(reader, factory); }
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:
@Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } return status > 199 && status < 400; }
Code Sample 2:
private int renumberOrderBy(long tableID) throws SnapInException { int count = 0; Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = getDataSource().getConnection(); con.setAutoCommit(false); stmt = con.createStatement(); StringBuffer query = new StringBuffer(); query.append("SELECT ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID).append(" FROM ").append(DatabaseConstants.TableName_JV_FIELDBEHAVIOR).append(" WHERE ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_TABLEID).append(" = ").append(tableID).append(" ORDER BY ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ORDERBY); Vector rowIDVector = new Vector(); rs = stmt.executeQuery(query.toString()); while (rs.next()) { count++; rowIDVector.add(rs.getLong(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID) + ""); } StringBuffer updateString = new StringBuffer(); updateString.append("UPDATE ").append(DatabaseConstants.TableName_JV_FIELDBEHAVIOR).append(" SET ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ORDERBY).append(" = ? WHERE ").append(DatabaseConstants.TableFieldName_JV_FIELDBEHAVIOR_ID).append(" = ?"); PreparedStatement pstmt = con.prepareStatement(updateString.toString()); int orderByValue = ORDERBY_BY_DELTA_VALUE; Enumeration en = rowIDVector.elements(); while (en.hasMoreElements()) { pstmt.setInt(1, orderByValue); pstmt.setString(2, en.nextElement().toString()); orderByValue += ORDERBY_BY_DELTA_VALUE; pstmt.executeUpdate(); } con.setAutoCommit(true); if (pstmt != null) { pstmt.close(); } } catch (java.sql.SQLException e) { if (con == null) { logger.error("java.sql.SQLException", e); } else { try { logger.error("Transaction is being rolled back."); con.rollback(); con.setAutoCommit(true); } catch (java.sql.SQLException e2) { logger.error("java.sql.SQLException", e2); } } } catch (Exception e) { logger.error("Error occured during RenumberOrderBy", e); } finally { getDataSourceHelper().releaseResources(con, stmt, rs); } return count; } |
11
| Code Sample 1:
private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(WebCastellumFilter.MODIFICATION_EXCLUDES_DEFAULT); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(WebCastellumFilter.RESPONSE_MODIFICATIONS_DEFAULT); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List tmpPatternsToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPatternsToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpPrefiltersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length); final List tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); }
Code Sample 2:
@Test public void testExactCopySize() throws IOException { final int size = Byte.SIZE + RANDOMIZER.nextInt(TEST_DATA.length - Long.SIZE); final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(size); final int cpySize = ExtraIOUtils.copy(in, out, size); assertEquals("Mismatched copy size", size, cpySize); final byte[] subArray = ArrayUtils.subarray(TEST_DATA, 0, size), outArray = out.toByteArray(); assertArrayEquals("Mismatched data", subArray, outArray); } |
00
| Code Sample 1:
public static void sendPostRequest() { String data = "text=Eschirichia coli"; try { URL url = new URL("http://taxonfinder.ubio.org/analyze?"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); StringBuffer answer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { answer.append(line); } writer.close(); reader.close(); System.out.println(answer.toString()); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
private static List<String> getContent(URL url) throws IOException { final HttpURLConnection http = (HttpURLConnection) url.openConnection(); try { http.connect(); final int code = http.getResponseCode(); if (code != 200) throw new IOException("IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]"); return getContent(http); } finally { http.disconnect(); } } |
11
| Code Sample 1:
public boolean saveVideoXMLOnWebserver(String text) { boolean error = false; FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.getWebserver().getUrl()); System.out.println("Connected to " + this.getWebserver().getUrl() + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); return false; } if (!ftp.login(this.getWebserver().getFtpBenutzer(), this.getWebserver().getFtpPasswort())) { System.err.println("FTP server: Login incorrect"); } String tmpSeminarID = this.getSeminarID(); if (tmpSeminarID == null) tmpSeminarID = "unbekannt"; try { ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); } catch (Exception e) { ftp.makeDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); ftp.changeWorkingDirectory(this.getWebserver().getDefaultPath() + "/" + tmpSeminarID + "/lectures/" + this.getId() + "/data"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ByteArrayInputStream videoIn = new ByteArrayInputStream(text.getBytes()); ftp.enterLocalPassiveMode(); ftp.storeFile("video.xml", videoIn); videoIn.close(); ftp.logout(); ftp.disconnect(); } catch (IOException e) { System.err.println("Job " + this.getId() + ": Datei video.xml konnte nicht auf Webserver kopiert werden."); error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return error; }
Code Sample 2:
public static void main(String[] args) { String email = "[email protected]"; String username = "josh8573"; String password = "josh8573"; String IDnumber = "3030"; double[] apogee = { 1000 }; double[] perigee = apogee; double[] inclination = { 58.0 }; int[] trp_solmax = { 0, 1, 2 }; double[] init_long_ascend = { 0 }; double[] init_displ_ascend = { 0 }; double[] displ_perigee_ascend = { 0 }; double[] orbit_sect = null; boolean[] gtrn_weather = { false, true }; boolean print_altitude = true; boolean print_inclination = false; boolean print_gtrn_weather = true; boolean print_ita = false; boolean print_ida = false; boolean print_dpa = false; ORBIT[] orbit_array; orbit_array = ORBIT.CreateOrbits(apogee, perigee, inclination, gtrn_weather, trp_solmax, init_long_ascend, init_displ_ascend, displ_perigee_ascend, orbit_sect, print_altitude, print_inclination, print_gtrn_weather, print_ita, print_ida, print_dpa); TRP[] trp_array = {}; GTRN[] gtrn_array = {}; if (orbit_array != null) { Vector trp_vector = new Vector(); for (int i = 0; i < orbit_array.length; i++) { TRP temp_t = orbit_array[i].getTRP(); if (temp_t != null) { trp_vector.add(temp_t); } } if (trp_vector.size() != 0) { TRP[] trp_to_convert = new TRP[trp_vector.size()]; trp_array = (TRP[]) trp_vector.toArray(trp_to_convert); } Vector gtrn_vector = new Vector(); for (int i = 0; i < orbit_array.length; i++) { GTRN temp_g = orbit_array[i].getGTRN(); if (temp_g != null) { gtrn_vector.add(temp_g); } } if (gtrn_vector.size() != 0) { GTRN[] gtrn_to_convert = new GTRN[gtrn_vector.size()]; gtrn_array = (GTRN[]) gtrn_vector.toArray(gtrn_to_convert); } } int[] flux_min_element = { 1 }; int[] flux_max_element = { 92 }; int[] weather_flux = { 00, 01, 11, 12, 13 }; boolean print_weather = true; boolean print_min_elem = false; boolean print_max_elem = false; ORBIT[] orbit_array_into_flux = orbit_array; FLUX[] flux_array; flux_array = FLUX.CreateFLUX_URF(flux_min_element, flux_max_element, weather_flux, orbit_array_into_flux, print_weather, print_min_elem, print_max_elem); FLUX[] flx_objects_into_trans = flux_array; int[] units = { 1 }; double[] thickness = { 100 }; boolean print_shielding = false; TRANS[] trans_array; trans_array = TRANS.CreateTRANS_URF(flx_objects_into_trans, units, thickness, print_shielding); URFInterface[] input_files_for_letspec = trans_array; int[] letspec_min_element = { 2 }; int[] letspec_max_element = { 0 }; double[] min_energy_value = { .1 }; boolean[] diff_spect = { false }; boolean print_min_energy = false; LETSPEC[] letspec_array; letspec_array = LETSPEC.CreateLETSPEC_URF(input_files_for_letspec, letspec_min_element, letspec_max_element, min_energy_value, diff_spect, print_min_energy); URFInterface[] input_files_for_pup = trans_array; double[] pup_params = { 20, 4, 0.5, .0153 }; PUP_Device[][] pup_device_array = { { new PUP_Device("sample", null, null, 50648448, 4, pup_params) } }; boolean print_bits_in_device_pup = false; boolean print_weibull_onset_pup = false; boolean print_weibull_width_pup = false; boolean print_weibull_exponent_pup = false; boolean print_weibull_cross_sect_pup = false; PUP[] pup_array; pup_array = PUP.CreatePUP_URF(input_files_for_pup, pup_device_array, print_bits_in_device_pup, print_weibull_onset_pup, print_weibull_width_pup, print_weibull_exponent_pup, print_weibull_cross_sect_pup); LETSPEC[] let_objects_into_hup = letspec_array; double[][] weib_params = { { 9.74, 30.25, 2.5, 22600 }, { 9.74, 30.25, 2.5, 2260 }, { 9.74, 30.25, 2.5, 226 }, { 9.74, 30.25, 2.5, 22.6 }, { 9.74, 30.25, 2.5, 2.26 }, { 9.74, 30.25, 2.5, .226 }, { 9.74, 30.25, 2.5, .0226 } }; HUP_Device[][] hup_device_array = new HUP_Device[7][1]; double z_depth = (float) 0.01; for (int i = 0; i < 7; i++) { hup_device_array[i][0] = new HUP_Device("sample", null, null, 0, 0, (Math.sqrt(weib_params[i][3]) / 100), 0, (int) Math.pow(10, i), 4, weib_params[i]); z_depth += .01; } boolean print_label = false; boolean print_commenta = false; boolean print_commentb = false; boolean print_RPP_x = false; boolean print_RPP_y = false; boolean print_RPP_z = false; boolean print_funnel_length = false; boolean print_bits_in_device_hup = true; boolean print_weibull_onset_hup = false; boolean print_weibull_width_hup = false; boolean print_weibull_exponent_hup = false; boolean print_weibull_cross_sect_hup = false; HUP[] hup_array; hup_array = HUP.CreateHUP_URF(let_objects_into_hup, hup_device_array, print_label, print_commenta, print_commentb, print_RPP_x, print_RPP_y, print_RPP_z, print_funnel_length, print_bits_in_device_hup, print_weibull_onset_hup, print_weibull_width_hup, print_weibull_exponent_hup, print_weibull_cross_sect_hup); System.out.println("Finished creating User Request Files"); int num_of_files = trp_array.length + gtrn_array.length + flux_array.length + trans_array.length + letspec_array.length + pup_array.length + hup_array.length; int index = 0; String[] files_to_upload = new String[num_of_files]; for (int a = 0; a < trp_array.length; a++) { files_to_upload[index] = trp_array[a].getThisFileName(); index++; } for (int a = 0; a < gtrn_array.length; a++) { files_to_upload[index] = gtrn_array[a].getThisFileName(); index++; } for (int a = 0; a < flux_array.length; a++) { files_to_upload[index] = flux_array[a].getThisFileName(); index++; } for (int a = 0; a < trans_array.length; a++) { files_to_upload[index] = trans_array[a].getThisFileName(); index++; } for (int a = 0; a < letspec_array.length; a++) { files_to_upload[index] = letspec_array[a].getThisFileName(); index++; } for (int a = 0; a < pup_array.length; a++) { files_to_upload[index] = pup_array[a].getThisFileName(); index++; } for (int a = 0; a < hup_array.length; a++) { files_to_upload[index] = hup_array[a].getThisFileName(); index++; } Logger log = Logger.getLogger(CreateAStudy.class); String host = "creme96.nrl.navy.mil"; String user = "anonymous"; String ftppass = email; Logger.setLevel(Level.ALL); FTPClient ftp = null; try { ftp = new FTPClient(); ftp.setRemoteHost(host); FTPMessageCollector listener = new FTPMessageCollector(); ftp.setMessageListener(listener); log.info("Connecting"); ftp.connect(); log.info("Logging in"); ftp.login(user, ftppass); log.debug("Setting up passive, ASCII transfers"); ftp.setConnectMode(FTPConnectMode.ACTIVE); ftp.setType(FTPTransferType.BINARY); log.info("Putting file"); for (int u = 0; u < files_to_upload.length; u++) { ftp.put(files_to_upload[u], files_to_upload[u]); } log.info("Quitting client"); ftp.quit(); log.debug("Listener log:"); log.info("Test complete"); } catch (Exception e) { log.error("Demo failed", e); e.printStackTrace(); } System.out.println("Finished FTPing User Request Files to common directory"); Upload_Files.upload(files_to_upload, username, password, IDnumber); System.out.println("Finished transfering User Request Files to your CREME96 personal directory"); RunRoutines.routines(files_to_upload, username, password, IDnumber); System.out.println("Finished running all of your uploaded routines"); } |
00
| Code Sample 1:
public static void main(String[] args) { paraProc(args); CanonicalGFF cgff = new CanonicalGFF(gffFilename); CanonicalGFF geneModel = new CanonicalGFF(modelFilename); CanonicalGFF transcriptGff = new CanonicalGFF(transcriptFilename); TreeMap ksTable1 = getKsTable(ksTable1Filename); TreeMap ksTable2 = getKsTable(ksTable2Filename); Map intronReadCntMap = new TreeMap(); Map intronSplicingPosMap = new TreeMap(); try { BufferedReader fr = new BufferedReader(new FileReader(inFilename)); while (fr.ready()) { String line = fr.readLine(); if (line.startsWith("#")) continue; String tokens[] = line.split("\t"); String chr = tokens[0]; int start = Integer.parseInt(tokens[1]); int stop = Integer.parseInt(tokens[2]); GenomeInterval intron = new GenomeInterval(chr, start, stop); int readCnt = Integer.parseInt(tokens[3]); intronReadCntMap.put(intron, readCnt); String splicingMapStr = tokens[4]; Map splicingMap = getSplicingMap(splicingMapStr); intronSplicingPosMap.put(intron, splicingMap); } fr.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } double[] hdCDF = getHdCdf(readLength, minimumOverlap); try { FileWriter fw = new FileWriter(outFilename); for (Iterator intronIterator = intronReadCntMap.keySet().iterator(); intronIterator.hasNext(); ) { GenomeInterval intron = (GenomeInterval) intronIterator.next(); int readCnt = ((Integer) intronReadCntMap.get(intron)).intValue(); TreeMap splicingMap = (TreeMap) intronSplicingPosMap.get(intron); Object ksInfoArray[] = distributionAccepter((TreeMap) splicingMap.clone(), readCnt, hdCDF, ksTable1, ksTable2); boolean ksAccepted = (Boolean) ksInfoArray[0]; double testK = (Double) ksInfoArray[1]; double standardK1 = (Double) ksInfoArray[2]; double standardK2 = (Double) ksInfoArray[3]; int positionCnt = splicingMap.size(); Object modelInfoArray[] = getModelAgreedSiteCnt(intron, cgff, geneModel, transcriptGff); int modelAgreedSiteCnt = (Integer) modelInfoArray[0]; int maxAgreedTransSiteCnt = (Integer) modelInfoArray[1]; boolean containedBySomeGene = (Boolean) modelInfoArray[2]; int numIntersectingGenes = (Integer) modelInfoArray[3]; int distance = intron.getStop() - intron.getStart(); fw.write(intron.getChr() + ":" + intron.getStart() + ".." + intron.getStop() + "\t" + distance + "\t" + readCnt + "\t" + splicingMap + "\t" + probabilityEvaluation(readLength, distance, readCnt, splicingMap, positionCnt) + "\t" + ksAccepted + "\t" + testK + "\t" + standardK1 + "\t" + standardK2 + "\t" + positionCnt + "\t" + modelAgreedSiteCnt + "\t" + maxAgreedTransSiteCnt + "\t" + containedBySomeGene + "\t" + numIntersectingGenes + "\n"); } fw.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } }
Code Sample 2:
void loadListFile(String listFileName, String majorType, String minorType, String languages, String annotationType) throws MalformedURLException, IOException { Lookup defaultLookup = new Lookup(listFileName, majorType, minorType, languages, annotationType); URL lurl = new URL(listsURL, listFileName); BufferedReader listReader = new BomStrippingInputStreamReader(lurl.openStream(), encoding); String line; int lines = 0; while (null != (line = listReader.readLine())) { GazetteerNode node = new GazetteerNode(line, unescapedSeparator, false); Lookup lookup = defaultLookup; Map<String, String> fm = node.getFeatureMap(); if (fm != null && fm.size() > 0) { lookup = new Lookup(listFileName, majorType, minorType, languages, annotationType); Set<String> keyset = fm.keySet(); if (keyset.size() <= 4) { Map<String, String> newfm = null; for (String key : keyset) { if (key.equals("majorType")) { String tmp = fm.get("majorType"); if (canonicalizeStrings) { tmp.intern(); } lookup.majorType = tmp; } else if (key.equals("minorType")) { String tmp = fm.get("minorType"); if (canonicalizeStrings) { tmp.intern(); } lookup.minorType = tmp; } else if (key.equals("languages")) { String tmp = fm.get("languages"); if (canonicalizeStrings) { tmp.intern(); } lookup.languages = tmp; } else if (key.equals("annotationType")) { String tmp = fm.get("annotationType"); if (canonicalizeStrings) { tmp.intern(); } lookup.annotationType = tmp; } else { if (newfm == null) { newfm = new HashMap<String, String>(); } String tmp = fm.get(key); if (canonicalizeStrings) { tmp.intern(); } newfm.put(key, tmp); } } if (newfm != null) { lookup.features = newfm; } } else { if (canonicalizeStrings) { for (String key : fm.keySet()) { String tmp = fm.get(key); tmp.intern(); fm.put(key, tmp); } } lookup.features = fm; } } addLookup(node.getEntry(), lookup); lines++; } logger.debug("Lines read: " + lines); } |
11
| Code Sample 1:
private void copyLocalFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } |
11
| Code Sample 1:
private void simulate() throws Exception { BufferedWriter out = null; out = new BufferedWriter(new FileWriter(outFile)); out.write("#Thread\tReputation\tAction\n"); out.flush(); System.out.println("Simulate..."); File file = new File(trsDemoSimulationfile); ObtainUserReputation obtainUserReputationRequest = new ObtainUserReputation(); ObtainUserReputationResponse obtainUserReputationResponse; RateUser rateUserRequest; RateUserResponse rateUserResponse; FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String call = br.readLine(); while (call != null) { rateUserRequest = generateRateUserRequest(call); try { rateUserResponse = trsPort.rateUser(rateUserRequest); System.out.println("----------------R A T I N G-------------------"); System.out.println("VBE: " + rateUserRequest.getVbeId()); System.out.println("VO: " + rateUserRequest.getVoId()); System.out.println("USER: " + rateUserRequest.getUserId()); System.out.println("SERVICE: " + rateUserRequest.getServiceId()); System.out.println("ACTION: " + rateUserRequest.getActionId()); System.out.println("OUTCOME: " + rateUserResponse.isOutcome()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the rateUser should be true: MESSAGE=" + rateUserResponse.getMessage(), true, rateUserResponse.isOutcome()); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(null); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(rateUserRequest.getVoId()); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } call = br.readLine(); } fis.close(); br.close(); out.flush(); out.close(); }
Code Sample 2:
private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); } |
00
| Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public String getHash(String key, boolean base64) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(key.getBytes()); if (base64) return new String(new Base64().encode(md.digest()), "UTF8"); else return new String(md.digest(), "UTF8"); } |
00
| Code Sample 1:
public JSONObject getTargetGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph tgt = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { tgt = manager.getTargetGraph(); if (tgt != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.ORANGES); factory.visit(tgt); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No target graph loaded."); } } catch (Exception e) { return JSONUtils.SimpleJSONError("Cannot load target graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
Code Sample 2:
@Override public void loadTest(StoryCardModel story) { String strUrl = story.getStoryCard().getAcceptanceTestUrl(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder loader; try { URL url = new URL(strUrl); loader = factory.newDocumentBuilder(); Document document; document = loader.parse(url.openStream()); this.numPass = Integer.parseInt(((Element) document.getElementsByTagName("num-pass").item(0)).getFirstChild().getNodeValue()); this.numFail = Integer.parseInt(((Element) document.getElementsByTagName("num-fail").item(0)).getFirstChild().getNodeValue()); this.numRuns = Integer.parseInt(((Element) document.getElementsByTagName("num-runs").item(0)).getFirstChild().getNodeValue()); this.numExceptions = Integer.parseInt(((Element) document.getElementsByTagName("num-exceptions").item(0)).getFirstChild().getNodeValue()); this.wikiText = ((Element) document.getElementsByTagName("wiki").item(0)).getFirstChild().getNodeValue(); } catch (Exception e) { util.Logger.singleton().error(e); } } |
11
| Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public StringBuffer render(RenderEngine c) { String logTime = null; if (c.getWorkerContext() != null) { logTime = c.getWorkerContext().getWorkerStart(); } if (c.isBreakState() || !c.canRender("u")) { return new StringBuffer(); } StringBuffer buffer = new StringBuffer(); varname = TagInspector.processElement(varname, c); action = TagInspector.processElement(action, c); filemode = TagInspector.processElement(filemode, c); xmlparse = TagInspector.processElement(xmlparse, c); encoding = TagInspector.processElement(encoding, c); decoding = TagInspector.processElement(decoding, c); filter = TagInspector.processElement(filter, c); sort = TagInspector.processElement(sort, c); useDocroot = TagInspector.processElement(useDocroot, c); useFilename = TagInspector.processElement(useFilename, c); useDest = TagInspector.processElement(useDest, c); xmlOutput = TagInspector.processElement(xmlOutput, c); renderOutput = TagInspector.processElement(renderOutput, c); callProc = TagInspector.processElement(callProc, c); vartype = TagInspector.processElement(vartype, c); if (sort == null || sort.equals("")) { sort = "asc"; } if (useFilename.equals("") && !action.equalsIgnoreCase("listing")) { return new StringBuffer(); } boolean isRooted = true; if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; } } if (isRooted && (useFilename.indexOf("/") == -1 || useFilename.startsWith("./"))) { if (c.getWorkerContext() != null && useFilename.startsWith("./")) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename.substring(2); Debug.inform("CWD path specified in filename, rewritten to '" + useFilename + "'"); } else if (c.getWorkerContext() != null && useFilename.indexOf("/") == -1) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename; Debug.inform("No path specified in filename, rewritten to '" + useFilename + "'"); } else { Debug.inform("No path specified in filename, no worker context, not rewriting filename."); } } StringBuffer filenameData = null; StringBuffer contentsData = null; StringBuffer fileDestData = null; contentsData = TagInspector.processBody(this, c); filenameData = new StringBuffer(useFilename); fileDestData = new StringBuffer(useDest); String currentDocroot = null; if (c.getWorkerContext() == null) { if (c.getRenderContext().getCurrentDocroot() == null) { currentDocroot = "."; } else { currentDocroot = c.getRenderContext().getCurrentDocroot(); } } else { currentDocroot = c.getWorkerContext().getDocRoot(); } if (!isRooted) { currentDocroot = ""; } if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; currentDocroot = ""; } } if (!currentDocroot.endsWith("/")) { if (!currentDocroot.equals("") && currentDocroot.length() > 0) { currentDocroot += "/"; } } if (filenameData != null) { filenameData = new StringBuffer(filenameData.toString().replaceAll("\\.\\.", "")); } if (fileDestData != null) { fileDestData = new StringBuffer(fileDestData.toString().replaceAll("\\.\\.", "")); } if (action.equalsIgnoreCase("read")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileInputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte data[] = null; boolean vfsLoaded = false; try { data = c.getVendContext().getFileAccess().getFile(c.getWorkerContext(), filenameData.toString().replaceAll("\\.\\.", ""), c.getClientContext().getMatchedHost(), c.getVendContext().getVend().getRenderExtension(c.getClientContext().getMatchedHost()), null); bos.write(data, 0, data.length); vfsLoaded = true; } catch (Exception e) { Debug.user(logTime, "Included file attempt with VFS of file '" + filenameData + "' failed: " + e); } if (data == null) { try { is = new FileInputStream(file); } catch (Exception e) { Debug.user(logTime, "Unable to render: Filename '" + currentDocroot + filenameData + "' does not exist."); return new StringBuffer(); } } if (xmlparse == null || xmlparse.equals("")) { if (data == null) { Debug.user(logTime, "Opening filename '" + currentDocroot + filenameData + "' for reading into buffer '" + varname + "'"); data = new byte[32768]; int totalBytesRead = 0; while (true) { int bytesRead; try { bytesRead = is.read(data); bos.write(data, 0, bytesRead); } catch (Exception e) { break; } if (bytesRead <= 0) { break; } totalBytesRead += bytesRead; } } byte docOutput[] = bos.toByteArray(); if (renderOutput != null && renderOutput.equalsIgnoreCase("ssp")) { String outputData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n" + new String(FileAccess.getDefault().processServerPageData(c.getWorkerContext(), docOutput)); docOutput = outputData.getBytes(); } Debug.user(logTime, "File read complete: " + docOutput.length + " byte(s)"); if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (encoding != null && encoding.equalsIgnoreCase("url")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.URLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.URLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("xml")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.XMLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.XMLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("base64")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Base64.encode(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Base64.encode(docOutput)); } } else if (encoding != null && (encoding.equalsIgnoreCase("javascript") || encoding.equalsIgnoreCase("js"))) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.JavascriptEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.JavascriptEncode(new String(docOutput))); } } else { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, new String(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(new String(docOutput)); } } } else { RenderEngine engine = new RenderEngine(null); DocumentEngine docEngine = null; try { if (vfsLoaded) { ByteArrayInputStream bais = new ByteArrayInputStream(data); docEngine = new DocumentEngine(bais); } else { docEngine = new DocumentEngine(is); } } catch (Exception e) { c.setExceptionState(true, "XML parse of data read from file failed: " + e.getMessage()); } engine.setDocumentEngine(docEngine); c.addNodeSet(varname, docEngine.rootTag.thisNode); } if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); } else if (action.equalsIgnoreCase("write")) { try { String rootDir = filenameData.toString(); if (rootDir.lastIndexOf("/") != -1 && rootDir.lastIndexOf("/") != 0) { rootDir = rootDir.substring(0, rootDir.lastIndexOf("/")); java.io.File mkdirFile = new java.io.File(currentDocroot + rootDir); if (!mkdirFile.mkdirs()) { Debug.inform("Unable to create directory '" + currentDocroot + rootDir + "'"); } else { Debug.inform("Created directory '" + currentDocroot + rootDir + "'"); } } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileOutputStream fos = null; if (file == null) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Cannot write to location specified"); return new StringBuffer(); } else if (file.isDirectory()) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Is a directory."); return new StringBuffer(); } if (filemode.equalsIgnoreCase("append")) { fos = new FileOutputStream(file, true); } else { fos = new FileOutputStream(file, false); } if (decoding != null && !decoding.equals("")) { if (decoding.equalsIgnoreCase("base64")) { try { byte contentsDecoded[] = Base64.decode(contentsData.toString().getBytes()); fos.write(contentsDecoded); } catch (Exception e) { c.setExceptionState(true, "Encoded data in <content> element does not contain valid Base64-" + "encoded data."); } } else { fos.write(contentsData.toString().getBytes()); } } else { fos.write(contentsData.toString().getBytes()); } try { fos.flush(); } catch (IOException e) { Debug.inform("Unable to flush output data: " + e.getMessage()); } fos.close(); Debug.user(logTime, "Wrote contents to filename '" + currentDocroot + filenameData + "' (length=" + contentsData.length() + ")"); } catch (IOException e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } catch (Exception e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } } else if (action.equalsIgnoreCase("listing")) { String filenameDataString = filenameData.toString(); if (filenameDataString.equals("")) { filenameDataString = c.getClientContext().getPostVariable("current_path"); } if (filenameDataString == null) { c.setExceptionState(true, "Filename cannot be blank when listing."); return new StringBuffer(); } while (filenameDataString.endsWith("/")) { filenameDataString = filenameDataString.substring(0, filenameDataString.length() - 1); } Vector fileList = new Vector(); java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String curDirname = filenameData.toString(); String parentDirectory = null; String[] dirEntries = curDirname.split("/"); int numSlashes = 0; for (int i = 0; i < curDirname.length(); i++) { if (curDirname.toString().charAt(i) == '/') { numSlashes++; } } parentDirectory = "/"; if (numSlashes > 1) { for (int i = 0; i < (dirEntries.length - 1); i++) { if (dirEntries[i] != null && !dirEntries[i].equals("")) { parentDirectory += dirEntries[i] + "/"; } } } if (parentDirectory.length() > 1 && parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_JAR) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); int depth = 0; for (int i = 0; i < filenameData.toString().length(); i++) { if (filenameData.toString().charAt(i) == '/') { depth++; } } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(list, new ZipSorterAscending()); } else { Arrays.sort(list, new ZipSorterDescending()); } for (int i = 0; i < list.length; i++) { ZipEntry zEntry = (ZipEntry) list[i]; String zipFile = filenameData.toString() + "/" + zEntry.getName(); String displayFilename = zipFile.replaceFirst(filenameData.toString(), ""); int curDepth = 0; if (zipFile.equalsIgnoreCase(".acl") || zipFile.equalsIgnoreCase("access.list") || zipFile.equalsIgnoreCase("application.inc") || zipFile.equalsIgnoreCase("global.inc") || zipFile.indexOf("/.proc") != -1 || zipFile.indexOf("/procedures") != -1) { continue; } for (int x = 0; x < displayFilename.length(); x++) { if (displayFilename.charAt(x) == '/') { curDepth++; } } if (zipFile.startsWith(filenameData.toString())) { String fileLength = "" + zEntry.getSize(); String fileType = "file"; if (curDepth == depth) { if (zEntry.isDirectory()) { fileType = "directory"; } else { fileType = "file"; } String fileMode = "read-only"; String fileTime = Long.toString(zEntry.getTime()); buffer.append(" <file name=\""); buffer.append(displayFilename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(time)", false, fileTime); } } else { if (curDepth == depth) { fileList.add(zipFile); } } } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_FS) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); java.io.File[] filesorted = new java.io.File[list.length]; for (int i = 0; i < list.length; i++) { filesorted[i] = (java.io.File) list[i]; } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(filesorted, new FileSorterAscending()); } else { Arrays.sort(filesorted, new FileSorterDescending()); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < filesorted.length; i++) { java.io.File zEntry = filesorted[i]; String filename = filenameData.toString() + "/" + zEntry.getName(); if (filename.equalsIgnoreCase(".acl") || filename.equalsIgnoreCase("access.list") || filename.equalsIgnoreCase("application.inc") || filename.equalsIgnoreCase("global.inc") || filename.indexOf("/.proc") != -1 || filename.indexOf("/procedures") != -1) { continue; } String displayFilename = filename.replaceFirst(filenameData.toString(), ""); String fileLength = "" + zEntry.length(); String fileType = "file"; if (zEntry.isDirectory()) { fileType = "directory"; } else if (zEntry.isFile()) { fileType = "file"; } else if (zEntry.isHidden()) { fileType = "hidden"; } else if (zEntry.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (zEntry.canRead() && !zEntry.canWrite()) { fileMode = "read-only"; } else if (!zEntry.canRead() && zEntry.canWrite()) { fileMode = "write-only"; } else if (zEntry.canRead() && zEntry.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(zEntry.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(filename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(zEntry); } c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else { String[] fileStringList = null; if (!filter.equals("")) { fileStringList = file.list(new ListFilter(filter)); } else { fileStringList = file.list(); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(fileStringList, new StringSorterAscending()); } else { Arrays.sort(fileStringList, new StringSorterDescending()); } if (fileStringList == null) { buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); } else { c.getVariableContainer().setVector(varname, fileList); } return new StringBuffer(); } else { Debug.user(logTime, "Directory '" + currentDocroot + filenameData + "' returns " + fileStringList.length + " entry(ies)"); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < fileStringList.length; i++) { file = new java.io.File(currentDocroot + filenameData.toString() + "/" + fileStringList[i]); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } else if (file.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(fileStringList[i]); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(fileStringList[i]); } c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } } else if (action.equalsIgnoreCase("delete")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.isDirectory()) { boolean success = deleteDir(new java.io.File(currentDocroot + filenameData.toString())); if (!success) { c.setExceptionState(true, "Unable to delete '" + currentDocroot + filenameData + "'"); } } else { String filenamePattern = null; if (filenameData.toString().indexOf("/") != -1) { filenamePattern = filenameData.toString().substring(filenameData.toString().lastIndexOf("/") + 1); } String filenameDirectory = currentDocroot; if (filenameData.toString().indexOf("/") != -1) { filenameDirectory += filenameData.substring(0, filenameData.toString().lastIndexOf("/")); } String[] fileStringList = null; file = new java.io.File(filenameDirectory); fileStringList = file.list(new ListFilter(filenamePattern)); for (int i = 0; i < fileStringList.length; i++) { (new java.io.File(filenameDirectory + "/" + fileStringList[i])).delete(); } } } else if (action.equalsIgnoreCase("rename") || action.equalsIgnoreCase("move")) { if (fileDestData.equals("")) { c.getVariableContainer().setVariable(varname + "-result", filenameData + ": File operation failed: No destination filename given."); return new StringBuffer(); } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); boolean success = file.renameTo(new java.io.File(currentDocroot + fileDestData.toString(), file.getName())); if (!success) { c.setExceptionState(true, "Unable to rename '" + currentDocroot + filenameData + "' to '" + currentDocroot + fileDestData + "'"); } } else if (action.equalsIgnoreCase("copy")) { if (fileDestData.equals("")) { c.setExceptionState(true, "File copy operation failed for file '" + filenameData + "': No destination file specified."); return new StringBuffer(); } FileChannel srcChannel; FileChannel destChannel; String filename = null; filename = currentDocroot + filenameData.toString(); if (vartype != null && vartype.equalsIgnoreCase("file")) { if (useFilename.indexOf("/") != -1) { useFilename = useFilename.substring(useFilename.lastIndexOf("/") + 1); } filename = c.getVariableContainer().getFileVariable(useFilename); } try { Debug.debug("Copying from file '" + filename + "' to '" + fileDestData.toString() + "'"); srcChannel = new FileInputStream(filename).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' failed to read: " + e.getMessage()); return new StringBuffer(); } try { destChannel = new FileOutputStream(currentDocroot + fileDestData.toString()).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy to '" + fileDestData + "' failed to write: " + e.getMessage()); return new StringBuffer(); } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", filenameData + " copy to " + fileDestData + ": File copy succeeded."); } else { return new StringBuffer("true"); } } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' to '" + fileDestData + "' failed: " + e.getMessage()); } } else if (action.equalsIgnoreCase("exists")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.exists()) { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "true"); } else { return new StringBuffer("true"); } } else { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "false"); } else { return new StringBuffer("false"); } } } else if (action.equalsIgnoreCase("mkdir")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.mkdirs()) { if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", "created"); } else { return new StringBuffer("true"); } } else { c.setExceptionState(true, "Unable to create directory '" + filenameData + "'"); } } else if (action.equalsIgnoreCase("info")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isAbsolute()) { fileType = "absolute"; } else if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (varname != null && !varname.equals("")) { c.getVariableContainer().setVariable(varname + ".length", fileLength); c.getVariableContainer().setVariable(varname + ".type", fileType); c.getVariableContainer().setVariable(varname + ".mode", fileMode); c.getVariableContainer().setVariable(varname + ".modtime", fileTime); } else { buffer = new StringBuffer(); buffer.append("<file name=\""); buffer.append(filenameData); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); return buffer; } } if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); } |
11
| Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
private static void copyFile(File sourceFile, File destFile) { try { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } catch (Exception e) { throw new RuntimeException(e); } } |
00
| Code Sample 1:
private void openConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(Global.getProxy()); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml; charset=" + XmlRpcMessages.getString("XmlRpcClient.Encoding")); if (requestProperties != null) { for (Iterator propertyNames = requestProperties.keySet().iterator(); propertyNames.hasNext(); ) { String propertyName = (String) propertyNames.next(); connection.setRequestProperty(propertyName, (String) requestProperties.get(propertyName)); } } }
Code Sample 2:
public void testWriteThreadsNoCompression() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.loadProfiles(CommandLineProcessorFactory.PROFILE.DB, CommandLineProcessorFactory.PROFILE.REST_CLIENT, CommandLineProcessorFactory.PROFILE.COLLECTOR); final LocalLogFileWriter writer = (LocalLogFileWriter) bootstrap.getBean(LogFileWriter.class); writer.init(); writer.setCompressionCodec(null); File fileInput = new File(baseDir, "testWriteOneFile/input"); fileInput.mkdirs(); File fileOutput = new File(baseDir, "testWriteOneFile/output"); fileOutput.mkdirs(); writer.setBaseDir(fileOutput); int fileCount = 100; int lineCount = 100; File[] inputFiles = createInput(fileInput, fileCount, lineCount); ExecutorService exec = Executors.newFixedThreadPool(fileCount); final CountDownLatch latch = new CountDownLatch(fileCount); for (int i = 0; i < fileCount; i++) { final File file = inputFiles[i]; final int count = i; exec.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { FileStatus.FileTrackingStatus status = FileStatus.FileTrackingStatus.newBuilder().setFileDate(System.currentTimeMillis()).setDate(System.currentTimeMillis()).setAgentName("agent1").setFileName(file.getName()).setFileSize(file.length()).setLogType("type1").build(); BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = reader.readLine()) != null) { writer.write(status, new ByteArrayInputStream((line + "\n").getBytes())); } } finally { IOUtils.closeQuietly(reader); } LOG.info("Thread[" + count + "] completed "); latch.countDown(); return true; } }); } latch.await(); exec.shutdown(); LOG.info("Shutdown thread service"); writer.close(); File[] outputFiles = fileOutput.listFiles(); assertNotNull(outputFiles); File testCombinedInput = new File(baseDir, "combinedInfile.txt"); testCombinedInput.createNewFile(); FileOutputStream testCombinedInputOutStream = new FileOutputStream(testCombinedInput); try { for (File file : inputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedInputOutStream); } } finally { testCombinedInputOutStream.close(); } File testCombinedOutput = new File(baseDir, "combinedOutfile.txt"); testCombinedOutput.createNewFile(); FileOutputStream testCombinedOutOutStream = new FileOutputStream(testCombinedOutput); try { System.out.println("----------------- " + testCombinedOutput.getAbsolutePath()); for (File file : outputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedOutOutStream); } } finally { testCombinedOutOutStream.close(); } FileUtils.contentEquals(testCombinedInput, testCombinedOutput); } |
11
| Code Sample 1:
private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); }
Code Sample 2:
public void searchEntity(HttpServletRequest req, HttpServletResponse resp, SearchCommand command) { setHeader(resp); logger.debug("Search: Looking for the entity with the id:" + command.getSearchedid()); String login = command.getLogin(); String password = command.getPassword(); SynchronizableUser currentUser = userAccessControl.authenticate(login, password); if (currentUser != null) { try { File tempFile = File.createTempFile("medoo", "search"); OutputStream fos = new FileOutputStream(tempFile); syncServer.searchEntity(currentUser, command.getSearchedid(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); } catch (ImogSerializationException ex) { logger.error(ex.getMessage(), ex); } } else { try { OutputStream out = resp.getOutputStream(); out.write("-ERROR-".getBytes()); out.flush(); out.close(); logger.debug("Search: user " + login + " has not been authenticated"); } catch (IOException ioe) { ioe.printStackTrace(); } } } |
11
| Code Sample 1:
private static void copyFile(File in, File out) throws Exception { final FileInputStream input = new FileInputStream(in); try { final FileOutputStream output = new FileOutputStream(out); try { final byte[] buf = new byte[4096]; int readBytes = 0; while ((readBytes = input.read(buf)) != -1) { output.write(buf, 0, readBytes); } } finally { output.close(); } } finally { input.close(); } }
Code Sample 2:
@Override public String transformSingleFile(X3DEditorSupport.X3dEditor xed) { Node[] node = xed.getActivatedNodes(); X3DDataObject dob = (X3DDataObject) xed.getX3dEditorSupport().getDataObject(); FileObject mySrc = dob.getPrimaryFile(); File mySrcF = FileUtil.toFile(mySrc); File myOutF = new File(mySrcF.getParentFile(), mySrc.getName() + ".x3d.gz"); TransformListener co = TransformListener.getInstance(); co.message(NbBundle.getMessage(getClass(), "Gzip_compression_starting")); co.message(NbBundle.getMessage(getClass(), "Saving_as_") + myOutF.getAbsolutePath()); co.moveToFront(); co.setNode(node[0]); try { FileInputStream fis = new FileInputStream(mySrcF); GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(myOutF)); byte[] buf = new byte[4096]; int ret; while ((ret = fis.read(buf)) > 0) gzos.write(buf, 0, ret); gzos.close(); } catch (Exception ex) { co.message(NbBundle.getMessage(getClass(), "Exception:__") + ex.getLocalizedMessage()); return null; } co.message(NbBundle.getMessage(getClass(), "Gzip_compression_complete")); return myOutF.getAbsolutePath(); } |
00
| Code Sample 1:
public Element rootFromURL(URL url) throws org.jdom.JDOMException, java.io.IOException { Element e; try { InputStream stream = new BufferedInputStream(url.openConnection().getInputStream()); return getRootViaURI(verify, stream); } catch (org.jdom.input.JDOMParseException e4) { throw e4; } catch (org.jdom.JDOMException e1) { if (!openWarn1) reportError1(url.toString(), e1); openWarn1 = true; try { InputStream stream = new BufferedInputStream(url.openConnection().getInputStream()); e = getRootViaURL(verify, stream); log.info("getRootViaURL succeeded as 2nd try"); return e; } catch (org.jdom.JDOMException e2) { if (!openWarn2) reportError2(url.toString(), e2); openWarn2 = true; InputStream stream = new BufferedInputStream(url.openConnection().getInputStream()); e = getRootViaRelative(verify, stream); log.info("GetRootViaRelative succeeded as 3rd try"); new Exception().printStackTrace(); return e; } } }
Code Sample 2:
public void deleteGroup(String groupID) throws XregistryException { try { Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_GROUP_SQL_MAIN); statement1.setString(1, groupID); int updateCount = statement1.executeUpdate(); if (updateCount == 0) { throw new XregistryException("Database is not updated, Can not find such Group " + groupID); } if (cascadingDeletes) { PreparedStatement statement2 = connection.prepareStatement(DELETE_GROUP_SQL_DEPEND); statement2.setString(1, groupID); statement2.setString(2, groupID); statement2.executeUpdate(); } connection.commit(); groups.remove(groupID); log.info("Delete Group " + groupID + (cascadingDeletes ? " with cascading deletes " : "")); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } } |
11
| Code Sample 1:
private void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
Code Sample 2:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file: " + dest.getName()); } } byte[] buffer = new byte[bufSize]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dest); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } } |
11
| Code Sample 1:
@Override public List<String> getNamedEntitites(String sentence) { List<String> namedEntities = new ArrayList<String>(); try { URL url = new URL(SERVICE_URL + "text=" + URLEncoder.encode(sentence, "UTF-8") + "&confidence=" + CONFIDENCE + "&support=" + SUPPORT); URLConnection conn = url.openConnection(); conn.setRequestProperty("accept", "application/json"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); JSONObject json = new JSONObject(sb.toString()); if (!json.isNull("Resources")) { JSONArray array = json.getJSONArray("Resources"); JSONObject entityObject; for (int i = 0; i < array.length(); i++) { entityObject = array.getJSONObject(i); System.out.println("Entity: " + entityObject.getString("@surfaceForm")); System.out.println("DBpedia URI: " + entityObject.getString("@URI")); System.out.println("Types: " + entityObject.getString("@types")); namedEntities.add(entityObject.getString("@surfaceForm")); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return namedEntities; }
Code Sample 2:
public IntactOntology parseOboFile(URL url, boolean keepTemporaryFile) throws PsiLoaderException { if (url == null) { throw new IllegalArgumentException("Please give a non null URL."); } StringBuffer buffer = new StringBuffer(1024 * 8); try { System.out.println("Loading URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()), 1024); String line; int lineCount = 0; while ((line = in.readLine()) != null) { lineCount++; buffer.append(line).append(NEW_LINE); if ((lineCount % 20) == 0) { System.out.print("."); System.out.flush(); if ((lineCount % 500) == 0) { System.out.println(" " + lineCount); } } } in.close(); File tempDirectory = new File(System.getProperty("java.io.tmpdir", "tmp")); if (!tempDirectory.exists()) { if (!tempDirectory.mkdirs()) { throw new IOException("Cannot create temp directory: " + tempDirectory.getAbsolutePath()); } } System.out.println("Using temp directory: " + tempDirectory.getAbsolutePath()); File tempFile = File.createTempFile("psimi.v25.", ".obo", tempDirectory); tempFile.deleteOnExit(); tempFile.deleteOnExit(); System.out.println("The OBO file is temporary store as: " + tempFile.getAbsolutePath()); BufferedWriter out = new BufferedWriter(new FileWriter(tempFile), 1024); out.write(buffer.toString()); out.flush(); out.close(); return parseOboFile(tempFile); } catch (IOException e) { throw new PsiLoaderException("Error while loading URL (" + url + ")", e); } } |
00
| Code Sample 1:
public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel inputFileChannel = new FileInputStream(sourceFile).getChannel(); FileChannel outputFileChannel = new FileOutputStream(destFile).getChannel(); long offset = 0L; long length = inputFileChannel.size(); final long MAXTRANSFERBUFFERLENGTH = 1024 * 1024; try { for (; offset < length; ) { offset += inputFileChannel.transferTo(offset, MAXTRANSFERBUFFERLENGTH, outputFileChannel); inputFileChannel.position(offset); } } finally { try { outputFileChannel.close(); } catch (Exception ignore) { } try { inputFileChannel.close(); } catch (IOException ignore) { } } }
Code Sample 2:
public ISpieler[] sortiereSpielerRamsch(ISpieler[] spieler) { for (int i = 0; i < spieler.length; i++) { for (int j = 0; j < spieler.length - 1; j++) { if (werteAugen(spieler[j].getStiche()) > werteAugen(spieler[j + 1].getStiche())) { ISpieler a = spieler[j]; spieler[j] = spieler[j + 1]; spieler[j + 1] = a; } } } return spieler; } |
00
| Code Sample 1:
public static String getContents(String urlStr) throws Exception { String contents = ""; URL url = new URL(urlStr); URLConnection openConnection = url.openConnection(); final char[] buffer = new char[1024 * 1024]; StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(openConnection.getInputStream(), "UTF-8"); int read; do { read = in.read(buffer, 0, buffer.length); if (read > 0) { out.append(buffer, 0, read); } } while (read >= 0); contents = out.toString(); return contents; }
Code Sample 2:
public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); } |
00
| Code Sample 1:
private static GSP loadGSP(URL url) { try { InputStream input = url.openStream(); int c; while ((c = input.read()) != -1) { result = result + (char) c; } Unmarshaller unmarshaller = getUnmarshaller(); unmarshaller.setValidation(false); GSP gsp = (GSP) unmarshaller.unmarshal(new InputSource()); return gsp; } catch (Exception e) { System.out.println("loadGSP " + e); e.printStackTrace(); return null; } }
Code Sample 2:
private static String getServiceResponse(final String requestName, final Template template, final Map variables) { OutputStreamWriter outputWriter = null; try { final StringWriter writer = new StringWriter(); final VelocityContext context = new VelocityContext(variables); template.merge(context, writer); final String request = writer.toString(); final URLConnection urlConnection = new URL(SERVICE_URL).openConnection(); urlConnection.setUseCaches(false); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2b4) Gecko/20091124 Firefox/3.6b4"); urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); urlConnection.setRequestProperty("Accept-Language", "en-us,en;q=0.5"); urlConnection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); urlConnection.setRequestProperty("Keep-Alive", "115"); urlConnection.setRequestProperty("Connection", "keep-alive"); urlConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); urlConnection.setRequestProperty("Content-Length", "" + request.length()); urlConnection.setRequestProperty("SOAPAction", requestName); outputWriter = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"); outputWriter.write(request); outputWriter.flush(); final InputStream result = urlConnection.getInputStream(); return IOUtils.toString(result); } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (outputWriter != null) { try { outputWriter.close(); } catch (IOException logOrIgnore) { } } } } |
00
| Code Sample 1:
protected void extractArchive(File archive) { ZipInputStream zis = null; FileOutputStream fos; ZipEntry entry; File curEntry; int n; try { zis = new ZipInputStream(new FileInputStream(archive)); while ((entry = zis.getNextEntry()) != null) { curEntry = new File(workingDir, entry.getName()); if (entry.isDirectory()) { System.out.println("skip directory: " + entry.getName()); continue; } System.out.print("zip-entry (file): " + entry.getName()); System.out.println(" ==> real path: " + curEntry.getAbsolutePath()); if (!curEntry.getParentFile().exists()) curEntry.getParentFile().mkdirs(); fos = new FileOutputStream(curEntry); while ((n = zis.read(buf, 0, buf.length)) > -1) fos.write(buf, 0, n); fos.close(); zis.closeEntry(); } } catch (Throwable t) { t.printStackTrace(); } finally { try { if (zis != null) zis.close(); } catch (Throwable t) { } } }
Code Sample 2:
public static String genetateSHA256(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] passWd = md.digest(); String hex = toHex(passWd); return hex; } |
00
| Code Sample 1:
public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } }
Code Sample 2:
public static String post(String strUrl, String strPostString) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(strPostString); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += s; } in.close(); return sRet; } catch (MalformedURLException e) { System.out.println("Internal Error. Malformed URL."); e.printStackTrace(); } catch (IOException e) { System.out.println("Internal I/O Error."); e.printStackTrace(); } return ""; } |
11
| Code Sample 1:
public static long copy(File src, long amount, File dst) { final int BUFFER_SIZE = 1024; long amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { close(in); flush(out); close(out); } return amount - amountToRead; }
Code Sample 2:
private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { assertTrue(resourceName.startsWith("/")); final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } } |
00
| Code Sample 1:
public Configuration load(URL url) throws ConfigurationException { LOG.info("Configuring from url : " + url.toString()); try { return load(url.openStream(), url.toString()); } catch (IOException ioe) { throw new ConfigurationException("Could not configure from URL : " + url, ioe); } }
Code Sample 2:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); HttpClient client = new DefaultHttpClient(); HttpGet httpGetRequest = new HttpGet("http://www.google.com/"); String line = "", responseString = ""; try { HttpResponse response = client.execute(httpGetRequest); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while ((line = br.readLine()) != null) { responseString += line; } br.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } tv.setText(responseString); setContentView(tv); } |
00
| Code Sample 1:
private void recvMessage(String from, String to) throws Exception { ConnectionFactoryImpl factory = new ConnectionFactoryImpl(); Receiver receiver = null; ProviderConnection connection = factory.createConnection(from, to); Connection conn = DBUtil.getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sql = ""; try { receiver = Receiver.createReceiver(connection); receiver.open(); EXTSSPMessage message = (EXTSSPMessage) receiver.receiveEX(); if (message == null) { System.out.println("no message"); } else { conn.setAutoCommit(false); EXTSSPHeader header = message.getEXHeader(); UUIDHexGenerator u = new UUIDHexGenerator(); String id = u.generate().toString(); pstmt = conn.prepareStatement(drawOutRecvSql(header, id)); pstmt.executeUpdate(); String xml = ""; TSSPBody body = message.getBody(); xml = body.getDomAsString(); xml = xml.replaceAll("ns1:", ""); saveClobMessage(pstmt, conn, rs, xml, id); String notify_id = ""; Iterator iter = message.getAttachments(); while (iter.hasNext()) { AttachmentPart a = (AttachmentPart) iter.next(); String contentId = a.getContentId(); if (contentId.startsWith(Constant.PREFIX_PERSON)) { DataHandler dh = a.getDataHandler(); InputStream is = dh.getInputStream(); byte[] temp = FileCopyUtils.copyToByteArray(is); String content = new String(temp); RecvDto recv = (RecvDto) XStreamConvert.xmlToBean(content); if (recv == null) throw new Exception("接收方信息对象转换错误!请检查存入的信息对象xml字符串是否正确:" + content); if (notify_id.equals("")) { notify_id = u.generate().toString(); header.setType(Constant.MESSAGETYPE_NOTIFY); pstmt = conn.prepareStatement(drawOutRecvSql(header, notify_id)); pstmt.executeUpdate(); String notify_content = header.getNotifyContent(); if (notify_content == null) notify_content = "接收到新的esb消息,但未定义通知消息内容!"; saveClobMessage(pstmt, conn, rs, notify_content, notify_id); } savePersonInfo(pstmt, conn, recv, notify_id); } else { DataHandler dh = a.getDataHandler(); InputStream is = dh.getInputStream(); String attid = u.generate().toString(); sql = "insert into message_recv_attachment(ATTACHMENTID," + "VERSION,MRECVID,BUSS_ID,ATTACHMENT) values('" + attid + "',0,'" + id + "','" + contentId + "',empty_blob())"; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); sql = "select attachment from message_recv_attachment" + " where attachmentid = '" + attid + "' for update"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); rs.next(); Blob blob = rs.getBlob(1); OutputStream blobOutputStream = ((oracle.sql.BLOB) blob).getBinaryOutputStream(); FileCopyUtils.copy(is, blobOutputStream); is.close(); blobOutputStream.close(); } } conn.commit(); conn.setAutoCommit(true); } receiver.commit(); } catch (Exception e) { e.printStackTrace(); try { System.out.println("received message, rollback"); if (receiver != null) { receiver.rollback(); } } catch (JAXMException e1) { e1.printStackTrace(); } } finally { DBUtil.close(rs, pstmt, conn); if (receiver != null) { try { receiver.close(); } catch (JAXMException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (JAXMException e) { e.printStackTrace(); } } } }
Code Sample 2:
public static boolean writeFile(HttpServletResponse resp, File reqFile) { boolean retVal = false; InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(reqFile)); IOUtils.copy(in, resp.getOutputStream()); logger.debug("File successful written to servlet response: " + reqFile.getAbsolutePath()); } catch (FileNotFoundException e) { logger.error("Resource not found: " + reqFile.getAbsolutePath()); } catch (IOException e) { logger.error(String.format("Error while rendering [%s]: %s", reqFile.getAbsolutePath(), e.getMessage()), e); } finally { IOUtils.closeQuietly(in); } return retVal; } |
11
| Code Sample 1:
public XmldbURI createFile(String newName, InputStream is, Long length, String contentType) throws IOException, PermissionDeniedException, CollectionDoesNotExistException { if (LOG.isDebugEnabled()) LOG.debug("Create '" + newName + "' in '" + xmldbUri + "'"); XmldbURI newNameUri = XmldbURI.create(newName); MimeType mime = MimeTable.getInstance().getContentTypeFor(newName); if (mime == null) { mime = MimeType.BINARY_TYPE; } DBBroker broker = null; Collection collection = null; BufferedInputStream bis = new BufferedInputStream(is); VirtualTempFile vtf = new VirtualTempFile(); BufferedOutputStream bos = new BufferedOutputStream(vtf); IOUtils.copy(bis, bos); bis.close(); bos.close(); vtf.close(); if (mime.isXMLType() && vtf.length() == 0L) { if (LOG.isDebugEnabled()) LOG.debug("Creating dummy XML file for null resource lock '" + newNameUri + "'"); vtf = new VirtualTempFile(); IOUtils.write("<null_resource/>", vtf); vtf.close(); } TransactionManager transact = brokerPool.getTransactionManager(); Txn txn = transact.beginTransaction(); try { broker = brokerPool.get(subject); collection = broker.openCollection(xmldbUri, Lock.WRITE_LOCK); if (collection == null) { LOG.debug("Collection " + xmldbUri + " does not exist"); transact.abort(txn); throw new CollectionDoesNotExistException(xmldbUri + ""); } if (mime.isXMLType()) { if (LOG.isDebugEnabled()) LOG.debug("Inserting XML document '" + mime.getName() + "'"); VirtualTempFileInputSource vtfis = new VirtualTempFileInputSource(vtf); IndexInfo info = collection.validateXMLResource(txn, broker, newNameUri, vtfis); DocumentImpl doc = info.getDocument(); doc.getMetadata().setMimeType(mime.getName()); collection.store(txn, broker, info, vtfis, false); } else { if (LOG.isDebugEnabled()) LOG.debug("Inserting BINARY document '" + mime.getName() + "'"); InputStream fis = vtf.getByteStream(); bis = new BufferedInputStream(fis); DocumentImpl doc = collection.addBinaryResource(txn, broker, newNameUri, bis, mime.getName(), length.longValue()); bis.close(); } transact.commit(txn); if (LOG.isDebugEnabled()) LOG.debug("Document created sucessfully"); } catch (EXistException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (TriggerException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (SAXException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (LockException e) { LOG.error(e); transact.abort(txn); throw new PermissionDeniedException(xmldbUri + ""); } catch (IOException e) { LOG.error(e); transact.abort(txn); throw e; } catch (PermissionDeniedException e) { LOG.error(e); transact.abort(txn); throw e; } finally { if (vtf != null) { vtf.delete(); } if (collection != null) { collection.release(Lock.WRITE_LOCK); } brokerPool.release(broker); if (LOG.isDebugEnabled()) LOG.debug("Finished creation"); } XmldbURI newResource = xmldbUri.append(newName); return newResource; }
Code Sample 2:
public static void putNextJarEntry(JarOutputStream modelStream, String name, File file) throws IOException { JarEntry entry = new JarEntry(name); entry.setSize(file.length()); modelStream.putNextEntry(entry); InputStream fileStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(fileStream, modelStream); fileStream.close(); } |
11
| Code Sample 1:
public static byte[] computeMD5(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(s.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }
Code Sample 2:
String digest(final UserAccountEntity account) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(account.getUserId().getBytes("UTF-8")); digest.update(account.getLastLogin().toString().getBytes("UTF-8")); digest.update(account.getPerson().getGivenName().getBytes("UTF-8")); digest.update(account.getPerson().getSurname().getBytes("UTF-8")); digest.update(account.getPerson().getEmail().getBytes("UTF-8")); digest.update(m_random); return new String(Base64.altEncode(digest.digest())); } catch (final Exception e) { LOG.error("Exception", e); throw new RuntimeException(e); } } |
11
| Code Sample 1:
public void performOk(final IProject project, final TomcatPropertyPage page) { page.setPropertyValue("tomcat.jdbc.driver", c_drivers.getText()); page.setPropertyValue("tomcat.jdbc.url", url.getText()); page.setPropertyValue("tomcat.jdbc.user", username.getText()); page.setPropertyValue("tomcat.jdbc.password", password.getText()); File lib = new File(page.tomcatHome.getText(), "lib"); if (!lib.exists()) { lib = new File(new File(page.tomcatHome.getText(), "common"), "lib"); if (!lib.exists()) { Logger.log(Logger.ERROR, "Not properly location of Tomcat Home at :: " + lib); throw new IllegalStateException("Not properly location of Tomcat Home"); } } final File conf = new File(page.tomcatHome.getText(), "conf/Catalina/localhost"); if (!conf.exists()) { final boolean create = NexOpenUIActivator.getDefault().getTomcatConfProperty(); if (create) { if (Logger.getLog().isDebugEnabled()) { Logger.getLog().debug("Create directory " + conf); } try { conf.mkdirs(); } catch (final SecurityException se) { Logger.getLog().error("Retrieved a Security exception creating " + conf, se); Logger.log(Logger.ERROR, "Not created " + conf + " directory. Not enough privilegies. Message :: " + se.getMessage()); } } } String str_driverLibrary = LIBRARIES.get(c_drivers.getText()); if ("<mysql_driver>".equals(str_driverLibrary)) { str_driverLibrary = NexOpenUIActivator.getDefault().getMySQLDriver(); } final File driverLibrary = new File(lib, str_driverLibrary); if (!driverLibrary.exists()) { InputStream driver = null; FileOutputStream fos = null; try { driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + str_driverLibrary)); fos = new FileOutputStream(driverLibrary); IOUtils.copy(driver, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the driver jar file to Tomcat", e); } finally { try { if (driver != null) { driver.close(); driver = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } page.processTomcatCfg(c_drivers.getText(), url.getText(), username.getText(), password.getText()); }
Code Sample 2:
private void regattaBackup() { SwingWorker sw = new SwingWorker() { Regatta lRegatta = fRegatta; public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; } }; sw.start(); } |
11
| Code Sample 1:
public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); }
Code Sample 2:
public void doImport(File f, boolean checkHosp) throws Exception { connector.getConnection().setAutoCommit(false); File base = f.getParentFile(); ZipInputStream in = new ZipInputStream(new FileInputStream(f)); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { String outFileName = entry.getName(); File outFile = new File(base, outFileName); OutputStream out = new FileOutputStream(outFile, false); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); } in.close(); importDirectory(base, checkHosp); connector.getConnection().commit(); } |
00
| Code Sample 1:
public static void copy(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(); }
Code Sample 2:
public static void main(String[] args) { try { URL url = new URL("http://localhost:6557"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); int responseCode = conn.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close(); conn.disconnect(); } catch (Exception ex) { Logger.getLogger(TestSSLConnection.class.getName()).log(Level.SEVERE, null, ex); } } |
11
| Code Sample 1:
public void writeToFile(File out) throws IOException, DocumentException { FileChannel inChannel = new FileInputStream(pdf_file).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 TempFileTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); tempFile = tempPath.createTempFile("attachment", ".txt"); OutputStream out = tempFile.getOutputStream(); IOUtils.copy(is, out); out.close(); } |
00
| Code Sample 1:
public void assign() throws Exception { if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or peer-viewer selected."); String[] pids = proposalIds.split(","); String[] uids = usrIds.split(","); int pnum = pids.length; int unum = uids.length; if (pnum == 0 || unum == 0) throw new Exception("No proposal or peer-viewer selected."); int i, j; String pStr = "update proposal set current_status='assigned' where "; for (i = 0; i < pnum; i++) { if (i > 0) pStr += " OR "; pStr += "PROPOSAL_ID=" + pids[i]; } Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DATE); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); String dt = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(day); PreparedStatement prepStmt = null; try { con = database.getConnection(); con.setAutoCommit(false); prepStmt = con.prepareStatement(pStr); prepStmt.executeUpdate(); pStr = "insert into event (summary,document1,document2,document3,publicComments,privateComments,ACTION_ID,eventDate,ROLE_ID,reviewText,USR_ID,PROPOSAL_ID,SUBJECTUSR_ID) values " + "('','','','','','','assigned','" + dt + "',2,'new'," + userId + ",?,?)"; prepStmt = con.prepareStatement(pStr); for (i = 0; i < pnum; i++) { for (j = 0; j < unum; j++) { prepStmt.setString(1, pids[i]); prepStmt.setString(2, uids[j]); prepStmt.executeUpdate(); } } con.commit(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } event_Form fr = new event_Form(); for (j = 0; j < unum; j++) { fr.setUSR_ID(userId); fr.setSUBJECTUSR_ID(uids[j]); systemManager.handleEvent(SystemManager.EVENT_PROPOSAL_ASSIGNED, fr, null, null); } }
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!!"); } } } |
00
| Code Sample 1:
private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; BOTLRuleDiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((BOTLRuleDiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } }
Code Sample 2:
public void play() throws FileNotFoundException, IOException, NoSuchAlgorithmException, FTPException { final int BUFFER = 2048; String host = "ftp.genome.jp"; String username = "anonymous"; String password = ""; FTPClient ftp = null; ftp = new FTPClient(); ftp.setRemoteHost(host); FTPMessageCollector listener = new FTPMessageCollector(); ftp.setMessageListener(listener); System.out.println("Connecting"); ftp.connect(); System.out.println("Logging in"); ftp.login(username, password); System.out.println("Setting up passive, ASCII transfers"); ftp.setConnectMode(FTPConnectMode.PASV); ftp.setType(FTPTransferType.ASCII); System.out.println("Directory before put:"); String[] files = ftp.dir(".", true); for (int i = 0; i < files.length; i++) System.out.println(files[i]); System.out.println("Quitting client"); ftp.quit(); String messages = listener.getLog(); System.out.println("Listener log:"); System.out.println(messages); System.out.println("Test complete"); } |
11
| Code Sample 1:
public static String encode(String text) { try { byte[] hash = new byte[32]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("UTF-8"), 0, text.length()); hash = md.digest(); return MD5.toHex(hash); } catch (NoSuchAlgorithmException ex) { return ex.getMessage(); } catch (UnsupportedEncodingException ex) { return ex.getMessage(); } }
Code Sample 2:
@Override public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.reset(); digest.update(((String) salt).getBytes("UTF-8")); String encodedRawPass = new String(digest.digest(rawPass.getBytes("UTF-8"))); return encodedRawPass.equals(encPass); } catch (Throwable e) { throw new DataAccessException("Error al codificar la contrase�a", e) { private static final long serialVersionUID = -302443565702455874L; }; } } |
11
| Code Sample 1:
@org.junit.Test public void testReadWrite() throws Exception { final String reference = "testString"; final Reader reader = new StringReader(reference); final StringWriter osString = new StringWriter(); final Reader teeStream = new TeeReaderWriter(reader, osString); IOUtils.copy(teeStream, new NullWriter()); teeStream.close(); osString.toString(); }
Code Sample 2:
public ServiceAdapterIfc deploy(String session, String name, byte jarBytes[], String jarName, String serviceClass, String serviceInterface) throws RemoteException, MalformedURLException, StartServiceException, SessionException { try { File jarFile = new File(jarName); jarName = jarFile.getName(); String jarName2 = jarName; jarFile = new File(jarName2); int n = 0; while (jarFile.exists()) { jarName2 = jarName + n++; jarFile = new File(jarName2); } FileOutputStream fos = new FileOutputStream(jarName2); IOUtils.copy(new ByteArrayInputStream(jarBytes), fos); SCClassLoader cl = new SCClassLoader(new URL[] { new URL("file://" + jarFile.getAbsolutePath()) }, getMasterNode().getSCClassLoaderCounter()); return startService(session, name, serviceClass, serviceInterface, cl); } catch (SessionException e) { throw e; } catch (Exception e) { throw new StartServiceException("Could not deploy service: " + e.getMessage(), e); } } |
00
| 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 boolean deploy(MMedia[] media) { if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) { log.warning("You have not defined your own server, we will not really deploy to localhost!"); return true; } FTPClient ftp = new FTPClient(); try { ftp.connect(getIP_Address()); if (ftp.login(getUserName(), getPassword())) log.info("Connected to " + getIP_Address() + " as " + getUserName()); else { log.warning("Could NOT connect to " + getIP_Address() + " as " + getUserName()); return false; } } catch (Exception e) { log.log(Level.WARNING, "Could NOT connect to " + getIP_Address() + " as " + getUserName(), e); return false; } boolean success = true; String cmd = null; try { cmd = "cwd"; ftp.changeWorkingDirectory(getFolder()); cmd = "list"; String[] fileNames = ftp.listNames(); log.log(Level.FINE, "Number of files in " + getFolder() + ": " + fileNames.length); cmd = "bin"; ftp.setFileType(FTPClient.BINARY_FILE_TYPE); for (int i = 0; i < media.length; i++) { if (!media[i].isSummary()) { log.log(Level.INFO, " Deploying Media Item:" + media[i].get_ID() + media[i].getExtension()); MImage thisImage = media[i].getImage(); byte[] buffer = thisImage.getData(); ByteArrayInputStream is = new ByteArrayInputStream(buffer); String fileName = media[i].get_ID() + media[i].getExtension(); cmd = "put " + fileName; ftp.storeFile(fileName, is); is.close(); } } } catch (Exception e) { log.log(Level.WARNING, cmd, e); success = false; } try { cmd = "logout"; ftp.logout(); cmd = "disconnect"; ftp.disconnect(); } catch (Exception e) { log.log(Level.WARNING, cmd, e); } ftp = null; return success; } |
11
| Code Sample 1:
public String getData() throws ValueFormatException, RepositoryException, IOException { InputStream is = getStream(); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); IOUtils.closeQuietly(is); return sw.toString(); }
Code Sample 2:
public JavaCodeAnalyzer(String filenameIn, String filenameOut, String lineLength) { try { File tmp = File.createTempFile("JavaCodeAnalyzer", "tmp"); BufferedReader br = new BufferedReader(new FileReader(filenameIn)); BufferedWriter out = new BufferedWriter(new FileWriter(tmp)); while (br.ready()) { out.write(br.read()); } br.close(); out.close(); jco = new JavaCodeOutput(tmp, filenameOut, lineLength); SourceCodeParser p = new JavaCCParserFactory().createParser(new FileReader(tmp), null); List statements = p.parseCompilationUnit(); ListIterator it = statements.listIterator(); eh = new ExpressionHelper(this, jco); Node n; printLog("Parsed file " + filenameIn + "\n"); while (it.hasNext()) { n = (Node) it.next(); parseObject(n); } tmp.delete(); } catch (Exception e) { System.err.println(getClass() + ": " + e); } } |
11
| Code Sample 1:
@Override public void setContentAsStream(InputStream input) throws IOException { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(htmlFile)); try { IOUtils.copy(input, output); } finally { output.close(); } if (this.getLastModified() != -1) { htmlFile.setLastModified(this.getLastModified()); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void concatFiles(final String as_base_file_name) throws IOException, FileNotFoundException { new File(as_base_file_name).createNewFile(); final OutputStream lo_out = new FileOutputStream(as_base_file_name, true); int ln_part = 1, ln_readed = -1; final byte[] lh_buffer = new byte[32768]; File lo_file = new File(as_base_file_name + "part1"); while (lo_file.exists() && lo_file.isFile()) { final InputStream lo_input = new FileInputStream(lo_file); while ((ln_readed = lo_input.read(lh_buffer)) != -1) { lo_out.write(lh_buffer, 0, ln_readed); } ln_part++; lo_file = new File(as_base_file_name + "part" + ln_part); } lo_out.flush(); lo_out.close(); } |
00
| Code Sample 1:
private static Reader getReader(String fname) throws IOException { InputStream is; if (isUrl(fname)) { URL url = new URL(fname); is = url.openStream(); } else { is = new FileInputStream(fname); } if (fname.endsWith(".zip")) { is = new ZipInputStream(is); } else if (fname.endsWith(".gz") || fname.endsWith(".gzip")) { is = new GZIPInputStream(is); } return new InputStreamReader(is); }
Code Sample 2:
public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 4., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); } |
00
| Code Sample 1:
public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); pilotData.id = Sequence.nextVal("pilot_id", jdbc); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); psta.setInt(19, pilotData.id); psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } }
Code Sample 2:
public static Image readImage(URL url, ImageMimeType type, int page) throws IOException { if (type.javaNativeSupport()) { return ImageIO.read(url.openStream()); } else if ((type.equals(ImageMimeType.DJVU)) || (type.equals(ImageMimeType.VNDDJVU)) || (type.equals(ImageMimeType.XDJVU))) { com.lizardtech.djvu.Document doc = new com.lizardtech.djvu.Document(url); doc.setAsync(false); DjVuPage[] p = new DjVuPage[1]; int size = doc.size(); if ((page != 0) && (page >= size)) { page = 0; } p[0] = doc.getPage(page, 1, true); p[0].setAsync(false); DjVuImage djvuImage = new DjVuImage(p, true); Rectangle pageBounds = djvuImage.getPageBounds(0); Image[] images = djvuImage.getImage(new JPanel(), new Rectangle(pageBounds.width, pageBounds.height)); if (images.length == 1) { Image img = images[0]; return img; } else return null; } else if (type.equals(ImageMimeType.PDF)) { PDDocument document = null; try { document = PDDocument.load(url.openStream()); int resolution = 96; List<?> pages = document.getDocumentCatalog().getAllPages(); PDPage pdPage = (PDPage) pages.get(page); BufferedImage image = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, resolution); return image; } finally { if (document != null) { document.close(); } } } else throw new IllegalArgumentException("unsupported mimetype '" + type.getValue() + "'"); } |
11
| Code Sample 1:
public void execute(File sourceFile, File destinationFile, Properties htmlCleanerConfig) { FileReader reader = null; Writer writer = null; try { reader = new FileReader(sourceFile); logger.info("Using source file: " + trimPath(userDir, sourceFile)); if (!destinationFile.getParentFile().exists()) { createDirectory(destinationFile.getParentFile()); } writer = new FileWriter(destinationFile); logger.info("Destination file: " + trimPath(userDir, destinationFile)); execute(reader, writer, htmlCleanerConfig); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); writer = null; } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
public static void main(String[] args) throws Exception { String localSrc = args[0]; String dst = args[1]; InputStream in = new BufferedInputStream(new FileInputStream(localSrc)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(dst), conf); OutputStream out = fs.create(new Path(dst), new Progressable() { public void progress() { System.out.print("."); } }); IOUtils.copyBytes(in, out, 4096, true); } |
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 Bitmap getImage() throws IOException { int recordBegin = 78 + 8 * mCount; Bitmap result = null; FileChannel channel = new FileInputStream(mFile).getChannel(); channel.position(mRecodeOffset[mPage]); ByteBuffer bodyBuffer; if (mPage + 1 < mCount) { int length = mRecodeOffset[mPage + 1] - mRecodeOffset[mPage]; bodyBuffer = channel.map(MapMode.READ_ONLY, mRecodeOffset[mPage], length); byte[] tmpCache = new byte[bodyBuffer.capacity()]; bodyBuffer.get(tmpCache); FileOutputStream o = new FileOutputStream("/sdcard/test.bmp"); o.write(tmpCache); o.flush(); o.getFD().sync(); o.close(); result = BitmapFactory.decodeByteArray(tmpCache, 0, length); } else { } channel.close(); return result; } |
00
| Code Sample 1:
public void startImport(ActionEvent evt) { final PsiExchange psiExchange = PsiExchangeFactory.createPsiExchange(IntactContext.getCurrentInstance().getSpringContext()); for (final URL url : urlsToImport) { try { if (log.isInfoEnabled()) log.info("Importing: " + url); psiExchange.importIntoIntact(url.openStream()); } catch (IOException e) { handleException(e); return; } } addInfoMessage("File successfully imported", Arrays.asList(urlsToImport).toString()); }
Code Sample 2:
public static int[] sortAscending(double input[]) { int[] order = new int[input.length]; for (int i = 0; i < order.length; i++) order[i] = i; for (int i = input.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (input[j] > input[j + 1]) { double mem = input[j]; input[j] = input[j + 1]; input[j + 1] = mem; int id = order[j]; order[j] = order[j + 1]; order[j + 1] = id; } } } return order; } |
11
| Code Sample 1:
public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
Code Sample 2:
protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException { IProject pj = pack.getJavaProject().getProject(); QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION); String location = pj.getPersistentProperty(qn); if (location != null) { IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA)); IFolder packageInfo = javaFolder.getFolder(location); if (!packageInfo.exists()) { Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists."); Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location); return; } IFile pkginfo = packageInfo.getFile("package-info.java"); if (!pkginfo.exists()) { Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists."); return; } InputStream in = pkginfo.getContents(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { IOUtils.copy(in, baos); String content = new String(baos.toByteArray()); VelocityEngine engine = VelocityEngineHolder.getEngine(); model.put("adapterType", getAdapterType()); model.put("packageInfo", location.replace('/', '.')); model.put("defaultNumberPerPage", "5"); model.put("defaultSortDirection", "asc"); if (isFacadeAdapter()) { model.put("facadeType", "true"); } if (content.indexOf("@ValueLists({})") > -1) { appendValueList(monitor, model, pkginfo, content, engine, true); return; } else if (content.indexOf("@ValueLists") > -1) { appendValueList(monitor, model, pkginfo, content, engine, false); return; } String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model); ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes()); try { pkginfo.setContents(bais, true, false, monitor); } finally { bais.close(); } return; } catch (IOException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e); throw new CoreException(status); } catch (VelocityException e) { IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e); throw new CoreException(status); } finally { try { baos.close(); in.close(); } catch (IOException e) { } } } Logger.log(Logger.INFO, "package-info location property does not exists."); } |
00
| Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private static Result request(AbstractHttpClient client, HttpUriRequest request) throws ClientProtocolException, IOException { HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); Result result = new Result(); result.setStatusCode(response.getStatusLine().getStatusCode()); result.setHeaders(response.getAllHeaders()); result.setCookie(assemblyCookie(client.getCookieStore().getCookies())); result.setHttpEntity(entity); return result; } |
Subsets and Splits