label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: private boolean copy_to_file_io(File src, File dst) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); is = new BufferedInputStream(is); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); byte buffer[] = new byte[1024 * 64]; int read; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } return true; } finally { try { if (is != null) is.close(); } catch (IOException e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (IOException e) { Debug.debug(e); } } } Code Sample 2: public void execute(File sourceFile, File destinationFile, Properties htmlCleanerConfig) { FileReader reader = null; Writer writer = null; try { reader = new FileReader(sourceFile); logger.info("Using source file: " + trimPath(userDir, sourceFile)); if (!destinationFile.getParentFile().exists()) { createDirectory(destinationFile.getParentFile()); } writer = new FileWriter(destinationFile); logger.info("Destination file: " + trimPath(userDir, destinationFile)); execute(reader, writer, htmlCleanerConfig); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); writer = null; } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { try { reader.close(); reader = null; } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: 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; } Code Sample 2: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
11
Code Sample 1: private static String GetSHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return LoginHttpPostProcessor.ConvertToHex(sha1hash); } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 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(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
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 boolean performModuleInstallation(Model m) { String seldir = directoryHandler.getSelectedDirectory(); if (seldir == null) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A target directory must be selected."); box.open(); return false; } String sjar = pathText.getText(); File fjar = new File(sjar); if (!fjar.exists()) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("A non-existing jar file has been selected."); box.open(); return false; } int count = 0; try { URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(fjar)); JarEntry entry = jis.getNextJarEntry(); while (entry != null) { String name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); Class<?> cls = loader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) { if (!testAlgorithm(cls, m)) return false; count++; } } entry = jis.getNextJarEntry(); } } catch (Exception e1) { Application.logexcept("Could not load classes from jar file.", e1); return false; } if (count == 0) { MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); box.setText("Cannot install"); box.setMessage("There don't seem to be any algorithms in the specified module."); box.open(); return false; } try { FileChannel ic = new FileInputStream(sjar).getChannel(); FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (Exception e) { Application.logexcept("Could not install module", e); return false; } result = new Object(); return true; }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private Object[] retrieveSecondURL(URL url, RSLink link) { link.setStatus(RSLink.STATUS_WAITING); Object[] result = new Object[2]; HttpURLConnection httpConn = null; BufferedReader inr = null; DataOutputStream outs = null; Pattern mirrorLinePattern = Pattern.compile("'<input.+checked.+type=\"radio\".+name=\"mirror\".+\\\\'.+\\\\'"); Pattern mirrorUrlPattern = Pattern.compile("\\\\'.+\\\\'"); Pattern counterPattern = Pattern.compile("var c=[0-9]+;"); Pattern counterIntPattern = Pattern.compile("[0-9]+"); try { String line = null; String urlLine = null; Integer counter = null; String postData = URLEncoder.encode("dl.start", "UTF-8") + "=" + URLEncoder.encode("Free", "UTF-8"); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); httpConn.setRequestProperty("Content-Language", "en-US"); httpConn.setDoOutput(true); httpConn.setDoInput(true); outs = new DataOutputStream(httpConn.getOutputStream()); outs.writeBytes(postData); outs.flush(); inr = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); Matcher matcher = null; while ((line = inr.readLine()) != null) { matcher = mirrorLinePattern.matcher(line); if (matcher.find()) { matcher = mirrorUrlPattern.matcher(line); if (matcher.find()) { urlLine = matcher.group().substring(2, matcher.group().length() - 2); result[0] = new URL(urlLine); } } matcher = counterPattern.matcher(line); if (matcher.find()) { matcher = counterIntPattern.matcher(line); if (matcher.find()) { counter = new Integer(matcher.group()); result[1] = counter; } } } } catch (IOException ex) { log("I/O Exception!"); } finally { try { if (outs != null) outs.close(); if (inr != null) inr.close(); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Can not close some connections:\n" + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE); } if (httpConn != null) httpConn.disconnect(); link.setStatus(RSLink.STATUS_NOTHING); return result; } }
11
Code Sample 1: public static String getSHA1Digest(String inputStr) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; byte[] sha1hash = null; md = MessageDigest.getInstance("SHA"); sha1hash = new byte[40]; md.update(inputStr.getBytes("iso-8859-1"), 0, inputStr.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: private String generateCode(String seed) { try { Security.addProvider(new FNVProvider()); MessageDigest digest = MessageDigest.getInstance("FNV-1a"); digest.update((seed + UUID.randomUUID().toString()).getBytes()); byte[] hash1 = digest.digest(); String sHash1 = "m" + (new String(LibraryBase64.encode(hash1))).replaceAll("=", "").replaceAll("-", "_"); return sHash1; } catch (Exception e) { e.printStackTrace(); } return ""; }
00
Code Sample 1: public void setUp() throws Exception { logger.finer("******************** set up ********************"); Properties props; if (XMLDBTestSuite.propertiesFileName == null) { String defaultPropsFileLocation = "test/xmldb/XMLDBTestSuite.properties"; URL url = this.getClass().getClassLoader().getResource(defaultPropsFileLocation); if (url == null) { throw new Exception("failed to find default props file at " + defaultPropsFileLocation); } props = loadProps(url.openConnection().getInputStream()); } else { props = loadProps(XMLDBTestSuite.propertiesFileName); } String driver = props.getProperty("driverName"); String collectionURI = props.getProperty("URI"); Database database = (Database) Class.forName(driver).newInstance(); collectionStorageHelper = new CollectionStorageHelper(collectionURI); rootCollectionName = collectionStorageHelper.getCollectionName(); Collection root = database.getCollection(collectionURI, null, null); CollectionManagementService service = (CollectionManagementService) root.getService(CollectionManagementService.SERVICE_NAME, "1.0"); String childCollection = "child"; removeChildCollection(root, childCollection, service); col = service.createCollection(childCollection); assertNotNull("XMLDBTestCase.setUp() - Collection could not be created", col); logger.info("created child collection '" + col.getName() + "' parent is '" + col.getParentCollection().getName() + "'"); assertEquals("Root collection name should match childs parent name", rootCollectionName, col.getParentCollection().getName()); document = createXMLFile(xmlFileName); assertNotNull("XMLDBTestCase.setUp() - failed to create XML file", document); } Code Sample 2: public void save(InputStream is) throws IOException { File dest = Config.getDataFile(getInternalDate(), getPhysMessageID()); OutputStream os = null; try { os = new FileOutputStream(dest); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
00
Code Sample 1: public static String getHashedStringMD5(String value) throws java.security.NoSuchAlgorithmException { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(value.getBytes()); byte[] buf = d.digest(); return new String(buf); } Code Sample 2: private void copyFile(String path) { try { File srcfile = new File(srcdir, path); File destfile = new File(destdir, path); File parent = destfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } FileInputStream fis = new FileInputStream(srcfile); FileOutputStream fos = new FileOutputStream(destfile); int bytes_read = 0; byte buffer[] = new byte[512]; while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } fis.close(); fos.close(); } catch (IOException e) { throw new BuildException("Error while copying file " + path); } }
00
Code Sample 1: public ResourceMigrator getCompletedResourceMigrator() { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; } Code Sample 2: public void actionPerformed(ActionEvent e) { String line, days; String oldType, newType; String dept = ""; buttonPressed = true; char first; int caretIndex; int tempIndex; int oldDisplayNum = displayNum; for (int i = 0; i < 10; i++) { if (e.getSource() == imageButtons[i]) { if (rePrintAnswer) printAnswer(); print.setVisible(true); selectTerm.setVisible(true); displayNum = i; textArea2.setCaretPosition(textArea2.getText().length() - 1); caretIndex = textArea2.getText().indexOf("#" + (i + 1)); if (caretIndex != -1) textArea2.setCaretPosition(caretIndex); repaint(); } } if (e.getSource() == print) { if (textArea2.getText().charAt(0) != '#') printAnswer(); String data = textArea2.getText(); int start = data.indexOf("#" + (displayNum + 1)); start = data.indexOf("\n", start); start++; int end = data.indexOf("\n---------", start); data = data.substring(start, end); String tr = ""; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String s = getCodeBase().toString() + "schedule.cgi?term=" + tr + "&data=" + URLEncoder.encode(data); try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == webSite) { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); String s = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(lst.getSelectedItem().toString()) + "&p_course=" + num; try { AppletContext a = getAppletContext(); URL u = new URL(s); a.showDocument(u, "_blank"); } catch (MalformedURLException rea) { } } if (e.getSource() == loadButton) { printSign("Loading..."); String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); String text = readURL(fileName); if (!publicSign.equals("Error loading.")) { textArea1.setText(text); fileName += ".2"; text = readURL(fileName); absorb(text); printAnswer(); for (int i = 0; i < 10; i++) { if (answer[i].gap != -1 && answer[i].gap != 9999 && answer[i].gap != 10000) { imageButtons[i].setVisible(true); } else imageButtons[i].setVisible(false); } if (!imageButtons[0].isVisible()) { print.setVisible(false); selectTerm.setVisible(false); } else { print.setVisible(true); selectTerm.setVisible(true); } printSign("Load complete."); } displayNum = 0; repaint(); } if (e.getSource() == saveButton) { String fileName = idField.getText(); fileName = fileName.replace(' ', '_'); printSign("Saving..."); writeURL(fileName, 1); printSign("Saving......"); fileName += ".2"; writeURL(fileName, 2); printSign("Save complete."); } if (e.getSource() == instructions) { showInstructions(); } if (e.getSource() == net) { drawWarning = false; String inputLine = ""; String text = ""; String out; String urlIn = ""; textArea2.setText("Retrieving Data..."); try { String tr; if (term.getSelectedItem() == "Spring") tr = "SP"; else if (term.getSelectedItem() == "Summer") tr = "SU"; else tr = "FL"; String num = courseNum.getText().toUpperCase(); dept = lst.getSelectedItem().toString(); { urlIn = "http://sis450.berkeley.edu:4200/OSOC/osoc?p_term=" + tr + "&p_deptname=" + URLEncoder.encode(dept) + "&p_course=" + num; try { URL url = new URL(getCodeBase().toString() + "getURL.cgi"); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); DataOutputStream out2 = new DataOutputStream(con.getOutputStream()); String content = "url=" + URLEncoder.encode(urlIn); out2.writeBytes(content); out2.flush(); DataInputStream in = new DataInputStream(con.getInputStream()); String s; while ((s = in.readLine()) != null) { } in.close(); } catch (IOException err) { } } URL yahoo = new URL(this.getCodeBase(), "classData.txt"); URLConnection yc = yahoo.openConnection(); StringBuffer buf = new StringBuffer(""); DataInputStream in = new DataInputStream(new BufferedInputStream(yc.getInputStream())); while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } text = buf.toString(); in.close(); } catch (IOException errr) { } String inText = (parseData(text, false)); if (inText.equals("-1")) inText = parseData(text, true); if (inText.equals("\n")) { textArea2.append("\nNO DATA FOUND \n(" + urlIn + ")"); } else textArea1.append(inText); repaint(); } badInput = false; if (e.getSource() == button1) { if (t != null && t.isAlive()) { t.stop(); epilogue(); return; } displayNum = 0; textArea2.setCaretPosition(0); for (int i = 0; i < 30; i++) for (int j = 0; j < 20; j++) { matrix[i][j] = new entry(); matrix[i][j].time = new Time[4]; for (int k = 0; k < 4; k++) { matrix[i][j].time[k] = new Time(); matrix[i][j].time[k].from = 0; } } val = new entry[30]; for (int i = 0; i < 30; i++) { val[i] = new entry(); val[i].time = new Time[4]; for (int j = 0; j < 4; j++) { val[i].time[j] = new Time(); val[i].time[j].from = 0; } } oldPercentDone = -5; oldAmountDone = -1 * PRINTINTERVAL; percentDone = 0; amountDone = 0; drawWarning = false; errorMessage = ""; String text1 = textArea1.getText(); if (text1.toUpperCase().indexOf("OR:") == -1) containsOR = false; else containsOR = true; text1 = removeOR(text1.toUpperCase()); StringTokenizer st = new StringTokenizer(text1, "\n"); clss = -1; timeEntry = -1; boolean noTimesListed = false; while (st.hasMoreTokens()) { line = st.nextToken().toString(); if (line.equals("")) break; else first = line.charAt(0); if (first == '0') { badInput = true; repaint(); break; } if (first >= '1' && first <= '9') { noTimesListed = false; timeEntry++; if (timeEntry == 30) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 30 time entries per class."); badInput = true; repaint(); return; } nextTime = -1; StringTokenizer andST = new StringTokenizer(line, ","); while (andST.hasMoreTokens()) { String temp; String entry; int index, fromTime, toTime; nextTime++; if (nextTime == 4) { rePrintAnswer = true; textArea2.setText("Error: Exceeded 4 time intervals per entry!"); badInput = true; repaint(); return; } StringTokenizer timeST = new StringTokenizer(andST.nextToken()); temp = timeST.nextToken().toString(); entry = ""; index = 0; if (temp.equals("")) break; while (temp.charAt(index) != '-') { entry += temp.charAt(index); index++; if (index >= temp.length()) { rePrintAnswer = true; textArea2.setText("Error: There should be no space before hyphens."); badInput = true; repaint(); return; } } try { fromTime = Integer.parseInt(entry); } catch (NumberFormatException re) { rePrintAnswer = true; textArea2.setText("Error: There should be no a/p sign after FROM_TIME."); badInput = true; repaint(); return; } index++; entry = ""; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } while (temp.charAt(index) >= '0' && temp.charAt(index) <= '9') { entry += temp.charAt(index); index++; if (index >= temp.length()) { badInput = true; repaint(); rePrintAnswer = true; textArea2.setText("Error: am/pm sign missing??"); return; } } toTime = Integer.parseInt(entry); if (temp.charAt(index) == 'a' || temp.charAt(index) == 'A') { } else { if (isLesse(fromTime, toTime) && !timeEq(toTime, 1200)) { if (String.valueOf(fromTime).length() == 4 || String.valueOf(fromTime).length() == 3) { fromTime += 1200; } else fromTime += 12; } if (!timeEq(toTime, 1200)) { if (String.valueOf(toTime).length() == 4 || String.valueOf(toTime).length() == 3) { toTime += 1200; } else toTime += 12; } } if (String.valueOf(fromTime).length() == 2 || String.valueOf(fromTime).length() == 1) fromTime *= 100; if (String.valueOf(toTime).length() == 2 || String.valueOf(toTime).length() == 1) toTime *= 100; matrix[timeEntry][clss].time[nextTime].from = fromTime; matrix[timeEntry][clss].time[nextTime].to = toTime; if (timeST.hasMoreTokens()) days = timeST.nextToken().toString(); else { rePrintAnswer = true; textArea2.setText("Error: days not specified?"); badInput = true; repaint(); return; } if (days.equals("")) return; if (days.indexOf("M") != -1 || days.indexOf("m") != -1) matrix[timeEntry][clss].time[nextTime].m = 1; if (days.indexOf("TU") != -1 || days.indexOf("Tu") != -1 || days.indexOf("tu") != -1) matrix[timeEntry][clss].time[nextTime].tu = 1; if (days.indexOf("W") != -1 || days.indexOf("w") != -1) matrix[timeEntry][clss].time[nextTime].w = 1; if (days.indexOf("TH") != -1 || days.indexOf("Th") != -1 || days.indexOf("th") != -1) matrix[timeEntry][clss].time[nextTime].th = 1; if (days.indexOf("F") != -1 || days.indexOf("f") != -1) matrix[timeEntry][clss].time[nextTime].f = 1; } } else { if (noTimesListed) clss--; clss++; if (clss == 20) { rePrintAnswer = true; textArea2.setText("Error: No more than 20 class entries!"); badInput = true; repaint(); return; } timeEntry = -1; line = line.trim(); for (int i = 0; i < 30; i++) matrix[i][clss].name = line; noTimesListed = true; } } for (int i = 0; i < 30; i++) { for (int j = 0; j < 4; j++) { val[i].time[j].from = 0; } } for (int i = 0; i < 10; i++) { beat10[i] = 10000; answer[i].gap = 10000; for (int j = 0; j < 30; j++) answer[i].classes[j].name = ""; } time = 0; calcTotal = 0; int k = 0; calculateTotalPercent(0, "\n"); amountToReach = calcTotal; button1.setLabel("...HALT GENERATION..."); printWarn(); if (t != null && t.isAlive()) t.stop(); t = new Thread(this, "Generator"); t.start(); } }
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 String copyTutorial() throws IOException { File inputFile = new File(getFilenameForOriginalTutorial()); File outputFile = new File(getFilenameForCopiedTutorial()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return getFilenameForCopiedTutorial(); }
00
Code Sample 1: public void generateHtmlPage(String real_filename, String url_filename) { String str_content = ""; URL m_url = null; URLConnection m_urlcon = null; try { m_url = new URL(url_filename); m_urlcon = m_url.openConnection(); InputStream in_stream = m_urlcon.getInputStream(); byte[] bytes = new byte[1]; Vector v_bytes = new Vector(); while (in_stream.read(bytes) != -1) { v_bytes.add(bytes); bytes = new byte[1]; } byte[] all_bytes = new byte[v_bytes.size()]; for (int i = 0; i < v_bytes.size(); i++) all_bytes[i] = ((byte[]) v_bytes.get(i))[0]; str_content = new String(all_bytes, "GBK"); } catch (Exception urle) { } try { oaFileOperation file_control = new oaFileOperation(); file_control.writeFile(str_content, real_filename, true); String strPath = url_filename.substring(0, url_filename.lastIndexOf("/") + 1); String strUrlFileName = url_filename.substring(url_filename.lastIndexOf("/") + 1); if (strUrlFileName.indexOf(".jsp") > 0) { strUrlFileName = strUrlFileName.substring(0, strUrlFileName.indexOf(".jsp")) + "_1.jsp"; m_url = new URL(strPath + strUrlFileName); m_url.openConnection(); } intWriteFileCount++; intWriteFileCount = (intWriteFileCount > 100000) ? 0 : intWriteFileCount; } catch (Exception e) { } m_urlcon = null; } 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(); }
11
Code Sample 1: private boolean copy(File in, File out) { try { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); FileChannel readableChannel = fis.getChannel(); FileChannel writableChannel = fos.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); fis.close(); fos.close(); return true; } catch (IOException ioe) { System.out.println("Copy Error: IOException during copy\r\n" + ioe.getMessage()); return false; } } Code Sample 2: public static final boolean compressToZip(final String sSource, final String sDest, final boolean bDeleteSourceOnSuccess) { ZipOutputStream os = null; InputStream is = null; try { os = new ZipOutputStream(new FileOutputStream(sDest)); is = new FileInputStream(sSource); final byte[] buff = new byte[1024]; int r; String sFileName = sSource; if (sFileName.indexOf('/') >= 0) sFileName = sFileName.substring(sFileName.lastIndexOf('/') + 1); os.putNextEntry(new ZipEntry(sFileName)); while ((r = is.read(buff)) > 0) os.write(buff, 0, r); is.close(); os.flush(); os.closeEntry(); os.close(); } catch (Throwable e) { Log.log(Log.WARNING, "lazyj.Utils", "compressToZip : cannot compress '" + sSource + "' to '" + sDest + "' because", e); return false; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } if (os != null) { try { os.close(); } catch (IOException ioe) { } } } if (bDeleteSourceOnSuccess) try { if (!(new File(sSource)).delete()) Log.log(Log.WARNING, "lazyj.Utils", "compressToZip: could not delete original file (" + sSource + ")"); } catch (SecurityException se) { Log.log(Log.ERROR, "lazyj.Utils", "compressToZip: security constraints prevents file deletion"); } return true; }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String 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(); } Code Sample 2: protected BufferedImage handleBNException() { if (params.uri.startsWith("http://purl.pt/")) try { URLConnection connection = new URL(params.uri).openConnection(); if (params.uri.endsWith("/")) params.uri = params.uri.substring(0, params.uri.length() - 1); int index = params.uri.lastIndexOf("/"); params.uri = "http://purl.pt/homepage/" + params.uri.substring(index + 1) + "/" + params.uri.substring(index + 1); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String url = null; while ((url = reader.readLine()) != null) { index = url.indexOf(params.uri); if (index != -1) { url = url.substring(index); url = url.substring(0, url.indexOf("\"")); break; } } if (url != null) { connection = new URL(url).openConnection(); return processNewUri(connection); } } catch (Exception e) { } return null; }
00
Code Sample 1: @Test public void parse() throws Exception { URL url = new URL("http://www.oki.com"); HtmlParser parser = new HtmlParser(); byte[] bytes = FileUtilities.getContents(url.openStream(), Integer.MAX_VALUE).toByteArray(); OutputStream parsed = parser.parse(new ByteArrayInputStream(bytes), new ByteArrayOutputStream()); assertTrue(parsed.toString().indexOf("Oki") > -1); } Code Sample 2: public static ArrayList search(String query) throws Exception { ArrayList list = new ArrayList(); String url = "http://hypem.com/playlist/search/" + query + "/xml/1/list.xspf"; HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); XmlNode node = XmlLoader.load(conn.getInputStream()); XmlNode tracks[] = node.getFirstChild("trackList").getChild("track"); for (int i = 0; i < tracks.length; i++) { String location = decrypt(tracks[i].getFirstChild("location").getText()); String annotation = tracks[i].getFirstChild("annotation").getText().replaceAll("[\r\n]", ""); list.add(location); System.out.print("found in Hypem: "); System.out.print(annotation); System.out.print(", "); System.out.println(location); } return list; }
11
Code Sample 1: public static String digest(String str) { StringBuffer sb = new StringBuffer(); try { MessageDigest md5 = MessageDigest.getInstance("md5"); md5.update(str.getBytes("ISO8859-1")); byte[] array = md5.digest(); for (int x = 0; x < 16; x++) { if ((array[x] & 0xff) < 0x10) sb.append("0"); sb.append(Long.toString(array[x] & 0xff, 16)); } } catch (Exception e) { System.out.println(e); } return sb.toString(); } Code Sample 2: public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
00
Code Sample 1: public boolean synch(boolean verbose) { try { this.verbose = verbose; if (verbose) System.out.println(" -- Synchronizing: " + destDir + " to " + urlStr); URLConnection urc = new URL(urlStr + "/" + MANIFEST).openConnection(); InputStream is = urc.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); while (true) { String str = r.readLine(); if (str == null) { break; } dealWith(str); } is.close(); } catch (Exception ex) { System.out.println("Synchronization of " + destDir + " failed."); ex.printStackTrace(); return false; } return true; } Code Sample 2: private void makeConn(String filename1, String filename2) { String basename = "http://www.bestmm.com/"; String urlname = basename + filename1 + "/pic/" + filename2 + ".jpg"; URL url = null; try { url = new URL(urlname); } catch (MalformedURLException e) { System.err.println("URL Format Error!"); System.exit(1); } try { conn = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.err.println("Error IO"); System.exit(2); } }
11
Code Sample 1: @Override public String transformSingleFile(X3DEditorSupport.X3dEditor xed) { Node[] node = xed.getActivatedNodes(); X3DDataObject dob = (X3DDataObject) xed.getX3dEditorSupport().getDataObject(); FileObject mySrc = dob.getPrimaryFile(); File mySrcF = FileUtil.toFile(mySrc); File myOutF = new File(mySrcF.getParentFile(), mySrc.getName() + ".x3d.gz"); TransformListener co = TransformListener.getInstance(); co.message(NbBundle.getMessage(getClass(), "Gzip_compression_starting")); co.message(NbBundle.getMessage(getClass(), "Saving_as_") + myOutF.getAbsolutePath()); co.moveToFront(); co.setNode(node[0]); try { FileInputStream fis = new FileInputStream(mySrcF); GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(myOutF)); byte[] buf = new byte[4096]; int ret; while ((ret = fis.read(buf)) > 0) gzos.write(buf, 0, ret); gzos.close(); } catch (Exception ex) { co.message(NbBundle.getMessage(getClass(), "Exception:__") + ex.getLocalizedMessage()); return null; } co.message(NbBundle.getMessage(getClass(), "Gzip_compression_complete")); return myOutF.getAbsolutePath(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public void testAutoCommit() throws Exception { Connection con = getConnectionOverrideProperties(new Properties()); try { Statement stmt = con.createStatement(); assertEquals(0, stmt.executeUpdate("create table #testAutoCommit (i int)")); con.setAutoCommit(false); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (0)")); con.setAutoCommit(false); con.rollback(); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (1)")); con.setAutoCommit(true); con.setAutoCommit(false); con.rollback(); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("select i from #testAutoCommit"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } finally { con.close(); } } Code Sample 2: public static void readAsFile(String fileName, String url) { BufferedInputStream in = null; BufferedOutputStream out = null; URLConnection conn = null; try { conn = new URL(url).openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(fileName)); int b; while ((b = in.read()) != -1) { out.write(b); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.flush(); out.close(); } catch (IOException e) { } } } }
11
Code Sample 1: boolean createSessionArchive(String archiveFilename) { byte[] buffer = new byte[1024]; try { ZipOutputStream archive = new ZipOutputStream(new FileOutputStream(archiveFilename)); for (mAnnotationsCursor.moveToFirst(); !mAnnotationsCursor.isAfterLast(); mAnnotationsCursor.moveToNext()) { FileInputStream in = new FileInputStream(mAnnotationsCursor.getString(ANNOTATIONS_FILE_NAME)); archive.putNextEntry(new ZipEntry("audio" + (mAnnotationsCursor.getPosition() + 1) + ".3gpp")); int length; while ((length = in.read(buffer)) > 0) archive.write(buffer, 0, length); archive.closeEntry(); in.close(); } archive.close(); } catch (IOException e) { Toast.makeText(mActivity, mActivity.getString(R.string.error_zip) + " " + e.getMessage(), Toast.LENGTH_SHORT).show(); return false; } return true; } Code Sample 2: private void createScript(File scriptsLocation, String relativePath, String scriptContent) { Writer fileWriter = null; try { File scriptFile = new File(scriptsLocation.getAbsolutePath() + "/" + relativePath); scriptFile.getParentFile().mkdirs(); fileWriter = new FileWriter(scriptFile); IOUtils.copy(new StringReader(scriptContent), fileWriter); } catch (IOException e) { throw new UnitilsException(e); } finally { IOUtils.closeQuietly(fileWriter); } }
00
Code Sample 1: public Model read(String uri, String base, String lang) { try { URL url = new URL(uri); return read(url.openStream(), base, lang); } catch (IOException e) { throw new OntologyException("I/O error while reading from uri " + uri); } } Code Sample 2: public ContourGenerator(URL url, float modelMean, float modelStddev) throws IOException { this.modelMean = modelMean; this.modelStddev = modelStddev; List termsList = new ArrayList(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); line = reader.readLine(); while (line != null) { if (!line.startsWith("***")) { parseAndAdd(termsList, line); } line = reader.readLine(); } terms = (F0ModelTerm[]) termsList.toArray(terms); reader.close(); }
11
Code Sample 1: public static List importSymbols(List symbols) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbols); IDQuoteFilter filter = new YahooIDQuoteFilter(); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; do { line = bufferedInput.readLine(); if (line != null) { try { IDQuote quote = filter.toIDQuote(line); quote.verify(); quotes.add(quote); } catch (QuoteFormatException e) { } } } while (line != null); bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; } Code Sample 2: public void play(File file) { try { URL url = new URL("http://127.0.0.1:8081/play.html?type=4&file=" + file.getAbsolutePath() + "&name=toto"); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: @Override protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String filename = ServletRequestUtils.getRequiredStringParameter(request, "id"); final File file = new File(path, filename + ".html"); logger.debug("Getting static content from: " + file.getPath()); final InputStream is = getServletContext().getResourceAsStream(file.getPath()); OutputStream out = null; if (is != null) { try { out = response.getOutputStream(); IOUtils.copy(is, out); } catch (IOException ioex) { logger.error(ioex); } finally { is.close(); if (out != null) { out.close(); } } } return null; } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: @SuppressWarnings("unchecked") protected void displayFreeMarkerResponse(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> variableMap) throws IOException { Enumeration<String> attrNameEnum = request.getSession().getAttributeNames(); String attrName; while (attrNameEnum.hasMoreElements()) { attrName = attrNameEnum.nextElement(); if (attrName != null && attrName.startsWith(ADMIN4J_SESSION_VARIABLE_PREFIX)) { variableMap.put("Session" + attrName, request.getSession().getAttribute(attrName)); } } variableMap.put("RequestAdmin4jCurrentUri", request.getRequestURI()); Template temp = FreemarkerUtils.createConfiguredTemplate(this.getClass(), templateName); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { temp.process(variableMap, new OutputStreamWriter(outStream)); response.setContentLength(outStream.size()); IOUtils.copy(new ByteArrayInputStream(outStream.toByteArray()), response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new Admin4jRuntimeException(e); } } Code Sample 2: void copyFile(String from, String to) throws IOException { File destFile = new File(to); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(from).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
00
Code Sample 1: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) { throw new IOException("FileCopy: no such source file: " + from_file.getPath()); } if (!from_file.isFile()) { throw new IOException("FileCopy: can't copy directory: " + from_file.getPath()); } if (!from_file.canRead()) { throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath()); } if (to_file.isDirectory()) { to_file = new File(to_file, from_file.getName()); } if (to_file.exists()) { if (!to_file.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath()); } int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(), "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice != JOptionPane.YES_OPTION) { throw new IOException("FileCopy: existing file was not overwritten."); } } else { String parent = to_file.getParent(); if (parent == null) { parent = Globals.getDefaultPath(); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } } Code Sample 2: public static String Execute(HttpRequestBase httprequest) throws IOException, ClientProtocolException { httprequest.setHeader("Accept", "application/json"); httprequest.setHeader("Content-type", "application/json"); String result = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httprequest); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { result += line + "\n"; } return result; }
00
Code Sample 1: @Test public void testCopy_readerToWriter_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (Writer) null); fail(); } catch (NullPointerException ex) { } } Code Sample 2: private HttpURLConnection getConnection(String url, int connTimeout, int readTimeout) throws IOException { HttpURLConnection con = null; con = (HttpURLConnection) new URL(url).openConnection(); if (connTimeout > 0) { if (!isJDK14orEarlier) { con.setConnectTimeout(connTimeout * 1000); } else { System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(connTimeout * 1000)); } } if (readTimeout > 0) { if (!isJDK14orEarlier) { con.setReadTimeout(readTimeout * 1000); } else { System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(readTimeout * 1000)); } } con.setInstanceFollowRedirects(false); return con; }
00
Code Sample 1: public static String readAsString(final URL url) throws java.io.IOException { InputStream inputStream = url.openStream(); try { return readAsString(inputStream); } finally { try { inputStream.close(); } catch (Throwable t) { } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private void copy(String imgPath, String path) { try { File input = new File(imgPath); File output = new File(path, input.getName()); if (output.exists()) { if (!MessageDialog.openQuestion(getShell(), "Overwrite", "There is already an image file " + input.getName() + " under the package.\n Do you really want to overwrite it?")) return; } byte[] data = new byte[1024]; FileInputStream fis = new FileInputStream(imgPath); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); int length; while ((length = bis.read(data)) > 0) { bos.write(data, 0, length); bos.flush(); } bos.close(); fis.close(); IJavaProject ijp = VisualSwingPlugin.getCurrentProject(); if (ijp != null) { ijp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); view.refresh(); view.expandAll(); } } catch (Exception e) { VisualSwingPlugin.getLogger().error(e); } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static String readUrlText(String urlString) throws IOException { URL url = new URL(urlString); InputStream stream = url.openStream(); StringBuilder buf = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(stream)); String str; while ((str = in.readLine()) != null) { buf.append(str); buf.append(System.getProperty("line.separator")); } } catch (IOException e) { System.out.println("Error reading text from URL [" + url + "]: " + e.toString()); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { System.out.println("Error closing after reading text from URL [" + url + "]: " + e.toString()); } } } return buf.toString(); } Code Sample 2: public String getScore(int id) { String title = null; try { URL url = new URL(BASE_URL + id + ".html"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { if (line.contains("<title>")) { title = line.substring(line.indexOf("<title>") + 7, line.indexOf("</title>")); title = title.substring(0, title.indexOf("|")).trim(); break; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } return title; }
11
Code Sample 1: public void copyFile(final File sourceFile, final File destinationFile) throws FileIOException { final FileChannel sourceChannel; try { sourceChannel = new FileInputStream(sourceFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, sourceFile, exception); } final FileChannel destinationChannel; try { destinationChannel = new FileOutputStream(destinationFile).getChannel(); } catch (FileNotFoundException exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, destinationFile, exception); } try { destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (Exception exception) { final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile; LOGGER.fatal(message); throw fileIOException(message, null, exception); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException exception) { LOGGER.error("closing source", exception); } } if (destinationChannel != null) { try { destinationChannel.close(); } catch (IOException exception) { LOGGER.error("closing destination", exception); } } } } Code Sample 2: private static URL downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } URL localURL = destFile.toURI().toURL(); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
11
Code Sample 1: private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); } Code Sample 2: public static void copyFile(File source, File dest) throws Exception { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { throw new Exception("Cannot copy file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath(), e); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { throw new Exception("Cannot close streams.", e); } } }
00
Code Sample 1: public static void loginBayFiles() throws Exception { HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); System.out.println("Trying to log in to bayfiles.com"); HttpPost httppost = new HttpPost("http://bayfiles.com/ajax_login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("action", "login")); formparams.add(new BasicNameValuePair("username", "")); formparams.add(new BasicNameValuePair("password", "")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); System.out.println("Getting cookies........"); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); if (escookie.getName().equalsIgnoreCase("SESSID")) { sessioncookie = "SESSID=" + escookie.getValue(); System.out.println(sessioncookie); login = true; System.out.println("BayFiles.com Login success :)"); } } if (!login) { System.out.println("BayFiles.com Login failed :("); } } Code Sample 2: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
00
Code Sample 1: public List<BadassEntry> parse() { mBadassEntries = new ArrayList<BadassEntry>(); try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains(START_PARSE)) flag1 = true; if (flag1 && line.contains(STOP_PARSE)) break; if (flag1) { if (line.contains(ENTRY_HINT)) { parseBadass(line); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mBadassEntries; } Code Sample 2: public synchronized String encrypt(String plaintext) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } catch (UnsupportedEncodingException e) { log().error("failed to encrypt the password.", e); throw new RuntimeException("failed to encrypt the password.", e); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
Code Sample 1: public void copy(String sourcePath, String targetPath) throws IOException { File sourceFile = new File(sourcePath); File targetFile = new File(targetPath); FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(sourceFile); fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) fileOutputStream.write(buffer, 0, bytesRead); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s265") + sourcePath, AcideLanguageManager.getInstance().getLabels().getString("s266"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException exception) { JOptionPane.showMessageDialog(null, AcideLanguageManager.getInstance().getLabels().getString("s267") + targetPath, AcideLanguageManager.getInstance().getLabels().getString("268"), JOptionPane.ERROR_MESSAGE); AcideLog.getLog().error(exception.getMessage()); } } } Code Sample 2: boolean isTextPage(URL url) { try { String ct = url.openConnection().getContentType().toLowerCase(); String s = url.toString(); Loro.log("LoroEDI: " + " content-type: " + ct); if (!ct.startsWith("text/") || s.endsWith(".jar") || s.endsWith(".lar")) { javax.swing.JOptionPane.showOptionDialog(null, Str.get("gui.1_browser_cannot_show_link", s), "", javax.swing.JOptionPane.DEFAULT_OPTION, javax.swing.JOptionPane.WARNING_MESSAGE, null, null, null); Loro.log("LoroEDI: " + " unable to display"); return false; } } catch (Exception ex) { Loro.log("LoroEDI: " + " Exception: " + ex.getMessage()); return false; } return true; }
00
Code Sample 1: public boolean limpiarContrincantexRonda(jugadorxDivxRonda unjxdxr) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = 0 " + " WHERE idJugxDivxRnd = " + unjxdxr.getIdJugxDivxRnd(); try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public static void main(String[] args) throws Exception { TripleDES tdes = new TripleDES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\testTDESENC.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\testTDESDEC.txt")); SingleKey key = new SingleKey(new Block(128), ""); key = new SingleKey(new Block("01011101110000101001100111001011101000001110111101001001101101101101100000011101100100110000101100001110000001111101001101001101"), ""); Mode mode = new ECBTripleDESMode(tdes); tdes.decrypt(reader, writer, key, mode); }
11
Code Sample 1: private static void copy(String srcFilename, String dstFilename, boolean override) throws IOException, XPathFactoryConfigurationException, SAXException, ParserConfigurationException, XPathExpressionException { File fileToCopy = new File(rootDir + "test-output/" + srcFilename); if (fileToCopy.exists()) { File newFile = new File(rootDir + "test-output/" + dstFilename); if (!newFile.exists() || override) { try { FileChannel srcChannel = new FileInputStream(rootDir + "test-output/" + srcFilename).getChannel(); FileChannel dstChannel = new FileOutputStream(rootDir + "test-output/" + dstFilename).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } } } Code Sample 2: public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputResource.getInputStream())); File targetDirectoryAsFile = new File(targetDirectory); if (!targetDirectoryAsFile.exists()) { FileUtils.forceMkdir(targetDirectoryAsFile); } File target = new File(targetDirectory, targetFile); BufferedOutputStream dest = null; while (zis.getNextEntry() != null) { if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); dest = new BufferedOutputStream(fos); IOUtils.copy(zis, dest); dest.flush(); dest.close(); } zis.close(); if (!target.exists()) { throw new IllegalStateException("Could not decompress anything from the archive!"); } return RepeatStatus.FINISHED; }
00
Code Sample 1: public static void download(String address, String localFileName, String rawClass, double newVer, int newStage) { OutputStream out = null; URLConnection conn = null; InputStream in = null; int totalBytes = 0; int dlBytes = 0; try { if (!Main.Updates.current.hasFile(rawClass)) { Main.Updates.current.addFile(newVer, newStage, rawClass); } Main.Updates.current.getFile(rawClass).downloading = true; Main.Updates.setImage(rawClass, "refresh.png"); java.io.File folder = new java.io.File(localFileName); folder.createNewFile(); URL url = new URL(address); out = new BufferedOutputStream(new FileOutputStream(localFileName)); conn = url.openConnection(); in = conn.getInputStream(); totalBytes = conn.getContentLength(); byte[] buffer = new byte[1024]; int numRead; long numWritten = 0; double incr = java.lang.Math.floor(totalBytes / 1000); Main.Interface.Update.prgStatus.setMaximum(1000); Main.Interface.Update.prgStatus.setString("0.0%"); while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); numWritten += numRead; dlBytes += numRead; int newVal = (dlBytes != totalBytes ? (int) java.lang.Math.floor(dlBytes / incr) : 1000); Main.Interface.Update.prgStatus.setValue(newVal); Main.Interface.Update.prgStatus.setString((newVal / 10) + "." + (newVal % 10) + "%"); } Main.Updates.current.getFile(rawClass).downloading = false; Main.Updates.current.getFile(rawClass).version = newVer; Main.Updates.current.getFile(rawClass).stage = newStage; Main.Updates.setImage(rawClass, "updater.png"); Main.Updates.updateTable(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException ioe) { } } } Code Sample 2: protected static void download(FtpSiteConnector connector, File localFile, String remotePath, final IProgressMonitor monitor) throws FtpException { if (!localFile.exists()) { FTPClient ftp = new FTPClient(); try { FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftp.configure(conf); String hostname = connector.getUrl().getHost(); ftp.connect(hostname); log.info("Connected to " + hostname); log.info(ftp.getReplyString()); boolean loggedIn = ftp.login(connector.getUsername(), connector.getPassword()); if (loggedIn) { log.info("downloading file: " + remotePath); ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); final long fileSize = getFileSize(ftp, remotePath); FileOutputStream dfile = new FileOutputStream(localFile); ftp.retrieveFile(remotePath, dfile, new CopyStreamListener() { public int worked = 0; public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) { int percent = percent(fileSize, totalBytesTransferred); int delta = percent - worked; if (delta > 0) { if (monitor != null) { monitor.worked(delta); } worked = percent; } } public void bytesTransferred(CopyStreamEvent event) { } private int percent(long totalBytes, long totalBytesTransferred) { long percent = (totalBytesTransferred * 100) / totalBytes; return Long.valueOf(percent).intValue(); } }); dfile.flush(); dfile.close(); ftp.logout(); } else { throw new FtpException("Invalid login"); } ftp.disconnect(); } catch (SocketException e) { log.error("File download failed with message: " + e.getMessage()); throw new FtpException("File download failed with message: " + e.getMessage()); } catch (IOException e) { log.error("File download failed with message: " + e.getMessage()); throw new FtpException("File download failed with message: " + e.getMessage()); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { throw new FtpException("File download failed with message: " + ioe.getMessage()); } } } } }
00
Code Sample 1: public static void putNextJarEntry(JarOutputStream modelStream, String name, File file) throws IOException { JarEntry entry = new JarEntry(name); entry.setSize(file.length()); modelStream.putNextEntry(entry); InputStream fileStream = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(fileStream, modelStream); fileStream.close(); } Code Sample 2: public String fetch(final String address) throws EncoderException { final String escapedAddress = new URLCodec().encode(address); final String requestUrl = GeoCodeFetch.urlXmlPath + "&" + "address=" + escapedAddress; this.log.debug("requestUrl: {}", requestUrl); try { final StringBuffer sb = new StringBuffer(); final URL url = new URL(requestUrl); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { this.log.debug("line: {}", line); sb.append(line); } reader.close(); return (sb.toString()); } catch (final MalformedURLException ex) { this.log.error(ExceptionUtils.getStackTrace(ex)); } catch (final IOException ex) { this.log.error(ExceptionUtils.getStackTrace(ex)); } return (""); }
11
Code Sample 1: public void copyTo(Bean bean, OutputStream out, int offset, int length) throws Exception { BeanInfo beanInfo = getBeanInfo(bean.getClass()); validate(bean, beanInfo, "copyTo"); if (blobCache != null && length < MAX_BLOB_CACHE_LENGHT) { byte[] bytes = null; synchronized (this) { String key = makeUniqueKey(bean, beanInfo, offset, length); if (blobCache.contains(key)) bytes = (byte[]) blobCache.get(key); else blobCache.put(key, bytes = toByteArray(bean, offset, length, beanInfo)); } InputStream in = new ByteArrayInputStream(bytes); IOUtils.copy(in, out); in.close(); } else { jdbcManager.queryScript(beanInfo.getBlobInfo(jdbcManager.getDb()).getReadScript(), bean, new JdbcOutputStreamRowMapper(out, offset, length)); } } Code Sample 2: public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } }
11
Code Sample 1: private boolean passwordMatches(String user, String plainPassword, String scrambledPassword) { MessageDigest md; byte[] temp_digest, pass_digest; byte[] hex_digest = new byte[35]; byte[] scrambled = scrambledPassword.getBytes(); try { md = MessageDigest.getInstance("MD5"); md.update(plainPassword.getBytes("US-ASCII")); md.update(user.getBytes("US-ASCII")); temp_digest = md.digest(); Utils.bytesToHex(temp_digest, hex_digest, 0); md.update(hex_digest, 0, 32); md.update(salt.getBytes()); pass_digest = md.digest(); Utils.bytesToHex(pass_digest, hex_digest, 3); hex_digest[0] = (byte) 'm'; hex_digest[1] = (byte) 'd'; hex_digest[2] = (byte) '5'; for (int i = 0; i < hex_digest.length; i++) { if (scrambled[i] != hex_digest[i]) { return false; } } } catch (Exception e) { logger.error(e); } return true; } Code Sample 2: public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
11
Code Sample 1: private void internalTransferComplete(File tmpfile) { System.out.println("transferComplete : " + tmpfile); try { File old = new File(m_destination.toString() + ".old"); old.delete(); File current = m_destination; current.renameTo(old); FileInputStream fis = new FileInputStream(tmpfile); FileOutputStream fos = new FileOutputStream(m_destination); BufferedInputStream in = new BufferedInputStream(fis); BufferedOutputStream out = new BufferedOutputStream(fos); for (int read = in.read(); read != -1; read = in.read()) { out.write(read); } out.flush(); in.close(); out.close(); fis.close(); fos.close(); tmpfile.delete(); setVisible(false); transferComplete(); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(this, "An error occurred while downloading!", "ACLocator Error", JOptionPane.ERROR_MESSAGE); } } Code Sample 2: public static void uncompress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new GZIPInputStream(new FileInputStream(srcFile)); output = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
11
Code Sample 1: @Test public void testExactCopySize() throws IOException { final int size = Byte.SIZE + RANDOMIZER.nextInt(TEST_DATA.length - Long.SIZE); final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(size); final int cpySize = ExtraIOUtils.copy(in, out, size); assertEquals("Mismatched copy size", size, cpySize); final byte[] subArray = ArrayUtils.subarray(TEST_DATA, 0, size), outArray = out.toByteArray(); assertArrayEquals("Mismatched data", subArray, outArray); } Code Sample 2: public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
11
Code Sample 1: public static String encode(String text) { try { byte[] hash = new byte[32]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes("UTF-8"), 0, text.length()); hash = md.digest(); return MD5.toHex(hash); } catch (NoSuchAlgorithmException ex) { return ex.getMessage(); } catch (UnsupportedEncodingException ex) { return ex.getMessage(); } } Code Sample 2: public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; }
00
Code Sample 1: @Override protected InputStream getResourceStream(String name) throws Exception { final BundleEntry entry = cpm.findLocalEntry(name); if (entry != null) return entry.getInputStream(); final URL url = cpm.getBaseData().getBundle().getResource(name); if (url != null) return url.openStream(); return null; } Code Sample 2: public synchronized void readModels(URL url, XmiExtensionParser xmiExtensionParser) throws OpenException { LOG.info("======================================="); LOG.info("== READING MODEL " + url); try { InputSource source = new InputSource(new XmiInputStream(url.openStream(), xmiExtensionParser, 100000, null)); source.setSystemId(url.toString()); readModels(source); } catch (IOException ex) { throw new OpenException(ex); } }
11
Code Sample 1: public static LicenseKey parseKey(String key) throws InvalidLicenseKeyException { final String f_key = key.trim(); StringTokenizer st = new StringTokenizer(f_key, FIELD_SEPERATOR); int tc = st.countTokens(); int tc_name = tc - 9; try { final String product = st.nextToken(); final String type = st.nextToken(); final String loadStr = st.nextToken(); final int load = Integer.parseInt(loadStr); final String lowMajorVersionStr = st.nextToken(); final int lowMajorVersion = Integer.parseInt(lowMajorVersionStr); final String lowMinorVersionStr = st.nextToken(); final double lowMinorVersion = Double.parseDouble("0." + lowMinorVersionStr); final String highMajorVersionStr = st.nextToken(); final int highMajorVersion = Integer.parseInt(highMajorVersionStr); final String highMinorVersionStr = st.nextToken(); final double highMinorVersion = Double.parseDouble("0." + highMinorVersionStr); String regName = ""; for (int i = 0; i < tc_name; i++) regName += (i == 0 ? st.nextToken() : FIELD_SEPERATOR + st.nextToken()); final String randomHexStr = st.nextToken(); final String md5Str = st.nextToken(); String subKey = f_key.substring(0, f_key.indexOf(md5Str) - 1); byte[] md5; MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(subKey.getBytes()); md.update(FIELD_SEPERATOR.getBytes()); md.update(zuonicsPassword.getBytes()); md5 = md.digest(); String testKey = subKey + FIELD_SEPERATOR; for (int i = 0; i < md5.length; i++) testKey += Integer.toHexString(md5[i]).toUpperCase(); if (!testKey.equals(f_key)) throw new InvalidLicenseKeyException("doesn't hash"); final String f_regName = regName; return new LicenseKey() { public String getProduct() { return product; } public String getType() { return type; } public int getLoad() { return load; } public String getRegName() { return f_regName; } public double getlowVersion() { return lowMajorVersion + lowMinorVersion; } public double getHighVersion() { return highMajorVersion + highMinorVersion; } public String getRandomHexStr() { return randomHexStr; } public String getMD5HexStr() { return md5Str; } public String toString() { return f_key; } public boolean equals(Object obj) { if (obj.toString().equals(toString())) return true; return false; } }; } catch (Exception e) { throw new InvalidLicenseKeyException(e.getMessage()); } } Code Sample 2: public static String encrypt(String text) { char[] toEncrypt = text.toCharArray(); StringBuffer hexString = new StringBuffer(); try { MessageDigest dig = MessageDigest.getInstance("MD5"); dig.reset(); String pw = ""; for (int i = 0; i < toEncrypt.length; i++) { pw += toEncrypt[i]; } dig.update(pw.getBytes()); byte[] digest = dig.digest(); int digestLength = digest.length; for (int i = 0; i < digestLength; i++) { hexString.append(hexDigit(digest[i])); } } catch (java.security.NoSuchAlgorithmException ae) { ae.printStackTrace(); } return hexString.toString(); }
00
Code Sample 1: private static String[] loadDB(String name) throws IOException { URL url = SpecialConstants.class.getResource(name); if (url == null) throw new FileNotFoundException("file " + name + " not found"); InputStream is = url.openStream(); try { InputStreamReader isr = new InputStreamReader(is, "utf8"); BufferedReader br = new BufferedReader(isr); ArrayList<String> entries = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; line = line.trim(); if (line.length() > 0 && line.charAt(0) != '#') { entries.add(line); } } String[] r = new String[entries.size()]; entries.toArray(r); return r; } finally { is.close(); } } Code Sample 2: private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; }
00
Code Sample 1: public static void main(String[] argv) { if (1 < argv.length) { File[] sources = Source(argv[0]); if (null != sources) { for (File src : sources) { File[] targets = Target(src, argv); if (null != targets) { final long srclen = src.length(); try { FileChannel source = new FileInputStream(src).getChannel(); try { for (File tgt : targets) { FileChannel target = new FileOutputStream(tgt).getChannel(); try { source.transferTo(0L, srclen, target); } finally { target.close(); } System.out.printf("Updated %s\n", tgt.getPath()); File[] deletes = Delete(src, tgt); if (null != deletes) { for (File del : deletes) { if (SVN) { if (SvnDelete(del)) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } else if (del.delete()) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } } if (SVN) SvnAdd(tgt); } } finally { source.close(); } } catch (Exception exc) { exc.printStackTrace(); System.exit(1); } } } System.exit(0); } else { System.err.printf("Source file(s) not found in '%s'\n", argv[0]); System.exit(1); } } else { usage(); System.exit(1); } } Code Sample 2: public static String getDigest(String user, String realm, String password, String method, String uri, String nonce, String nc, String cnonce, String qop) { String digest1 = user + ":" + realm + ":" + password; String digest2 = method + ":" + uri; try { MessageDigest digestOne = MessageDigest.getInstance("md5"); digestOne.update(digest1.getBytes()); String hexDigestOne = getHexString(digestOne.digest()); MessageDigest digestTwo = MessageDigest.getInstance("md5"); digestTwo.update(digest2.getBytes()); String hexDigestTwo = getHexString(digestTwo.digest()); String digest3 = hexDigestOne + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + hexDigestTwo; MessageDigest digestThree = MessageDigest.getInstance("md5"); digestThree.update(digest3.getBytes()); String hexDigestThree = getHexString(digestThree.digest()); return hexDigestThree; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public static String send(String ipStr, int port, String password, String command, InetAddress localhost, int localPort) throws SocketTimeoutException, BadRcon, ResponseEmpty { StringBuffer response = new StringBuffer(); try { rconSocket = new Socket(); rconSocket.bind(new InetSocketAddress(localhost, localPort)); rconSocket.connect(new InetSocketAddress(ipStr, port), RESPONSE_TIMEOUT); out = rconSocket.getOutputStream(); in = rconSocket.getInputStream(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(in)); rconSocket.setSoTimeout(RESPONSE_TIMEOUT); String digestSeed = ""; boolean loggedIn = false; boolean keepGoing = true; while (keepGoing) { String receivedContent = buffRead.readLine(); if (receivedContent.startsWith("### Digest seed: ")) { digestSeed = receivedContent.substring(17, receivedContent.length()); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(digestSeed.getBytes()); md5.update(password.getBytes()); String digestStr = "login " + digestedToHex(md5.digest()) + "\n"; out.write(digestStr.getBytes()); } catch (NoSuchAlgorithmException e1) { response.append("MD5 algorithm not available - unable to complete RCON request."); keepGoing = false; } } else if (receivedContent.startsWith("error: not authenticated: you can only invoke 'login'")) { throw new BadRcon(); } else if (receivedContent.startsWith("Authentication failed.")) { throw new BadRcon(); } else if (receivedContent.startsWith("Authentication successful, rcon ready.")) { keepGoing = false; loggedIn = true; } } if (loggedIn) { String cmd = "exec " + command + "\n"; out.write(cmd.getBytes()); readResponse(buffRead, response); if (response.length() == 0) { throw new ResponseEmpty(); } } } catch (SocketTimeoutException timeout) { throw timeout; } catch (UnknownHostException e) { response.append("UnknownHostException: " + e.getMessage()); } catch (IOException e) { response.append("Couldn't get I/O for the connection: " + e.getMessage()); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (rconSocket != null) { rconSocket.close(); } } catch (IOException e1) { } } return response.toString(); } Code Sample 2: public static String calculate(String str) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(str.getBytes()); byte byteData[] = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException ex) { return null; } }
11
Code Sample 1: private boolean saveDocumentXml(String repository, String tempRepo) { boolean result = true; try { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "documents/document"; InputSource insource = new InputSource(new FileInputStream(tempRepo + File.separator + AppConstants.DMS_XML)); NodeList nodeList = (NodeList) xpath.evaluate(expression, insource, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeName()); DocumentModel document = new DocumentModel(); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node child = childs.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName() != null && child.getFirstChild() != null && child.getFirstChild().getNodeValue() != null) { System.out.println(child.getNodeName() + "::" + child.getFirstChild().getNodeValue()); } if (Document.FLD_ID.equals(child.getNodeName())) { if (child.getFirstChild() != null) { String szId = child.getFirstChild().getNodeValue(); if (szId != null && szId.length() > 0) { try { document.setId(new Long(szId)); } catch (Exception e) { e.printStackTrace(); } } } } else if (document.FLD_NAME.equals(child.getNodeName())) { document.setName(child.getFirstChild().getNodeValue()); document.setTitle(document.getName()); document.setDescr(document.getName()); document.setExt(getExtension(document.getName())); } else if (document.FLD_LOCATION.equals(child.getNodeName())) { document.setLocation(child.getFirstChild().getNodeValue()); } else if (document.FLD_OWNER.equals(child.getNodeName())) { Long id = new Long(child.getFirstChild().getNodeValue()); User user = new UserModel(); user.setId(id); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setOwner(user); } } } } boolean isSave = docService.save(document); if (isSave) { String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File fileFolder = new File(sbRepo.append(sbFolder).toString()); if (!fileFolder.exists()) { fileFolder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(fileFolder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(tempRepo + File.separator + document.getName()).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); document.setSize(fcSource.size()); log.info("Batch upload file " + document.getName() + " into [" + document.getLocation() + "] as " + document.getName() + "." + document.getExt()); folder.setId(DEFAULT_FOLDER); folder = (Folder) folderService.find(folder); if (folder != null && folder.getId() != null) { document.setFolder(folder); } workspace.setId(DEFAULT_WORKSPACE); workspace = (Workspace) workspaceService.find(workspace); if (workspace != null && workspace.getId() != null) { document.setWorkspace(workspace); } user.setId(DEFAULT_USER); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setCrtby(user.getId()); } document.setCrtdate(new Date()); document = (DocumentModel) docService.resetDuplicateDocName(document); docService.save(document); DocumentIndexer.indexDocument(preference, document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: public static String hashPassword(String plaintext) { if (plaintext == null) { return ""; } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); md.update(plaintext.getBytes("UTF-8")); } catch (Exception e) { logger.log(Level.SEVERE, "Problem hashing password.", e); } return new String(Base64.encodeBase64(md.digest())); } Code Sample 2: @Test public void testCopy_inputStreamToWriter() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
00
Code Sample 1: public void delete(Channel channel) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(channel.getPath(), "1", connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); String sqlStr = "delete from t_ip_channel where channel_path=?"; preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); sqlStr = "delete from t_ip_channel_order where channel_order_site = ?"; preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException ex) { connection.rollback(); log.error("ɾ��Ƶ��ʧ�ܣ�channelPath=" + channel.getPath(), ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } } Code Sample 2: @Test public void testTrainingDefault() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
11
Code Sample 1: protected void copyFile(File source, File destination) throws ApplicationException { try { OutputStream out = new FileOutputStream(destination); DataInputStream in = new DataInputStream(new FileInputStream(source)); byte[] buf = new byte[8192]; for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) { out.write(buf, 0, nread); } in.close(); out.close(); } catch (IOException e) { throw new ApplicationException("Can't copy file " + source + " to " + destination); } } Code Sample 2: @Override public void execute(String[] args) throws Exception { Options cmdLineOptions = getCommandOptions(); try { GnuParser parser = new GnuParser(); CommandLine commandLine = parser.parse(cmdLineOptions, TolvenPlugin.getInitArgs()); String srcRepositoryURLString = commandLine.getOptionValue(CMD_LINE_SRC_REPOSITORYURL_OPTION); Plugins libraryPlugins = RepositoryMetadata.getRepositoryPlugins(new URL(srcRepositoryURLString)); String srcPluginId = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_ID_OPTION); PluginDetail plugin = RepositoryMetadata.getPluginDetail(srcPluginId, libraryPlugins); if (plugin == null) { throw new RuntimeException("Could not locate plugin: " + srcPluginId + " in repository: " + srcRepositoryURLString); } String srcPluginVersionString = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_VERSION_OPTION); PluginVersionDetail srcPluginVersion = null; if (srcPluginVersion == null) { srcPluginVersion = RepositoryMetadata.getLatestVersion(plugin); } else { srcPluginVersion = RepositoryMetadata.getPluginVersionDetail(srcPluginVersionString, plugin); } if (plugin == null) { throw new RuntimeException("Could not find a plugin version for: " + srcPluginId + " in repository: " + srcRepositoryURLString); } String destPluginId = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_ID_OPTION); FileUtils.deleteDirectory(getPluginTmpDir()); URL srcURL = new URL(srcPluginVersion.getUri()); File newPluginDir = new File(getPluginTmpDir(), destPluginId); try { InputStream in = null; FileOutputStream out = null; File tmpZip = new File(getPluginTmpDir(), new File(srcURL.getFile()).getName()); try { in = srcURL.openStream(); out = new FileOutputStream(tmpZip); IOUtils.copy(in, out); TolvenZip.unzip(tmpZip, newPluginDir); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (tmpZip != null) { tmpZip.delete(); } } File pluginManifestFile = new File(newPluginDir, "tolven-plugin.xml"); if (!pluginManifestFile.exists()) { throw new RuntimeException(srcURL.toExternalForm() + "has no plugin manifest"); } Plugin pluginManifest = RepositoryMetadata.getPlugin(pluginManifestFile.toURI().toURL()); pluginManifest.setId(destPluginId); String destPluginVersion = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_VERSION_OPTION); if (destPluginVersion == null) { destPluginVersion = DEFAULT_DEST_VERSION; } pluginManifest.setVersion(destPluginVersion); String pluginManifestXML = RepositoryMetadata.getPluginManifest(pluginManifest); FileUtils.writeStringToFile(pluginManifestFile, pluginManifestXML); File pluginFragmentManifestFile = new File(newPluginDir, "tolven-plugin-fragment.xml"); if (pluginFragmentManifestFile.exists()) { PluginFragment pluginManifestFragment = RepositoryMetadata.getPluginFragment(pluginFragmentManifestFile.toURI().toURL()); Requires requires = pluginManifestFragment.getRequires(); if (requires == null) { throw new RuntimeException("No <requires> detected for plugin fragment in: " + srcURL.toExternalForm()); } if (requires.getImport().size() != 1) { throw new RuntimeException("There should be only one import for plugin fragment in: " + srcURL.toExternalForm()); } requires.getImport().get(0).setPluginId(destPluginId); requires.getImport().get(0).setPluginVersion(destPluginVersion); String pluginFragmentManifestXML = RepositoryMetadata.getPluginFragmentManifest(pluginManifestFragment); FileUtils.writeStringToFile(pluginFragmentManifestFile, pluginFragmentManifestXML); } String destDirname = commandLine.getOptionValue(CMD_LINE_DEST_DIR_OPTION); File destDir = new File(destDirname); File destZip = new File(destDir, destPluginId + "-" + destPluginVersion + ".zip"); destDir.mkdirs(); TolvenZip.zip(newPluginDir, destZip); } finally { if (newPluginDir != null) { FileUtils.deleteDirectory(newPluginDir); } } } catch (ParseException ex) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getName(), cmdLineOptions); throw new RuntimeException("Could not parse command line for: " + getClass().getName(), ex); } }
00
Code Sample 1: public String Hash(String plain) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes(), 0, plain.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (Exception ex) { Log.serverlogger.warn("No such Hash algorithm", ex); return ""; } } Code Sample 2: public void testReleaseConnectionOnAbort() throws Exception { HttpParams mgrpar = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(mgrpar, 1); ThreadSafeClientConnManager mgr = createTSCCM(mgrpar, null); final HttpHost target = getServerHttp(); final HttpRoute route = new HttpRoute(target, null, false); final int rsplen = 8; final String uri = "/random/" + rsplen; HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); ManagedClientConnection conn = getConnection(mgr, route); conn.open(route, httpContext, defaultParams); HttpResponse response = Helper.execute(request, conn, target, httpExecutor, httpProcessor, defaultParams, httpContext); assertEquals("wrong status in first response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); try { getConnection(mgr, route, 100L, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException e) { } assertTrue(conn instanceof AbstractClientConnAdapter); ((AbstractClientConnAdapter) conn).abortConnection(); conn = getConnection(mgr, route, 5L, TimeUnit.SECONDS); assertFalse("connection should have been closed", conn.isOpen()); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public 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; }
00
Code Sample 1: public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2010May cb = new AcmSearchresultPageParser_2010May(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartPositions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartPositions().get(i); System.out.println(i + "pos= " + m); } } Code Sample 2: public final InputSource getInputSource() { if (url == null) throw new RuntimeException("Cannot find table defs"); try { InputStream stream = url.openStream(); InputStreamReader reader = new InputStreamReader(stream); return new InputSource(reader); } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } } Code Sample 2: public void run() { try { File outDir = new File(outDirTextField.getText()); if (!outDir.exists()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen directory does not exist!", "Directory Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.isDirectory()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "The chosen file is not a directory!", "Not a Directory Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (!outDir.canWrite()) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Cannot write to the chosen directory!", "Directory Not Writeable Error", JOptionPane.ERROR_MESSAGE); } }); return; } File archiveDir = new File("foo.bar").getAbsoluteFile().getParentFile(); URL baseUrl = UnpackWizard.class.getClassLoader().getResource(UnpackWizard.class.getName().replaceAll("\\.", "/") + ".class"); if (baseUrl.getProtocol().equals("jar")) { String jarPath = baseUrl.getPath(); jarPath = jarPath.substring(0, jarPath.indexOf('!')); if (jarPath.startsWith("file:")) { try { archiveDir = new File(new URI(jarPath)).getAbsoluteFile().getParentFile(); } catch (URISyntaxException e1) { e1.printStackTrace(System.err); } } } SortedMap<Integer, String> inputFileNames = new TreeMap<Integer, String>(); for (Entry<Object, Object> anEntry : indexProperties.entrySet()) { String key = anEntry.getKey().toString(); if (key.startsWith("archive file ")) { inputFileNames.put(Integer.parseInt(key.substring("archive file ".length())), anEntry.getValue().toString()); } } byte[] buff = new byte[64 * 1024]; try { long bytesToWrite = 0; long bytesReported = 0; long bytesWritten = 0; for (String aFileName : inputFileNames.values()) { File aFile = new File(archiveDir, aFileName); if (aFile.exists()) { if (aFile.isFile()) { bytesToWrite += aFile.length(); } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" is not a standard file!", "Non Standard File Error", JOptionPane.ERROR_MESSAGE); } }); return; } } else { final File wrongFile = aFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "File \"" + wrongFile.getAbsolutePath() + "\" does not exist!", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } } MultiFileInputStream mfis = new MultiFileInputStream(archiveDir, inputFileNames.values().toArray(new String[inputFileNames.size()])); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(mfis)); TarArchiveEntry tarEntry = tis.getNextTarEntry(); while (tarEntry != null) { File outFile = new File(outDir.getAbsolutePath() + "/" + tarEntry.getName()); if (outFile.exists()) { final File wrongFile = outFile; SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(UnpackWizard.this, "Was about to write out file \"" + wrongFile.getAbsolutePath() + "\" but it already " + "exists.\nPlease [re]move existing files out of the way " + "and try again.", "File Not Found Error", JOptionPane.ERROR_MESSAGE); } }); return; } if (tarEntry.isDirectory()) { outFile.getAbsoluteFile().mkdirs(); } else { outFile.getAbsoluteFile().getParentFile().mkdirs(); OutputStream os = new BufferedOutputStream(new FileOutputStream(outFile)); int len = tis.read(buff, 0, buff.length); while (len != -1) { os.write(buff, 0, len); bytesWritten += len; if (bytesWritten - bytesReported > (10 * 1024 * 1024)) { bytesReported = bytesWritten; final int progress = (int) (bytesReported * 100 / bytesToWrite); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(progress); } }); } len = tis.read(buff, 0, buff.length); } os.close(); } tarEntry = tis.getNextTarEntry(); } long expectedCrc = 0; try { expectedCrc = Long.parseLong(indexProperties.getProperty("CRC32", "0")); } catch (NumberFormatException e) { System.err.println("Error while obtaining the expected CRC"); e.printStackTrace(System.err); } if (mfis.getCRC() == expectedCrc) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Extraction completed successfully!", "Done!", JOptionPane.INFORMATION_MESSAGE); } }); return; } else { System.err.println("CRC Error: was expecting " + expectedCrc + " but got " + mfis.getCRC()); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "CRC Error: the data extracted does not have the expected CRC!\n" + "You should probably delete the extracted files, as they are " + "likely to be invalid.", "CRC Error", JOptionPane.ERROR_MESSAGE); } }); return; } } catch (final IOException e) { e.printStackTrace(System.err); SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); JOptionPane.showMessageDialog(UnpackWizard.this, "Input/Output Error: " + e.getLocalizedMessage(), "Input/Output Error", JOptionPane.ERROR_MESSAGE); } }); return; } } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(0); setEnabled(true); } }); } }
11
Code Sample 1: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; } Code Sample 2: public static void copyFile(String src, String target) throws IOException { FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(target).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: protected final void loadLogFile(String filename) throws IOException { cleanUp(true, false); InputStream is = null; OutputStream os = null; File f = File.createTempFile("log", null); try { is = getClass().getResourceAsStream(filename); Assert.isTrue(is != null, "File not found: " + filename); os = new FileOutputStream(f); IOUtils.copy(is, os); setLogFile(f); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
00
Code Sample 1: public void createResource(String resourceUri, boolean publish, User user) throws IOException { PermissionAPI perAPI = APILocator.getPermissionAPI(); Logger.debug(this.getClass(), "createResource"); resourceUri = stripMapping(resourceUri); String hostName = getHostname(resourceUri); String path = getPath(resourceUri); String folderName = getFolderName(path); String fileName = getFileName(path); fileName = deleteSpecialCharacter(fileName); if (fileName.startsWith(".")) { return; } Host host = HostFactory.getHostByHostName(hostName); Folder folder = FolderFactory.getFolderByPath(folderName, host); boolean hasPermission = perAPI.doesUserHavePermission(folder, PERMISSION_WRITE, user, false); if (hasPermission) { if (!checkFolderFilter(folder, fileName)) { throw new IOException("The file doesn't comply the folder's filter"); } if (host.getInode() != 0 && folder.getInode() != 0) { File file = new File(); file.setTitle(fileName); file.setFileName(fileName); file.setShowOnMenu(false); file.setLive(publish); file.setWorking(true); file.setDeleted(false); file.setLocked(false); file.setModDate(new Date()); String mimeType = FileFactory.getMimeType(fileName); file.setMimeType(mimeType); String author = user.getFullName(); file.setAuthor(author); file.setModUser(author); file.setSortOrder(0); file.setShowOnMenu(false); try { Identifier identifier = null; if (!isResource(resourceUri)) { WebAssetFactory.createAsset(file, user.getUserId(), folder, publish); identifier = IdentifierCache.getIdentifierFromIdentifierCache(file); } else { File actualFile = FileFactory.getFileByURI(path, host, false); identifier = IdentifierCache.getIdentifierFromIdentifierCache(actualFile); WebAssetFactory.createAsset(file, user.getUserId(), folder, identifier, false, false); WebAssetFactory.publishAsset(file); String assetsPath = FileFactory.getRealAssetsRootPath(); new java.io.File(assetsPath).mkdir(); java.io.File workingIOFile = FileFactory.getAssetIOFile(file); DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingIOFile.getPath()); if (file != null && file.getInode() > 0) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(workingIOFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); java.io.File newVersionFile = FileFactory.getAssetIOFile(file); vc.remove(ResourceManager.RESOURCE_TEMPLATE + newVersionFile.getPath()); FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); } java.util.List<Tree> parentTrees = TreeFactory.getTreesByChild(file); for (Tree tree : parentTrees) { Tree newTree = TreeFactory.getTree(tree.getParent(), file.getInode()); if (newTree.getChild() == 0) { newTree.setParent(tree.getParent()); newTree.setChild(file.getInode()); newTree.setRelationType(tree.getRelationType()); newTree.setTreeOrder(0); TreeFactory.saveTree(newTree); } } } List<Permission> permissions = perAPI.getPermissions(folder); for (Permission permission : permissions) { Permission filePermission = new Permission(); filePermission.setPermission(permission.getPermission()); filePermission.setRoleId(permission.getRoleId()); filePermission.setInode(identifier.getInode()); perAPI.save(filePermission); } } catch (Exception ex) { Logger.debug(this, ex.toString()); } } } else { throw new IOException("You don't have access to add that folder/host"); } } Code Sample 2: public String generateFilename() { MessageDigest md; byte[] sha1hash = new byte[40]; Random r = new Random(); String fileName = ""; String token = ""; while (true) { token = Long.toString(Math.abs(r.nextLong()), 36) + Long.toString(System.currentTimeMillis()); try { md = MessageDigest.getInstance("SHA-1"); md.update(token.getBytes("iso-8859-1"), 0, token.length()); sha1hash = md.digest(); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); } fileName = convertToHex(sha1hash); if (!new File(Configuration.ImageUploadPath + fileName).exists()) { break; } } return fileName; }
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: public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception { ObjectFactory factory = new ObjectFactory(); SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest(); IdType pid = factory.createIdType(); pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"); sdr.setPatientId(pid); ClassLoader classLoader = JUnitHelper.class.getClassLoader(); DocumentsType documents = factory.createDocumentsType(); for (int i = 0; i < count; ++i) { DocumentType document = factory.createDocumentType(); if ((documentIds != null) && (documentIds.length > i)) { document.setId(documentIds[i]); } CodeType type = factory.createCodeType(); type.setCode("51855-5"); type.setCodeSystem("2.16.840.1.113883.6.1"); document.setType(type); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream is = classLoader.getResourceAsStream(file); assertNotNull(is); IOUtils.copy(is, bos); document.setContent(bos.toByteArray()); documents.getDocument().add(document); } sdr.setDocuments(documents); QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest"); JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr); StringWriter sw = new StringWriter(); marshaller.marshal(element, sw); String xml = sw.toString(); logger.debug(xml); OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml); List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content", URIConstants.XDSBRIDGE_URI); for (OMElement contentNode : list) { OMText binaryNode = (OMText) contentNode.getFirstOMChild(); if (binaryNode != null) { binaryNode.setOptimize(true); } } return result; }
00
Code Sample 1: public static SearchItem register(String... args) { SearchItem _return = new SearchItem(); String line = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(URL_REGISTER); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("firtname", args[0])); nameValuePairs.add(new BasicNameValuePair("lastname", args[1])); nameValuePairs.add(new BasicNameValuePair("email", args[2])); nameValuePairs.add(new BasicNameValuePair("phone", args[3])); nameValuePairs.add(new BasicNameValuePair("password", args[4])); nameValuePairs.add(new BasicNameValuePair("confirmpassword", args[5])); 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); _return.set(0, XMLfunctions.getValue(e, "success")); if ("false".endsWith(_return.get(0))) { _return.set(1, XMLfunctions.getValue(e, "error")); } else { _return.set(1, XMLfunctions.getValue(e, "message")); } return _return; } catch (Exception e) { line = "<results status=\"error\"><msg>Can't connect to server</msg></results>"; line = null; _return.set(0, "false"); _return.set(1, ""); } return _return; } Code Sample 2: public static void main(String[] argv) { ComboPooledDataSource cpds = null; Connection c = null; try { cpds = new ComboPooledDataSource(); cpds.setDriverClass("org.postgresql.Driver"); cpds.setJdbcUrl("jdbc:postgresql://localhost/c3p0-test"); cpds.setUser("swaldman"); cpds.setPassword("test"); cpds.setMinPoolSize(5); cpds.setAcquireIncrement(5); cpds.setMaxPoolSize(20); c = cpds.getConnection(); c.setAutoCommit(false); Statement stmt = c.createStatement(); stmt.executeUpdate("CREATE TABLE pwtest_table (col1 char(5), col2 char(5))"); ResultSet rs = stmt.executeQuery("SELECT * FROM pwtest_table"); System.err.println("rs: " + rs); System.err.println("rs.getStatement(): " + rs.getStatement()); System.err.println("rs.getStatement().getConnection(): " + rs.getStatement().getConnection()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (c != null) c.rollback(); } catch (Exception e) { e.printStackTrace(); } try { if (cpds != null) cpds.close(); } catch (Exception e) { e.printStackTrace(); } } }
11
Code Sample 1: @Test public void testWriteModel() { Model model = new Model(); model.setName("MY_MODEL1"); Stereotype st1 = new Stereotype(); st1.setName("Pirulito1"); PackageObject p1 = new PackageObject("p1"); ClassType type1 = new ClassType("Class1"); type1.setStereotype(st1); type1.addMethod(new Method("doSomething")); p1.add(type1); ClassType type2 = new ClassType("Class2"); Method m2 = new Method("doSomethingElse"); m2.setType(type1); type2.addMethod(m2); p1.add(type2); Generalization g = new Generalization(); g.setSource(type1); g.setTarget(type1); p1.add(g); model.add(p1); ModelWriter writer = new ModelWriter(); try { File modelFile = new File("target", "test.model"); writer.write(model, modelFile); File xmlFile = new File("target", "test.xml"); xmlFile.createNewFile(); IOUtils.copy(new GZIPInputStream(new FileInputStream(modelFile)), new FileOutputStream(xmlFile)); } catch (IOException e) { log.error(e.getMessage(), e); Assert.fail(e.getMessage()); } } Code Sample 2: public StringBuffer render(RenderEngine c) { String logTime = null; if (c.getWorkerContext() != null) { logTime = c.getWorkerContext().getWorkerStart(); } if (c.isBreakState() || !c.canRender("u")) { return new StringBuffer(); } StringBuffer buffer = new StringBuffer(); varname = TagInspector.processElement(varname, c); action = TagInspector.processElement(action, c); filemode = TagInspector.processElement(filemode, c); xmlparse = TagInspector.processElement(xmlparse, c); encoding = TagInspector.processElement(encoding, c); decoding = TagInspector.processElement(decoding, c); filter = TagInspector.processElement(filter, c); sort = TagInspector.processElement(sort, c); useDocroot = TagInspector.processElement(useDocroot, c); useFilename = TagInspector.processElement(useFilename, c); useDest = TagInspector.processElement(useDest, c); xmlOutput = TagInspector.processElement(xmlOutput, c); renderOutput = TagInspector.processElement(renderOutput, c); callProc = TagInspector.processElement(callProc, c); vartype = TagInspector.processElement(vartype, c); if (sort == null || sort.equals("")) { sort = "asc"; } if (useFilename.equals("") && !action.equalsIgnoreCase("listing")) { return new StringBuffer(); } boolean isRooted = true; if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; } } if (isRooted && (useFilename.indexOf("/") == -1 || useFilename.startsWith("./"))) { if (c.getWorkerContext() != null && useFilename.startsWith("./")) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename.substring(2); Debug.inform("CWD path specified in filename, rewritten to '" + useFilename + "'"); } else if (c.getWorkerContext() != null && useFilename.indexOf("/") == -1) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename; Debug.inform("No path specified in filename, rewritten to '" + useFilename + "'"); } else { Debug.inform("No path specified in filename, no worker context, not rewriting filename."); } } StringBuffer filenameData = null; StringBuffer contentsData = null; StringBuffer fileDestData = null; contentsData = TagInspector.processBody(this, c); filenameData = new StringBuffer(useFilename); fileDestData = new StringBuffer(useDest); String currentDocroot = null; if (c.getWorkerContext() == null) { if (c.getRenderContext().getCurrentDocroot() == null) { currentDocroot = "."; } else { currentDocroot = c.getRenderContext().getCurrentDocroot(); } } else { currentDocroot = c.getWorkerContext().getDocRoot(); } if (!isRooted) { currentDocroot = ""; } if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; currentDocroot = ""; } } if (!currentDocroot.endsWith("/")) { if (!currentDocroot.equals("") && currentDocroot.length() > 0) { currentDocroot += "/"; } } if (filenameData != null) { filenameData = new StringBuffer(filenameData.toString().replaceAll("\\.\\.", "")); } if (fileDestData != null) { fileDestData = new StringBuffer(fileDestData.toString().replaceAll("\\.\\.", "")); } if (action.equalsIgnoreCase("read")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileInputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte data[] = null; boolean vfsLoaded = false; try { data = c.getVendContext().getFileAccess().getFile(c.getWorkerContext(), filenameData.toString().replaceAll("\\.\\.", ""), c.getClientContext().getMatchedHost(), c.getVendContext().getVend().getRenderExtension(c.getClientContext().getMatchedHost()), null); bos.write(data, 0, data.length); vfsLoaded = true; } catch (Exception e) { Debug.user(logTime, "Included file attempt with VFS of file '" + filenameData + "' failed: " + e); } if (data == null) { try { is = new FileInputStream(file); } catch (Exception e) { Debug.user(logTime, "Unable to render: Filename '" + currentDocroot + filenameData + "' does not exist."); return new StringBuffer(); } } if (xmlparse == null || xmlparse.equals("")) { if (data == null) { Debug.user(logTime, "Opening filename '" + currentDocroot + filenameData + "' for reading into buffer '" + varname + "'"); data = new byte[32768]; int totalBytesRead = 0; while (true) { int bytesRead; try { bytesRead = is.read(data); bos.write(data, 0, bytesRead); } catch (Exception e) { break; } if (bytesRead <= 0) { break; } totalBytesRead += bytesRead; } } byte docOutput[] = bos.toByteArray(); if (renderOutput != null && renderOutput.equalsIgnoreCase("ssp")) { String outputData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n" + new String(FileAccess.getDefault().processServerPageData(c.getWorkerContext(), docOutput)); docOutput = outputData.getBytes(); } Debug.user(logTime, "File read complete: " + docOutput.length + " byte(s)"); if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (encoding != null && encoding.equalsIgnoreCase("url")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.URLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.URLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("xml")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.XMLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.XMLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("base64")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Base64.encode(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Base64.encode(docOutput)); } } else if (encoding != null && (encoding.equalsIgnoreCase("javascript") || encoding.equalsIgnoreCase("js"))) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.JavascriptEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.JavascriptEncode(new String(docOutput))); } } else { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, new String(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(new String(docOutput)); } } } else { RenderEngine engine = new RenderEngine(null); DocumentEngine docEngine = null; try { if (vfsLoaded) { ByteArrayInputStream bais = new ByteArrayInputStream(data); docEngine = new DocumentEngine(bais); } else { docEngine = new DocumentEngine(is); } } catch (Exception e) { c.setExceptionState(true, "XML parse of data read from file failed: " + e.getMessage()); } engine.setDocumentEngine(docEngine); c.addNodeSet(varname, docEngine.rootTag.thisNode); } if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); } else if (action.equalsIgnoreCase("write")) { try { String rootDir = filenameData.toString(); if (rootDir.lastIndexOf("/") != -1 && rootDir.lastIndexOf("/") != 0) { rootDir = rootDir.substring(0, rootDir.lastIndexOf("/")); java.io.File mkdirFile = new java.io.File(currentDocroot + rootDir); if (!mkdirFile.mkdirs()) { Debug.inform("Unable to create directory '" + currentDocroot + rootDir + "'"); } else { Debug.inform("Created directory '" + currentDocroot + rootDir + "'"); } } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileOutputStream fos = null; if (file == null) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Cannot write to location specified"); return new StringBuffer(); } else if (file.isDirectory()) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Is a directory."); return new StringBuffer(); } if (filemode.equalsIgnoreCase("append")) { fos = new FileOutputStream(file, true); } else { fos = new FileOutputStream(file, false); } if (decoding != null && !decoding.equals("")) { if (decoding.equalsIgnoreCase("base64")) { try { byte contentsDecoded[] = Base64.decode(contentsData.toString().getBytes()); fos.write(contentsDecoded); } catch (Exception e) { c.setExceptionState(true, "Encoded data in &lt;content&gt; element does not contain valid Base64-" + "encoded data."); } } else { fos.write(contentsData.toString().getBytes()); } } else { fos.write(contentsData.toString().getBytes()); } try { fos.flush(); } catch (IOException e) { Debug.inform("Unable to flush output data: " + e.getMessage()); } fos.close(); Debug.user(logTime, "Wrote contents to filename '" + currentDocroot + filenameData + "' (length=" + contentsData.length() + ")"); } catch (IOException e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } catch (Exception e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } } else if (action.equalsIgnoreCase("listing")) { String filenameDataString = filenameData.toString(); if (filenameDataString.equals("")) { filenameDataString = c.getClientContext().getPostVariable("current_path"); } if (filenameDataString == null) { c.setExceptionState(true, "Filename cannot be blank when listing."); return new StringBuffer(); } while (filenameDataString.endsWith("/")) { filenameDataString = filenameDataString.substring(0, filenameDataString.length() - 1); } Vector fileList = new Vector(); java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String curDirname = filenameData.toString(); String parentDirectory = null; String[] dirEntries = curDirname.split("/"); int numSlashes = 0; for (int i = 0; i < curDirname.length(); i++) { if (curDirname.toString().charAt(i) == '/') { numSlashes++; } } parentDirectory = "/"; if (numSlashes > 1) { for (int i = 0; i < (dirEntries.length - 1); i++) { if (dirEntries[i] != null && !dirEntries[i].equals("")) { parentDirectory += dirEntries[i] + "/"; } } } if (parentDirectory.length() > 1 && parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_JAR) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); int depth = 0; for (int i = 0; i < filenameData.toString().length(); i++) { if (filenameData.toString().charAt(i) == '/') { depth++; } } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(list, new ZipSorterAscending()); } else { Arrays.sort(list, new ZipSorterDescending()); } for (int i = 0; i < list.length; i++) { ZipEntry zEntry = (ZipEntry) list[i]; String zipFile = filenameData.toString() + "/" + zEntry.getName(); String displayFilename = zipFile.replaceFirst(filenameData.toString(), ""); int curDepth = 0; if (zipFile.equalsIgnoreCase(".acl") || zipFile.equalsIgnoreCase("access.list") || zipFile.equalsIgnoreCase("application.inc") || zipFile.equalsIgnoreCase("global.inc") || zipFile.indexOf("/.proc") != -1 || zipFile.indexOf("/procedures") != -1) { continue; } for (int x = 0; x < displayFilename.length(); x++) { if (displayFilename.charAt(x) == '/') { curDepth++; } } if (zipFile.startsWith(filenameData.toString())) { String fileLength = "" + zEntry.getSize(); String fileType = "file"; if (curDepth == depth) { if (zEntry.isDirectory()) { fileType = "directory"; } else { fileType = "file"; } String fileMode = "read-only"; String fileTime = Long.toString(zEntry.getTime()); buffer.append(" <file name=\""); buffer.append(displayFilename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(time)", false, fileTime); } } else { if (curDepth == depth) { fileList.add(zipFile); } } } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_FS) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); java.io.File[] filesorted = new java.io.File[list.length]; for (int i = 0; i < list.length; i++) { filesorted[i] = (java.io.File) list[i]; } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(filesorted, new FileSorterAscending()); } else { Arrays.sort(filesorted, new FileSorterDescending()); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < filesorted.length; i++) { java.io.File zEntry = filesorted[i]; String filename = filenameData.toString() + "/" + zEntry.getName(); if (filename.equalsIgnoreCase(".acl") || filename.equalsIgnoreCase("access.list") || filename.equalsIgnoreCase("application.inc") || filename.equalsIgnoreCase("global.inc") || filename.indexOf("/.proc") != -1 || filename.indexOf("/procedures") != -1) { continue; } String displayFilename = filename.replaceFirst(filenameData.toString(), ""); String fileLength = "" + zEntry.length(); String fileType = "file"; if (zEntry.isDirectory()) { fileType = "directory"; } else if (zEntry.isFile()) { fileType = "file"; } else if (zEntry.isHidden()) { fileType = "hidden"; } else if (zEntry.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (zEntry.canRead() && !zEntry.canWrite()) { fileMode = "read-only"; } else if (!zEntry.canRead() && zEntry.canWrite()) { fileMode = "write-only"; } else if (zEntry.canRead() && zEntry.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(zEntry.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(filename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(zEntry); } c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else { String[] fileStringList = null; if (!filter.equals("")) { fileStringList = file.list(new ListFilter(filter)); } else { fileStringList = file.list(); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(fileStringList, new StringSorterAscending()); } else { Arrays.sort(fileStringList, new StringSorterDescending()); } if (fileStringList == null) { buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); } else { c.getVariableContainer().setVector(varname, fileList); } return new StringBuffer(); } else { Debug.user(logTime, "Directory '" + currentDocroot + filenameData + "' returns " + fileStringList.length + " entry(ies)"); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < fileStringList.length; i++) { file = new java.io.File(currentDocroot + filenameData.toString() + "/" + fileStringList[i]); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } else if (file.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(fileStringList[i]); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(fileStringList[i]); } c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } } else if (action.equalsIgnoreCase("delete")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.isDirectory()) { boolean success = deleteDir(new java.io.File(currentDocroot + filenameData.toString())); if (!success) { c.setExceptionState(true, "Unable to delete '" + currentDocroot + filenameData + "'"); } } else { String filenamePattern = null; if (filenameData.toString().indexOf("/") != -1) { filenamePattern = filenameData.toString().substring(filenameData.toString().lastIndexOf("/") + 1); } String filenameDirectory = currentDocroot; if (filenameData.toString().indexOf("/") != -1) { filenameDirectory += filenameData.substring(0, filenameData.toString().lastIndexOf("/")); } String[] fileStringList = null; file = new java.io.File(filenameDirectory); fileStringList = file.list(new ListFilter(filenamePattern)); for (int i = 0; i < fileStringList.length; i++) { (new java.io.File(filenameDirectory + "/" + fileStringList[i])).delete(); } } } else if (action.equalsIgnoreCase("rename") || action.equalsIgnoreCase("move")) { if (fileDestData.equals("")) { c.getVariableContainer().setVariable(varname + "-result", filenameData + ": File operation failed: No destination filename given."); return new StringBuffer(); } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); boolean success = file.renameTo(new java.io.File(currentDocroot + fileDestData.toString(), file.getName())); if (!success) { c.setExceptionState(true, "Unable to rename '" + currentDocroot + filenameData + "' to '" + currentDocroot + fileDestData + "'"); } } else if (action.equalsIgnoreCase("copy")) { if (fileDestData.equals("")) { c.setExceptionState(true, "File copy operation failed for file '" + filenameData + "': No destination file specified."); return new StringBuffer(); } FileChannel srcChannel; FileChannel destChannel; String filename = null; filename = currentDocroot + filenameData.toString(); if (vartype != null && vartype.equalsIgnoreCase("file")) { if (useFilename.indexOf("/") != -1) { useFilename = useFilename.substring(useFilename.lastIndexOf("/") + 1); } filename = c.getVariableContainer().getFileVariable(useFilename); } try { Debug.debug("Copying from file '" + filename + "' to '" + fileDestData.toString() + "'"); srcChannel = new FileInputStream(filename).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' failed to read: " + e.getMessage()); return new StringBuffer(); } try { destChannel = new FileOutputStream(currentDocroot + fileDestData.toString()).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy to '" + fileDestData + "' failed to write: " + e.getMessage()); return new StringBuffer(); } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", filenameData + " copy to " + fileDestData + ": File copy succeeded."); } else { return new StringBuffer("true"); } } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' to '" + fileDestData + "' failed: " + e.getMessage()); } } else if (action.equalsIgnoreCase("exists")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.exists()) { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "true"); } else { return new StringBuffer("true"); } } else { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "false"); } else { return new StringBuffer("false"); } } } else if (action.equalsIgnoreCase("mkdir")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.mkdirs()) { if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", "created"); } else { return new StringBuffer("true"); } } else { c.setExceptionState(true, "Unable to create directory '" + filenameData + "'"); } } else if (action.equalsIgnoreCase("info")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isAbsolute()) { fileType = "absolute"; } else if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (varname != null && !varname.equals("")) { c.getVariableContainer().setVariable(varname + ".length", fileLength); c.getVariableContainer().setVariable(varname + ".type", fileType); c.getVariableContainer().setVariable(varname + ".mode", fileMode); c.getVariableContainer().setVariable(varname + ".modtime", fileTime); } else { buffer = new StringBuffer(); buffer.append("<file name=\""); buffer.append(filenameData); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); return buffer; } } if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); }
11
Code Sample 1: public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception { CipherInputStream in; OutputStream out; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.DECRYPT_MODE, key); in = new CipherInputStream(new FileInputStream(encryptedFile), cipher); out = new FileOutputStream(decryptedFile); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); } Code Sample 2: public static void copyFile4(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); IOUtils.copy(in, out); in.close(); out.close(); }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 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(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static String encriptaSenha(String string) throws ApplicationException { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(string.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); throw new ApplicationException("Erro ao Encriptar Senha"); } }
00
Code Sample 1: public final int sendMetaData(FileInputStream fis) throws Exception { try { UUID uuid = UUID.randomUUID(); HttpClient client = new SSLHttpClient(); StringBuilder builder = new StringBuilder(mServer).append("?cmd=meta").append("&id=" + uuid); HttpPost method = new HttpPost(builder.toString()); String fileName = uuid + ".metadata"; FileInputStreamPart part = new FileInputStreamPart("data", fileName, fis); MultipartEntity requestContent = new MultipartEntity(new Part[] { part }); method.setEntity(requestContent); HttpResponse response = client.execute(method); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { return 0; } else { return -1; } } catch (Exception e) { throw new Exception("send meta data", e); } } Code Sample 2: public static byte[] loadFile(File file) throws IOException { BufferedInputStream in = null; ByteArrayOutputStream sink = null; try { in = new BufferedInputStream(new FileInputStream(file)); sink = new ByteArrayOutputStream(); IOUtils.copy(in, sink); return sink.toByteArray(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(sink); } }
00
Code Sample 1: private void retrieveClasses(URL url, Map<String, T> cmds) { try { String resource = URLDecoder.decode(url.getPath(), "UTF-8"); File directory = new File(resource); if (directory.exists()) { String[] files = directory.list(); for (String file : files) { if (file.endsWith(".class")) { addInstanceIfCommand(pckgname + '.' + file.substring(0, file.length() - 6), cmds); } } } else { JarURLConnection con = (JarURLConnection) url.openConnection(); String starts = con.getEntryName(); Enumeration<JarEntry> entriesEnum = con.getJarFile().entries(); while (entriesEnum.hasMoreElements()) { ZipEntry entry = (ZipEntry) entriesEnum.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) { classname = classname.substring(1); } classname = classname.replace('/', '.'); addInstanceIfCommand(classname, cmds); } } } } catch (IOException ioe) { LOG.warning("couldn't retrieve classes of " + url + ". Reason: " + ioe); } } Code Sample 2: @SuppressWarnings("unchecked") private Map getURLMap(String request) throws IOException { Map map = null; try { URL url = new URL(dbURL + request); URLConnection conn = url.openConnection(); conn.connect(); JSONParser parser = JSONParser.defaultJSONParser(); InputStreamSource stream = new InputStreamSource(conn.getInputStream(), true); map = parser.parse(Map.class, stream); stream.destroy(); } catch (MalformedURLException mue) { System.err.println("Internal malformed url Exception: " + mue); } return map; }
11
Code Sample 1: private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } } Code Sample 2: @Override public void createCopy(File sourceFile, File destinnationFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinnationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: private void publishCMap(LWMap map) throws IOException { try { File savedCMap = PublishUtil.createIMSCP(Publisher.resourceVector); InputStream istream = new BufferedInputStream(new FileInputStream(savedCMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("IMSCP", "zip"))); int fileLength = (int) savedCMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } catch (IOException ex) { throw ex; } catch (Exception ex) { System.out.println(ex); VueUtil.alert(VUE.getDialogParent(), VueResources.getString("dialog.export.message") + ex.getMessage(), VueResources.getString("dialog.export.title"), JOptionPane.ERROR_MESSAGE); } } Code Sample 2: 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; }
00
Code Sample 1: private void documentFileChooserActionPerformed(java.awt.event.ActionEvent evt) { if (evt.getActionCommand().equals(JFileChooser.APPROVE_SELECTION)) { File selectedFile = documentFileChooser.getSelectedFile(); File collectionCopyFile; String newDocumentName = selectedFile.getName(); Document newDocument = new Document(newDocumentName); if (activeCollection.containsDocument(newDocument)) { int matchingFilenameDistinguisher = 1; StringBuilder distinguisherReplacer = new StringBuilder(); newDocumentName = newDocumentName.concat("(" + matchingFilenameDistinguisher + ")"); newDocument.setDocumentName(newDocumentName); while (activeCollection.containsDocument(newDocument)) { matchingFilenameDistinguisher++; newDocumentName = distinguisherReplacer.replace(newDocumentName.length() - 2, newDocumentName.length() - 1, new Integer(matchingFilenameDistinguisher).toString()).toString(); newDocument.setDocumentName(newDocumentName); } } Scanner tokenizer = null; FileChannel fileSource = null; FileChannel collectionDestination = null; HashMap<String, Integer> termHashMap = new HashMap<String, Integer>(); Index collectionIndex = activeCollection.getIndex(); int documentTermMaxFrequency = 0; int currentTermFrequency; try { tokenizer = new Scanner(new BufferedReader(new FileReader(selectedFile))); tokenizer.useDelimiter(Pattern.compile("\\p{Space}|\\p{Punct}|\\p{Cntrl}")); String nextToken; while (tokenizer.hasNext()) { nextToken = tokenizer.next().toLowerCase(); if (!nextToken.isEmpty()) if (termHashMap.containsKey(nextToken)) termHashMap.put(nextToken, termHashMap.get(nextToken) + 1); else termHashMap.put(nextToken, 1); } Term newTerm; for (String term : termHashMap.keySet()) { newTerm = new Term(term); if (!collectionIndex.termExists(newTerm)) collectionIndex.addTerm(newTerm); currentTermFrequency = termHashMap.get(term); if (currentTermFrequency > documentTermMaxFrequency) documentTermMaxFrequency = currentTermFrequency; collectionIndex.addOccurence(newTerm, newDocument, currentTermFrequency); } activeCollection.addDocument(newDocument); String userHome = System.getProperty("user.home"); String fileSeparator = System.getProperty("file.separator"); collectionCopyFile = new File(userHome + fileSeparator + "Infrared" + fileSeparator + activeCollection.getDocumentCollectionName() + fileSeparator + newDocumentName); collectionCopyFile.createNewFile(); fileSource = new FileInputStream(selectedFile).getChannel(); collectionDestination = new FileOutputStream(collectionCopyFile).getChannel(); collectionDestination.transferFrom(fileSource, 0, fileSource.size()); } catch (FileNotFoundException e) { System.err.println(e.getMessage() + " This error should never occur! The file was just selected!"); return; } catch (IOException e) { JOptionPane.showMessageDialog(this, "An I/O error occured during file transfer!", "File transfer I/O error", JOptionPane.WARNING_MESSAGE); return; } finally { try { if (tokenizer != null) tokenizer.close(); if (fileSource != null) fileSource.close(); if (collectionDestination != null) collectionDestination.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } else if (evt.getActionCommand().equalsIgnoreCase(JFileChooser.CANCEL_SELECTION)) processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } Code Sample 2: protected void givenTestRepository(String repositoryId) throws Exception { HttpResponse response = executeDeleteWithResponse("/repositories/" + repositoryId); consume(response.getEntity()); response = executePost("/repositories", createRepositoryXml(repositoryId)); assertEquals(content(response), SC_CREATED, statusCode(response)); }
00
Code Sample 1: public float stampPerson(PEntry pe) throws SQLException { conn.setAutoCommit(false); float result; try { Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("SELECT now();"); rset.next(); Timestamp now = rset.getTimestamp("now()"); Calendar cal = new GregorianCalendar(); cal.setTime(now); if (pe.getState() != 0) { for (int i = 0; i < pe.getOpenItems().size(); i++) { Workitem wi = (Workitem) pe.getOpenItems().get(i); long diff = now.getTime() - wi.getIntime(); float diffp = diff * (float) 1f / pe.getOpenItems().size(); stmt.executeUpdate("UPDATE stampzk SET outtime='" + now.getTime() + "', diff='" + diff + "', diffp='" + diffp + "' WHERE stampzkid='" + wi.getStampZkId() + "';"); } rset = stmt.executeQuery("SELECT intime FROM stamppersonal WHERE stamppersonalid='" + pe.getState() + "';"); rset.next(); long inDate = rset.getLong("intime"); long diff = (now.getTime() - inDate); stmt.executeUpdate("UPDATE stamppersonal SET outtime='" + now.getTime() + "', diff='" + diff + "' WHERE stamppersonalid='" + pe.getState() + "';"); stmt.executeUpdate("UPDATE personal SET stamppersonalid='0' WHERE personalnr='" + pe.getPersonalId() + "';"); stmt.executeUpdate("UPDATE personalyearworktime SET worktime=worktime+" + (float) diff / 3600000f + " WHERE year=" + cal.get(Calendar.YEAR) + " AND personalid='" + pe.getPersonalId() + "';"); rset = stmt.executeQuery("SELECT SUM(diff) AS twt FROM stamppersonal WHERE personalid='" + pe.getPersonalId() + "' AND datum='" + cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH) + "';"); rset.next(); result = (float) rset.getInt("twt") / 3600000f; } else { stmt.executeUpdate("INSERT INTO stamppersonal SET personalid='" + pe.getPersonalId() + "', intime='" + now.getTime() + "', datum='" + cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH) + "';"); rset = stmt.executeQuery("SELECT stamppersonalid FROM stamppersonal WHERE personalid='" + pe.getPersonalId() + "' AND outtime='0' ORDER BY stamppersonalid DESC LIMIT 1;"); rset.next(); int sppid = rset.getInt("stamppersonalid"); stmt.executeUpdate("UPDATE personal SET stamppersonalid='" + sppid + "' WHERE personalnr='" + pe.getPersonalId() + "';"); Calendar yest = new GregorianCalendar(); yest.setTime(now); yest.add(Calendar.DAY_OF_YEAR, -1); rset = stmt.executeQuery("SELECT SUM(diff) AS twt FROM stamppersonal WHERE personalid='" + pe.getPersonalId() + "' AND datum='" + cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH) + "';"); rset.next(); float today = (float) rset.getInt("twt") / 3600000f; rset = stmt.executeQuery("SELECT worktime FROM personalyearworktime WHERE personalid='" + pe.getPersonalId() + "' AND year='" + cal.get(Calendar.YEAR) + "';"); rset.next(); float ist = rset.getFloat("worktime") - today; rset = stmt.executeQuery("SELECT duetime FROM dueworktime WHERE datum='" + yest.get(Calendar.YEAR) + "-" + (yest.get(Calendar.MONTH) + 1) + "-" + yest.get(Calendar.DAY_OF_MONTH) + "' AND personalid='" + pe.getPersonalId() + "';"); rset.next(); result = ist - rset.getFloat("duetime"); } } catch (SQLException sqle) { conn.rollback(); conn.setAutoCommit(true); throw sqle; } conn.commit(); conn.setAutoCommit(true); return result; } Code Sample 2: public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { URL url = configuration.get(publicID); try { if (url != null) return url.openStream(); } catch (IOException ex) { throw new XMLStreamException(String.format("Unable to open stream for resource %s: %s", url, InternalUtils.toMessage(ex)), ex); } return null; }
00
Code Sample 1: public void getLyricsFromMAWebSite(TrackMABean tb) throws Exception { URL fileURL = new URL("http://www.metal-archives.com/viewlyrics.php?id=" + tb.getMaid()); URLConnection urlConnection = fileURL.openConnection(); InputStream httpStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1")); String ligne; boolean chargerLyrics = false; StringBuffer sb = new StringBuffer(""); String lyrics = null; while ((ligne = br.readLine()) != null) { log.debug("==> " + ligne); if (chargerLyrics && ligne.indexOf("<center>") != -1) { break; } if (chargerLyrics) { sb.append(ligne.trim()); } if (!chargerLyrics && ligne.indexOf("<center>") != -1) { chargerLyrics = true; } } lyrics = sb.toString(); lyrics = lyrics.replaceAll("<br>", "\n").trim(); log.debug("Parole : " + lyrics); tb.setLyrics(lyrics); br.close(); httpStream.close(); } Code Sample 2: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); int i; Vector images = new Vector(); images = dataBase.allImageSearch(); lengthOfTask = images.size() * 2; String directory = directoryPath + "Images" + myDirectory.separator; File newDirectoryFolder = new File(directory); newDirectoryFolder.mkdirs(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); doc = domBuilder.newDocument(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Element dbElement = doc.createElement("dataBase"); for (i = 0; ((i < images.size()) && !stop); i++) { current = i; String element = (String) images.elementAt(i); String pathSrc = "Images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(myDirectory.separator) + 1, pathSrc.length()); String pathDst = directory + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector keyWords = new Vector(); keyWords = dataBase.asociatedConceptSearch((String) images.elementAt(i)); Element imageElement = doc.createElement("image"); Element imageNameElement = doc.createElement("name"); imageNameElement.appendChild(doc.createTextNode(name)); imageElement.appendChild(imageNameElement); for (int j = 0; j < keyWords.size(); j++) { Element keyWordElement = doc.createElement("keyWord"); keyWordElement.appendChild(doc.createTextNode((String) keyWords.elementAt(j))); imageElement.appendChild(keyWordElement); } dbElement.appendChild(imageElement); } try { doc.appendChild(dbElement); File dst = new File(directory.concat("Images")); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF-8")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(bufferWriter); transformer.transform(source, result); bufferWriter.close(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } current = lengthOfTask; }
00
Code Sample 1: public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } } Code Sample 2: public static String sendSoapMsg(String SOAPUrl, byte[] b, String SOAPAction) throws IOException { log.finest("HTTP REQUEST SIZE " + b.length); if (SOAPAction.startsWith("\"") == false) SOAPAction = "\"" + SOAPAction + "\""; URL url = new URL(SOAPUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty("Pragma", "no-cache"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); StringBuffer response = new StringBuffer(1024); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); log.finest("HTTP RESPONSE SIZE: " + response.length()); return response.toString(); }
00
Code Sample 1: public ArrayList<Jane16Results> callExternalService(ServiceType type, HashMap<String, String> params) throws Exception { URL url = initURL(type, params); XMLParser parser = initParser(type); InputStream in = url.openStream(); ArrayList<Jane16Results> results = new ArrayList<Jane16Results>(); byte[] buf = new byte[1024]; ArrayList<Byte> arrByte = new ArrayList<Byte>(); int len; while ((len = in.read(buf)) > 0) { for (int i = 0; i < len; i++) { arrByte.add(buf[i]); } } in.close(); byte[] data = new byte[arrByte.size()]; int i = 0; for (Byte b : arrByte) { data[i++] = b; } results = parser.parse(data); return results; } Code Sample 2: public boolean exists(String filename) { String localFileName = (java.io.File.separatorChar != '/') ? filename.replace('/', java.io.File.separatorChar) : filename; for (int i = 0; i < dirs.length; i++) { if (zipEntries[i] != null) { if (zipEntries[i].get(filename) != null) return true; String dir = ""; String name = filename; int index = filename.lastIndexOf('/'); if (index >= 0) { dir = filename.substring(0, index); name = filename.substring(index + 1); } Vector directory = (Vector) zipEntries[i].get(dir); if (directory != null && directory.contains(name)) return true; continue; } if (bases[i] != null) { try { URL url = new URL(bases[i], filename); URLConnection conn = url.openConnection(); conn.connect(); conn.getInputStream().close(); return true; } catch (IOException ex) { } continue; } if (dirs[i] == null) continue; if (zips[i] != null) { String fullname = zipDirs[i] != null ? zipDirs[i] + filename : filename; ZipEntry ze = zips[i].getEntry(fullname); if (ze != null) return true; } else { try { File f = new File(dirs[i], localFileName); if (f.exists()) return true; } catch (SecurityException ex) { } } } return false; }
00
Code Sample 1: public boolean update(int idJugador, jugador jugadorModificado) { int intResult = 0; String sql = "UPDATE jugador " + "SET apellidoPaterno = ?, apellidoMaterno = ?, nombres = ?, fechaNacimiento = ?, " + " pais = ?, rating = ?, sexo = ? " + " WHERE idJugador = " + idJugador; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(jugadorModificado); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); } Code Sample 2: public static InputStreamReader getInputStreamReader(String name) throws java.io.IOException { URL url = getURL(name); if (url != null) { return new InputStreamReader(url.openStream()); } throw new FileNotFoundException("UniverseData: Resource \"" + name + "\" not found."); }
00
Code Sample 1: public void doActionOn(TomcatProject prj) throws Exception { String path = TomcatLauncherPlugin.getDefault().getManagerAppUrl(); try { path += "/reload?path=" + prj.getWebPath(); URL url = new URL(path); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String user = TomcatLauncherPlugin.getDefault().getManagerAppUser(); String password = TomcatLauncherPlugin.getDefault().getManagerAppPassword(); return new PasswordAuthentication(user, password.toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getContent(); connection.disconnect(); Authenticator.setDefault(null); } catch (Exception e) { throw new Exception("The following url was used : \n" + path + "\n\nCheck manager app settings (username and password)\n\n"); } } Code Sample 2: private Properties loadProperties(final String propertiesName) throws IOException { Properties bundle = null; final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final URL url = loader.getResource(propertiesName); if (url == null) { throw new IOException("Properties file " + propertiesName + " not found"); } final InputStream is = url.openStream(); if (is != null) { bundle = new Properties(); bundle.load(is); } else { throw new IOException("Properties file " + propertiesName + " not avilable"); } return bundle; }
00
Code Sample 1: public static File copy(String inFileName, String outFileName) throws IOException { File inputFile = new File(inFileName); File outputFile = new File(outFileName); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return outputFile; } Code Sample 2: private void loadMap(URI uri) throws IOException { BufferedReader reader = null; InputStream stream = null; try { URL url = uri.toURL(); stream = url.openStream(); if (url.getFile().endsWith(".gz")) { stream = new GZIPInputStream(stream); } reader = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { String[] parts = line.split(" "); if (parts.length == 2) { pinyinZhuyinMap.put(parts[0], parts[1]); zhuyinPinyinMap.put(parts[1], parts[0]); } } } } finally { if (reader != null) { reader.close(); } } }
00
Code Sample 1: public static void ftpUpload(FTPConfig config, String directory, File file, String remoteFileName) throws IOException { FTPClient server = new FTPClient(); server.connect(config.host, config.port); assertValidReplyCode(server.getReplyCode(), server); server.login(config.userName, config.password); assertValidReplyCode(server.getReplyCode(), server); assertValidReplyCode(server.cwd(directory), server); server.setFileTransferMode(FTP.IMAGE_FILE_TYPE); server.setFileType(FTP.IMAGE_FILE_TYPE); server.storeFile(remoteFileName, new FileInputStream(file)); assertValidReplyCode(server.getReplyCode(), server); server.sendNoOp(); server.disconnect(); } Code Sample 2: public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { throw new ForumException("" + e); } return hexString.toString(); }
11
Code Sample 1: public synchronized String getSerialNumber() { if (serialNum != null) return serialNum; final StringBuffer buf = new StringBuffer(); Iterator it = classpath.iterator(); while (it.hasNext()) { ClassPathEntry entry = (ClassPathEntry) it.next(); buf.append(entry.getResourceURL().toString()); buf.append(":"); } serialNum = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { MessageDigest digest = MessageDigest.getInstance("SHA"); digest.update(buf.toString().getBytes()); byte[] data = digest.digest(); serialNum = new BASE64Encoder().encode(data); return serialNum; } catch (NoSuchAlgorithmException exp) { BootSecurityManager.securityLogger.log(Level.SEVERE, exp.getMessage(), exp); return buf.toString(); } } }); return serialNum; } Code Sample 2: private byte[] md5Digest(String pPassword) { if (pPassword == null) { throw new NullPointerException("input null text for hashing"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pPassword.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Cannot find MD5 algorithm"); } }
00
Code Sample 1: private HttpURLConnection prepare(URL url, String method) { if (this.username != null && this.password != null) { this.headers.put("Authorization", "Basic " + Codec.encodeBASE64(this.username + ":" + this.password)); } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); checkFileBody(connection); connection.setRequestMethod(method); for (String key : this.headers.keySet()) { connection.setRequestProperty(key, headers.get(key)); } return connection; } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: private File downloadURL(URL url) { MerlotDebug.msg("Downloading URL: " + url); String filename = url.getFile(); if (filename.indexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } File userPluginsDir = new File(XMLEditorSettings.USER_MERLOT_DIR, "plugins"); File cache = new File(userPluginsDir, filename); try { if (!userPluginsDir.exists()) { userPluginsDir.mkdirs(); } URLConnection connection = url.openConnection(); if (cache.exists() && cache.canRead()) { connection.connect(); long remoteTimestamp = connection.getLastModified(); if (remoteTimestamp == 0 || remoteTimestamp > cache.lastModified()) { cache = downloadContent(connection, cache); } else { MerlotDebug.msg("Using cached version for URL: " + url); } } else { cache = downloadContent(connection, cache); } } catch (IOException ex) { MerlotDebug.exception(ex); } if (cache != null && cache.exists()) { return cache; } else { return null; } }
00
Code Sample 1: public void testHttpsConnection() { try { URL url = new URL("https://addons.mozilla.org/zh-CN/firefox/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.getOutputStream().write("hello".getBytes()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private void request() { try { connection = (HttpURLConnection) new URL(url).openConnection(); if (isCometConnection) { connection.setReadTimeout(0); } else { connection.setReadTimeout(30000); } connection.setInstanceFollowRedirects(false); connection.setDoInput(true); connection.setRequestMethod(method); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB5"); if ("post".equalsIgnoreCase(method)) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } if (user != null) { String auth = user + ":" + (password != null ? password : ""); String base64Auth = HttpRequest.Base64.byteArrayToBase64(auth.getBytes()); connection.setRequestProperty("Authorization", "Basic " + base64Auth); } for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); connection.setRequestProperty(key, (String) headers.get(key)); } connection.setUseCaches(false); if (checkAbort()) return; if ("post".equalsIgnoreCase(method)) { DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); activeOS = dos; if (content != null) { dos.writeBytes(content); } if (checkAbort()) return; dos.flush(); dos.close(); activeOS = null; } if (checkAbort()) return; InputStream is = null; try { is = connection.getInputStream(); } catch (IOException e) { if (checkAbort()) return; readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection = null; readyState = 0; return; } activeIS = is; if (readyState < 2) { readyState = 2; status = connection.getResponseCode(); statusText = connection.getResponseMessage(); if (onreadystatechange != null) { onreadystatechange.onSent(); } } receiving = initializeReceivingMonitor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buffer = new byte[10240]; int read; while (!toAbort && (read = is.read(buffer)) != -1) { if (checkAbort()) return; if (readyState != 3) { readyState = 3; if (onreadystatechange != null) { onreadystatechange.onReceiving(); } } boolean received = false; if (receiving != null) { received = receiving.receiving(baos, buffer, 0, read); } if (!received) { baos.write(buffer, 0, read); } } if (checkAbort()) return; is.close(); activeIS = null; responseText = null; String type = connection.getHeaderField("Content-Type"); if (type != null) { String charset = null; String lowerType = type.toLowerCase(); int idx = lowerType.indexOf("charset="); if (idx != -1) { charset = type.substring(idx + 8); } else { idx = lowerType.indexOf("/xml"); if (idx != -1) { String tmp = baos.toString(); Matcher matcher = Pattern.compile("<\\?.*encoding\\s*=\\s*[\'\"]([^'\"]*)[\'\"].*\\?>", Pattern.MULTILINE).matcher(tmp); if (matcher.find()) { charset = matcher.group(1); } else { responseText = tmp; } } else { idx = lowerType.indexOf("html"); if (idx != -1) { String tmp = baos.toString(); Matcher matcher = Pattern.compile("<meta.*content\\s*=\\s*[\'\"][^'\"]*charset\\s*=\\s*([^'\"]*)\\s*[\'\"].*>", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(tmp); if (matcher.find()) { charset = matcher.group(1); } else { responseText = tmp; } } } } if (charset != null) { try { responseText = baos.toString(charset); } catch (UnsupportedEncodingException e) { } } } if (responseText == null) { try { responseText = baos.toString("iso-8859-1"); } catch (UnsupportedEncodingException e) { responseText = baos.toString(); } } readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection.disconnect(); readyState = 0; } catch (Exception e) { if (checkAbort()) return; e.printStackTrace(); readyState = 4; if (onreadystatechange != null) { onreadystatechange.onLoaded(); } connection = null; readyState = 0; } }
00
Code Sample 1: public static void loadConfig(URL urlFile) throws CacheException { Document document; try { document = Utilities.getDocument(urlFile.openStream()); } catch (IOException e) { throw new CacheException("Could not open '" + urlFile.getFile() + "'", e); } catch (JAnalyticsException e) { throw new CacheException("Could not open '" + urlFile.getFile() + "'", e); } Element element = (Element) document.getElementsByTagName(DOCUMENT_CACHE_ELEMENT_NAME).item(0); if (element != null) { String className = element.getAttribute(CLASSNAME_ATTRIBUTE_NAME); if (className != null) { Properties config = new Properties(); NodeList nodes = element.getElementsByTagName(PARAM_ELEMENT_NAME); if (nodes != null) { for (int i = 0, count = nodes.getLength(); i < count; i++) { Node node = nodes.item(i); if (node instanceof Element) { Element n = (Element) node; String name = n.getAttribute(NAME_ATTRIBUTE_NAME); String value = n.getAttribute(VALUE_ATTRIBUTE_NAME); config.put(name, value); } } } loadConfig(className, config); } } } Code Sample 2: public static String remove_file(String sessionid, String key) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "remove_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "remove_file")); nameValuePairs.add(new BasicNameValuePair("keys", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", resultJsonString); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; }
11
Code Sample 1: private static void unpackEntry(File destinationFile, ZipInputStream zin, ZipEntry entry) throws Exception { if (!entry.isDirectory()) { createFolders(destinationFile.getParentFile()); FileOutputStream fis = new FileOutputStream(destinationFile); try { IOUtils.copy(zin, fis); } finally { zin.closeEntry(); fis.close(); } } else { createFolders(destinationFile); } } Code Sample 2: public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 4., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); }
11
Code Sample 1: public String genPass() { String salto = "Z1mX502qLt2JTcW9MTDTGBBw8VBQQmY2"; String clave = (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10) + "" + (int) (Math.random() * 10); password = clave; String claveConSalto = clave + salto; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); m.update(claveConSalto.getBytes("utf-8"), 0, claveConSalto.length()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String claveCifrada = new BigInteger(1, m.digest()).toString(16); return claveCifrada + ":" + salto; } Code Sample 2: private static String getVisitorId(String guid, String account, String userAgent, Cookie cookie) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (cookie != null && cookie.getValue() != null) { return cookie.getValue(); } String message; if (!isEmpty(guid)) { message = guid + account; } else { message = userAgent + getRandomNumber() + UUID.randomUUID().toString(); } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(message.getBytes("UTF-8"), 0, message.length()); byte[] sum = m.digest(); BigInteger messageAsNumber = new BigInteger(1, sum); String md5String = messageAsNumber.toString(16); while (md5String.length() < 32) { md5String = "0" + md5String; } return "0x" + md5String.substring(0, 16); }
11
Code Sample 1: public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint, String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml, String charset, InternetHeaders headers, String priority) throws MailException { try { if (charset == null) { charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName()); } if ((body == null) || body.trim().equals("")) { body = " "; } Email email = null; if (isHtml) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charset); Users user = getUser(hsession, repositoryName); Identity identity = getIdentity(hsession, ideIdint, user); InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName()); InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName()); InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null); InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null); InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null); if (_from != null) { email.setFrom(_from.getAddress(), _from.getPersonal()); } if (_returnPath != null) { email.addHeader("Return-Path", _returnPath.getAddress()); email.addHeader("Errors-To", _returnPath.getAddress()); email.addHeader("X-Errors-To", _returnPath.getAddress()); } if (_replyTo != null) { email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal()); } if ((_to != null) && (_to.length > 0)) { HashSet aux = new HashSet(_to.length); Collections.addAll(aux, _to); email.setTo(aux); } if ((_cc != null) && (_cc.length > 0)) { HashSet aux = new HashSet(_cc.length); Collections.addAll(aux, _cc); email.setCc(aux); } if ((_bcc != null) && (_bcc.length > 0)) { HashSet aux = new HashSet(_bcc.length); Collections.addAll(aux, _bcc); email.setBcc(aux); } email.setSubject(subject); Date now = new Date(); email.setSentDate(now); File dir = new File(System.getProperty("user.home") + File.separator + "tmp"); if (!dir.exists()) { dir.mkdir(); } if ((attachments != null) && (attachments.size() > 0)) { for (int i = 0; i < attachments.size(); i++) { ByteArrayInputStream bais = null; FileOutputStream fos = null; try { MailPartObj obj = (MailPartObj) attachments.get(i); File file = new File(dir, obj.getName()); bais = new ByteArrayInputStream(obj.getAttachent()); fos = new FileOutputStream(file); IOUtils.copy(bais, fos); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(file.getPath()); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("File Attachment: " + file.getName()); attachment.setName(file.getName()); if (email instanceof MultiPartEmail) { ((MultiPartEmail) email).attach(attachment); } } catch (Exception ex) { } finally { IOUtils.closeQuietly(bais); IOUtils.closeQuietly(fos); } } } if (headers != null) { Header xheader; Enumeration xe = headers.getAllHeaders(); for (; xe.hasMoreElements(); ) { xheader = (Header) xe.nextElement(); if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) { email.addHeader(xheader.getName(), xheader.getValue()); } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) { email.addHeader(xheader.getName(), xheader.getValue()); } } } if (priority != null) { if (priority.equals("high")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "1"); } else if (priority.equals("low")) { email.addHeader("Importance", priority); email.addHeader("X-priority", "5"); } } if (email instanceof HtmlEmail) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } email.setMailSession(session); email.buildMimeMessage(); MimeMessage mime = email.getMimeMessage(); int size = MessageUtilities.getMessageSize(mime); if (!controlQuota(hsession, user, size)) { throw new MailException("ErrorMessages.mail.quota.exceded"); } messageable.storeDraftMessage(getId(), mime, user); } catch (MailException e) { throw e; } catch (Exception e) { throw new MailException(e); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } } Code Sample 2: private static void copyFile(String src, String dst) throws InvocationTargetException { try { FileChannel srcChannel; srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (FileNotFoundException e) { throw new InvocationTargetException(e, Messages.ALFWizardCreationAction_errorSourceFilesNotFound); } catch (IOException e) { throw new InvocationTargetException(e, Messages.ALFWizardCreationAction_errorCopyingFiles); } }
11
Code Sample 1: public static void zipFile(String file, String entry) throws IOException { FileInputStream in = new FileInputStream(file); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file + ".zip")); out.putNextEntry(new ZipEntry(entry)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.closeEntry(); out.close(); File fin = new File(file); fin.delete(); } Code Sample 2: public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } }
00
Code Sample 1: protected void copyFile(File src, File dest) throws Exception { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); long transferred = destChannel.transferFrom(srcChannel, 0, srcChannel.size()); if (transferred != srcChannel.size()) throw new Exception("Could not transfer entire file"); srcChannel.close(); destChannel.close(); } Code Sample 2: private HttpURLConnection getConnection(String url, int connTimeout, int readTimeout) throws IOException { HttpURLConnection con = null; con = (HttpURLConnection) new URL(url).openConnection(); if (connTimeout > 0) { if (!isJDK14orEarlier) { con.setConnectTimeout(connTimeout * 1000); } else { System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(connTimeout * 1000)); } } if (readTimeout > 0) { if (!isJDK14orEarlier) { con.setReadTimeout(readTimeout * 1000); } else { System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(readTimeout * 1000)); } } con.setInstanceFollowRedirects(false); return con; }
00
Code Sample 1: private GmailContact convertContactToGmailContact(Contact contact) throws GmailManagerException { boolean homePhone = false, homePhone2 = false, homeFax = false, homeMobile = false, homePager = false; boolean businessPhone = false, businessPhone2 = false, businessFax = false, businessMobile = false, businessPager = false; boolean otherPhone = false, otherFax = false; if (log.isTraceEnabled()) log.trace("Converting Foundation contact to Gmail contact: Name:" + contact.getName().getFirstName().getPropertyValueAsString()); try { GmailContact gmailContact = new GmailContact(); gmailContact.setId(contact.getUid()); Name name = contact.getName(); if (name != null) if (name.getFirstName() != null && name.getFirstName().getPropertyValueAsString() != null) { StringBuffer buffer = new StringBuffer(); buffer.append(name.getFirstName().getPropertyValueAsString()).append(" "); if (name.getMiddleName() != null && name.getMiddleName().getPropertyValueAsString() != null) buffer.append(name.getMiddleName().getPropertyValueAsString()).append(" "); if (name.getLastName() != null && name.getLastName().getPropertyValueAsString() != null) buffer.append(name.getLastName().getPropertyValueAsString()).append(" "); if (log.isDebugEnabled()) log.debug("NAME: " + buffer.toString().trim()); gmailContact.setName(buffer.toString().trim()); } if (contact.getPersonalDetail() != null) { if (contact.getPersonalDetail().getEmails() != null && contact.getPersonalDetail().getEmails().size() > 0) { if (contact.getPersonalDetail().getEmails().get(0) != null) { Email email1 = (Email) contact.getPersonalDetail().getEmails().get(0); if (email1.getPropertyValueAsString() != null && email1.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL1: " + email1.getPropertyValueAsString()); gmailContact.setEmail(email1.getPropertyValueAsString()); } } if (contact.getPersonalDetail().getEmails().size() > 1 && contact.getPersonalDetail().getEmails().get(1) != null) { Email email2 = (Email) contact.getPersonalDetail().getEmails().get(1); if (email2.getPropertyValueAsString() != null && email2.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL2: " + email2.getPropertyValueAsString()); gmailContact.setEmail2(email2.getPropertyValueAsString()); } } } Address address = contact.getPersonalDetail().getAddress(); if (address != null) if (address.getStreet() != null) if (address.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(address.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("HOME_ADDRESS: " + addressBuffer.toString()); gmailContact.setHomeAddress(addressBuffer.toString()); } Address addressOther = contact.getPersonalDetail().getOtherAddress(); if (addressOther != null) if (addressOther.getStreet() != null) if (addressOther.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(addressOther.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(addressOther.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("OTHER_ADDRESS: " + addressBuffer.toString()); gmailContact.setOtherAddress(addressBuffer.toString()); } if (contact.getPersonalDetail().getPhones() != null && contact.getPersonalDetail().getPhones().size() > 0) { for (int i = 0; i < contact.getPersonalDetail().getPhones().size(); i++) { Phone phone = (Phone) contact.getPersonalDetail().getPhones().get(i); if (log.isDebugEnabled()) log.debug("PERSONAL_PHONE: " + phone.getPropertyValueAsString() + " type:" + phone.getPhoneType()); if (phone.getPhoneType().equals(SIFC.HOME_TELEPHONE_NUMBER) && homePhone == false) { gmailContact.setHomePhone(phone.getPropertyValueAsString()); homePhone = true; } else if (phone.getPhoneType().equals(SIFC.HOME2_TELEPHONE_NUMBER) && homePhone2 == false) { gmailContact.setHomePhone2(phone.getPropertyValueAsString()); homePhone2 = true; } else if (phone.getPhoneType().equals(SIFC.HOME_FAX_NUMBER) && homeFax == false) { gmailContact.setHomeFax(phone.getPropertyValueAsString()); homeFax = true; } else if ((phone.getPhoneType().equals(SIFC.MOBILE_TELEPHONE_NUMBER) || phone.getPhoneType().equals(SIFC.MOBILE_HOME_TELEPHONE_NUMBER)) && homeMobile == false) { gmailContact.setMobilePhone(phone.getPropertyValueAsString()); homeMobile = true; } else if (phone.getPhoneType().equals(SIFC.PAGER_NUMBER) && homePager == false) { gmailContact.setPager(phone.getPropertyValueAsString()); homePager = true; } else if (phone.getPhoneType().equals(SIFC.OTHER_TELEPHONE_NUMBER) && otherPhone == false) { gmailContact.setOtherPhone(phone.getPropertyValueAsString()); otherPhone = true; } else if (phone.getPhoneType().equals(SIFC.OTHER_FAX_NUMBER) && otherFax == false) { gmailContact.setOtherFax(phone.getPropertyValueAsString()); otherFax = true; } else { if (log.isDebugEnabled()) log.debug("GOOGLE - Whoops - Personal Phones UNKNOWN TYPE:" + phone.getPhoneType() + " VALUE:" + phone.getPropertyValueAsString()); } } } } if (contact.getBusinessDetail() != null) { if (contact.getBusinessDetail().getEmails() != null && contact.getBusinessDetail().getEmails().size() > 0) { if (contact.getBusinessDetail().getEmails().get(0) != null) { Email email3 = (Email) contact.getBusinessDetail().getEmails().get(0); if (email3.getPropertyValueAsString() != null && email3.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("EMAIL3: " + email3.getPropertyValueAsString()); gmailContact.setEmail3(email3.getPropertyValueAsString()); } } } Address address = contact.getBusinessDetail().getAddress(); if (address != null) if (address.getStreet() != null) if (address.getStreet().getPropertyValueAsString() != null) { StringBuffer addressBuffer = new StringBuffer(); addressBuffer.append(address.getStreet().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getPostalCode().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCity().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getState().getPropertyValueAsString()).append(" "); addressBuffer.append(address.getCountry().getPropertyValueAsString()); if (log.isDebugEnabled()) log.debug("BUSINESS_ADDRESS: " + addressBuffer.toString()); gmailContact.setBusinessAddress(addressBuffer.toString()); } if (contact.getBusinessDetail().getPhones() != null && contact.getBusinessDetail().getPhones().size() > 0) { for (int i = 0; i < contact.getBusinessDetail().getPhones().size(); i++) { Phone phone = (Phone) contact.getBusinessDetail().getPhones().get(i); if (log.isDebugEnabled()) log.debug("BUSINESS_PHONE: " + phone.getPropertyValueAsString() + " type:" + phone.getPhoneType()); if (phone.getPhoneType().equals(SIFC.BUSINESS_TELEPHONE_NUMBER) && businessPhone == false) { gmailContact.setBusinessPhone(phone.getPropertyValueAsString()); businessPhone = true; } else if (phone.getPhoneType().equals(SIFC.BUSINESS2_TELEPHONE_NUMBER) && businessPhone2 == false) { gmailContact.setBusinessPhone2(phone.getPropertyValueAsString()); businessPhone2 = true; } else if (phone.getPhoneType().equals(SIFC.BUSINESS_FAX_NUMBER) && businessFax == false) { gmailContact.setBusinessFax(phone.getPropertyValueAsString()); businessFax = true; } else if (phone.getPhoneType().equals(SIFC.MOBILE_BUSINESS_TELEPHONE_NUMBER) && homeMobile == false && businessMobile == false) { gmailContact.setMobilePhone(phone.getPropertyValueAsString()); businessMobile = true; } else if (phone.getPhoneType().equals(SIFC.PAGER_NUMBER) && homePager == false && businessPager == false) { gmailContact.setPager(phone.getPropertyValueAsString()); businessPager = true; } else { if (log.isDebugEnabled()) log.debug("GOOGLE - Whoops - Business Phones UNKNOWN TYPE:" + phone.getPhoneType() + " VALUE:" + phone.getPropertyValueAsString()); } } } if (contact.getBusinessDetail().getCompany() != null) if (contact.getBusinessDetail().getCompany().getPropertyValueAsString() != null) { if (log.isDebugEnabled()) log.debug("COMPANY: " + contact.getBusinessDetail().getCompany().getPropertyValueAsString()); gmailContact.setCompany(contact.getBusinessDetail().getCompany().getPropertyValueAsString()); } if (contact.getBusinessDetail().getTitles() != null && contact.getBusinessDetail().getTitles().size() > 0) { if (contact.getBusinessDetail().getTitles().get(0) != null) { Title title = (Title) contact.getBusinessDetail().getTitles().get(0); if (log.isDebugEnabled()) log.debug("TITLE: " + title.getPropertyValueAsString()); gmailContact.setJobTitle(title.getPropertyValueAsString()); } } } if (contact.getNotes() != null && contact.getNotes().size() > 0) { if (contact.getNotes().get(0) != null) { Note notes = (Note) contact.getNotes().get(0); if (notes.getPropertyValueAsString() != null && notes.getPropertyValueAsString().equals("") == false) { if (log.isDebugEnabled()) log.debug("NOTES: " + notes.getPropertyValueAsString()); gmailContact.setNotes(notes.getPropertyValueAsString()); } } } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(contact.toString().getBytes()); gmailContact.setMd5Hash(new BigInteger(m.digest()).toString()); return gmailContact; } catch (Exception e) { throw new GmailManagerException("GOOGLE Gmail - convertContactToGmailContact error: " + e.getMessage()); } } Code Sample 2: @Override public void action(String msg, String uri, Gateway gateway) throws Exception { String city = "成都"; if (msg.indexOf("#") != -1) { city = msg.substring(msg.indexOf("#") + 1); } String url = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode={city}&theUserID="; url = url.replace("{city}", URLEncoder.encode(city, "UTF8")); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); if (conn.getResponseCode() == 200) { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(conn.getInputStream()); List strings = doc.getRootElement().getChildren(); String[] sugguestions = getText(strings.get(6)).split("\n"); StringBuffer buffer = new StringBuffer(); buffer.append("欢迎使用MapleSMS的天气服务!\n"); buffer.append("你查询的是 " + getText(strings.get(1)) + "的天气。\n"); buffer.append(getText(strings.get(4)) + "。\n"); buffer.append(getText(strings.get(5)) + "。\n"); buffer.append(sugguestions[0] + "\n"); buffer.append(sugguestions[1] + "\n"); buffer.append(sugguestions[7] + "\n"); buffer.append("感谢你使用MapleSMS的天气服务!祝你愉快!"); gateway.sendSMS(uri, buffer.toString()); } else { gateway.sendSMS(uri, "对不起,你输入的城市格式有误,请检查后再试~"); } }
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 void zip(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); } }
00
Code Sample 1: private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; } Code Sample 2: private boolean doStudentCreditUpdate(Double dblCAmnt, String stuID) throws Exception { Connection conn = null; Statement stmt = null; ResultSet rs = null; Boolean blOk = false; String strMessage = ""; try { conn = dbMan.getPOSConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); String host = getHostName(); String stuId = student.getStudentNumber(); String building = settings.get(DBSettings.MAIN_BUILDING); String cashier = dbMan.getPOSUser(); if (hasStudentCredit()) { stmt = conn.createStatement(); if (stmt.executeUpdate("UPDATE " + strPOSPrefix + "studentcredit set credit_amount = credit_amount + " + round2Places(dblCAmnt) + " WHERE credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("UPDATE " + strPOSPrefix + "studentcredit set credit_lastused = NOW() where credit_active = '1' and credit_studentid = '" + stuId + "'") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("INSERT into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_datetime ) values( '" + stuId + "', '" + round2Places(dblCAmnt) + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { strMessage = "Unable to update student credit log."; blOk = false; } } else { strMessage = "Unable to update student credit account."; blOk = false; } } else { strMessage = "Unable to update student credit account."; blOk = false; } } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit (credit_amount,credit_active,credit_studentid,credit_lastused) values('" + round2Places(dblCAmnt) + "','1','" + stuId + "', NOW())") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_datetime ) values( '" + stuId + "', '" + round2Places(dblCAmnt) + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { strMessage = "Unable to update student credit log."; blOk = false; } } else { strMessage = "Unable to create new student credit account."; blOk = false; } } if (blOk) { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "creditTrans ( ctStudentNumber, ctCreditAction, ctBuilding, ctRegister, ctUser, ctDateTime ) values( '" + stuId + "', '" + round2Places(dblCAmnt) + "', '" + building + "', '" + host + "', '" + cashier + "', NOW() )") == 1) { stmt.close(); blOk = true; } else blOk = false; } if (blOk) { conn.commit(); return true; } else { conn.rollback(); throw new Exception("Error detected during credit adjustment! " + strMessage); } } catch (Exception exp) { try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); return false; } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { stmt = null; } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); } } } } exp.printStackTrace(); throw new Exception("Error detected during credit adjustment: " + exp.getMessage()); } }
11
Code Sample 1: private void copyIntoFile(String resource, File output) throws IOException { FileOutputStream out = null; InputStream in = null; try { out = FileUtils.openOutputStream(output); in = GroovyInstanceTest.class.getResourceAsStream(resource); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } } Code Sample 2: public static void extractZipPackage(String fileName, String destinationFolder) throws Exception { if (NullStatus.isNull(destinationFolder)) { destinationFolder = ""; } new File(destinationFolder).mkdirs(); File inputFile = new File(fileName); ZipFile zipFile = new ZipFile(inputFile); Enumeration<? extends ZipEntry> oEnum = zipFile.entries(); while (oEnum.hasMoreElements()) { ZipEntry zipEntry = oEnum.nextElement(); File file = new File(destinationFolder + "/" + zipEntry.getName()); if (zipEntry.isDirectory()) { file.mkdirs(); } else { String destinationFolderName = destinationFolder + "/" + zipEntry.getName(); destinationFolderName = destinationFolderName.substring(0, destinationFolderName.lastIndexOf("/")); new File(destinationFolderName).mkdirs(); FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(zipFile.getInputStream(zipEntry), fos); fos.close(); } } }
00
Code Sample 1: public static void copyFile(File file, File dest_file) throws FileNotFoundException, IOException { DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest_file))); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) > 0) { out.write(buffer, 0, read); } in.close(); out.close(); } Code Sample 2: public void fetchPublicContent(int id) throws IOException { String fileName = FILE_NAME_PREFIX + id + ".xml"; File file = new File(fileName); if (file.exists()) { System.out.println("user: " + id + " not fetched because it already exists"); return; } OutputStream out = new FileOutputStream(file, false); URL url = new URL("http://twitter.com/statuses/followers.xml?id=" + id); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); int i = 0; while ((i = in.read()) != -1) { out.write(i); } in.close(); out.close(); }
11
Code Sample 1: public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.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); } } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private void doConvert(HttpServletResponse response, ConversionRequestResolver rr, EGE ege, ConversionsPath cpath) throws FileUploadException, IOException, RequestResolvingException, EGEException, FileNotFoundException, ConverterException, ZipException { InputStream is = null; OutputStream os = null; if (ServletFileUpload.isMultipartContent(rr.getRequest())) { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(rr.getRequest()); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { is = item.openStream(); applyConversionsProperties(rr.getConversionProperties(), cpath); DataBuffer buffer = new DataBuffer(0, EGEConstants.BUFFER_TEMP_PATH); String alloc = buffer.allocate(is); InputStream ins = buffer.getDataAsStream(alloc); is.close(); try { ValidationResult vRes = ege.performValidation(ins, cpath.getInputDataType()); if (vRes.getStatus().equals(ValidationResult.Status.FATAL)) { ValidationServlet valServ = new ValidationServlet(); valServ.printValidationResult(response, vRes); try { ins.close(); } finally { buffer.removeData(alloc, true); } return; } } catch (ValidatorException vex) { LOGGER.warn(vex.getMessage()); } finally { try { ins.close(); } catch (Exception ex) { } } File zipFile = null; FileOutputStream fos = null; String newTemp = UUID.randomUUID().toString(); IOResolver ior = EGEConfigurationManager.getInstance().getStandardIOResolver(); File buffDir = new File(buffer.getDataDir(alloc)); zipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + EZP_EXT); fos = new FileOutputStream(zipFile); ior.compressData(buffDir, fos); ins = new FileInputStream(zipFile); File szipFile = new File(EGEConstants.BUFFER_TEMP_PATH + File.separator + newTemp + ZIP_EXT); fos = new FileOutputStream(szipFile); try { try { ege.performConversion(ins, fos, cpath); } finally { fos.close(); } boolean isComplex = EGEIOUtils.isComplexZip(szipFile); response.setContentType(APPLICATION_OCTET_STREAM); String fN = item.getName().substring(0, item.getName().lastIndexOf(".")); if (isComplex) { String fileExt; if (cpath.getOutputDataType().getMimeType().equals(APPLICATION_MSWORD)) { fileExt = DOCX_EXT; } else { fileExt = ZIP_EXT; } response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); FileInputStream fis = new FileInputStream(szipFile); os = response.getOutputStream(); try { EGEIOUtils.copyStream(fis, os); } finally { fis.close(); } } else { String fileExt = getMimeExtensionProvider().getFileExtension(cpath.getOutputDataType().getMimeType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fN + fileExt + "\""); os = response.getOutputStream(); EGEIOUtils.unzipSingleFile(new ZipFile(szipFile), os); } } finally { ins.close(); if (os != null) { os.flush(); os.close(); } buffer.clear(true); szipFile.delete(); if (zipFile != null) { zipFile.delete(); } } } } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } }
00
Code Sample 1: @Override public boolean exists() { if (local_file.exists()) { return true; } else { try { URLConnection c = remote_url.openConnection(); try { c.setConnectTimeout(CIO.getLoadingTimeOut()); c.connect(); return c.getContentLength() > 0; } catch (Exception err) { err.printStackTrace(); return false; } finally { if (c instanceof HttpURLConnection) { ((HttpURLConnection) c).disconnect(); } } } catch (IOException e) { e.printStackTrace(); return false; } } } Code Sample 2: public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) startWindow(prop); else if (tag.equals("splitpanel")) startSplitPanel(prop); else if (tag.equals("desktoppane")) startDesktopPane(prop); else if (tag.equals("tabcontrol")) startTabcontrol(prop); else if (tag.equals("panel")) startPanel(prop); else if (tag.equals("statusbar")) startStatusbar(prop); else if (tag.equals("toolbar")) startToolbar(prop); else if (tag.equals("toolbarbutton")) startToolbarbutton(prop); else if (tag.equals("menu")) startMenu(prop); else if (tag.equals("menuitem")) startMenuitem(prop); else if (tag.equals("separator")) menu.addSeparator(); else if (tag.equals("choice")) startChoice(prop); else if (tag.equals("list")) startList(prop); else if (tag.equals("option")) startOption(prop); else if (tag.equals("label")) startLabel(prop); else if (tag.equals("button")) startButton(prop); else if (tag.equals("groupbox")) startGroupbox(prop); else if (tag.equals("radiobutton")) startRadioButton(prop); else if (tag.equals("checkbox")) startCheckbox(prop); else if (tag.equals("image")) startImage(prop); else if (tag.equals("textarea")) startTextArea(prop); else if (tag.equals("singlelineedit")) startSingleLineEdit(prop); else if (tag.equals("treeview")) startTreeview(prop); else if (tag.equals("treeitem")) startTreeitem(prop); else if (tag.equals("table")) startTable(prop); else if (tag.equals("header")) startHeader(prop); else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.addRow(); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("rmbmenuitem")) { if (prop == null) { System.err.println("datawindow.menuitem without properties"); return; } String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); JMenuItem mi = new JMenuItem(label); mi.setActionCommand(action); mi.addActionListener(win); rmbmenu.add(mi); } else if (tag.equals("rmbseparator")) { rmbmenu.addSeparator(); } else if (tag.equals("script")) { win.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; win.script += buffer + "\n"; } r.close(); win.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[win] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
11
Code Sample 1: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } } Code Sample 2: public int[] bubbleSort(int[] data) { for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length - i - 1; j++) { if (data[j] > data[j + 1]) { int temp = data[j]; data[j] = data[j + 1]; data[j + 1] = temp; } } } return data; }
00
Code Sample 1: public void run() { FTPClient ftp = null; try { StarkHhDownloaderEtcProperties etcProperties = new StarkHhDownloaderEtcProperties(getUri()); StarkHhDownloaderVarProperties varProperties = new StarkHhDownloaderVarProperties(getUri()); ftp = new FTPClient(); int reply; ftp.connect(etcProperties.getHostname()); log("Connecting to ftp server at " + etcProperties.getHostname() + "."); log("Server replied with '" + ftp.getReplyString() + "'."); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw UserException.newOk("FTP server refused connection."); } log("Connected to server, now logging in."); ftp.login(etcProperties.getUsername(), etcProperties.getPassword()); log("Server replied with '" + ftp.getReplyString() + "'."); List<String> directories = etcProperties.getDirectories(); for (int i = 0; i < directories.size(); i++) { log("Checking the directory '" + directories.get(i) + "'."); boolean found = false; FTPFile[] filesArray = ftp.listFiles(directories.get(i)); List<FTPFile> files = Arrays.asList(filesArray); Collections.sort(files, new Comparator<FTPFile>() { public int compare(FTPFile file1, FTPFile file2) { if (file2.getTimestamp().getTime().equals(file1.getTimestamp().getTime())) { return file2.getName().compareTo(file1.getName()); } else { return file1.getTimestamp().getTime().compareTo(file2.getTimestamp().getTime()); } } }); for (FTPFile file : files) { if (file.getType() == FTPFile.FILE_TYPE && (varProperties.getLastImportDate(i) == null ? true : (file.getTimestamp().getTime().equals(varProperties.getLastImportDate(i).getDate()) ? file.getName().compareTo(varProperties.getLastImportName(i)) < 0 : file.getTimestamp().getTime().after(varProperties.getLastImportDate(i).getDate())))) { String fileName = directories.get(i) + "\\" + file.getName(); if (file.getSize() == 0) { log("Ignoring '" + fileName + "'because it has zero length"); } else { log("Attempting to download '" + fileName + "'."); InputStream is = ftp.retrieveFileStream(fileName); if (is == null) { reply = ftp.getReplyCode(); throw UserException.newOk("Can't download the file '" + file.getName() + "', server says: " + reply + "."); } log("File stream obtained successfully."); hhImporter = new HhDataImportProcess(getContract().getId(), new Long(0), is, fileName + ".df2", file.getSize()); hhImporter.run(); List<VFMessage> messages = hhImporter.getMessages(); hhImporter = null; if (messages.size() > 0) { for (VFMessage message : messages) { log(message.getDescription()); } throw UserException.newInvalidParameter("Problem loading file."); } } if (!ftp.completePendingCommand()) { throw UserException.newOk("Couldn't complete ftp transaction: " + ftp.getReplyString()); } varProperties.setLastImportDate(i, new MonadDate(file.getTimestamp().getTime())); varProperties.setLastImportName(i, file.getName()); found = true; } } if (!found) { log("No new files found."); } } } catch (UserException e) { try { log(e.getVFMessage().getDescription()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (IOException e) { try { log(e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } } catch (Throwable e) { try { log("Exception: " + e.getClass().getName() + " Message: " + e.getMessage()); } catch (ProgrammerException e1) { throw new RuntimeException(e1); } catch (UserException e1) { throw new RuntimeException(e1); } ChellowLogger.getLogger().logp(Level.SEVERE, "ContextListener", "contextInitialized", "Can't initialize context.", e); } finally { if (ftp != null && ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); log("Logged out."); } catch (IOException ioe) { } catch (ProgrammerException e) { } catch (UserException e) { } } } } Code Sample 2: private void refreshCacheFile(RepositoryFile file, File cacheFile) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(cacheFile); InputStream is = file.getInputStream(); int count = IOUtils.copy(is, fos); logger.debug("===========================================================> wrote bytes to cache " + count); fos.flush(); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(file.getInputStream()); }
00
Code Sample 1: public InputStream getResource(String resourceName) throws IOException { if (!resourceName.startsWith("/")) { resourceName += "/"; } URL url = bc.getBundle().getResource(COOS_CONFIG_PATH + resourceName); InputStream is = null; try { FileInputStream fis = new FileInputStream(configDir + resourceName); is = substitute(fis); } catch (Exception e) { } if (is == null) { is = url.openStream(); is = substitute(is); } return is; } Code Sample 2: public void setContentMD5() { MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); contentMD5 = null; } messagedigest.update(content.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } contentMD5 = chk; }
00
Code Sample 1: private String getSearchResults(String id) { try { final URL url = new URL("http://www.jaap.nl/api/jaapAPI.do?clientId=iPhone&limit=5&request=details&id=" + id + "&format=JSON&field=street_nr&field=zip&field=city&field=price&field=thumb&field=since&field=houseType&field=area&field=rooms&field=id"); final StringBuilder builder = new StringBuilder(); final BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream())); String s = ""; while ((s = rd.readLine()) != null) { builder.append(s); } rd.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } }
11
Code Sample 1: public static String getAnalysisServletOutput(String inputXml) { java.io.BufferedWriter bWriter = null; URLConnection connection = null; String resultString = ""; bWriter = null; connection = null; String target = ServletConstant.ANALYSIS_SERVLET; String message = "\nTHIS MESSAGE IS SENT FROM THE CLIENT APPLET \n\r"; try { URL url = new URL(target); connection = (HttpURLConnection) url.openConnection(); ((HttpURLConnection) connection).setRequestMethod("POST"); connection.setDoOutput(true); bWriter = new java.io.BufferedWriter(new java.io.OutputStreamWriter(connection.getOutputStream())); bWriter.write(message); bWriter.flush(); bWriter.close(); java.io.BufferedReader bReader = null; bReader = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream())); String line; StringBuffer sb = new StringBuffer(); while ((line = bReader.readLine()) != null) { sb.append(line); } resultString = sb.toString(); bReader.close(); ((HttpURLConnection) connection).disconnect(); } catch (java.io.IOException ex) { resultString += ex.toString(); } finally { if (bWriter != null) { try { bWriter.close(); } catch (Exception ex) { resultString += ex.toString(); } } if (connection != null) { try { ((HttpURLConnection) connection).disconnect(); } catch (Exception ex) { resultString += ex.toString(); } } } return resultString; } Code Sample 2: private ExamModel(URL urlQuestions) throws IOException, DataCoherencyException { BufferedReader in = new BufferedReader(new InputStreamReader(urlQuestions.openStream())); String line; questions = new ArrayList<Question>(); questionsMap = new HashMap<String, Question>(); in = new BufferedReader(new InputStreamReader(urlQuestions.openStream(), "UTF-8")); int questionNumber = 0; Question question; String questText = ""; String hash = ""; int lookingFor = ExamModel.READING_HASH; while ((line = in.readLine()) != null) { switch(lookingFor) { case ExamModel.READING_HASH: if (line.length() == 0 || line.trim().length() == 0) continue; hash = line; questionNumber++; lookingFor = ExamModel.READING_QUESTION; break; case ExamModel.READING_QUESTION: if (line.equals("--")) { question = new Question(questionNumber, hash, questText); questions.add(question); questionsMap.put(question.getHash(), question); questText = ""; hash = null; lookingFor = ExamModel.READING_HASH; } else { questText = questText.concat(line + Constants.nl); } break; default: throw new DataCoherencyException("Neočekávaný konec souboru!"); } } questions.trimToSize(); in.close(); }
11
Code Sample 1: public void run() { LOG.debug(this); String[] parts = createCmdArray(getCommand()); Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(parts); if (isBlocking()) { process.waitFor(); StringWriter out = new StringWriter(); IOUtils.copy(process.getInputStream(), out); String stdout = out.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stdout)) { LOG.info("Process stdout:\n" + stdout); } StringWriter err = new StringWriter(); IOUtils.copy(process.getErrorStream(), err); String stderr = err.toString().replaceFirst("\\s+$", ""); if (StringUtils.isNotBlank(stderr)) { LOG.error("Process stderr:\n" + stderr); } } } catch (IOException ioe) { LOG.error(String.format("Could not exec [%s]", getCommand()), ioe); } catch (InterruptedException ie) { LOG.error(String.format("Interrupted [%s]", getCommand()), ie); } } Code Sample 2: public synchronized boolean copyTmpDataFile(String fpath) throws IOException { if (tmpDataOutput != null) tmpDataOutput.close(); tmpDataOutput = null; if (tmpDataFile == null) return false; File nfp = new File(fpath); if (nfp.exists()) nfp.delete(); FileInputStream src = new FileInputStream(tmpDataFile); FileOutputStream dst = new FileOutputStream(nfp); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) dst.write(buffer, 0, bytesRead); src.close(); dst.close(); return true; }