label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void getZipFiles(String filename) { try { String destinationname = "c:\\mods\\peu\\"; byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(filename)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); System.out.println("entryname " + entryName); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(destinationname + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (Exception e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public static String encryptMd5(String plaintext) { String hashtext = ""; try { MessageDigest m; m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; }
Code Sample 2:
public File createTemporaryFile() throws IOException { URL url = clazz.getResource(resource); if (url == null) { throw new IOException("No resource available from '" + clazz.getName() + "' for '" + resource + "'"); } String extension = getExtension(resource); String prefix = "resource-temporary-file-creator"; File file = File.createTempFile(prefix, extension); InputStream input = url.openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(file); com.volantis.synergetics.io.IOUtils.copyAndClose(input, output); return file; } |
11
| Code Sample 1:
public static String digestString(String data, String algorithm) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance(algorithm); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds; _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; }
Code Sample 2:
public static String toMD5String(String plainText) { if (TextUtils.isEmpty(plainText)) { plainText = ""; } StringBuilder text = new StringBuilder(); for (int i = plainText.length() - 1; i >= 0; i--) { text.append(plainText.charAt(i)); } plainText = text.toString(); MessageDigest mDigest; try { mDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return plainText; } mDigest.update(plainText.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); } |
00
| Code Sample 1:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
Code Sample 2:
public void refreshStatus() { if (!enabledDisplay) return; try { String url = getServerFortURL(); BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String data = null; int counter = 0; while ((data = reader.readLine()) != null && counter < 9) { status[counter] = UNKNOWN; if (data.matches(".*_alsius.gif.*")) { status[counter] = ALSIUS; counter++; } if (data.matches(".*_syrtis.gif.*")) { status[counter] = SYRTIS; counter++; } if (data.matches(".*_ignis.gif.*")) { status[counter] = IGNIS; counter++; } } } catch (Exception exc) { for (int i = 0; i < status.length; i++) status[i] = UNKNOWN; } } |
00
| Code Sample 1:
public static void copy(String sourceName, String destName, StatusWindow status) throws IOException { File src = new File(sourceName); File dest = new File(destName); BufferedInputStream source = null; BufferedOutputStream destination = null; byte[] buffer; int bytes_read; long byteCount = 0; if (!src.exists()) throw new IOException("Source not found: " + src); if (!src.canRead()) throw new IOException("Source is unreadable: " + src); if (src.isFile()) { if (!dest.exists()) { File parentdir = Utils.parent(dest); if (!parentdir.exists()) parentdir.mkdir(); } else if (dest.isDirectory()) { if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName()); } } else if (src.isDirectory()) { if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest); if (!dest.exists()) dest.mkdir(); } if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest); if (src.isFile()) { try { if (status != null) { status.setMaximum(100); status.setMessage(Utils.trimFileName(src.toString(), 40), 50); } source = new BufferedInputStream(new FileInputStream(src)); destination = new BufferedOutputStream(new FileOutputStream(dest)); buffer = new byte[4096]; byteCount = 0; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (status != null) { status.setMessage(Utils.trimFileName(src.toString(), 40), 100); } if (source != null) source.close(); if (destination != null) destination.close(); } } else if (src.isDirectory()) { String targetfile, target, targetdest; String[] files = src.list(); if (status != null) { status.setMaximum(files.length); } for (int i = 0; i < files.length; i++) { if (status != null) { status.setMessage(Utils.trimFileName(src.toString(), 40), i); } targetfile = files[i]; target = src + File.separator + targetfile; targetdest = dest + File.separator + targetfile; if ((new File(target)).isDirectory()) { copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath(), status); } else { try { byteCount = 0; source = new BufferedInputStream(new FileInputStream(target)); destination = new BufferedOutputStream(new FileOutputStream(targetdest)); buffer = new byte[4096]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); byteCount = byteCount + bytes_read; } } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } } } }
Code Sample 2:
private static String md5(String text) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(text.getBytes("UTF-8")); byte[] messageDigest = digest.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } |
11
| Code Sample 1:
public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test1.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.encrypt(reader, writer, key, mode); }
Code Sample 2:
public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; } |
00
| Code Sample 1:
public static String getContent(String url, String code) { HttpURLConnection connect = null; try { URL myurl = new URL(url); connect = (HttpURLConnection) myurl.openConnection(); connect.setConnectTimeout(30000); connect.setReadTimeout(30000); connect.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB5; .NET CLR 1.1.4322; .NET CLR 2.0.50727; Alexa Toolbar; MAXTHON 2.0)"); return StringUtil.convertStreamToString(connect.getInputStream(), code); } catch (Exception e) { slogger.warn(e.getMessage()); } finally { if (connect != null) { connect.disconnect(); } } slogger.warn("这个没找到" + url); return null; }
Code Sample 2:
public String parse(String queryText) throws ParseException { try { StringBuilder sb = new StringBuilder(); queryText = Val.chkStr(queryText); if (queryText.length() > 0) { URL url = new URL(getUrl(queryText)); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } } return sb.toString(); } catch (IOException ex) { throw new ParseException("Ontology parser is unable to parse term: \"" + queryText + "\" due to internal error: " + ex.getMessage()); } } |
00
| Code Sample 1:
private URL resolveRedirects(URL url, int redirectCount) throws IOException { URLConnection uc = url.openConnection(); if (uc instanceof HttpURLConnection) { HttpURLConnection huc = (HttpURLConnection) uc; huc.setInstanceFollowRedirects(false); huc.connect(); int responseCode = huc.getResponseCode(); String location = huc.getHeaderField("location"); huc.disconnect(); if ((responseCode == HttpURLConnection.HTTP_MOVED_TEMP) && (redirectCount < 5)) { try { URL newUrl = new URL(location); return resolveRedirects(newUrl, redirectCount + 1); } catch (MalformedURLException ex) { return url; } } else return url; } else return url; }
Code Sample 2:
public List<String> makeQuery(String query) { List<String> result = new ArrayList<String>(); try { query = URLUTF8Encoder.encode(query); URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query); URLConnection connection = url.openConnection(); connection.addRequestProperty("Referer", "http://poo.sk"); String line; StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } String response = builder.toString(); JSONObject json = new JSONObject(response); Long count = Long.decode(json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount")); LOG.info("Found " + count + " potential pages"); JSONArray ja = json.getJSONObject("responseData").getJSONArray("results"); for (int i = 0; i < ja.length(); i++) { JSONObject j = ja.getJSONObject(i); result.add(j.getString("url")); } } catch (Exception e) { LOG.error("Couldnt query Google for some reason check exception below"); e.printStackTrace(); } return result; } |
00
| Code Sample 1:
public void run() { isRunning = true; try { URL url = new URL("http://dcg.ethz.ch/projects/sinalgo/version"); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.connect(); PrintStream ps = new PrintStream(con.getOutputStream()); ps.println("GET index.html HTTP/1.1"); ps.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = in.readLine(); if (line != null) { if (line.equals(Configuration.versionString)) { if (displayIfOK) { Main.info("You are using the most recent version of Sinalgo."); } } else { String msg = "\n" + "+----------------------------------------------------------------------\n" + "| You are currently running Sinalgo " + Configuration.versionString + ".\n" + "| A more recent version of Sinalgo is available (" + line + ")\n" + "+---------------------------------------------------------------------\n" + "| To download the latest version, please visit\n" + "| http://sourceforge.net/projects/sinalgo/\n" + "+---------------------------------------------------------------------\n" + "| You may turn off these version checks through the 'Settings' dialog.\n" + "| Note: Sinalgo automatically tests for updates at most once\n" + "| every 24 hours.\n" + "+---------------------------------------------------------------------\n"; Main.warning(msg); } } } catch (Exception e) { String msg = "\n" + ">----------------------------------------------------------------------\n" + "> Unable to test for updates of Sinalgo. The installed version\n" + "> is " + Configuration.versionString + "\n" + ">---------------------------------------------------------------------\n" + "> To check for more recent versions, please visit\n" + "> http://sourceforge.net/projects/sinalgo/\n" + ">---------------------------------------------------------------------\n" + "> You may turn off these version checks through the 'Settings' dialog.\n" + "| Note: Sinalgo automatically tests for updates at most once\n" + "| every 24 hours.\n" + ">---------------------------------------------------------------------\n"; Main.warning(msg); } finally { isRunning = false; AppConfig.getAppConfig().timeStampOfLastUpdateCheck = System.currentTimeMillis(); } }
Code Sample 2:
public String sendRequest(HTTPHandler.RequestData requestData) throws HTTPHandlerException { try { final String urlString = requestData.getURLString(); final URL url = new URL(urlString); final String postString = requestData.getPostString(); m_pluginThreadContext.startTimer(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); final Iterator headersIterator = requestData.getHeaders().entrySet().iterator(); while (headersIterator.hasNext()) { final Map.Entry entry = (Map.Entry) headersIterator.next(); connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } final AuthorizationData authorizationData = requestData.getAuthorizationData(); if (authorizationData != null && authorizationData instanceof HTTPHandler.BasicAuthorizationData) { final HTTPHandler.BasicAuthorizationData basicAuthorizationData = (HTTPHandler.BasicAuthorizationData) authorizationData; connection.setRequestProperty("Authorization", "Basic " + Codecs.base64Encode(basicAuthorizationData.getUser() + ":" + basicAuthorizationData.getPassword())); } connection.setInstanceFollowRedirects(m_followRedirects); if (m_useCookies) { final String cookieString = m_cookieHandler.getCookieString(url, m_useCookiesVersionString); if (cookieString != null) { connection.setRequestProperty("Cookie", cookieString); } } connection.setUseCaches(false); if (postString != null) { connection.setRequestMethod("POST"); connection.setDoOutput(true); final BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream()); final PrintWriter out = new PrintWriter(bos); out.write(postString); out.close(); } connection.connect(); final int responseCode = connection.getResponseCode(); if (m_timeToFirstByteIndex != null) { m_pluginThreadContext.getCurrentTestStatistics().addValue(m_timeToFirstByteIndex, System.currentTimeMillis() - m_pluginThreadContext.getStartTime()); } if (m_useCookies) { int headerIndex = 1; String headerKey = null; String headerValue = connection.getHeaderField(headerIndex); while (headerValue != null) { headerKey = connection.getHeaderFieldKey(headerIndex); if (headerKey != null && "Set-Cookie".equals(headerKey)) { m_cookieHandler.setCookies(headerValue, url); } headerValue = connection.getHeaderField(++headerIndex); } } if (responseCode == HttpURLConnection.HTTP_OK) { final InputStreamReader isr = new InputStreamReader(connection.getInputStream()); final BufferedReader in = new BufferedReader(isr); final StringWriter stringWriter = new StringWriter(512); char[] buffer = new char[512]; int charsRead = 0; if (!m_dontReadBody) { while ((charsRead = in.read(buffer, 0, buffer.length)) > 0) { stringWriter.write(buffer, 0, charsRead); } } in.close(); stringWriter.close(); m_pluginThreadContext.logMessage(urlString + " OK"); return stringWriter.toString(); } else if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { m_pluginThreadContext.logMessage(urlString + " was not modified"); } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == 307) { m_pluginThreadContext.logMessage(urlString + " returned a redirect (" + responseCode + "). " + "Ensure the next URL is " + connection.getHeaderField("Location")); return null; } else { m_pluginThreadContext.logError("Unknown response code: " + responseCode + " for " + urlString); } return null; } catch (Exception e) { throw new HTTPHandlerException(e.getMessage(), e); } finally { m_pluginThreadContext.stopTimer(); } } |
11
| Code Sample 1:
public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } }
Code Sample 2:
private void copyFile(File dir, File fileToAdd) { try { byte[] readBuffer = new byte[1024]; File file = new File(dir.getCanonicalPath() + File.separatorChar + fileToAdd.getName()); if (file.createNewFile()) { FileInputStream fis = new FileInputStream(fileToAdd); FileOutputStream fos = new FileOutputStream(file); int bytesRead; do { bytesRead = fis.read(readBuffer); fos.write(readBuffer, 0, bytesRead); } while (bytesRead == 0); fos.flush(); fos.close(); fis.close(); } else { logger.severe("unable to create file:" + file.getAbsolutePath()); } } catch (IOException ioe) { logger.severe("unable to create file:" + ioe); } } |
00
| Code Sample 1:
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; for (JarFile java3DJar : this.java3DJars) { JarEntry jarEntry = java3DJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = java3DJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } }
Code Sample 2:
private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } } |
00
| Code Sample 1:
public Transaction() throws Exception { Connection Conn = null; Statement Stmt = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Conn = DriverManager.getConnection(DBUrl); Conn.setAutoCommit(true); Stmt = Conn.createStatement(); try { Stmt.executeUpdate("DROP TABLE trans_test"); } catch (SQLException sqlEx) { } Stmt.executeUpdate("CREATE TABLE trans_test (id int not null primary key, decdata double) type=BDB"); Conn.setAutoCommit(false); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.0)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Conn.rollback(); System.out.println("Roll Ok"); ResultSet RS = Stmt.executeQuery("SELECT * from trans_test"); if (!RS.next()) { System.out.println("Ok"); } else { System.out.println("Rollback failed"); } Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.485115)"); Conn.commit(); RS = Stmt.executeQuery("SELECT * from trans_test where id=2"); if (RS.next()) { System.out.println(RS.getDouble(2)); System.out.println("Ok"); } else { System.out.println("Rollback failed"); } } catch (Exception ex) { throw ex; } finally { if (Stmt != null) { try { Stmt.close(); } catch (SQLException SQLEx) { } } if (Conn != null) { try { Conn.close(); } catch (SQLException SQLEx) { } } } }
Code Sample 2:
public ISOMsg filter(ISOChannel channel, ISOMsg m, LogEvent evt) throws VetoException { if (key == null || fields == null) throw new VetoException("MD5Filter not configured"); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getKey()); int[] f = getFields(m); for (int i = 0; i < f.length; i++) { int fld = f[i]; if (m.hasField(fld)) { ISOComponent c = m.getComponent(fld); if (c instanceof ISOBinaryField) md.update((byte[]) c.getValue()); else md.update(((String) c.getValue()).getBytes()); } } byte[] digest = md.digest(); if (m.getDirection() == ISOMsg.OUTGOING) { m.set(new ISOBinaryField(64, digest, 0, 8)); m.set(new ISOBinaryField(128, digest, 8, 8)); } else { byte[] rxDigest = new byte[16]; if (m.hasField(64)) System.arraycopy((byte[]) m.getValue(64), 0, rxDigest, 0, 8); if (m.hasField(128)) System.arraycopy((byte[]) m.getValue(128), 0, rxDigest, 8, 8); if (!Arrays.equals(digest, rxDigest)) { evt.addMessage(m); evt.addMessage("MAC expected: " + ISOUtil.hexString(digest)); evt.addMessage("MAC received: " + ISOUtil.hexString(rxDigest)); throw new VetoException("invalid MAC"); } m.unset(64); m.unset(128); } } catch (NoSuchAlgorithmException e) { throw new VetoException(e); } catch (ISOException e) { throw new VetoException(e); } return m; } |
11
| Code Sample 1:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(128); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error: " + e); } try { 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(); StringBuffer sb = new StringBuffer(32); for (int j = 0; j < array.length; ++j) { int b = array[j] & TWO_BYTES; if (b < PAD_BELOW) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { logger.error("Error:" + e); } }
Code Sample 2:
public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; } |
11
| Code Sample 1:
public void xtest11() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/UML2.pdf"); InputStream page1 = manager.cut(pdf, 1, 1); OutputStream outputStream = new FileOutputStream("/tmp/page.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); }
Code Sample 2:
public static void write(File file, InputStream source) throws IOException { OutputStream outputStream = null; assert file != null : "file must not be null."; assert file.isFile() : "file must be a file."; assert file.canWrite() : "file must be writable."; assert source != null : "source must not be null."; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(source, outputStream); outputStream.flush(); } finally { IOUtils.closeQuietly(outputStream); } } |
00
| Code Sample 1:
public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[8192]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
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:
public static String novoMetodoDeCriptografarParaMD5QueNaoFoiUtilizadoAinda(String input) { if (input == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); BigInteger hash = new BigInteger(1, digest.digest()); String output = hash.toString(16); if (output.length() < 32) { int sizeDiff = 32 - output.length(); do { output = "0" + output; } while (--sizeDiff > 0); } return output; } catch (NoSuchAlgorithmException ns) { LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), ns); return input; } catch (UnsupportedEncodingException e) { LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), e); return input; } }
Code Sample 2:
public static String getMD5(String in) { if (in == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(in.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xFF & hash[i]); if (hex.length() == 1) { hex = "0" + hex; } hexString.append(hex); } return hexString.toString(); } catch (Exception e) { Debug.logException(e); } return null; } |
11
| Code Sample 1:
private String fetchHTML(String s) { String str; StringBuffer sb = new StringBuffer(); try { URL url = new URL(s); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while ((str = br.readLine()) != null) { sb.append(str); } } catch (MalformedURLException e) { } catch (IOException e) { } return sb.toString(); }
Code Sample 2:
public static String read(URL url) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringWriter res = new StringWriter(); PrintWriter writer = new PrintWriter(new BufferedWriter(res)); String line; while ((line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); return res.toString(); } |
11
| Code Sample 1:
private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException, XMLStreamException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); byte[] byteArray = baos.toByteArray(); String resMessage = new String(byteArray, "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + resMessage); return resMessage; }
Code Sample 2:
private String createVisadFile(String fileName) throws FileNotFoundException, IOException { ArrayList<String> columnNames = new ArrayList<String>(); String visadFile = fileName + ".visad"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); String firstLine = buf.readLine().replace('"', ' '); StringTokenizer st = new StringTokenizer(firstLine, ","); while (st.hasMoreTokens()) columnNames.add(st.nextToken()); StringBuilder headerBuilder = new StringBuilder(); headerBuilder.append("(").append(columnNames.get(0)).append("->("); for (int i = 1; i < columnNames.size(); i++) { headerBuilder.append(columnNames.get(i)); if (i < columnNames.size() - 1) headerBuilder.append(","); } headerBuilder.append("))"); BufferedWriter out = new BufferedWriter(new FileWriter(visadFile)); out.write(headerBuilder.toString() + "\n"); out.write(firstLine + "\n"); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return visadFile; } |
11
| Code Sample 1:
public static void copy(File src, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.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 boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
private static void doCopyFile(FileInputStream in, FileOutputStream out) { FileChannel inChannel = null, outChannel = null; try { inChannel = in.getChannel(); outChannel = out.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw ManagedIOException.manage(e); } finally { if (inChannel != null) { close(inChannel); } if (outChannel != null) { close(outChannel); } } } |
11
| Code Sample 1:
public static void entering(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new BufferedInputStream(new FileInputStream(args[0]))); int constantIndex = writer.getStringConstantIndex("Entering "); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int printlnRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); int printRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "print", "(Ljava/lang/String;)V"); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); if (method.getName().equals("readConstant")) continue; CodeAttribute attribute = method.getCodeAttribute(); ArrayList instructions = new ArrayList(10); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("dup"), 0, null, false)); instructions.add(Instruction.appropriateLdc(constantIndex, false)); operands = new byte[2]; NetByte.intToPair(printRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(Instruction.appropriateLdc(writer.getStringConstantIndex(method.getName()), false)); operands = new byte[2]; NetByte.intToPair(printlnRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); attribute.insertInstructions(0, 0, instructions); attribute.codeCheck(); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); }
Code Sample 2:
@Override public Collection<IAuthor> doImport() throws Exception { progress.initialize(2, "Ściągam autorów amerykańskich"); String url = "http://pl.wikipedia.org/wiki/Kategoria:Ameryka%C5%84scy_autorzy_fantastyki"; UrlResource resource = new UrlResource(url); InputStream urlInputStream = resource.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(urlInputStream, writer); progress.advance("Parsuję autorów amerykańskich"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String httpDoc = writer.toString(); httpDoc = httpDoc.replaceFirst("(?s)<!DOCTYPE.+?>\\n", ""); httpDoc = httpDoc.replaceAll("(?s)<script.+?</script>", ""); httpDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" + httpDoc; ByteArrayInputStream byteInputStream = new ByteArrayInputStream(httpDoc.getBytes("UTF-8")); Document doc = builder.parse(byteInputStream); ArrayList<String> authorNames = new ArrayList<String>(); ArrayList<IAuthor> authors = new ArrayList<IAuthor>(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList list = (NodeList) xpath.evaluate("//ul/li/div/div/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } list = (NodeList) xpath.evaluate("//td/ul/li/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } for (String name : authorNames) { int idx = name.lastIndexOf(' '); String fname = name.substring(0, idx).trim(); String lname = name.substring(idx + 1).trim(); authors.add(new Author(fname, lname)); } progress.advance("Wykonano"); return authors; } |
00
| Code Sample 1:
public boolean copyFile(File source, File dest) { try { FileReader in = new FileReader(source); FileWriter out = new FileWriter(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return true; } catch (Exception e) { return false; } }
Code Sample 2:
public void run() { try { String data = URLEncoder.encode("send_id", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"); data += "&" + URLEncoder.encode("author", "UTF-8") + "=" + URLEncoder.encode(name.getText(), "UTF-8"); data += "&" + URLEncoder.encode("location", "UTF-8") + "=" + URLEncoder.encode(System.getProperty("user.language"), "UTF-8"); data += "&" + URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(email.getText(), "UTF-8"); data += "&" + URLEncoder.encode("content", "UTF-8") + "=" + URLEncoder.encode(comment.getText(), "UTF-8"); data += "&" + URLEncoder.encode("rate", "UTF-8") + "=" + URLEncoder.encode(rate.getSelectedItem().toString(), "UTF-8"); System.out.println(data); URL url = new URL("http://javablock.sourceforge.net/book/index.php"); 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 address = rd.readLine(); JPanel panel = new JPanel(); panel.add(new JLabel("Comment added")); panel.add(new JTextArea("visit: http://javablock.sourceforge.net/")); JOptionPane.showMessageDialog(null, new JLabel("Comment sended correctly!")); wr.close(); rd.close(); hide(); } catch (IOException ex) { Logger.getLogger(guestBook.class.getName()).log(Level.SEVERE, null, ex); } } |
11
| Code Sample 1:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Git git = Git.getCurrent(req.getSession()); GitComponentReader gitReader = git.getComponentReader("warpinjector"); String id = req.getParameter("id"); GitElement element = gitReader.getElement(id); String path = (String) element.getAttribute("targetdir"); File folder = new File(path); PrintWriter out = helper.getPrintWriter(resp); MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages"); Locale locale = req.getLocale(); helper.header(out, messageBundle, locale); if (git.getUser() == null) { helper.notLoggedIn(out, messageBundle, locale); } else { try { MultiPartRequest request = new MultiPartRequest(req); FileInfo info = request.getFileInfo("userfile"); File file = info.getFile(); out.println("tempfile found: " + file.getPath() + "<br>"); String fileName = info.getFileName(); File target = new File(folder, fileName); out.println("copying tempfile to: " + target.getPath() + "<br>"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(target); byte buf[] = new byte[1024]; int n; while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); out.println("copy successful - deleting old tempfile<br>"); out.println("deletion result. " + file.delete() + "<p>"); out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale)); out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>"); } catch (Exception ex) { out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale)); } } helper.footer(out); }
Code Sample 2:
public void run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } } |
00
| Code Sample 1:
public void actionPerformed(ActionEvent event) { System.out.println("STARTING on" + getQueryField().getText()); try { URL url = new URL(getQueryField().getText()); getResponseField().setText("opening URL"); DataInputStream inputStream = new DataInputStream(url.openStream()); getResponseField().setText("collating response"); String line = inputStream.readLine(); String totalString = ""; while (line != null) { totalString += line + "\n"; line = inputStream.readLine(); } System.out.println("FINISHING"); getResponseField().setText(totalString); System.out.println("FINISHED"); } catch (Exception exception) { getResponseField().setText(exception.getMessage() + "\n"); } }
Code Sample 2:
public static final boolean zipUpdate(String zipfile, String name, String oldname, byte[] contents, boolean delete) { try { File temp = File.createTempFile("atf", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); OutputStream os = new BufferedOutputStream(new FileOutputStream(temp)); ZipInputStream zin = new ZipInputStream(in); ZipOutputStream zout = new ZipOutputStream(os); ZipEntry e; ZipEntry e2; byte buffer[] = new byte[TEMP_FILE_BUFFER_SIZE]; int bytesRead; boolean found = false; boolean rename = false; String oname = name; if (oldname != null) { name = oldname; rename = true; } while ((e = zin.getNextEntry()) != null) { if (!e.isDirectory()) { String ename = e.getName(); if (delete && ename.equals(name)) continue; e2 = new ZipEntry(rename ? oname : ename); zout.putNextEntry(e2); if (ename.equals(name)) { found = true; zout.write(contents); } else { while ((bytesRead = zin.read(buffer)) != -1) zout.write(buffer, 0, bytesRead); } zout.closeEntry(); } } if (!found && !delete) { e = new ZipEntry(name); zout.putNextEntry(e); zout.write(contents); zout.closeEntry(); } zin.close(); zout.close(); File fp = new File(zipfile); fp.delete(); MLUtil.copyFile(temp, fp); temp.delete(); return (true); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } return (false); } |
11
| Code Sample 1:
private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); WebResponse response = wc.getResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
Code Sample 2:
private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; } |
11
| Code Sample 1:
private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } }
Code Sample 2:
public static void copyDirectory(File sourceDirectory, File targetDirectory) throws IOException { File[] sourceFiles = sourceDirectory.listFiles(FILE_FILTER); File[] sourceDirectories = sourceDirectory.listFiles(DIRECTORY_FILTER); targetDirectory.mkdirs(); if (sourceFiles != null && sourceFiles.length > 0) { for (int i = 0; i < sourceFiles.length; i++) { File sourceFile = sourceFiles[i]; FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetDirectory + File.separator + sourceFile.getName()); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(8192); long size = fcin.size(); long n = 0; while (n < size) { buf.clear(); if (fcin.read(buf) < 0) { break; } buf.flip(); n += fcout.write(buf); } fcin.close(); fcout.close(); fis.close(); fos.close(); } } if (sourceDirectories != null && sourceDirectories.length > 0) { for (int i = 0; i < sourceDirectories.length; i++) { File directory = sourceDirectories[i]; File newTargetDirectory = new File(targetDirectory, directory.getName()); copyDirectory(directory, newTargetDirectory); } } } |
00
| 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 SearchItem loadRecord(String id, boolean isContact) { String line = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(isContact ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", Common.token)); nameValuePairs.add(new BasicNameValuePair("id", id)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, isContact ? "Name__Last__First_" : "Name"); String phone = ""; if (!isContact) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, isContact ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, isContact ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); SearchItem item = new SearchItem(); item.set(1, Name__Last__First_); item.set(2, phone); item.set(3, phone); item.set(4, Email1); item.set(5, Home_Fax); item.set(6, Address1); item.set(7, Address2); item.set(8, City); item.set(9, State); item.set(10, Zip); item.set(11, Profile); item.set(12, Country); item.set(13, success); item.set(14, error); return item; } catch (Exception e) { line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; line = null; } return null; } |
00
| Code Sample 1:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
Code Sample 2:
public static void copy(FileInputStream from, FileOutputStream to) throws IOException { FileChannel fromChannel = from.getChannel(); FileChannel toChannel = to.getChannel(); copy(fromChannel, toChannel); fromChannel.close(); toChannel.close(); } |
00
| Code Sample 1:
private void loadProperties() throws IOException { if (properties == null) { return; } printDebugIfEnabled("Loading properties"); InputStream inputStream = configurationSource.openStream(); Properties newProperties = new Properties(); try { newProperties.load(inputStream); } finally { inputStream.close(); } String importList = newProperties.getProperty(KEY_IMPORT); if (importList != null) { importList = importList.trim(); if (importList.length() > 0) { String[] filesToImport = importList.split(","); if (filesToImport != null && filesToImport.length != 0) { String configurationContext = configurationSource.toExternalForm(); int lastSlash = configurationContext.lastIndexOf('/'); lastSlash += 1; configurationContext = configurationContext.substring(0, lastSlash); for (int i = 0; i < filesToImport.length; i++) { String filenameToImport = filesToImport[i]; URL urlToImport = new URL(configurationContext + filenameToImport); InputStream importStream = null; try { printDebugIfEnabled("Importing file", urlToImport); importStream = urlToImport.openStream(); newProperties.load(importStream); } catch (IOException e) { printError("Error importing properties file: " + filenameToImport + "(" + urlToImport + ")", e, true); } finally { if (importStream != null) importStream.close(); } } } } } if (devDebug) { Set properties = newProperties.entrySet(); printDebugIfEnabled("_____ Properties List START _____"); for (Iterator iterator = properties.iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); printDebugIfEnabled((String) entry.getKey(), entry.getValue()); } printDebugIfEnabled("______ Properties List END ______"); } properties.clear(); properties.putAll(newProperties); }
Code Sample 2:
private void copy(String inputPath, String outputPath, String name) { try { FileReader in = new FileReader(inputPath + name); FileWriter out = new FileWriter(outputPath + name); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public static void compress(final File zip, final Map<InputStream, String> entries, final IProgressMonitor monitor) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); try { for (InputStream inputStream : entries.keySet()) { ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream))); out.putNextEntry(zipEntry); IOUtils.copy(inputStream, out); out.closeEntry(); inputStream.close(); if (monitor != null) monitor.worked(1); } } finally { IOUtils.closeQuietly(out); } }
Code Sample 2:
@Override public void objectToEntry(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } } |
11
| Code Sample 1:
public static void unzip(File zipInFile, File outputDir) throws Exception { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(zipInFile); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipInFile)); ZipEntry entry = (ZipEntry) zipInputStream.getNextEntry(); File curOutDir = outputDir; while (entry != null) { if (entry.isDirectory()) { curOutDir = new File(curOutDir, entry.getName()); curOutDir.mkdirs(); continue; } File outFile = new File(curOutDir, entry.getName()); File tempDir = outFile.getParentFile(); if (!tempDir.exists()) tempDir.mkdirs(); outFile.createNewFile(); BufferedOutputStream outstream = new BufferedOutputStream(new FileOutputStream(outFile)); int n; byte[] buf = new byte[1024]; while ((n = zipInputStream.read(buf, 0, 1024)) > -1) outstream.write(buf, 0, n); outstream.flush(); outstream.close(); zipInputStream.closeEntry(); entry = zipInputStream.getNextEntry(); } zipInputStream.close(); zipFile.close(); }
Code Sample 2:
private void stripOneFilex(File inFile, File outFile) throws IOException { StreamTokenizer reader = new StreamTokenizer(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); reader.slashSlashComments(false); reader.slashStarComments(false); reader.eolIsSignificant(true); int token; while ((token = reader.nextToken()) != StreamTokenizer.TT_EOF) { switch(token) { case StreamTokenizer.TT_NUMBER: throw new IllegalStateException("didn't expect TT_NUMBER: " + reader.nval); case StreamTokenizer.TT_WORD: System.out.print(reader.sval); writer.write("WORD:" + reader.sval, 0, reader.sval.length()); default: char outChar = (char) reader.ttype; System.out.print(outChar); writer.write(outChar); } } } |
11
| Code Sample 1:
public static void copy(File src, File dest, boolean overwrite) throws IOException { if (!src.exists()) throw new IOException("File source does not exists"); if (dest.exists()) { if (!overwrite) throw new IOException("File destination already exists"); dest.delete(); } else { dest.createNewFile(); } InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dest); byte[] buffer = new byte[1024 * 4]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } os.close(); is.close(); }
Code Sample 2:
public static void main(String[] args) throws IOException { String zipPath = "C:\\test.zip"; CZipInputStream zip_in = null; try { byte[] c = new byte[1024]; int slen; zip_in = new CZipInputStream(new FileInputStream(zipPath), "utf-8"); do { ZipEntry file = zip_in.getNextEntry(); if (file == null) break; String fileName = file.getName(); System.out.println(fileName); String ext = fileName.substring(fileName.lastIndexOf(".")); long seed = new Date(System.currentTimeMillis()).getTime(); String newFileName = Long.toString(seed) + ext; FileOutputStream out = new FileOutputStream(newFileName); while ((slen = zip_in.read(c, 0, c.length)) != -1) out.write(c, 0, slen); out.close(); } while (true); } catch (ZipException zipe) { zipe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { zip_in.close(); } } |
11
| Code Sample 1:
protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } }
Code Sample 2:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); } |
11
| Code Sample 1:
public static void copyFile(File src, File dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); try { byte[] buf = new byte[1024]; int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } catch (IOException e) { throw e; } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } } catch (IOException e) { logger.error("Error coping file from " + src + " to " + dst, e); } }
Code Sample 2:
private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } } |
00
| Code Sample 1:
public boolean isPasswordCorrect(String attempt) { try { MessageDigest digest = MessageDigest.getInstance(attempt); digest.update(salt); digest.update(attempt.getBytes("UTF-8")); byte[] attemptHash = digest.digest(); return attemptHash.equals(hash); } catch (UnsupportedEncodingException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex); return false; } }
Code Sample 2:
protected static void clearTables() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (2, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (3, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (4, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (5, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (6, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (7, '')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (8, '')"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } |
00
| Code Sample 1:
public WebResponse getResponse(WebRequest webRequest, String charset) throws IOException { initHttpClient(); switch(webRequest.getRequestMethod()) { case GET: httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpGet(webRequest.getUrl()))); break; case HEAD: httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpHead(webRequest.getUrl()))); break; case OPTIONS: httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpOptions(webRequest.getUrl()))); break; case TRACE: httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpTrace(webRequest.getUrl()))); break; case DELETE: httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpDelete(webRequest.getUrl()))); break; case POST: httpRequest.set(populateHttpEntityEnclosingRequestBaseMethod(webRequest, new HttpPost(webRequest.getUrl()))); break; case PUT: httpRequest.set(populateHttpEntityEnclosingRequestBaseMethod(webRequest, new HttpPut(webRequest.getUrl()))); break; default: throw new RuntimeException("Method not yet supported: " + webRequest.getRequestMethod()); } WebResponse resp; HttpResponse response = executeMethod(httpRequest.get()); if (response == null) { throw new IOException("LIGHTHTTP. An empty response received from server. Possible reason: host is offline"); } resp = processResponse(response, httpRequest.get(), charset); httpRequest.set(null); return resp; }
Code Sample 2:
public static String digest(String password) { try { byte[] digest; synchronized (__md5Lock) { if (__md == null) { try { __md = MessageDigest.getInstance("MD5"); } catch (Exception e) { Log.warn(e); return null; } } __md.reset(); __md.update(password.getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } return __TYPE + TypeUtil.toString(digest, 16); } catch (Exception e) { Log.warn(e); return null; } } |
00
| Code Sample 1:
public void fetchKey() throws IOException { String strurl = MessageFormat.format(keyurl, new Object[] { username, secret, login, session }); StringBuffer result = new StringBuffer(); BufferedReader reader = null; URL url = null; try { url = new URL(strurl); reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { result.append(line); } } finally { try { if (reader != null) reader.close(); } catch (Exception e) { } } Pattern p = Pattern.compile("<key>(.*)</key>"); Matcher m = p.matcher(result.toString()); if (m.matches()) { this.key = m.group(1); } }
Code Sample 2:
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; } |
11
| Code Sample 1:
public String openFileAsText(String resource) throws IOException { StringWriter wtr = new StringWriter(); InputStreamReader rdr = new InputStreamReader(openFile(resource)); try { IOUtils.copy(rdr, wtr); } finally { IOUtils.closeQuietly(rdr); } return wtr.toString(); }
Code Sample 2:
public static void copy(String file1, String file2) throws IOException { File inputFile = new File(file1); File outputFile = new File(file2); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); System.out.println("Copy file from: " + file1 + " to: " + file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } |
00
| Code Sample 1:
private boolean authenticate(String reply) { String user = reply.substring(0, reply.indexOf(" ")); String resp = reply.substring(reply.indexOf(" ") + 1); if (!module.users.contains(user)) { error = "so such user " + user; return false; } try { LineNumberReader secrets = new LineNumberReader(new FileReader(module.secretsFile)); String line; while ((line = secrets.readLine()) != null) { if (line.startsWith(user + ":")) { MessageDigest md4 = MessageDigest.getInstance("BrokenMD4"); md4.update(new byte[4]); md4.update(line.substring(line.indexOf(":") + 1).getBytes("US-ASCII")); md4.update(challenge.getBytes("US-ASCII")); String hash = Util.base64(md4.digest()); if (hash.equals(resp)) { secrets.close(); return true; } } } secrets.close(); } catch (Exception e) { logger.fatal(e.toString()); error = "server configuration error"; return false; } error = "authentication failure for module " + module.name; return false; }
Code Sample 2:
public static Document getSkeleton() { Document doc = null; String filesep = System.getProperty("file.separator"); try { java.net.URL url = Skeleton.class.getResource(filesep + "simplemassimeditor" + filesep + "resources" + filesep + "configskeleton.xml"); InputStream input = url.openStream(); DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); try { doc = parser.parse(input); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return doc; } |
11
| Code Sample 1:
private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } } |
00
| Code Sample 1:
public void setInitialValues(String Tag, Vector subfields) { this.tftag.setText(Tag); presentineditor = new ArrayList(); this.glosf = subfields; for (int i = 0; i < subfields.size(); i++) { this.dlm2.addElement(subfields.elementAt(i).toString().trim()); presentineditor.add(subfields.elementAt(i).toString().trim()); } String xmlreq = CataloguingXMLGenerator.getInstance().getSubFieldsRepeat("5", Tag); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "MarcDictionaryServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element retroot = retdoc.getRootElement(); hashtable = new Hashtable(); List list = retroot.getChildren(); System.out.println("Point of execution came here " + list.size()); for (int i = 0; i < list.size(); i++) { List chilist = ((Element) list.get(i)).getChildren(); hashtable.put(((Element) chilist.get(0)).getText().trim(), ((Element) chilist.get(1)).getText().trim()); } System.out.println(hashtable); Enumeration keys = hashtable.keys(); while (keys.hasMoreElements()) this.dlm1.addElement(keys.nextElement()); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
public void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } } |
00
| Code Sample 1:
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 = LocalNameGenerator.class.getResource("/" + 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; } } }
Code Sample 2:
public static String post(String url, Map params, String line_delimiter) { String response = ""; try { URL _url = new URL(url); URLConnection conn = _url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); String postdata = ""; int mapsize = params.size(); Iterator keyValue = params.entrySet().iterator(); for (int i = 0; i < mapsize; i++) { Map.Entry entry = (Map.Entry) keyValue.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (i > 0) postdata += "&"; postdata += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); } wr.write(postdata); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) response += line + line_delimiter; wr.close(); rd.close(); } catch (Exception e) { System.err.println(e); } return response; } |
11
| Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; } |
11
| Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { BufferedInputStream is = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[1024]; int count = 0; while ((count = is.read(buf, 0, 1024)) != -1) os.write(buf, 0, count); is.close(); os.close(); }
Code Sample 2:
private void tar(FileHolder fileHolder, boolean gzipIt) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File tarDestFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(tarDestFile); if (gzipIt) { outStream = new GZIPOutputStream(outStream); } TarOutputStream tarOutStream = new TarOutputStream(outStream); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); TarEntry tarEntry = null; try { tarEntry = new TarEntry(selectedFile, selectedFile.getName()); } catch (InvalidHeaderException e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + selectedFile); logger.logError(errEntry); } tarOutStream.putNextEntry(tarEntry); while ((bytes_read = inStream.read(buffer)) != -1) { tarOutStream.write(buffer, 0, bytes_read); } tarOutStream.closeEntry(); inStream.close(); super.processorSyncFlag.restartWaitUntilFalse(); } tarOutStream.close(); } catch (Exception e) { errEntry.setThrowable(e); errEntry.setAppContext("tar()"); errEntry.setAppMessage("Error tar'ing: " + tarDestFile); logger.logError(errEntry); } } |
00
| Code Sample 1:
private String MD5(String s) { Log.d("MD5", "Hashing '" + s + "'"); String hash = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); hash = new BigInteger(1, m.digest()).toString(16); Log.d("MD5", "Hash: " + hash); } catch (Exception e) { Log.e("MD5", e.getMessage()); } return hash; }
Code Sample 2:
public T04MixedOTSDTMUnitTestCase(String name) throws java.io.IOException { super(name); java.net.URL url = ClassLoader.getSystemResource("host0.cosnaming.jndi.properties"); jndiProps = new java.util.Properties(); jndiProps.load(url.openStream()); } |
00
| Code Sample 1:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
Code Sample 2:
public static void downloadFromUrl(URL url, String localFilename, String userAgent) throws IOException { InputStream is = null; FileOutputStream fos = null; System.setProperty("java.net.useSystemProxies", "true"); try { URLConnection urlConn = url.openConnection(); if (userAgent != null) { urlConn.setRequestProperty("User-Agent", userAgent); } is = urlConn.getInputStream(); fos = new FileOutputStream(localFilename); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { try { if (is != null) { is.close(); } } finally { if (fos != null) { fos.close(); } } } } |
00
| Code Sample 1:
public String[] retrieveFasta(String id) throws Exception { URL url = new URL("http://www.ebi.ac.uk/ena/data/view/" + id + "&display=fasta"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String header = reader.readLine(); StringBuffer seq = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { seq.append(line); } reader.close(); return new String[] { header, seq.toString() }; }
Code Sample 2:
private SystemProperties() { Properties p = new Properties(); ClassLoader classLoader = getClass().getClassLoader(); try { URL url = classLoader.getResource("system.properties"); if (url != null) { InputStream is = url.openStream(); p.load(is); is.close(); System.out.println("Loading " + url); } } catch (Exception e) { e.printStackTrace(); } try { URL url = classLoader.getResource("system-ext.properties"); if (url != null) { InputStream is = url.openStream(); p.load(is); is.close(); System.out.println("Loading " + url); } } catch (Exception e) { e.printStackTrace(); } boolean systemPropertiesLoad = GetterUtil.get(System.getProperty(SYSTEM_PROPERTIES_LOAD), true); boolean systemPropertiesFinal = GetterUtil.get(System.getProperty(SYSTEM_PROPERTIES_FINAL), true); if (systemPropertiesLoad) { Enumeration enu = p.propertyNames(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); if (systemPropertiesFinal || Validator.isNull(System.getProperty(key))) { System.setProperty(key, (String) p.get(key)); } } } PropertiesUtil.fromProperties(p, _props); } |
11
| Code Sample 1:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String act = request.getParameter("act"); if (null == act) { } else if ("down".equalsIgnoreCase(act)) { String vest = request.getParameter("vest"); String id = request.getParameter("id"); if (null == vest) { t_attach_Form attach = null; t_attach_QueryMap query = new t_attach_QueryMap(); attach = query.getByID(id); if (null != attach) { String filename = attach.getAttach_name(); String fullname = attach.getAttach_fullname(); response.addHeader("Content-Disposition", "attachment;filename=" + filename + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); } } } else if ("review".equalsIgnoreCase(vest)) { t_infor_review_QueryMap reviewQuery = new t_infor_review_QueryMap(); t_infor_review_Form review = reviewQuery.getByID(id); String seq = request.getParameter("seq"); String name = null, fullname = null; if ("1".equals(seq)) { name = review.getAttachname1(); fullname = review.getAttachfullname1(); } else if ("2".equals(seq)) { name = review.getAttachname2(); fullname = review.getAttachfullname2(); } else if ("3".equals(seq)) { name = review.getAttachname3(); fullname = review.getAttachfullname3(); } String downTypeStr = DownType.getInst().getDownTypeByFileName(name); logger.debug("filename=" + name + " downtype=" + downTypeStr); response.setContentType(downTypeStr); response.addHeader("Content-Disposition", "attachment;filename=" + name + ""); File file = new File(fullname); if (file.exists()) { java.io.FileInputStream in = new FileInputStream(file); org.apache.commons.io.IOUtils.copy(in, response.getOutputStream()); in.close(); } } } else if ("upload".equalsIgnoreCase(act)) { String infoId = request.getParameter("inforId"); logger.debug("infoId=" + infoId); } } catch (Exception e) { } }
Code Sample 2:
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(); } } } |
00
| Code Sample 1:
private void importUrl(String str) throws Exception { URL url = new URL(str); InputStream xmlStream = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); MessageHolder messages = MessageHolder.getInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlStream); Element rootElement = document.getDocumentElement(); EntrySetParser entrySetParser = new EntrySetParser(); EntrySetTag entrySet = entrySetParser.process(rootElement); UpdateProteinsI proteinFactory = new UpdateProteins(); BioSourceFactory bioSourceFactory = new BioSourceFactory(); ControlledVocabularyRepository.check(); EntrySetChecker.check(entrySet, proteinFactory, bioSourceFactory); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printCheckerReport(System.err); } else { EntrySetPersister.persist(entrySet); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printPersisterReport(System.err); } else { System.out.println("The data have been successfully saved in your Intact node."); } } }
Code Sample 2:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } |
11
| Code Sample 1:
public boolean refresh() { try { synchronized (text) { stream = (new URL(url)).openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; StringBuilder sb = new StringBuilder(); while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } text = sb.toString(); } price = 0; date = null; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return false; } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
11
| Code Sample 1:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
Code Sample 2:
public void end() throws Exception { handle.waitFor(); Calendar endTime = Calendar.getInstance(); File resultsDir = new File(runDir, "results"); if (!resultsDir.isDirectory()) throw new Exception("The results directory not found!"); String resHtml = null; String resTxt = null; String[] resultFiles = resultsDir.list(); for (String resultFile : resultFiles) { if (resultFile.indexOf("html") >= 0) resHtml = resultFile; else if (resultFile.indexOf("txt") >= 0) resTxt = resultFile; } if (resHtml == null) throw new IOException("SPECweb2005 output (html) file not found"); if (resTxt == null) throw new IOException("SPECweb2005 output (txt) file not found"); File resultHtml = new File(resultsDir, resHtml); copyFile(resultHtml.getAbsolutePath(), runDir + "SPECWeb-result.html", false); BufferedReader reader = new BufferedReader(new FileReader(new File(resultsDir, resTxt))); logger.fine("Text file: " + resultsDir + resTxt); Writer writer = new FileWriter(runDir + "summary.xml"); SummaryParser parser = new SummaryParser(getRunId(), startTime, endTime, logger); parser.convert(reader, writer); writer.close(); reader.close(); } |
00
| Code Sample 1:
private void onCheckConnection() { BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { public void run() { String baseUrl; if (_rdoSRTM3FtpUrl.getSelection()) { } else { baseUrl = _txtSRTM3HttpUrl.getText().trim(); try { final URL url = new URL(baseUrl); final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.connect(); final int response = urlConn.getResponseCode(); final String responseMessage = urlConn.getResponseMessage(); final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage }); MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message); } catch (final IOException e) { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl)); e.printStackTrace(); } } } }); }
Code Sample 2:
public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } |
00
| Code Sample 1:
public boolean checkConnection() { int tries = 3; for (int i = 0; i < tries; i++) { try { final URL url = new URL(wsURL); final URLConnection conn = url.openConnection(); conn.setReadTimeout(3000); conn.getContent(); return true; } catch (IOException ex) { Logger.getLogger(ExternalSalesHelper.class.getName()).log(Level.SEVERE, null, ex); } try { Thread.currentThread().sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(OrdersSync.class.getName()).log(Level.SEVERE, null, ex); } } return false; }
Code Sample 2:
public void createBankSignature() { byte b; try { _bankMessageDigest = MessageDigest.getInstance("MD5"); _bankSig = Signature.getInstance("MD5/RSA/PKCS#1"); _bankSig.initSign((PrivateKey) _bankPrivateKey); _bankMessageDigest.update(getBankString().getBytes()); _bankMessageDigestBytes = _bankMessageDigest.digest(); _bankSig.update(_bankMessageDigestBytes); _bankSignatureBytes = _bankSig.sign(); } catch (Exception e) { } ; } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void copyFile(String from, String to) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File inScriptFile = null; try { inScriptFile = new File(monitorCallShellScriptUrl.toURI()); } catch (URISyntaxException e) { throw e; } File outScriptFile = new File(to); FileChannel inChannel = new FileInputStream(inScriptFile).getChannel(); FileChannel outChannel = new FileOutputStream(outScriptFile).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } } |
00
| Code Sample 1:
public void updatePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "update WM_PORTAL_PORTLET_NAME " + "set TYPE=? " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); ps.setString(1, portletNameBean.getPortletName()); RsetTools.setLong(ps, 2, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
Code Sample 2:
private static Pair<URL, DTObject> loadRecruitersConf(URL url) throws ExternalConfigException, SyntaxException, IOException { Assert.notNullArg(url, "resourceName may not be null"); InputStream is = url.openStream(); try { Object value = ObjectParser.parse(is); if (!(value instanceof DTObject)) { throw new ExternalConfigException("The global value in " + url + " must be a DTObject"); } return new Pair<URL, DTObject>(url, (DTObject) value); } finally { is.close(); } } |
00
| Code Sample 1:
public Vector downSync(Vector v) throws SQLException { Vector retVector = new Vector(); try { con = allocateConnection(tableName); PreparedStatement update = con.prepareStatement("update cont_Contact set owner=?,firstname=?," + "lastname=?,nickname=?,title=?,organization=?,orgunit=?," + "emailaddr=?,homeph=?,workph=?,cellph=?,im=?,imno=?," + "fax=?,homeaddr=?,homelocality=?,homeregion=?," + "homepcode=?,homecountry=?,workaddr=?,worklocality=?," + "workregion=?,workpcode=?,workcountry=?,website=?," + "wapsite=?,comments=?,birthday=?,syncstatus=?,dirtybits=? " + "where OId=? and syncstatus=?"); PreparedStatement insert = con.prepareStatement("insert into cont_Contact (owner,firstname,lastname," + "nickname,title,organization,orgunit,emailaddr,homeph," + "workph,cellph,im,imno,fax,homeaddr,homelocality," + "homeregion,homepcode,homecountry,workaddr,worklocality," + "workregion,workpcode,workcountry,website,wapsite," + "comments,birthday,syncstatus,dirtybits,quicklist) " + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," + "?,?,?,?,?,?,?,?)"); PreparedStatement insert1 = con.prepareStatement(DBUtil.getQueryCurrentOID(con, "cont_Contact", "newoid")); PreparedStatement delete1 = con.prepareStatement("delete from cont_Contact_Group_Rel where externalcontact=?"); PreparedStatement delete2 = con.prepareStatement("delete from cont_Contact where OId=? " + "and (syncstatus=? or syncstatus=?)"); for (int i = 0; i < v.size(); i++) { try { DO = (ExternalContactDO) v.elementAt(i); if (DO.getSyncstatus() == INSERT) { insert.setBigDecimal(1, DO.getOwner()); insert.setString(2, DO.getFirstname()); insert.setString(3, DO.getLastname()); insert.setString(4, DO.getNickname()); insert.setString(5, DO.getTitle()); insert.setString(6, DO.getOrganization()); insert.setString(7, DO.getOrgunit()); insert.setString(8, DO.getEmail()); insert.setString(9, DO.getHomeph()); insert.setString(10, DO.getWorkph()); insert.setString(11, DO.getCellph()); insert.setString(12, DO.getIm()); insert.setString(13, DO.getImno()); insert.setString(14, DO.getFax()); insert.setString(15, DO.getHomeaddr()); insert.setString(16, DO.getHomelocality()); insert.setString(17, DO.getHomeregion()); insert.setString(18, DO.getHomepcode()); insert.setString(19, DO.getHomecountry()); insert.setString(20, DO.getWorkaddr()); insert.setString(21, DO.getWorklocality()); insert.setString(22, DO.getWorkregion()); insert.setString(23, DO.getWorkpcode()); insert.setString(24, DO.getWorkcountry()); insert.setString(25, DO.getWebsite()); insert.setString(26, DO.getWapsite()); insert.setString(27, DO.getComments()); if (DO.getBirthday() != null) insert.setDate(28, DO.getBirthday()); else insert.setNull(28, Types.DATE); insert.setInt(29, RESET); insert.setInt(30, RESET); insert.setInt(31, 0); con.executeUpdate(insert, null); con.reset(); rs = con.executeQuery(insert1, null); if (rs.next()) DO.setOId(rs.getBigDecimal("newoid")); con.reset(); retVector.add(DO); } else if (DO.getSyncstatus() == UPDATE) { update.setBigDecimal(1, DO.getOwner()); update.setString(2, DO.getFirstname()); update.setString(3, DO.getLastname()); update.setString(4, DO.getNickname()); update.setString(5, DO.getTitle()); update.setString(6, DO.getOrganization()); update.setString(7, DO.getOrgunit()); update.setString(8, DO.getEmail()); update.setString(9, DO.getHomeph()); update.setString(10, DO.getWorkph()); update.setString(11, DO.getCellph()); update.setString(12, DO.getIm()); update.setString(13, DO.getImno()); update.setString(14, DO.getFax()); update.setString(15, DO.getHomeaddr()); update.setString(16, DO.getHomelocality()); update.setString(17, DO.getHomeregion()); update.setString(18, DO.getHomepcode()); update.setString(19, DO.getHomecountry()); update.setString(20, DO.getWorkaddr()); update.setString(21, DO.getWorklocality()); update.setString(22, DO.getWorkregion()); update.setString(23, DO.getWorkpcode()); update.setString(24, DO.getWorkcountry()); update.setString(25, DO.getWebsite()); update.setString(26, DO.getWapsite()); update.setString(27, DO.getComments()); if (DO.getBirthday() != null) update.setDate(28, DO.getBirthday()); else update.setNull(28, Types.DATE); update.setInt(29, RESET); update.setInt(30, RESET); update.setBigDecimal(31, DO.getOId()); update.setInt(32, RESET); if (con.executeUpdate(update, null) < 1) retVector.add(DO); con.reset(); } else if (DO.getSyncstatus() == DELETE) { try { con.setAutoCommit(false); delete1.setBigDecimal(1, DO.getOId()); con.executeUpdate(delete1, null); delete2.setBigDecimal(1, DO.getOId()); delete2.setInt(2, RESET); delete2.setInt(3, DELETE); if (con.executeUpdate(delete2, null) < 1) { con.rollback(); retVector.add(DO); } else { con.commit(); } } catch (Exception e) { con.rollback(); retVector.add(DO); throw e; } finally { con.reset(); } } } catch (Exception e) { if (DO != null) logError("Sync-ExternalContactDO.owner = " + DO.getOwner().toString() + " oid = " + (DO.getOId() != null ? DO.getOId().toString() : "NULL"), e); } } if (rs != null) { rs.close(); } } catch (SQLException e) { if (DEBUG) logError("", e); throw e; } finally { release(); } return retVector; }
Code Sample 2:
private File copyFromURL(URL url, String dir) throws IOException { File urlFile = new File(url.getFile()); File dest = new File(dir, urlFile.getName()); logger.log("Extracting " + urlFile.getName() + " to " + dir + "..."); FileOutputStream os = new FileOutputStream(dest); InputStream is = url.openStream(); byte data[] = new byte[4096]; int ct; while ((ct = is.read(data)) >= 0) os.write(data, 0, ct); is.close(); os.close(); logger.log("ok\n"); return dest; } |
00
| Code Sample 1:
public static String readFromURL(String urlStr) throws IOException { URL url = new URL(urlStr); StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); return sb.toString(); }
Code Sample 2:
private void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("Filename", new StringBody(file.getName())); mpEntity.addPart("Filedata", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(mpEntity); NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine()); NULogger.getLogger().info("Now uploading your file into sharesend.com"); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); status = UploadStatus.GETTINGLINK; HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } NULogger.getLogger().log(Level.INFO, "Upload Response : {0}", uploadresponse); NULogger.getLogger().log(Level.INFO, "Download Link : http://sharesend.com/{0}", uploadresponse); downloadlink = "http://sharesend.com/" + uploadresponse; downURL = downloadlink; httpclient.getConnectionManager().shutdown(); uploadFinished(); } |
00
| Code Sample 1:
public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileInputStream lfisSourceFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) { throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer); } lfisSourceFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfisSourceFile != null) { try { lfisSourceFile.close(); } catch (Exception e) { } } } }
Code Sample 2:
public ViewedCandidatesIndex getAllViewedCandidates() throws BookKeeprCommunicationException { try { synchronized (httpClient) { HttpGet req = new HttpGet(remoteHost.getUrl() + "/cand/viewed"); req.setHeader("Accept-Encoding", "gzip"); HttpResponse resp = httpClient.execute(req); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { InputStream in = resp.getEntity().getContent(); Header hdr = resp.getFirstHeader("Content-Encoding"); String enc = ""; if (hdr != null) { enc = resp.getFirstHeader("Content-Encoding").getValue(); } if (enc.equals("gzip")) { in = new GZIPInputStream(in); } XMLAble xmlable = XMLReader.read(in); in.close(); if (xmlable instanceof ViewedCandidatesIndex) { ViewedCandidatesIndex p = (ViewedCandidatesIndex) xmlable; return p; } else { resp.getEntity().consumeContent(); throw new BookKeeprCommunicationException("BookKeepr returned the wrong thing for ViewedCandidatesIndex"); } } catch (SAXException ex) { Logger.getLogger(BookKeeprConnection.class.getName()).log(Level.WARNING, "Got a malformed message from the bookkeepr", ex); throw new BookKeeprCommunicationException(ex); } } else { throw new BookKeeprCommunicationException("Got a " + resp.getStatusLine().getStatusCode() + " from the BookKeepr"); } } } catch (HttpException ex) { throw new BookKeeprCommunicationException(ex); } catch (IOException ex) { throw new BookKeeprCommunicationException(ex); } catch (URISyntaxException ex) { throw new BookKeeprCommunicationException(ex); } } |
11
| Code Sample 1:
public void actionPerformed(ActionEvent evt) { try { File tempFile = new File("/tmp/controler.xml"); File f = new File("/tmp/controler-temp.xml"); BufferedInputStream copySource = new BufferedInputStream(new FileInputStream(tempFile)); BufferedOutputStream copyDestination = new BufferedOutputStream(new FileOutputStream(f)); int read = 0; while (read != -1) { read = copySource.read(buffer, 0, BUFFER_SIZE); if (read != -1) { copyDestination.write(buffer, 0, read); } } copyDestination.write(new String("</log>\n").getBytes()); copySource.close(); copyDestination.close(); XMLParser parser = new XMLParser("Controler"); parser.parse(f); f.delete(); } catch (IOException ex) { System.out.println("An error occured during the file copy!"); } }
Code Sample 2:
public static File gzipLog() throws IOException { RunnerClass.nfh.flush(); File log = new File(RunnerClass.homedir + "pj.log"); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File(log.getCanonicalPath() + ".pjl"))); FileInputStream in = new FileInputStream(log); int bufferSize = 4 * 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) out.write(buffer, 0, bytesRead); out.close(); in.close(); return new File(log.getCanonicalPath() + ".pjl"); } |
11
| Code Sample 1:
public static byte[] encrypt(String x) throws NoSuchAlgorithmException { MessageDigest d = null; d = MessageDigest.getInstance("SHA-1"); d.reset(); d.update(x.getBytes()); return d.digest(); }
Code Sample 2:
public void print(PrintWriter out) { out.println("<?xml version=\"1.0\"?>\n" + "<?xml-stylesheet type=\"text/xsl\" href=\"http://www.urbigene.com/foaf/foaf2html.xsl\" ?>\n" + "<rdf:RDF \n" + "xml:lang=\"en\" \n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" \n" + "xmlns=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"); out.println("<!-- generated with SciFoaf http://www.urbigene.com/foaf -->"); if (this.mainAuthor == null && this.authors.getAuthorCount() > 0) { this.mainAuthor = this.authors.getAuthorAt(0); } if (this.mainAuthor != null) { out.println("<foaf:PersonalProfileDocument rdf:about=\"\">\n" + "\t<foaf:primaryTopic rdf:nodeID=\"" + this.mainAuthor.getID() + "\"/>\n" + "\t<foaf:maker rdf:resource=\"mailto:[email protected]\"/>\n" + "\t<dc:title>FOAF for " + XMLUtilities.escape(this.mainAuthor.getName()) + "</dc:title>\n" + "\t<dc:description>\n" + "\tFriend-of-a-Friend description for " + XMLUtilities.escape(this.mainAuthor.getName()) + "\n" + "\t</dc:description>\n" + "</foaf:PersonalProfileDocument>\n\n"); } for (int i = 0; i < this.laboratories.size(); ++i) { Laboratory lab = this.laboratories.getLabAt(i); out.println("<foaf:Group rdf:ID=\"laboratory_ID" + i + "\" >"); out.println("\t<foaf:name>" + XMLUtilities.escape(lab.toString()) + "</foaf:name>"); for (int j = 0; j < lab.getAuthorCount(); ++j) { out.println("\t<foaf:member rdf:resource=\"#" + lab.getAuthorAt(j).getID() + "\" />"); } out.println("</foaf:Group>\n\n"); } for (int i = 0; i < this.authors.size(); ++i) { Author author = authors.getAuthorAt(i); out.println("<foaf:Person rdf:ID=\"" + xmlName(author.getID()) + "\" >"); out.println("\t<foaf:name>" + xmlName(author.getName()) + "</foaf:name>"); out.println("\t<foaf:title>Dr</foaf:title>"); out.println("\t<foaf:family_name>" + xmlName(author.getLastName()) + "</foaf:family_name>"); if (author.getForeName() != null && author.getForeName().length() > 2) { out.println("\t<foaf:firstName>" + xmlName(author.getForeName()) + "</foaf:firstName>"); } String prop = author.getProperty("foaf:mbox"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; if (tokens[j].equals("mailto:")) continue; if (!tokens[j].startsWith("mailto:")) tokens[j] = "mailto:" + tokens[j]; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(tokens[j].getBytes()); byte[] digest = md.digest(); out.print("\t<foaf:mbox_sha1sum>"); for (int k = 0; k < digest.length; k++) { String hex = Integer.toHexString(digest[k]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); out.print(hex); } out.println("</foaf:mbox_sha1sum>"); } catch (Exception err) { out.println("\t<foaf:mbox rdf:resource=\"" + tokens[j] + "\" />"); } } } prop = author.getProperty("foaf:nick"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (tokens[j].trim().length() == 0) continue; out.println("\t<foaf:surname>" + XMLUtilities.escape(tokens[j]) + "</foaf:surname>"); } } prop = author.getProperty("foaf:homepage"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:homepage rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } out.println("\t<foaf:publications rdf:resource=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&cmd=Search&itool=pubmed_Abstract&term=" + author.getTerm() + "\"/>"); prop = author.getProperty("foaf:img"); if (prop != null) { String tokens[] = prop.split("[\t ]+"); for (int j = 0; j < tokens.length; ++j) { if (!tokens[j].trim().startsWith("http://")) continue; if (tokens[j].trim().equals("http://")) continue; out.println("\t<foaf:depiction rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>"); } } AuthorList knows = this.whoknowwho.getKnown(author); for (int j = 0; j < knows.size(); ++j) { out.println("\t<foaf:knows rdf:resource=\"#" + xmlName(knows.getAuthorAt(j).getID()) + "\" />"); } Paper publications[] = this.papers.getAuthorPublications(author).toArray(); if (!(publications.length == 0)) { HashSet meshes = new HashSet(); for (int j = 0; j < publications.length; ++j) { meshes.addAll(publications[j].meshTerms); } for (Iterator itermesh = meshes.iterator(); itermesh.hasNext(); ) { MeshTerm meshterm = (MeshTerm) itermesh.next(); out.println("\t<foaf:interest>\n" + "\t\t<rdf:Description rdf:about=\"" + meshterm.getURL() + "\">\n" + "\t\t\t<dc:title>" + XMLUtilities.escape(meshterm.toString()) + "</dc:title>\n" + "\t\t</rdf:Description>\n" + "\t</foaf:interest>"); } } out.println("</foaf:Person>\n\n"); } Paper paperarray[] = this.papers.toArray(); for (int i = 0; i < paperarray.length; ++i) { out.println("<foaf:Document rdf:about=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=pubmed&dopt=Abstract&list_uids=" + paperarray[i].getPMID() + "\">"); out.println("<dc:title>" + XMLUtilities.escape(paperarray[i].getTitle()) + "</dc:title>"); for (Iterator iter = paperarray[i].authors.iterator(); iter.hasNext(); ) { Author author = (Author) iter.next(); out.println("<dc:author rdf:resource=\"#" + XMLUtilities.escape(author.getID()) + "\"/>"); } out.println("</foaf:Document>"); } out.println("</rdf:RDF>"); } |
11
| Code Sample 1:
public void run(Preprocessor pp) throws SijappException { for (int i = 0; i < this.filenames.length; i++) { File srcFile = new File(this.srcDir, this.filenames[i]); BufferedReader reader; try { InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile), "CP1251"); reader = new BufferedReader(isr); } catch (Exception e) { throw (new SijappException("File " + srcFile.getPath() + " could not be read")); } File destFile = new File(this.destDir, this.filenames[i]); BufferedWriter writer; try { (new File(destFile.getParent())).mkdirs(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile), "CP1251"); writer = new BufferedWriter(osw); } catch (Exception e) { throw (new SijappException("File " + destFile.getPath() + " could not be written")); } try { pp.run(reader, writer); } catch (SijappException e) { try { reader.close(); } catch (IOException f) { } try { writer.close(); } catch (IOException f) { } try { destFile.delete(); } catch (SecurityException f) { } throw (new SijappException(srcFile.getPath() + ":" + e.getMessage())); } try { reader.close(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } }
Code Sample 2:
private String copyAndHash(InputStream input, File into) throws IOException { MessageDigest digest = createMessageDigest(); DigestInputStream dis = new DigestInputStream(input, digest); IOException ex; FileOutputStream fos = null; try { fos = new FileOutputStream(into); IOUtils.copyLarge(dis, fos); byte[] hash = digest.digest(); Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } return formatter.toString(); } catch (IOException e) { ex = e; } finally { IOUtils.closeQuietly(dis); IOUtils.closeQuietly(fos); } if (logger.isWarnEnabled()) logger.warn("Couldn't retrieve data from input!", ex); deleteTempFile(into); throw ex; } |
11
| Code Sample 1:
public static void copyDirs(File sourceDir, File destDir) throws IOException { if (!destDir.exists()) destDir.mkdirs(); for (File file : sourceDir.listFiles()) { if (file.isDirectory()) { copyDirs(file, new File(destDir, file.getName())); } else { FileChannel srcChannel = new FileInputStream(file).getChannel(); File out = new File(destDir, file.getName()); out.createNewFile(); FileChannel dstChannel = new FileOutputStream(out).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } }
Code Sample 2:
public static final boolean zipExtract(String zipfile, String name, String dest) { boolean f = false; try { InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); ZipInputStream zin = new ZipInputStream(in); ZipEntry e; while ((e = zin.getNextEntry()) != null) { if (e.getName().equals(name)) { FileOutputStream out = new FileOutputStream(dest); byte b[] = new byte[TEMP_FILE_BUFFER_SIZE]; int len = 0; while ((len = zin.read(b)) != -1) out.write(b, 0, len); out.close(); f = true; break; } } zin.close(); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } return (f); } |
11
| Code Sample 1:
public String obfuscateString(String string) { String obfuscatedString = null; try { MessageDigest md = MessageDigest.getInstance(ENCRYPTION_ALGORITHM); md.update(string.getBytes()); byte[] digest = md.digest(); obfuscatedString = new String(Base64.encode(digest)).replace(DELIM_PATH, '='); } catch (NoSuchAlgorithmException e) { StatusHandler.log("SHA not available", null); obfuscatedString = LABEL_FAILED_TO_OBFUSCATE; } return obfuscatedString; }
Code Sample 2:
public static String getMD5Hash(String input) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(input.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { String byteStr = Integer.toHexString(result[i]); String swap = null; switch(byteStr.length()) { case 1: swap = "0" + Integer.toHexString(result[i]); break; case 2: swap = Integer.toHexString(result[i]); break; case 8: swap = (Integer.toHexString(result[i])).substring(6, 8); break; } hexString.append(swap); } return hexString.toString(); } catch (Exception ex) { System.out.println("Fehler beim Ermitteln eines Hashs (" + ex.getMessage() + ")"); } return null; } |
11
| Code Sample 1:
public byte[] uniqueID(String name, String topic) { String key; byte[] id; synchronized (cache_) { key = name + "|" + topic; id = (byte[]) cache_.get(key); if (id == null) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); md.update(name.getBytes()); md.update(topic.getBytes()); id = md.digest(); cache_.put(key, id); if (debug_) { System.out.println("Cached " + key + " [" + id[0] + "," + id[1] + ",...]"); } } catch (NoSuchAlgorithmException e) { throw new Error("SHA not available!"); } } } return id; }
Code Sample 2:
public static String makeMD5(String input) throws Exception { String dstr = null; byte[] digest; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); digest = md.digest(); dstr = new BigInteger(1, digest).toString(16); if (dstr.length() % 2 > 0) { dstr = "0" + dstr; } } catch (Exception e) { throw new Exception("Erro inesperado em makeMD5(): " + e.toString(), e); } return dstr; } |
00
| Code Sample 1:
public static void shakeSort(int[] a) { if (a == null) { throw new IllegalArgumentException("Null-pointed array"); } int k = 0; int left = 0; int right = a.length - 1; while (right - left > 0) { k = 0; for (int i = 0; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } right = k; k = a.length - 1; for (int i = left; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } left = k; } }
Code Sample 2:
protected ResourceBundle loadBundle(String prefix) { URL url = Thread.currentThread().getContextClassLoader().getResource(prefix + ".properties"); if (url != null) { try { return new PropertyResourceBundle(url.openStream()); } catch (IOException e) { throw ThrowableManagerRegistry.caught(e); } } return null; } |
11
| Code Sample 1:
public static void copyFile5(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copyLarge(in, out); in.close(); out.close(); }
Code Sample 2:
public static long checksum(IFile file) throws IOException { InputStream contents; try { contents = file.getContents(); } catch (CoreException e) { throw new CausedIOException("Failed to calculate checksum.", e); } CheckedInputStream in = new CheckedInputStream(contents, new Adler32()); try { IOUtils.copy(in, new NullOutputStream()); } catch (IOException e) { throw new CausedIOException("Failed to calculate checksum.", e); } finally { IOUtils.closeQuietly(in); } return in.getChecksum().getValue(); } |
11
| Code Sample 1:
public void parseFile(String filespec, URL documentBase) { DataInputStream in = null; if (filespec == null || filespec.length() == 0) { in = new DataInputStream(System.in); } else { try { URL url = null; if (documentBase == null && _documentBase != null) { documentBase = _documentBase; } if (documentBase == null) { url = new URL(filespec); } else { try { url = new URL(documentBase, filespec); } catch (NullPointerException e) { url = new URL(filespec); } } in = new DataInputStream(url.openStream()); } catch (MalformedURLException e) { try { in = new DataInputStream(new FileInputStream(filespec)); } catch (FileNotFoundException me) { _errorMsg = new String[2]; _errorMsg[0] = "File not found: " + filespec; _errorMsg[1] = me.getMessage(); return; } catch (SecurityException me) { _errorMsg = new String[2]; _errorMsg[0] = "Security Exception: " + filespec; _errorMsg[1] = me.getMessage(); return; } } catch (IOException ioe) { _errorMsg = new String[3]; _errorMsg[0] = "Failure opening URL: "; _errorMsg[1] = " " + filespec; _errorMsg[2] = ioe.getMessage(); return; } } try { BufferedReader din = new BufferedReader(new InputStreamReader(in)); String line = din.readLine(); while (line != null) { _parseLine(line); line = din.readLine(); } } catch (MalformedURLException e) { _errorMsg = new String[2]; _errorMsg[0] = "Malformed URL: " + filespec; _errorMsg[1] = e.getMessage(); return; } catch (IOException e) { _errorMsg = new String[2]; _errorMsg[0] = "Failure reading data: " + filespec; _errorMsg[1] = e.getMessage(); _errorMsg[1] = e.getMessage(); } finally { try { in.close(); } catch (IOException me) { } } }
Code Sample 2:
private void getRdfResponse(StringBuilder sb, String url) { try { String inputLine = null; BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while ((inputLine = reader.readLine()) != null) { sb.append(inputLine); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
private static void copyObjects(File[] source, String target) { for (int i = 0; i < source.length; i++) { try { File inputFile = source[i]; File outputFile = new File(target + source[i].getName()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int j = 0; j < ex.getStackTrace().length; j++) Logger.error(" " + ex.getStackTrace()[j].toString()); ex.printStackTrace(); } } }
Code Sample 2:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } |
11
| Code Sample 1:
public static boolean copyFile(File soureFile, File destFile) { boolean copySuccess = false; if (soureFile != null && destFile != null && soureFile.exists()) { try { new File(destFile.getParent()).mkdirs(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(soureFile)); for (int currentByte = in.read(); currentByte != -1; currentByte = in.read()) out.write(currentByte); in.close(); out.close(); copySuccess = true; } catch (Exception e) { copySuccess = false; } } return copySuccess; }
Code Sample 2:
private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } |
00
| Code Sample 1:
private InputStream getStreamFromUrl(URL url, String notFoundMessage) throws ApolloAdapterException { InputStream stream = null; if (url == null) { String message = "Couldn't find url for " + filename; logger.error(message); throw new ApolloAdapterException(message); } if (url != null) { try { stream = url.openStream(); } catch (IOException e) { logger.error(e.getMessage(), e); stream = null; throw new ApolloAdapterException(e); } } return stream; }
Code Sample 2:
public static String md5hash(String text) { java.security.MessageDigest md; try { md = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.update(text.getBytes()); byte[] md5bytes = md.digest(); return new String(org.apache.commons.codec.binary.Hex.encodeHex(md5bytes)); } |
00
| Code Sample 1:
protected void downgradeHistory(Collection<String> versions) { Assert.notEmpty(versions); try { Connection connection = this.database.getDefaultConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE " + this.logTableName + " SET RESULT = 'DOWNGRADED' WHERE TYPE = 'B' AND TARGET = ? AND RESULT = 'COMPLETE'"); boolean commit = false; try { for (String version : versions) { statement.setString(1, version); int modified = statement.executeUpdate(); Assert.isTrue(modified <= 1, "Expecting not more than 1 record to be updated, not " + modified); } commit = true; } finally { statement.close(); if (commit) connection.commit(); else connection.rollback(); } } catch (SQLException e) { throw new SystemException(e); } }
Code Sample 2:
protected void readInput(String filename, List<String> list) throws IOException { URL url = GeneratorBase.class.getResource(filename); if (url == null) { throw new FileNotFoundException("specified file not available - " + filename); } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { list.add(line.trim()); } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } |
11
| Code Sample 1:
public void execute(File tsvFile, File xmlFile) { BufferedReader reader = null; Writer writer = null; Boolean isFileSuccessfullyConverted = Boolean.TRUE; TableConfiguration tableConfig = null; try { xmlFile.getParentFile().mkdirs(); reader = new BufferedReader(new InputStreamReader(new FileInputStream(tsvFile), INPUT_ENCODING)); writer = new OutputStreamWriter(new FileOutputStream(xmlFile), OUTPUT_ENCODING); tableConfig = Tsv2DocbookConverter.convert2(tableConfigManager, idScanner.extractIdentification(tsvFile), reader, writer, inputPolisher); isFileSuccessfullyConverted = (tableConfig != null); } catch (UnsupportedEncodingException e) { logger.error("Failed to create reader with UTF-8 encoding: " + e.getMessage(), e); } catch (FileNotFoundException fnfe) { logger.error("Failed to open tsv input file '" + tsvFile + "'. " + fnfe.getMessage()); } catch (Throwable cause) { logger.error("Failed to convert input tsv file '" + tsvFile + "'.", cause); } finally { if (reader != null) { try { reader.close(); } catch (IOException ioe) { logger.warn("Unable to close input file.", ioe); } } if (writer != null) { try { writer.close(); } catch (IOException ioe) { logger.warn("Unable to close output file.", ioe); } } } if (isFileSuccessfullyConverted) { String newOutputFileName = tableConfig.getFileName(idScanner.extractIdentification(tsvFile)); if (newOutputFileName != null) { File newOutputFile = new File(xmlFile.getParentFile(), newOutputFileName); if (!xmlFile.renameTo(newOutputFile)) { logger.warn("Unable to rename '" + xmlFile + "' to '" + newOutputFile + "'."); logger.info("Created successfully '" + xmlFile + "'."); } else { logger.info("Created successfully '" + newOutputFileName + "'."); } } else { logger.info("Created successfully '" + xmlFile + "'."); } } else { logger.warn("Unable to convert input tsv file '" + Tsv2DocBookApplication.trimPath(sourceDir, tsvFile) + "' to docbook."); if (xmlFile.exists() && !xmlFile.delete()) { logger.warn("Unable to remove (empty) output file '" + xmlFile + "', which was created as target for the docbook table."); } } }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } |
11
| Code Sample 1:
public static void copyFile(FileInputStream source, FileOutputStream target) throws Exception { FileChannel inChannel = source.getChannel(); FileChannel outChannel = target.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESENC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.encrypt(reader, writer, key, mode); } |
00
| Code Sample 1:
public APIResponse create(Item item) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/item/create").openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setUseCaches(false); connection.setConnectTimeout(TIMEOUT); connection.connect(); marshaller.marshal(item, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8"))); connection.getOutputStream().flush(); connection.getOutputStream().close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine())); response.setDone(true); response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration())))); connection.getInputStream().close(); } else { response.setDone(false); response.setMessage("Create Item Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
Code Sample 2:
public void run() { BufferedInputStream bis = null; URLConnection url = null; String textType = null; StringBuffer sb = new StringBuffer(); try { if (!location.startsWith("http://")) { location = "http://" + location; } url = (new URL(location)).openConnection(); size = url.getContentLength(); textType = url.getContentType(); lastModified = url.getIfModifiedSince(); InputStream is = url.getInputStream(); bis = new BufferedInputStream(is); if (textType.startsWith("text/plain")) { int i; i = bis.read(); ++position; status = " Reading From URL..."; this.setChanged(); this.notifyObservers(); while (i != END_OF_STREAM) { sb.append((char) i); i = bis.read(); ++position; if (position % (size / 25) == 0) { this.setChanged(); this.notifyObservers(); } if (abortLoading) { break; } } status = " Finished reading URL..."; } else if (textType.startsWith("text/html")) { int i; i = bis.read(); char c = (char) i; ++position; status = " Reading From URL..."; this.setChanged(); this.notifyObservers(); boolean enclosed = false; if (c == '<') { enclosed = true; } while (i != END_OF_STREAM) { if (enclosed) { if (c == '>') { enclosed = false; } } else { if (c == '<') { enclosed = true; } else { sb.append((char) i); } } i = bis.read(); c = (char) i; ++position; if (size == 0) { if (position % (size / 25) == 0) { this.setChanged(); this.notifyObservers(); } } if (abortLoading) { break; } } status = " Finished reading URL..."; } else { status = " Unable to read document type: " + textType + "..."; } bis.close(); try { document.insertString(0, sb.toString(), SimpleAttributeSet.EMPTY); } catch (BadLocationException ble) { ble.printStackTrace(); } finished = true; this.setChanged(); this.notifyObservers(); } catch (IOException ioe) { try { document.insertString(0, sb.toString(), SimpleAttributeSet.EMPTY); } catch (BadLocationException ble) { ble.printStackTrace(); } status = " IO Error Reading From URL..."; finished = true; this.setChanged(); this.notifyObservers(); } } |
11
| Code Sample 1:
private String convert(InputStream input, String encoding) throws Exception { Process p = Runtime.getRuntime().exec("tidy -q -f /dev/null -wrap 0 --output-xml yes --doctype omit --force-output true --new-empty-tags " + emptyTags + " --quote-nbsp no -utf8"); Thread t = new CopyThread(input, p.getOutputStream()); t.start(); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(p.getInputStream(), output); p.waitFor(); t.join(); 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 createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); }
Code Sample 2:
private Reader getReader(String uri, Query query) throws SourceException { if (OntoramaConfig.DEBUG) { System.out.println("uri = " + uri); } InputStreamReader reader = null; try { System.out.println("class UrlSource, uri = " + uri); URL url = new URL(uri); URLConnection connection = url.openConnection(); reader = new InputStreamReader(connection.getInputStream()); } catch (MalformedURLException urlExc) { throw new SourceException("Url " + uri + " specified for this ontology source is not well formed, error: " + urlExc.getMessage()); } catch (IOException ioExc) { throw new SourceException("Couldn't read input data source for " + uri + ", error: " + ioExc.getMessage()); } return reader; } |
11
| Code Sample 1:
private String transferWSDL(String usernameAndPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (this.password != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(usernameAndPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { logger.error("Failed to download wsdl from URL : " + wsdlURL); throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
Code Sample 2:
public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException { LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'."); assert (file.exists() && file.isFile()); if (targetDirectory.exists() == false) { LOG.debug("Creating target directory."); if (targetDirectory.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!"); } } ZipInputStream zipin = null; try { zipin = new ZipInputStream(new FileInputStream(file)); ZipEntry nextZipEntry = zipin.getNextEntry(); while (nextZipEntry != null) { LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'."); if (nextZipEntry.isDirectory()) { LOG.debug("Skipping directory."); continue; } final File targetFile = new File(targetDirectory, nextZipEntry.getName()); final File parentTargetFile = targetFile.getParentFile(); if (parentTargetFile.exists() == false) { LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'."); if (parentTargetFile.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!"); } } InputStream input = null; FileOutputStream output = null; try { input = zipFile.getInputStream(nextZipEntry); if (targetFile.createNewFile() == false) { throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!"); } output = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = input.read(buffer, 0, buffer.length); while (readBytes > 0) { output.write(buffer, 0, readBytes); readBytes = input.read(buffer, 0, buffer.length); } } finally { PtCloseUtil.close(input, output); } nextZipEntry = zipin.getNextEntry(); } } catch (IOException e) { throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(zipin); } } |
00
| Code Sample 1:
public static String md5String(String string) { try { MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(string.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); String result = ""; for (int i = 0; i < digest.length; i++) { int value = digest[i]; if (value < 0) value += 256; result += Integer.toHexString(value); } return result; } catch (UnsupportedEncodingException error) { throw new IllegalArgumentException(error); } catch (NoSuchAlgorithmException error) { throw new IllegalArgumentException(error); } }
Code Sample 2:
public void copyTo(String newname) throws IOException { FileChannel srcChannel = new FileInputStream(dosname).getChannel(); FileChannel dstChannel = new FileOutputStream(newname).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } |
11
| Code Sample 1:
private static void writeBinaryFile(String filename, String target) throws IOException { File outputFile = new File(target); AgentFilesystem.forceDir(outputFile.getParent()); FileOutputStream output = new FileOutputStream(new File(target)); FileInputStream inputStream = new FileInputStream(filename); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > -1) output.write(buffer, 0, bytesRead); inputStream.close(); output.close(); }
Code Sample 2:
public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("Expected arguments: fileName log"); String fileName = args[0]; String logFile = args[1]; LineNumberReader reader = null; PrintWriter writer = null; try { Reader reader0 = new FileReader(fileName); reader = new LineNumberReader(reader0); Writer writer0 = new FileWriter(logFile); BufferedWriter writer1 = new BufferedWriter(writer0); writer = new PrintWriter(writer1); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() >= 81) { writer.println("Analyzing Sudoku #" + reader.getLineNumber()); System.out.println("Analyzing Sudoku #" + reader.getLineNumber()); Grid grid = new Grid(); for (int i = 0; i < 81; i++) { char ch = line.charAt(i); if (ch >= '1' && ch <= '9') { int value = (ch - '0'); grid.setCellValue(i % 9, i / 9, value); } } Solver solver = new Solver(grid); solver.rebuildPotentialValues(); try { Map<Rule, Integer> rules = solver.solve(null); Map<String, Integer> ruleNames = solver.toNamedList(rules); double difficulty = 0; String hardestRule = ""; for (Rule rule : rules.keySet()) { if (rule.getDifficulty() > difficulty) { difficulty = rule.getDifficulty(); hardestRule = rule.getName(); } } for (String rule : ruleNames.keySet()) { int count = ruleNames.get(rule); writer.println(Integer.toString(count) + " " + rule); System.out.println(Integer.toString(count) + " " + rule); } writer.println("Hardest technique: " + hardestRule); System.out.println("Hardest technique: " + hardestRule); writer.println("Difficulty: " + difficulty); System.out.println("Difficulty: " + difficulty); } catch (UnsupportedOperationException ex) { writer.println("Failed !"); System.out.println("Failed !"); } writer.println(); System.out.println(); writer.flush(); } else System.out.println("Skipping incomplete line: " + line); line = reader.readLine(); } writer.close(); reader.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.print("Finished."); } |
11
| Code Sample 1:
public static boolean copyFile(String sourceFileName, String destFileName) { if (sourceFileName == null || destFileName == null) return false; if (sourceFileName.equals(destFileName)) return false; try { java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); try { byte[] buf = new byte[31000]; int read = in.read(buf); while (read > -1) { out.write(buf, 0, read); read = in.read(buf); } } finally { in.close(); out.close(); } } catch (Exception e) { System.out.println(e.toString()); return false; } return true; }
Code Sample 2:
public void copyFile(String source, String destination, String description, boolean recursive) throws Exception { File sourceFile = new File(source); File destinationFile = new File(destination); if (!sourceFile.exists()) { throw new Exception("source file (" + source + ") does not exist!"); } if (!sourceFile.isFile()) { throw new Exception("source file (" + source + ") is not a file!"); } if (!sourceFile.canRead()) { throw new Exception("source file (" + source + ") is not readable!"); } if (destinationFile.exists()) { m_out.print(" - " + destination + " exists, removing... "); if (destinationFile.delete()) { m_out.println("REMOVED"); } else { m_out.println("FAILED"); throw new Exception("unable to delete existing file: " + sourceFile); } } m_out.print(" - copying " + source + " to " + destination + "... "); if (!destinationFile.getParentFile().exists()) { if (!destinationFile.getParentFile().mkdirs()) { throw new Exception("unable to create directory: " + destinationFile.getParent()); } } if (!destinationFile.createNewFile()) { throw new Exception("unable to create file: " + destinationFile); } FileChannel from = null; FileChannel to = null; try { from = new FileInputStream(sourceFile).getChannel(); to = new FileOutputStream(destinationFile).getChannel(); to.transferFrom(from, 0, from.size()); } catch (FileNotFoundException e) { throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e); } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } m_out.println("DONE"); } |
11
| Code Sample 1:
private void zip(FileHolder fileHolder, int zipCompressionLevel) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File zipDestFile = new File(fileHolder.destFiles[0]); try { ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipDestFile)); for (int i = 0; i < fileHolder.selectedFileList.size(); i++) { File selectedFile = fileHolder.selectedFileList.get(i); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); ZipEntry entry = new ZipEntry(selectedFile.getName()); outStream.setLevel(zipCompressionLevel); outStream.putNextEntry(entry); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.closeEntry(); this.inStream.close(); } outStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error zipping: " + zipDestFile); logger.logError(errEntry); } return; }
Code Sample 2:
public void updateFiles(String ourPath) { System.out.println("Update"); DataInputStream dis = null; DataOutputStream dos = null; for (int i = 0; i < newFiles.size() && i < nameNewFiles.size(); i++) { try { dis = new DataInputStream(new FileInputStream((String) newFiles.get(i))); dos = new DataOutputStream(new FileOutputStream((new StringBuilder(String.valueOf(ourPath))).append("\\").append((String) nameNewFiles.get(i)).toString())); } catch (IOException e) { System.out.println(e.toString()); System.exit(0); } try { do dos.writeChar(dis.readChar()); while (true); } catch (EOFException e) { } catch (IOException e) { System.out.println(e.toString()); } } } |
11
| Code Sample 1:
private static boolean copyFile(File src, File dest) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { e.printStackTrace(); } if (fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
public void convert(File file, String fromEncoding, String toEncoding) throws IOException { InputStream in = new FileInputStream(file); StringWriter cache = new StringWriter(); Reader reader = new InputStreamReader(in, fromEncoding); char[] buffer = new char[128]; int read; while ((read = reader.read(buffer)) > -1) { cache.write(buffer, 0, read); } reader.close(); in.close(); Log.warn(this, "read from file " + file + " (" + fromEncoding + "):" + cache); OutputStream out = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(out, toEncoding); writer.write(cache.toString()); cache.close(); writer.close(); out.close(); } |
00
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static String loadUrlContentAsString(URL url) throws IOException { char[] buf = new char[2048]; StringBuffer ret = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); for (int chars = reader.read(buf); chars != -1; chars = reader.read(buf)) { ret.append(buf, 0, chars); } reader.close(); return ret.toString(); } |
00
| Code Sample 1:
public String md5Encode(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(pass.getBytes()); byte[] result = md.digest(); return new String(result); }
Code Sample 2:
public void writeOutput(String directory) throws IOException { File f = new File(directory); int i = 0; if (f.isDirectory()) { for (AppInventorScreen screen : screens.values()) { File screenFile = new File(getScreenFilePath(f.getAbsolutePath(), screen)); screenFile.getParentFile().mkdirs(); screenFile.createNewFile(); FileWriter out = new FileWriter(screenFile); String initial = files.get(i).toString(); Map<String, String> types = screen.getTypes(); String[] lines = initial.split("\n"); for (String key : types.keySet()) { if (!key.trim().equals(screen.getName().trim())) { String value = types.get(key); boolean varFound = false; boolean importFound = false; for (String line : lines) { if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*=.*;$")) varFound = true; if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*;$")) varFound = true; if (line.matches("^\\s*import\\s+.*" + value + "\\s*;$")) importFound = true; } if (!varFound) initial = initial.replaceFirst("(?s)(?<=\\{\n)", "\tprivate " + value + " " + key + ";\n"); if (!importFound) initial = initial.replaceFirst("(?=import)", "import com.google.devtools.simple.runtime.components.android." + value + ";\n"); } } out.write(initial); out.close(); i++; } File manifestFile = new File(getManifestFilePath(f.getAbsolutePath(), manifest)); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); FileWriter out = new FileWriter(manifestFile); out.write(manifest.toString()); out.close(); File projectFile = new File(getProjectFilePath(f.getAbsolutePath(), project)); projectFile.getParentFile().mkdirs(); projectFile.createNewFile(); out = new FileWriter(projectFile); out.write(project.toString()); out.close(); String[] copyResourceFilenames = { "proguard.cfg", "project.properties", "libSimpleAndroidRuntime.jar", "\\.classpath", "res/drawable/icon.png", "\\.settings/org.eclipse.jdt.core.prefs" }; for (String copyResourceFilename : copyResourceFilenames) { InputStream is = getClass().getResourceAsStream("/resources/" + copyResourceFilename.replace("\\.", "")); File outputFile = new File(f.getAbsoluteFile() + File.separator + copyResourceFilename.replace("\\.", ".")); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; if (is == null) System.out.println("/resources/" + copyResourceFilename.replace("\\.", "")); if (os == null) System.out.println(f.getAbsolutePath() + File.separator + copyResourceFilename.replace("\\.", ".")); while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } for (String assetName : assets) { InputStream is = new FileInputStream(new File(assetsDir.getAbsolutePath() + File.separator + assetName)); File outputFile = new File(f.getAbsoluteFile() + File.separator + assetName); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } File assetsOutput = new File(getAssetsFilePath(f.getAbsolutePath())); new File(assetsDir.getAbsoluteFile() + File.separator + "assets").renameTo(assetsOutput); } } |
11
| Code Sample 1:
public void salva(UploadedFile imagem, Usuario usuario) { File destino; if (usuario.getId() == null) { destino = new File(pastaImagens, usuario.hashCode() + ".jpg"); } else { destino = new File(pastaImagens, usuario.getId() + ".jpg"); } try { IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino)); } catch (Exception e) { throw new RuntimeException("Erro ao copiar imagem", e); } redimensionar(destino.getPath(), destino.getPath(), "jpg", 110, 110); }
Code Sample 2:
public File copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); copyChannel(inChannel, outChannel); return out; } |
11
| Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
@SuppressWarnings("unchecked") @Override public synchronized void drop(DropTargetDropEvent arg0) { Helper.log().debug("Dropped"); Transferable t = arg0.getTransferable(); try { arg0.acceptDrop(arg0.getDropAction()); List<File> filelist = (List<File>) t.getTransferData(t.getTransferDataFlavors()[0]); for (File file : filelist) { Helper.log().debug(file.getAbsolutePath()); if (file.getName().toLowerCase().contains(".lnk")) { Helper.log().debug(file.getName() + " is a link"); File target = new File(rp.getRoot().getFullPath() + "/" + file.getName()); Helper.log().debug("I have opened the mayor at " + target.getAbsolutePath()); FileOutputStream fo = new FileOutputStream(target); FileInputStream fi = new FileInputStream(file); int i = 0; while (fi.available() > 0) { fo.write(fi.read()); System.out.print("."); i++; } Helper.log().debug(i + " bytes have been written to " + target.getAbsolutePath()); fo.close(); fi.close(); } } rp.redraw(); } catch (Throwable tr) { tr.printStackTrace(); } Helper.log().debug(arg0.getSource().toString()); }
Code Sample 2:
public static void transfer(File src, File dest, boolean removeSrc) throws FileNotFoundException, IOException { Log.warning("source: " + src); Log.warning("dest: " + dest); if (!src.canRead()) { throw new IOException("can not read src file: " + src); } if (!dest.getParentFile().isDirectory()) { if (!dest.getParentFile().mkdirs()) { throw new IOException("failed to make directories: " + dest.getParent()); } } FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); Log.warning("starting transfer from position " + fcin.position() + " to size " + fcin.size()); fcout.transferFrom(fcin, 0, fcin.size()); Log.warning("closing streams and channels"); fcin.close(); fcout.close(); fis.close(); fos.close(); if (removeSrc) { Log.warning("deleting file " + src); src.delete(); } } |
11
| Code Sample 1:
protected Configuration() { try { Enumeration<URL> resources = getClass().getClassLoader().getResources("activejdbc_models.properties"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); LogFilter.log(logger, "Load models from: " + url.toExternalForm()); InputStream inputStream = null; try { inputStream = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { String[] parts = Util.split(line, ':'); String modelName = parts[0]; String dbName = parts[1]; if (modelsMap.get(dbName) == null) { modelsMap.put(dbName, new ArrayList<String>()); } modelsMap.get(dbName).add(modelName); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) inputStream.close(); } } } catch (IOException e) { throw new InitException(e); } if (modelsMap.isEmpty()) { LogFilter.log(logger, "ActiveJDBC Warning: Cannot locate any models, assuming project without models."); return; } try { InputStream in = getClass().getResourceAsStream("/activejdbc.properties"); if (in != null) properties.load(in); } catch (Exception e) { throw new InitException(e); } String cacheManagerClass = properties.getProperty("cache.manager"); if (cacheManagerClass != null) { try { Class cmc = Class.forName(cacheManagerClass); cacheManager = (CacheManager) cmc.newInstance(); } catch (Exception e) { throw new InitException("failed to initialize a CacheManager. Please, ensure that the property " + "'cache.manager' points to correct class which extends 'activejdbc.cache.CacheManager' class and provides a default constructor.", e); } } }
Code Sample 2:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } |
00
| Code Sample 1:
public static InputStream download_file(String sessionid, String key) { InputStream is = null; String urlString = "https://s2.cloud.cm/rpc/raw?c=Storage&m=download_file&key=" + key; try { String apple = ""; URL url = new URL(urlString); Log.d("current running function name:", "download_file"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", "PHPSESSID=" + sessionid); conn.setRequestMethod("POST"); conn.setDoInput(true); is = conn.getInputStream(); return is; } catch (Exception e) { e.printStackTrace(); Log.d("download problem", "download problem"); } return is; }
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(); } |
11
| Code Sample 1:
public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } }
Code Sample 2:
public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } } |
11
| Code Sample 1:
private String getManifestVersion() { URL url = AceTree.class.getResource("/org/rhwlab/help/messages/manifest.html"); InputStream istream = null; String s = ""; try { istream = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(istream)); while (br.ready()) { s = br.readLine(); if (s.indexOf("Manifest-Version:") == 0) { s = s.substring(17); break; } System.out.println("read: " + s); } br.close(); } catch (Exception e) { e.printStackTrace(); } return "Version: " + s + C.NL; }
Code Sample 2:
public static TestResponse post(String urlString, byte[] data, String contentType, String accept) throws IOException { HttpURLConnection httpCon = null; byte[] result = null; byte[] errorResult = null; try { URL url = new URL(urlString); httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("POST"); httpCon.setRequestProperty("Content-Type", contentType); httpCon.setRequestProperty("Accept", accept); if (data != null) { OutputStream output = httpCon.getOutputStream(); output.write(data); output.close(); } BufferedInputStream in = new BufferedInputStream(httpCon.getInputStream()); ByteArrayOutputStream os = new ByteArrayOutputStream(); int next = in.read(); while (next > -1) { os.write(next); next = in.read(); } os.flush(); result = os.toByteArray(); os.close(); } catch (IOException e) { e.printStackTrace(); } finally { InputStream errorStream = httpCon.getErrorStream(); if (errorStream != null) { BufferedInputStream errorIn = new BufferedInputStream(errorStream); ByteArrayOutputStream errorOs = new ByteArrayOutputStream(); int errorNext = errorIn.read(); while (errorNext > -1) { errorOs.write(errorNext); errorNext = errorIn.read(); } errorOs.flush(); errorResult = errorOs.toByteArray(); errorOs.close(); } return new TestResponse(httpCon.getResponseCode(), errorResult, result); } } |
11
| Code Sample 1:
private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; }
Code Sample 2:
@Override public void create(DisciplinaDTO disciplina) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "insert into Disciplina select nextval('sq_Disciplina') as id, ? as nome"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setString(1, disciplina.getNome()); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de inserir dados de Disciplina no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } } |
11
| Code Sample 1:
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
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(); } |
11
| Code Sample 1:
public static boolean copy(InputStream is, File file) { try { IOUtils.copy(is, new FileOutputStream(file)); return true; } catch (Exception e) { logger.severe(e.getMessage()); return false; } }
Code Sample 2:
private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } } |
11
| Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
public void copyFile(File from, File to) { try { InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to); int readCount; byte[] bytes = new byte[1024]; while ((readCount = in.read(bytes)) != -1) { out.write(bytes, 0, readCount); } out.flush(); in.close(); out.close(); } catch (Exception ex) { throw new BuildException(ex.getMessage(), ex); } } |
11
| Code Sample 1:
public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); }
Code Sample 2:
public AssessmentItemType getAssessmentItemType(String filename) { if (filename.contains(" ") && (System.getProperty("os.name").contains("Windows"))) { File source = new File(filename); String tempDir = System.getenv("TEMP"); File dest = new File(tempDir + "/temp.xml"); MQMain.logger.info("Importing from " + dest.getAbsolutePath()); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } filename = tempDir + "/temp.xml"; } } AssessmentItemType assessmentItemType = null; JAXBElement<?> jaxbe = null; try { XMLReader reader = XMLReaderFactory.createXMLReader(); ChangeNamespace convertfromv2p0tov2p1 = new ChangeNamespace(reader, "http://www.imsglobal.org/xsd/imsqti_v2p0", "http://www.imsglobal.org/xsd/imsqti_v2p1"); SAXSource source = null; try { FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = null; try { isr = new InputStreamReader(fis, "UTF-8"); } catch (UnsupportedEncodingException e) { } InputSource is = new InputSource(isr); source = new SAXSource(convertfromv2p0tov2p1, is); } catch (FileNotFoundException e) { MQMain.logger.error("SAX/getAssessmentItemType/file not found"); } jaxbe = (JAXBElement<?>) MQModel.qtiCf.unmarshal(MQModel.imsqtiUnmarshaller, source); assessmentItemType = (AssessmentItemType) jaxbe.getValue(); } catch (JAXBException e) { MQMain.logger.error("JAX/getAssessmentItemType", e); } catch (SAXException e) { MQMain.logger.error("SAX/getAssessmentItemType", e); } return assessmentItemType; } |
11
| Code Sample 1:
static byte[] getPassword(final String name, final String password) { try { final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); messageDigest.update(name.getBytes()); messageDigest.update(password.getBytes()); return messageDigest.digest(); } catch (final NoSuchAlgorithmException e) { throw new JobException(e); } }
Code Sample 2:
private String xifraPassword() throws Exception { String password2 = instance.getUsuaris().getPassword2(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(password2.getBytes(), 0, password2.length()); password2 = new BigInteger(1, m.digest()).toString(16); return password2; } |
11
| Code Sample 1:
static String encodeEmailAsUserId(String email) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(email.toLowerCase().getBytes()); StringBuilder builder = new StringBuilder(); builder.append("1"); for (byte b : md5.digest()) { builder.append(String.format("%02d", new Object[] { Integer.valueOf(b & 0xFF) })); } return builder.toString().substring(0, 20); } catch (NoSuchAlgorithmException ex) { } return ""; }
Code Sample 2:
public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); } |
11
| Code Sample 1:
public static void copyFile(File srcFile, File dstFile) { logger.info("Create file : " + dstFile.getPath()); try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel dstChannel = new FileOutputStream(dstFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
static boolean writeProperties(Map<String, String> customProps, File destination) throws IOException { synchronized (PropertiesIO.class) { L.info(Msg.msg("PropertiesIO.writeProperties.start")); File tempFile = null; BufferedInputStream existingCfgInStream = null; FileInputStream in = null; FileOutputStream out = null; PrintStream ps = null; FileChannel fromChannel = null, toChannel = null; String line = null; try { existingCfgInStream = new BufferedInputStream(destination.exists() ? new FileInputStream(destination) : defaultPropertiesStream()); tempFile = File.createTempFile("properties-", ".tmp", null); ps = new PrintStream(tempFile); while ((line = Utils.readLine(existingCfgInStream)) != null) { String lineReady2write = setupLine(line, customProps); ps.println(lineReady2write); } destination.getParentFile().mkdirs(); in = new FileInputStream(tempFile); out = new FileOutputStream(destination, false); fromChannel = in.getChannel(); toChannel = out.getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); L.info(Msg.msg("PropertiesIO.writeProperties.done").replace("#file#", destination.getAbsolutePath())); return true; } finally { if (existingCfgInStream != null) existingCfgInStream.close(); if (ps != null) ps.close(); if (fromChannel != null) fromChannel.close(); if (toChannel != null) toChannel.close(); if (out != null) out.close(); if (in != null) in.close(); if (tempFile != null && tempFile.exists()) tempFile.delete(); } } } |
11
| Code Sample 1:
public boolean backupFile(File oldFile, File newFile) { boolean isBkupFileOK = false; FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(oldFile).getChannel(); targetChannel = new FileOutputStream(newFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying config file", e); } finally { if ((newFile != null) && (newFile.exists()) && (newFile.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.log(Level.INFO, "closing channels failed"); } } return isBkupFileOK; }
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; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.