label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: private static Map loadHandlerList(final String resourceName, ClassLoader loader) { if (loader == null) loader = ClassLoader.getSystemClassLoader(); final Map result = new HashMap(); try { final Enumeration resources = loader.getResources(resourceName); if (resources != null) { while (resources.hasMoreElements()) { final URL url = (URL) resources.nextElement(); final Properties mapping; InputStream urlIn = null; try { urlIn = url.openStream(); mapping = new Properties(); mapping.load(urlIn); } catch (IOException ioe) { continue; } finally { if (urlIn != null) try { urlIn.close(); } catch (Exception ignore) { } } for (Enumeration keys = mapping.propertyNames(); keys.hasMoreElements(); ) { final String protocol = (String) keys.nextElement(); final String implClassName = mapping.getProperty(protocol); final Object currentImpl = result.get(protocol); if (currentImpl != null) { if (implClassName.equals(currentImpl.getClass().getName())) continue; else throw new IllegalStateException("duplicate " + "protocol handler class [" + implClassName + "] for protocol " + protocol); } result.put(protocol, loadURLStreamHandler(implClassName, loader)); } } } } catch (IOException ignore) { } return result; } Code Sample 2: protected void discoverRegistryEntries() { DataSourceRegistry registry = this; try { ClassLoader loader = DataSetURI.class.getClassLoader(); Enumeration<URL> urls; if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFactory.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerExtension(ss[0], ss[i], null); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory.mimeTypes"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { registry.registerMimeType(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormat.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFormat.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerFormatter(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceEditorPanel.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerEditor(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { s = s.trim(); if (s.length() > 0) { String[] ss = s.split("\\s"); for (int i = 1; i < ss.length; i++) { if (ss[i].contains(".")) { System.err.println("META-INF/org.virbo.datasource.DataSourceFormatEditorPanel.extensions contains extension that contains period: "); System.err.println(ss[0] + " " + ss[i] + " in " + url); System.err.println("This sometimes happens when extension files are concatenated, so check that all are terminated by end-of-line"); System.err.println(""); throw new IllegalArgumentException("DataSourceFactory.extensions contains extension that contains period: " + url); } registry.registerFormatEditor(ss[0], ss[i]); } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); } Code Sample 2: public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: @Override public int onPut(Operation operation) { synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections++; if (logger.isDebugEnabled()) { logger.debug("Connection accepted, total number of connections: " + MuleObexRequestHandler.connections); } } int result = ResponseCodes.OBEX_HTTP_OK; try { headers = operation.getReceivedHeaders(); if (!this.maxFileSize.equals(ObexServer.UNLIMMITED_FILE_SIZE)) { Long fileSize = (Long) headers.getHeader(HeaderSet.LENGTH); if (fileSize == null) { result = ResponseCodes.OBEX_HTTP_LENGTH_REQUIRED; } if (fileSize > this.maxFileSize) { result = ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE; } } if (result != ResponseCodes.OBEX_HTTP_OK) { InputStream in = operation.openInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); data = out.toByteArray(); if (interrupted) { data = null; result = ResponseCodes.OBEX_HTTP_GONE; } } return result; } catch (IOException e) { return ResponseCodes.OBEX_HTTP_UNAVAILABLE; } finally { synchronized (this) { this.notify(); } synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections--; if (logger.isDebugEnabled()) { logger.debug("Connection closed, total number of connections: " + MuleObexRequestHandler.connections); } } } } Code Sample 2: public static String hashURL(String url) { if (url == null) { throw new IllegalArgumentException("URL may not be null. "); } String result = null; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); if (md != null) { md.reset(); md.update(url.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); result = hash.toString(16); } md = null; } catch (NoSuchAlgorithmException ex) { result = null; } return result; }
11
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 void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: public static void exportDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = input + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE); } else { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); HashMap<Integer, String> languageIDs = new HashMap<Integer, String>(); HashMap<Integer, String> typeIDs = new HashMap<Integer, String>(); long tiempoInicio = System.currentTimeMillis(); Element dataBaseXML = new Element("database"); Element languages = new Element("languages"); Statement stat = G.conn.createStatement(); ResultSet rs = stat.executeQuery("select * from language order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); languageIDs.put(id, name); Element language = new Element("language"); language.setText(name); languages.addContent(language); } dataBaseXML.addContent(languages); rs = stat.executeQuery("select * from type order by id"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); typeIDs.put(id, name); } rs = stat.executeQuery("select distinct name from main order by name"); while (rs.next()) { String name = rs.getString("name"); Element image = new Element("image"); image.setAttribute("id", name); Statement stat2 = G.conn.createStatement(); ResultSet rs2 = stat2.executeQuery("select distinct idL from main where name = \"" + name + "\" order by idL"); while (rs2.next()) { int idL = rs2.getInt("idL"); Element language = new Element("language"); language.setAttribute("id", languageIDs.get(idL)); Statement stat3 = G.conn.createStatement(); ResultSet rs3 = stat3.executeQuery("select * from main where name = \"" + name + "\" and idL = " + idL + " order by idT"); while (rs3.next()) { int idT = rs3.getInt("idT"); String word = rs3.getString("word"); Element wordE = new Element("word"); wordE.setAttribute("type", typeIDs.get(idT)); wordE.setText(word); language.addContent(wordE); String pathSrc = input + File.separator + name.substring(0, 1).toUpperCase() + File.separator + name; String pathDst = output + File.separator + 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()); } } rs3.close(); stat3.close(); image.addContent(language); } rs2.close(); stat2.close(); dataBaseXML.addContent(image); } rs.close(); stat.close(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); FileOutputStream f = new FileOutputStream(output + File.separator + G.imagesName); out.output(dataBaseXML, f); f.flush(); f.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static File createTempFile(InputStream contentStream, String ext) throws IOException { ExceptionUtils.throwIfNull(contentStream, "contentStream"); File file = File.createTempFile("test", ext); FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copy(contentStream, fos, false); } finally { fos.close(); } return file; }
00
Code Sample 1: protected void addAssetResources(MimeMultipart pkg, MarinerPageContext context) throws PackagingException { boolean includeFullyQualifiedURLs = context.getBooleanDevicePolicyValue("protocol.mime.fully.qualified.urls"); MarinerRequestContext requestContext = context.getRequestContext(); ApplicationContext ac = ContextInternals.getApplicationContext(requestContext); PackageResources pr = ac.getPackageResources(); List encodedURLs = pr.getEncodedURLs(); Map assetURLMap = pr.getAssetURLMap(); Iterator iterator; String encodedURL; PackageResources.Asset asset; String assetURL = null; BodyPart assetPart; if (encodedURLs != null) { iterator = encodedURLs.iterator(); } else { iterator = assetURLMap.keySet().iterator(); } while (iterator.hasNext()) { encodedURL = (String) iterator.next(); asset = (PackageResources.Asset) assetURLMap.get(encodedURL); assetURL = asset.getValue(); if (includeFullyQualifiedURLs || !isFullyQualifiedURL(assetURL)) { if (isToBeAdded(assetURL, context)) { assetPart = new MimeBodyPart(); try { if (!asset.getOnClientSide()) { URL url = null; URLConnection connection; try { url = context.getAbsoluteURL(new MarinerURL(assetURL)); connection = url.openConnection(); if (connection != null) { connection.setDoInput(true); connection.setDoOutput(false); connection.setAllowUserInteraction(false); connection.connect(); connection.getInputStream(); assetPart.setDataHandler(new DataHandler(url)); assetPart.setHeader("Content-Location", assetURL); pkg.addBodyPart(assetPart); } } catch (MalformedURLException e) { if (logger.isDebugEnabled()) { logger.debug("Ignoring asset with malformed URL: " + url.toString()); } } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Ignoring asset with URL that doesn't " + "exist: " + assetURL + " (" + url.toString() + ")"); } } } else { assetPart.setHeader("Content-Location", "file://" + assetURL); } } catch (MessagingException e) { throw new PackagingException(exceptionLocalizer.format("could-not-add-asset", encodedURL), e); } } } } } Code Sample 2: public void assign() throws Exception { if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or peer-viewer selected."); String[] pids = proposalIds.split(","); String[] uids = usrIds.split(","); int pnum = pids.length; int unum = uids.length; if (pnum == 0 || unum == 0) throw new Exception("No proposal or peer-viewer selected."); int i, j; String pStr = "update proposal set current_status='assigned' where "; for (i = 0; i < pnum; i++) { if (i > 0) pStr += " OR "; pStr += "PROPOSAL_ID=" + pids[i]; } Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DATE); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); String dt = String.valueOf(year) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(day); PreparedStatement prepStmt = null; try { con = database.getConnection(); con.setAutoCommit(false); prepStmt = con.prepareStatement(pStr); prepStmt.executeUpdate(); pStr = "insert into event (summary,document1,document2,document3,publicComments,privateComments,ACTION_ID,eventDate,ROLE_ID,reviewText,USR_ID,PROPOSAL_ID,SUBJECTUSR_ID) values " + "('','','','','','','assigned','" + dt + "',2,'new'," + userId + ",?,?)"; prepStmt = con.prepareStatement(pStr); for (i = 0; i < pnum; i++) { for (j = 0; j < unum; j++) { prepStmt.setString(1, pids[i]); prepStmt.setString(2, uids[j]); prepStmt.executeUpdate(); } } con.commit(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } event_Form fr = new event_Form(); for (j = 0; j < unum; j++) { fr.setUSR_ID(userId); fr.setSUBJECTUSR_ID(uids[j]); systemManager.handleEvent(SystemManager.EVENT_PROPOSAL_ASSIGNED, fr, null, null); } }
11
Code Sample 1: public FileReader(String filePath, Configuration aConfiguration) throws IOException { file = new File(URLDecoder.decode(filePath, "UTF-8")).getCanonicalFile(); readerConf = aConfiguration; if (file.isDirectory()) { File indexFile = new File(file, "index.php"); File indexFile_1 = new File(file, "index.html"); if (indexFile.exists() && !indexFile.isDirectory()) { file = indexFile; } else if (indexFile_1.exists() && !indexFile_1.isDirectory()) { file = indexFile_1; } else { if (!readerConf.getOption("showFolders").equals("Yes")) { makeErrorPage(503, "Permision denied"); } else { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); File[] files = file.listFiles(); makeHeader(200, -1, new Date(System.currentTimeMillis()).toString(), "text/html"); String title = "Index of " + file; out.write(("<html><head><title>" + title + "</title></head><body><h3>Index of " + file + "</h3><p>\n").getBytes()); for (int i = 0; i < files.length; i++) { file = files[i]; String filename = file.getName(); String description = ""; if (file.isDirectory()) { description = "&lt;DIR&gt;"; } out.write(("<a href=\"" + file.getPath().substring(readerConf.getOption("wwwPath").length()) + "\">" + filename + "</a> " + description + "<br>\n").getBytes()); } out.write(("</p><hr><p>yawwwserwer</p></body><html>").getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } } } else if (!file.exists()) { makeErrorPage(404, "File Not Found."); } else if (getExtension() == ".exe" || getExtension().contains(".py")) { FileOutputStream out = new FileOutputStream(readerConf.getOption("wwwPath") + "/temp/temp.php"); out.write((runCommand(filePath)).getBytes()); file = new File(URLDecoder.decode(readerConf.getOption("wwwPath") + "/temp/temp.php", "UTF-8")).getCanonicalFile(); } else { System.out.println(getExtension()); makeHeader(200, file.length(), new Date(file.lastModified()).toString(), TYPES.get(getExtension()).toString()); } System.out.println(file); } Code Sample 2: protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException { String from = getTemplateDir() + inputFilePath; try { logger.debug("Copying from " + from + " to " + outputFilePath); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); if (inputStream == null) { throw new GenerationException("Source file not found: " + from); } FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath)); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } catch (Exception e) { throw new GenerationException("Error while copying file: " + from, e); } }
11
Code Sample 1: private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } } Code Sample 2: public void testReaderWriterUC2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public void extractSong(Song s, File dir) { FileInputStream fin = null; FileOutputStream fout = null; File dest = new File(dir, s.file.getName()); if (dest.equals(s.file)) return; byte[] buf = new byte[COPY_BLOCKSIZE]; try { fin = new FileInputStream(s.file); fout = new FileOutputStream(dest); int read = 0; do { read = fin.read(buf); if (read > 0) fout.write(buf, 0, read); } while (read > 0); } catch (IOException ex) { ex.printStackTrace(); Dialogs.showErrorDialog("xtract.error"); } finally { try { fin.close(); fout.close(); } catch (Exception ex) { } } }
00
Code Sample 1: private void parseXMLFile() { String u = WeatherApplication.SERVER + location + ".xml"; InputStream in = null; String str = null; try { URL url = new URL(u); HttpURLConnection con = (HttpURLConnection) url.openConnection(); in = url.openStream(); ParserToolXML prt = new ParserToolXML(in); if (prt.doc == null) { System.err.println(FILE_NOT_FOUND_MSG + u); return; } NodeList ndl = prt.doc.getElementsByTagName("weather"); for (int i = 0; i < ndl.getLength(); i++) { Forecast f = new Forecast(); str = prt.searchElementValue(ndl.item(i), "date"); f.setDate(str); str = prt.searchElementValue(ndl.item(i), "daycode"); f.setDaycode(Integer.parseInt(str.trim())); str = prt.searchElementValue(ndl.item(i), "nightcode"); f.setNightcode(Integer.parseInt(str.trim())); str = prt.searchElementValue(ndl.item(i), "maxtemp"); f.setDaytemp(Integer.parseInt(str.trim())); str = prt.searchElementValue(ndl.item(i), "mintemp"); f.setNighttemp(Integer.parseInt(str.trim())); str = prt.searchElementValue(ndl.item(i), "winddirectionday"); f.setDaywinddir(str); str = prt.searchElementValue(ndl.item(i), "windspeedday"); f.setDaywindspeed(Integer.parseInt(str.trim())); str = prt.searchElementValue(ndl.item(i), "winddirectionnight"); f.setNightwinddir(str); str = prt.searchElementValue(ndl.item(i), "windspeednight"); f.setNightwindspeed(Integer.parseInt(str.trim())); forecastlist.addElement(f); } } catch (MalformedURLException e) { System.err.println(MALFORMED_URL_MSG + u); System.err.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { } catch (NumberFormatException e) { System.err.println(FILE_CORRUPT_MSG + u); System.err.println("-" + str + "-"); System.err.println(e.getMessage()); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { System.err.println(COULD_NOT_CLOSE_FILE_MSG + u); e.printStackTrace(); } } } } Code Sample 2: protected void discoverFactories() { DataSourceRegistry registry = this; try { ClassLoader loader = DataSetURI.class.getClassLoader(); Enumeration<URL> urls; if (loader == null) { urls = ClassLoader.getSystemResources("META-INF/org.virbo.datasource.DataSourceFactory"); } else { urls = loader.getResources("META-INF/org.virbo.datasource.DataSourceFactory"); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String s = reader.readLine(); while (s != null) { if (s.trim().length() > 0) { List<String> extensions = null; List<String> mimeTypes = null; String factoryClassName = s; try { Class c = Class.forName(factoryClassName); DataSourceFactory f = (DataSourceFactory) c.newInstance(); try { Method m = c.getMethod("extensions", new Class[0]); extensions = (List<String>) m.invoke(f, new Object[0]); } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { ex.printStackTrace(); } try { Method m = c.getMethod("mimeTypes", new Class[0]); mimeTypes = (List<String>) m.invoke(f, new Object[0]); } catch (NoSuchMethodException ex) { } catch (InvocationTargetException ex) { ex.printStackTrace(); } } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } if (extensions != null) { for (String e : extensions) { registry.registerExtension(factoryClassName, e, null); } } if (mimeTypes != null) { for (String m : mimeTypes) { registry.registerMimeType(factoryClassName, m); } } } s = reader.readLine(); } reader.close(); } } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(final File sourceFile, final File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel source = null; FileChannel destination = null; try { source = (inStream = new FileInputStream(sourceFile)).getChannel(); destination = (outStream = new FileOutputStream(destFile)).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { closeIO(source); closeIO(inStream); closeIO(destination); closeIO(outStream); } } Code Sample 2: private void addPNMLFileToLibrary(File selected) { try { FileChannel srcChannel = new FileInputStream(selected.getAbsolutePath()).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(matchingOrderXML).getParent() + "/" + selected.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); order.add(new ComponentDescription(false, selected.getName().replaceAll(".pnml", ""), 1.0)); updateComponentList(); } catch (IOException ioe) { JOptionPane.showMessageDialog(dialog, "Could not add the PNML file " + selected.getName() + " to the library!"); } }
00
Code Sample 1: public static String getMD5Str(String source) { String s = null; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); md.update(source.getBytes()); byte tmp[] = md.digest(); char str[] = new char[16 * 2]; int k = 0; for (int i = 0; i < 16; i++) { byte byte0 = tmp[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } s = new String(str); } catch (Exception e) { e.printStackTrace(); } return s; } Code Sample 2: @Override public LispObject execute(LispObject first, LispObject second) throws ConditionThrowable { Pathname zipfilePathname = coerceToPathname(first); byte[] buffer = new byte[4096]; try { String zipfileNamestring = zipfilePathname.getNamestring(); if (zipfileNamestring == null) return error(new SimpleError("Pathname has no namestring: " + zipfilePathname.writeToString())); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfileNamestring)); LispObject list = second; while (list != NIL) { Pathname pathname = coerceToPathname(list.CAR()); String namestring = pathname.getNamestring(); if (namestring == null) { out.close(); File zipfile = new File(zipfileNamestring); zipfile.delete(); return error(new SimpleError("Pathname has no namestring: " + pathname.writeToString())); } File file = new File(namestring); FileInputStream in = new FileInputStream(file); ZipEntry entry = new ZipEntry(file.getName()); out.putNextEntry(entry); int n; while ((n = in.read(buffer)) > 0) out.write(buffer, 0, n); out.closeEntry(); in.close(); list = list.CDR(); } out.close(); } catch (IOException e) { return error(new LispError(e.getMessage())); } return zipfilePathname; }
00
Code Sample 1: public static String createMD5(String str) { String sig = null; String strSalt = str + sSalt; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(strSalt.getBytes(), 0, strSalt.length()); byte byteData[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } sig = sb.toString(); } catch (NoSuchAlgorithmException e) { System.err.println("Can not use md5 algorithm"); } return sig; } Code Sample 2: 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(); } }
11
Code Sample 1: public static void compressFile(File orig) throws IOException { File file = new File(INPUT + orig.toString()); File target = new File(OUTPUT + orig.toString().replaceAll(".xml", ".xml.gz")); System.out.println(" Compressing \"" + file.getName() + "\" into \"" + target + "\""); long l = file.length(); FileInputStream fileinputstream = new FileInputStream(file); GZIPOutputStream gzipoutputstream = new GZIPOutputStream(new FileOutputStream(target)); byte abyte0[] = new byte[1024]; int i; while ((i = fileinputstream.read(abyte0)) != -1) gzipoutputstream.write(abyte0, 0, i); fileinputstream.close(); gzipoutputstream.close(); long l1 = target.length(); System.out.println(" Initial size: " + l + "; Compressed size: " + l1 + "."); System.out.println(" Done."); System.out.println(); } Code Sample 2: public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Git git = Git.getCurrent(req.getSession()); GitComponentReader gitReader = git.getComponentReader("warpinjector"); String id = req.getParameter("id"); GitElement element = gitReader.getElement(id); String path = (String) element.getAttribute("targetdir"); File folder = new File(path); PrintWriter out = helper.getPrintWriter(resp); MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages"); Locale locale = req.getLocale(); helper.header(out, messageBundle, locale); if (git.getUser() == null) { helper.notLoggedIn(out, messageBundle, locale); } else { try { MultiPartRequest request = new MultiPartRequest(req); FileInfo info = request.getFileInfo("userfile"); File file = info.getFile(); out.println("tempfile found: " + file.getPath() + "<br>"); String fileName = info.getFileName(); File target = new File(folder, fileName); out.println("copying tempfile to: " + target.getPath() + "<br>"); FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(target); byte buf[] = new byte[1024]; int n; while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n); fis.close(); fos.close(); out.println("copy successful - deleting old tempfile<br>"); out.println("deletion result. " + file.delete() + "<p>"); out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale)); out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>"); } catch (Exception ex) { out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale)); } } helper.footer(out); }
11
Code Sample 1: public static String encrypt(String x) throws Exception { MessageDigest mdEnc = MessageDigest.getInstance("SHA-1"); mdEnc.update(x.getBytes(), 0, x.length()); String md5 = new BigInteger(1, mdEnc.digest()).toString(16); return md5; } Code Sample 2: public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } }
11
Code Sample 1: public static String md5(String plain) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { PApplet.println("[ERROR]: md5() " + e); return ""; } md5.reset(); md5.update(plain.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i += 1) { hexString.append(Integer.toHexString(0xFF & result[i])); } return hexString.toString(); } Code Sample 2: public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
11
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void writeToFile(final File file, final InputStream in) throws IOException { IOUtils.createFile(file); FileOutputStream fos = null; try { fos = new FileOutputStream(file); IOUtils.copyStream(in, fos); } finally { IOUtils.closeIO(fos); } }
11
Code Sample 1: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) abort("FileCopy: no such source file: " + from_file.getName()); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_file.getName()); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_file.getName()); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_file.getName()); } else { 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) { e.printStackTrace(); } } if (to != null) { try { to.close(); } catch (IOException e) { e.printStackTrace(); } } } } Code Sample 2: public static void copyFile(File in, File out) { if (!in.exists() || !in.canRead()) { LOGGER.warn("Can't copy file : " + in); return; } if (!out.getParentFile().exists()) { if (!out.getParentFile().mkdirs()) { LOGGER.info("Didn't create parent directories : " + out.getParentFile().getAbsolutePath()); } } if (!out.exists()) { try { out.createNewFile(); } catch (IOException e) { LOGGER.error("Exception creating new file : " + out.getAbsolutePath(), e); } } LOGGER.debug("Copying file : " + in + ", to : " + out); FileChannel inChannel = null; FileChannel outChannel = null; FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(in); inChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(out); outChannel = fileOutputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { LOGGER.error("Exception copying file : " + in + ", to : " + out, e); } finally { close(fileInputStream); close(fileOutputStream); if (inChannel != null) { try { inChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing input channel : ", e); } } if (outChannel != null) { try { outChannel.close(); } catch (Exception e) { LOGGER.error("Exception closing output channel : ", e); } } } }
00
Code Sample 1: public List<PathObject> fetchPath(BoardObject board) throws NetworkException { if (boardPathMap.containsKey(board.getId())) { return boardPathMap.get(board.getId()).getChildren(); } HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_0AN_BOARD + board.getId()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); Document doc = XmlOperator.readDocument(entity.getContent()); PathObject parent = new PathObject(); BBSBodyParseHelper.parsePathList(doc, parent); parent = searchAndCreatePathFromRoot(parent); boardPathMap.put(board.getId(), parent); return parent.getChildren(); } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } } Code Sample 2: public static boolean sendPostRequest(String path, Map<String, String> params, String encoding) throws Exception { StringBuilder sb = new StringBuilder(""); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), encoding)).append('&'); } sb.deleteCharAt(sb.length() - 1); } byte[] data = sb.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { InputStream inputStream = conn.getInputStream(); return ResponseResult.parseXML(inputStream); } return false; }
11
Code Sample 1: private void doDecrypt(boolean createOutput) throws IOException { FileInputStream input = null; FileOutputStream output = null; File tempOutput = null; try { input = new FileInputStream(infile); String cipherBaseFilename = basename(infile); byte[] magic = new byte[MAGIC.length]; input.read(magic); for (int i = 0; i < MAGIC.length; i++) { if (MAGIC[i] != magic[i]) throw new IOException("Not a BORK file (bad magic number)"); } short version = readShort(input); if (version / 1000 > VERSION / 1000) throw new IOException("File created by an incompatible future version: " + version + " > " + VERSION); String cipherName = readString(input); Cipher cipher = createCipher(cipherName, createSessionKey(password, cipherBaseFilename)); CipherInputStream decryptedInput = new CipherInputStream(input, cipher); long headerCrc = Unsigned.promote(readInt(decryptedInput)); decryptedInput.resetCRC(); outfile = new File(outputDir, readString(decryptedInput)); if (!createOutput || outfile.exists()) { skipped = true; return; } tempOutput = File.createTempFile("bork", null, outputDir); tempOutput.deleteOnExit(); byte[] buffer = new byte[BUFFER_SIZE]; output = new FileOutputStream(tempOutput); int bytesRead; while ((bytesRead = decryptedInput.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); output = null; if (headerCrc != decryptedInput.getCRC()) { outfile = null; throw new IOException("CRC mismatch: password is probably incorrect"); } if (!tempOutput.renameTo(outfile)) throw new IOException("Failed to rename temp output file " + tempOutput + " to " + outfile); outfile.setLastModified(infile.lastModified()); } finally { close(input); close(output); if (tempOutput != null) tempOutput.delete(); } } 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 static TerminatedInputStream find(URL url, String entryName) throws IOException { if (url.getProtocol().equals("file")) { return find(new File(url.getFile()), entryName); } else { return find(url.openStream(), entryName); } } Code Sample 2: protected String getGraphPath(String name) throws ServletException { String hash; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(name.getBytes()); hash = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to hash file name: " + e); } File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir"); return tempDir.getAbsolutePath() + File.separatorChar + hash; }
11
Code Sample 1: static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public static boolean unzip_and_merge(String infile, String outfile) { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(infile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); FileOutputStream fos = new FileOutputStream(outfile); dest = new BufferedOutputStream(fos, BUFFER); while (zis.getNextEntry() != null) { int count; byte data[] = new byte[BUFFER]; while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); } dest.close(); zis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
00
Code Sample 1: public void run() { try { exists_ = true; URL url = getContentURL(); URLConnection cnx = url.openConnection(); cnx.connect(); lastModified_ = cnx.getLastModified(); length_ = cnx.getContentLength(); type_ = cnx.getContentType(); if (isDirectory()) { InputStream in = cnx.getInputStream(); BufferedReader nr = new BufferedReader(new InputStreamReader(in)); FuVectorString v = readList(nr); nr.close(); v.sort(); v.uniq(); list_ = v.toArray(); } } catch (Exception ex) { exists_ = false; } done[0] = true; } Code Sample 2: @Override public void execute(JobExecutionContext context) throws JobExecutionException { super.execute(context); debug("Start execute job " + this.getClass().getName()); try { String name = "nixspam-ip.dump.gz"; String f = this.path_app_root + "/" + this.properties.get("dir") + "/"; try { org.apache.commons.io.FileUtils.forceMkdir(new File(f)); } catch (IOException ex) { fatal("IOException", ex); } f += "/" + name; String url = "http://www.dnsbl.manitu.net/download/" + name; debug("(1) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); com.utils.IOUtil.unzip(f, f.replace(".gz", "")); File file_to_read = new File(f.replaceAll(".gz", "")); BigFile lines = null; try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Excpetion", e); return; } try { Statement stat = conn_url.createStatement(); stat.executeUpdate(properties.get("query_delete")); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } boolean ok = true; int i = 0; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.substring(line.indexOf(" ")); line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } boolean del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); name = "spam-ip.com_" + DateTimeUtil.getNowWithFormat("MM-dd-yyyy") + ".csv"; f = this.path_app_root + "/" + this.properties.get("dir") + "/"; org.apache.commons.io.FileUtils.forceMkdir(new File(f)); f += "/" + name; url = "http://spam-ip.com/csv_dump/" + name; debug("(2) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); file_to_read = new File(f); try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Exception", e); return; } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } ok = true; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.split(",")[1]; line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); if (ok) { debug("Import della BlackList Concluso tot righe: " + i); try { conn_url.commit(); } catch (SQLException e) { fatal("SQLException", e); } } else { fatal("Problemi con la Blacklist"); } try { conn_url.setAutoCommit(true); } catch (SQLException e) { fatal("SQLException", e); } try { Statement stat = this.conn_url.createStatement(); stat.executeUpdate("VACUUM"); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } } catch (IOException ex) { fatal("IOException", ex); } debug("End execute job " + this.getClass().getName()); }
00
Code Sample 1: public static String getMD5Hash(String in) { StringBuffer result = new StringBuffer(32); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(in.getBytes()); Formatter f = new Formatter(result); for (byte b : md5.digest()) { f.format("%02x", b); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return result.toString(); } Code Sample 2: @Test public final void testImportODS() throws Exception { URL url = ODSTableImporterTest.class.getResource("/Messages.ods"); InputStream in = url.openStream(); ODSTableImporter b = new ODSTableImporter(); b.importODS(in, null); assertMessagesOds(b); }
11
Code Sample 1: private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); ServletContext ctx = getServletContext(); RequestDispatcher rd = ctx.getRequestDispatcher(SETUP_JSP); HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(true); session.setAttribute(ERROR_TAG, "You need to have run the Sniffer before running " + "the Grinder. Go to <a href=\"/index.jsp\">the start page</a> " + " to run the Sniffer."); rd = ctx.getRequestDispatcher(ERROR_JSP); } else { session.setMaxInactiveInterval(-1); String pValue = request.getParameter(ACTION_TAG); if (pValue != null && pValue.equals(START_TAG)) { rd = ctx.getRequestDispatcher(WAIT_JSP); int p = 1; int t = 1; int c = 1; try { p = Integer.parseInt(request.getParameter("procs")); p = p > MAX_PROCS ? MAX_PROCS : p; } catch (NumberFormatException e) { } try { t = Integer.parseInt(request.getParameter("threads")); t = t > MAX_THREADS ? MAX_THREADS : t; } catch (NumberFormatException e) { } try { c = Integer.parseInt(request.getParameter("cycles")); c = c > MAX_CYCLES ? MAX_CYCLES : c; } catch (NumberFormatException e) { } try { String dirname = (String) session.getAttribute(OUTPUT_TAG); File workdir = new File(dirname); (new File(dirname + File.separator + LOG_DIR)).mkdir(); FileInputStream gpin = new FileInputStream(GPROPS); FileOutputStream gpout = new FileOutputStream(dirname + File.separator + GPROPS); copyBytes(gpin, gpout); gpin.close(); InitialContext ictx = new InitialContext(); Boolean isSecure = (Boolean) session.getAttribute(SECURE_TAG); if (isSecure.booleanValue()) { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpsPlugin" + "\n").getBytes()); String certificate = (String) ictx.lookup(CERTIFICATE); String password = (String) ictx.lookup(PASSWORD); gpout.write(("grinder.plugin.parameter.clientCert=" + certificate + "\n").getBytes()); gpout.write(("grinder.plugin.parameter.clientCertPassword=" + password + "\n").getBytes()); } else { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpPlugin\n").getBytes()); } gpout.write(("grinder.processes=" + p + "\n").getBytes()); gpout.write(("grinder.threads=" + t + "\n").getBytes()); gpout.write(("grinder.cycles=" + c + "\n").getBytes()); gpin = new FileInputStream(dirname + File.separator + SNIFFOUT); copyBytes(gpin, gpout); gpin.close(); gpout.close(); String classpath = (String) ictx.lookup(CLASSPATH); String cmd[] = new String[JAVA_PROCESS.length + 1 + GRINDER_PROCESS.length]; int i = 0; int n = JAVA_PROCESS.length; System.arraycopy(JAVA_PROCESS, 0, cmd, i, n); cmd[n] = classpath; i = n + 1; n = GRINDER_PROCESS.length; System.arraycopy(GRINDER_PROCESS, 0, cmd, i, n); for (int j = 0; j < cmd.length; ++j) { System.out.print(cmd[j] + " "); } Process proc = Runtime.getRuntime().exec(cmd, null, workdir); session.setAttribute(PROCESS_TAG, proc); } catch (NamingException e) { e.printStackTrace(); session.setAttribute(ERROR_MSG_TAG, e.toString()); session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(ERROR_JSP); } catch (Throwable e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } else if (pValue != null && pValue.equals(CHECK_TAG)) { boolean finished = true; try { Process p = (Process) session.getAttribute(PROCESS_TAG); int result = p.exitValue(); } catch (IllegalThreadStateException e) { finished = false; } if (finished) { session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(RESULTS_JSP); } else { rd = ctx.getRequestDispatcher(WAIT_JSP); } } try { rd.forward(request, response); } catch (ServletException e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); } Code Sample 2: @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_local_version_" + datastream + ".xml\""); } String xmlContent = URLDecoder.decode(req.getParameterValues(Constants.PARAM_CONTENT)[0], "UTF-8"); InputStream is = new ByteArrayInputStream(xmlContent.getBytes("UTF-8")); ServletOutputStream os = resp.getOutputStream(); IOUtils.copyStreams(is, os); os.flush(); }
00
Code Sample 1: private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } Code Sample 2: public static String rename_tag(String sessionid, String originalTag, String newTagName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_tag"); 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", "rename_tag")); nameValuePairs.add(new BasicNameValuePair("new_tag_name", newTagName)); nameValuePairs.add(new BasicNameValuePair("absolute_tag", originalTag)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
11
Code Sample 1: private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: private static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: public void onMessage(Message message) { LOG.debug("onMessage"); DownloadMessage downloadMessage; try { downloadMessage = new DownloadMessage(message); } catch (JMSException e) { LOG.error("JMS error: " + e.getMessage(), e); return; } String caName = downloadMessage.getCaName(); boolean update = downloadMessage.isUpdate(); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { LOG.debug("CA status not marked for processing"); return; } String crlUrl = certificateAuthority.getCrlUrl(); if (null == crlUrl) { LOG.warn("No CRL url for CA " + certificateAuthority.getName()); certificateAuthority.setStatus(Status.NONE); return; } NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); } HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20)); LOG.debug("downloading CRL from: " + crlUrl); GetMethod getMethod = new GetMethod(crlUrl); getMethod.addRequestHeader("User-Agent", "jTrust CRL Client"); int statusCode; try { statusCode = httpClient.executeMethod(getMethod); } catch (Exception e) { downloadFailed(caName, crlUrl); throw new RuntimeException(); } if (HttpURLConnection.HTTP_OK != statusCode) { LOG.debug("HTTP status code: " + statusCode); downloadFailed(caName, crlUrl); throw new RuntimeException(); } String crlFilePath; File crlFile = null; try { crlFile = File.createTempFile("crl-", ".der"); InputStream crlInputStream = getMethod.getResponseBodyAsStream(); OutputStream crlOutputStream = new FileOutputStream(crlFile); IOUtils.copy(crlInputStream, crlOutputStream); IOUtils.closeQuietly(crlInputStream); IOUtils.closeQuietly(crlOutputStream); crlFilePath = crlFile.getAbsolutePath(); LOG.debug("temp CRL file: " + crlFilePath); } catch (IOException e) { downloadFailed(caName, crlUrl); if (null != crlFile) { crlFile.delete(); } throw new RuntimeException(e); } try { this.notificationService.notifyHarvester(caName, crlFilePath, update); } catch (JMSException e) { crlFile.delete(); throw new RuntimeException(e); } } Code Sample 2: public void save() { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(new FileFilter() { public String getDescription() { return "PDF File"; } public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf"); } }); if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) { return; } File targetFile = fc.getSelectedFile(); if (!targetFile.getName().toLowerCase().endsWith(".pdf")) { targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf"); } if (targetFile.exists()) { if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) { return; } } try { final InputStream is = new FileInputStream(filename); try { final OutputStream os = new FileOutputStream(targetFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); } } finally { os.close(); } } finally { is.close(); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public boolean verify(String digest, String password) throws NoSuchAlgorithmException { String alg = null; int size = 0; if (digest.regionMatches(true, 0, "{CRYPT}", 0, 7)) { digest = digest.substring(7); return UnixCrypt.matches(digest, password); } else if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) { digest = digest.substring(5); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) { digest = digest.substring(6); alg = "SHA-1"; size = 20; } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) { digest = digest.substring(5); alg = "MD5"; size = 16; } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) { digest = digest.substring(6); alg = "MD5"; size = 16; } MessageDigest msgDigest = MessageDigest.getInstance(alg); byte[][] hs = split(Base64.decode(digest.toCharArray()), size); byte[] hash = hs[0]; byte[] salt = hs[1]; msgDigest.reset(); msgDigest.update(password.getBytes()); msgDigest.update(salt); byte[] pwhash = msgDigest.digest(); return msgDigest.isEqual(hash, pwhash); } Code Sample 2: private static String fetch(String urltxt, String cookie) { try { URL url = new URL(urltxt); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream source = url.openStream(); String data = new Scanner(source).useDelimiter("\\A").next(); Pattern p = Pattern.compile("form action=\"(.*)\" method=\"post\""); Matcher m = p.matcher(data); if (!m.find()) return ""; urltxt = m.group(1); url = new URL(urltxt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", cookie); conn.setRequestMethod("POST"); conn.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write("dl.start=PREMIUM"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); while ((data = in.readLine()) != null) sb.append(data + System.getProperty("line.separator")); data = urltxt.substring(urltxt.lastIndexOf("/") + 1); p = Pattern.compile("<tr><td><a href=\"(.*?)" + data); m = p.matcher(sb.toString()); data = (m.find()) ? (m.group(1) + data + System.getProperty("line.separator")) : ""; return data; } catch (Exception e) { return ""; } }
00
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public static String getCssFile(String url) { StringBuffer buffer = new StringBuffer(); try { buffer = new StringBuffer(); URL urlToCrawl = new URL(url); URLConnection urlToCrawlConnection = urlToCrawl.openConnection(); urlToCrawlConnection.setRequestProperty("User-Agent", "USER_AGENT"); urlToCrawlConnection.setRequestProperty("Referer", "REFERER"); urlToCrawlConnection.setUseCaches(false); InputStreamReader isr = new InputStreamReader(urlToCrawlConnection.getInputStream()); BufferedReader in = new BufferedReader(isr); String str; while ((str = in.readLine()) != null) buffer.append(str); FileOutputStream fos = new FileOutputStream("c:\\downloads\\" + System.currentTimeMillis() + ".css"); Writer out = new OutputStreamWriter(fos); out.write(buffer.toString()); out.close(); } catch (Exception e) { System.out.println("Error Downloading css file" + e); } return buffer.toString(); }
11
Code Sample 1: public String getWeather(String cityName, String fileAddr) { try { URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather=" + cityName); InputStream inputstream = url.openStream(); String s, str; BufferedReader in = new BufferedReader(new InputStreamReader(inputstream)); StringBuffer stringbuffer = new StringBuffer(); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileAddr), "utf-8")); while ((s = in.readLine()) != null) { stringbuffer.append(s); } str = new String(stringbuffer); out.write(str); out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } File file = new File(fileAddr); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String str = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); NodeList nodelist1 = (NodeList) doc.getElementsByTagName("forecast_conditions"); NodeList nodelist2 = nodelist1.item(0).getChildNodes(); str = nodelist2.item(4).getAttributes().item(0).getNodeValue() + ",temperature:" + nodelist2.item(1).getAttributes().item(0).getNodeValue() + "℃-" + nodelist2.item(2).getAttributes().item(0).getNodeValue() + "℃"; } catch (Exception e) { e.printStackTrace(); } return str; } Code Sample 2: public static IChemModel readInChI(URL url) throws CDKException { IChemModel chemModel = new ChemModel(); try { IMoleculeSet moleculeSet = new MoleculeSet(); chemModel.setMoleculeSet(moleculeSet); StdInChIParser parser = new StdInChIParser(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { if (line.toLowerCase().startsWith("inchi=")) { IAtomContainer atc = parser.parseInchi(line); moleculeSet.addAtomContainer(atc); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new CDKException(e.getMessage()); } return chemModel; }
00
Code Sample 1: protected static String getURLandWriteToDisk(String url, Model retModel) throws MalformedURLException, IOException { String path = null; URL ontURL = new URL(url); InputStream ins = ontURL.openStream(); InputStreamReader bufRead; OutputStreamWriter bufWrite; int offset = 0, read = 0; initModelHash(); if (System.getProperty("user.dir") != null) { String delimiter; path = System.getProperty("user.dir"); if (path.contains("/")) { delimiter = "/"; } else { delimiter = "\\"; } char c = path.charAt(path.length() - 1); if (c == '/' || c == '\\') { path = path.substring(0, path.length() - 2); } path = path.substring(0, path.lastIndexOf(delimiter) + 1); path = path.concat("ontologies" + delimiter + "downloaded"); (new File(path)).mkdir(); path = path.concat(delimiter); path = createFullPath(url, path); bufWrite = new OutputStreamWriter(new FileOutputStream(path)); bufRead = new InputStreamReader(ins); read = bufRead.read(); while (read != -1) { bufWrite.write(read); offset += read; read = bufRead.read(); } bufRead.close(); bufWrite.close(); ins.close(); FileInputStream fs = new FileInputStream(path); retModel.read(fs, ""); } return path; } Code Sample 2: public static Document loadXML(URL url) { Document doc = null; try { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = docBuilder.parse(url.openStream()); } catch (ParserConfigurationException pce) { } catch (SAXException saxe) { } catch (IOException ioe) { } return doc; }
11
Code Sample 1: public static void unzip(File sourceZipFile, File unzipDestinationDirectory, FileFilter filter) throws IOException { unzipDestinationDirectory.mkdirs(); if (!unzipDestinationDirectory.exists()) { throw new IOException("Unable to create destination directory: " + unzipDestinationDirectory); } ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); if (!entry.isDirectory()) { String currentEntry = entry.getName(); File destFile = new File(unzipDestinationDirectory, currentEntry); if (filter == null || filter.accept(destFile)) { File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); FileOutputStream fos = new FileOutputStream(destFile); IOUtils.copyLarge(is, fos); fos.flush(); IOUtils.closeQuietly(fos); } } } zipFile.close(); } Code Sample 2: protected void onSubmit() { super.onSubmit(); if (!this.hasError()) { final FileUpload upload = fileUploadField.getFileUpload(); if (upload != null) { try { StringWriter xmlSourceWriter = new StringWriter(); IOUtils.copy(upload.getInputStream(), xmlSourceWriter); processSubmittedDoap(xmlSourceWriter.toString()); } catch (IOException e) { setResponsePage(new ErrorReportPage(new UserReportableException("Unable to add doap using RDF supplied", DoapFormPage.class, e))); } } } }
11
Code Sample 1: private static List retrieveQuotes(Report report, Symbol symbol, String prefix, TradingDate startDate, TradingDate endDate) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbol, prefix, startDate, endDate); EODQuoteFilter filter = new GoogleEODQuoteFilter(symbol); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.getProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line = bufferedInput.readLine(); while (line != null) { line = bufferedInput.readLine(); if (line != null) { try { EODQuote quote = filter.toEODQuote(line); quotes.add(quote); verify(report, quote); } catch (QuoteFormatException e) { report.addError(Locale.getString("GOOGLE_DISPLAY_URL") + ":" + symbol + ":" + Locale.getString("ERROR") + ": " + e.getMessage()); } } } 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) { } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); }
11
Code Sample 1: public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static String md5Encrypt(String valueToEncrypted) { String encryptedValue = ""; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(valueToEncrypted.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); encryptedValue = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } return encryptedValue; }
11
Code Sample 1: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } } Code Sample 2: public static void copyFile(File sourceFile, File targetFile) throws IOException { if (sourceFile == null || targetFile == null) { throw new NullPointerException("Source file and target file must not be null"); } File directory = targetFile.getParentFile(); if (!directory.exists() && !directory.mkdirs()) { throw new IOException("Could not create directory '" + directory + "'"); } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); try { byte[] buffer = new byte[32768]; for (int readBytes = inputStream.read(buffer); readBytes > 0; readBytes = inputStream.read(buffer)) { outputStream.write(buffer, 0, readBytes); } } catch (IOException ex) { targetFile.delete(); throw ex; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } }
11
Code Sample 1: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; } Code Sample 2: private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException { FileChannel inputChannel = new FileInputStream(inputFile).getChannel(); FileChannel outputChannel = new FileOutputStream(outputFile).getChannel(); try { inputChannel.transferTo(0, inputChannel.size(), outputChannel); } catch (IOException e) { throw e; } finally { if (inputChannel != null) inputChannel.close(); if (outputChannel != null) outputChannel.close(); } }
00
Code Sample 1: public IStatus runInUIThread(IProgressMonitor monitor) { monitor.beginTask(Strings.MSG_CONNECT_SERVER, 3); InputStream in = null; try { URL url = createOpenUrl(resource, pref); if (url != null) { URLConnection con = url.openConnection(); monitor.worked(1); monitor.setTaskName(Strings.MSG_WAIT_FOR_SERVER); con.connect(); in = con.getInputStream(); in.read(); monitor.worked(1); monitor.setTaskName(NLS.bind(Strings.MSG_OPEN_URL, url)); open(url, resource.getProject(), pref); monitor.worked(1); } } catch (ConnectException con) { if (count < 3) { ConnectAndOpenJob job = new ConnectAndOpenJob(resource, pref, ++count); job.schedule(1000L); } else { Activator.log(con); } } catch (Exception e) { Activator.log(e); } finally { Streams.close(in); monitor.done(); } return Status.OK_STATUS; } Code Sample 2: public static String post(String strUrl, String data) throws Exception { URL url = new URL(strUrl); final String method = "POST"; final String host = url.getHost(); final String contentType = "application/x-www-form-urlencoded"; final int contentLength = getContentLength(data); final String encoding = "UTF-8"; final String connection = "Close"; Config.log(DEBUG, "Sending data to: " + url + " (host=" + host + ", encoding=" + encoding + ", method=" + method + ", Content-Type=" + contentType + ", Content-Length=" + contentLength + ", Connection=" + connection + "):" + "\r\n" + data); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(method); conn.setRequestProperty("host", host); conn.setRequestProperty("content-type", contentType); conn.setRequestProperty("Content-Encoding", encoding); conn.setRequestProperty("content-length", contentLength + ""); conn.setRequestProperty("connection", connection); if (tools.valid(Config.JSON_RPC_WEBSERVER_USERNAME) && tools.valid(Config.JSON_RPC_WEBSERVER_PASSWORD)) { String authString = Config.JSON_RPC_WEBSERVER_USERNAME + ":" + Config.JSON_RPC_WEBSERVER_PASSWORD; String authStringEnc = new sun.misc.BASE64Encoder().encode(authString.getBytes()); conn.setRequestProperty("Authorization", "Basic " + authStringEnc); } conn.setReadTimeout((int) (Config.JSON_RPC_TIMEOUT_SECONDS * 1000)); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); writer.close(); int responseCode = 400; try { responseCode = conn.getResponseCode(); } catch (Exception x) { Config.log(ERROR, "Failed to get response code from HTTP Server. Check your URL and username/password.", x); } String response = readStream(responseCode == 200 ? conn.getInputStream() : conn.getErrorStream()); if (response == null) { return null; } Config.log(DEBUG, "Raw response from POST. Response Code = " + conn.getResponseCode() + " (" + conn.getResponseMessage() + "):\r\n" + response); return response.toString(); }
11
Code Sample 1: protected byte[] createFileID() { try { COSDocument cosDoc = cosGetDoc(); if (cosDoc == null) { return null; } ILocator locator = cosDoc.getLocator(); if (locator == null) { return null; } IRandomAccess ra = cosDoc.stGetDoc().getRandomAccess(); if (ra == null) { ra = new RandomAccessByteArray(StringTools.toByteArray("DummyValue")); } MessageDigest digest = MessageDigest.getInstance("MD5"); long time = System.currentTimeMillis(); digest.update(String.valueOf(time).getBytes()); digest.update(locator.getFullName().getBytes()); digest.update(String.valueOf(ra.getLength()).getBytes()); COSInfoDict infoDict = getInfoDict(); if (infoDict != null) { for (Iterator it = infoDict.cosGetDict().iterator(); it.hasNext(); ) { COSObject object = (COSObject) it.next(); digest.update(object.stringValue().getBytes()); } } return digest.digest(); } catch (Exception e) { throw new IllegalStateException(e); } } Code Sample 2: private static String md5(String digest, String data) throws IOException { MessageDigest messagedigest; try { messagedigest = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } messagedigest.update(data.getBytes("ISO-8859-1")); byte[] bytes = messagedigest.digest(); StringBuilder stringbuffer = new StringBuilder(bytes.length * 2); for (int j = 0; j < bytes.length; j++) { int k = bytes[j] >>> 4 & 0x0f; stringbuffer.append(hexChars[k]); k = bytes[j] & 0x0f; stringbuffer.append(hexChars[k]); } return stringbuffer.toString(); }
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 void initialize() { List providers = new ArrayList(); while (this.urls.hasMoreElements()) { URL url = (URL) this.urls.nextElement(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { String provider = uncommentLine(line).trim(); if (provider != null && provider.length() > 0) { providers.add(provider); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } this.iterator = providers.iterator(); }
00
Code Sample 1: public void postData(Reader data, Writer output) { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) solrUrl.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new PostException("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + POST_ENCODING); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, POST_ENCODING); pipe(data, writer); writer.close(); } catch (IOException e) { throw new PostException("IOException while posting data", e); } finally { if (out != null) out.close(); } InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); } catch (IOException e) { throw new PostException("IOException while reading response", e); } finally { if (in != null) in.close(); } } catch (IOException e) { try { fatal("Solr returned an error: " + urlc.getResponseMessage()); } catch (IOException f) { } fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e); } finally { if (urlc != null) urlc.disconnect(); } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public static InputStream call(String serviceUrl, Map parameters) throws IOException, RestException { StringBuffer urlString = new StringBuffer(serviceUrl); String query = RestClient.buildQueryString(parameters); HttpURLConnection conn; if ((urlString.length() + query.length() + 1) > MAX_URI_LENGTH_FOR_GET) { URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.getOutputStream().write(query.getBytes()); } else { if (query.length() > 0) { urlString.append("?").append(query); } URL url = new URL(urlString.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_STRING); conn.setRequestMethod("GET"); } int responseCode = conn.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream(); int read; byte[] readBuffer = new byte[ERROR_READ_BUFFER_SIZE]; InputStream errorStream = conn.getErrorStream(); while (-1 != (read = errorStream.read(readBuffer))) { errorBuffer.write(readBuffer, 0, read); } throw new RestException("Request failed, HTTP " + responseCode + ": " + conn.getResponseMessage(), errorBuffer.toByteArray()); } return conn.getInputStream(); } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: public static void storePolicy(DBBroker broker, XmldbURI docPath) throws EXistException, IOException { XmldbURI docName = docPath.lastSegment(); URL url = XACMLUtil.class.getResource(docPath.toString()); if (url == null) return; String content = toString(url.openStream()); if (content == null) return; Collection collection = getPolicyCollection(broker); if (collection == null) return; TransactionManager transact = broker.getBrokerPool().getTransactionManager(); Txn txn = transact.beginTransaction(); try { IndexInfo info = collection.validateXMLResource(txn, broker, docName, content); collection.store(txn, broker, info, content, false); transact.commit(txn); } catch (Exception e) { transact.abort(txn); if (e instanceof EXistException) throw (EXistException) e; throw new EXistException("Error storing policy '" + docPath + "'", e); } } Code Sample 2: private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); } if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && headers == null || !headers.containsKey("Accept-Encoding")) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse response = client.execute(hr, context); byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; if (code < 200 || code >= 300) { try { HttpEntity entity = response.getEntity(); byte[] s = AQUtility.toBytes(entity.getContent()); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } catch (Exception e) { AQUtility.debug(e); } } else { HttpEntity entity = response.getEntity(); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); PredefinedBAOS baos = new PredefinedBAOS(size); Header encoding = entity.getContentEncoding(); if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) { InputStream is = new GZIPInputStream(entity.getContent()); AQUtility.copy(is, baos); } else { entity.writeTo(baos); } data = baos.toByteArray(); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).client(client).context(context).headers(response.getAllHeaders()); }
11
Code Sample 1: private void analyseCorpus(final IStatusDisplayer fStatus) { final String sDistrosFile = "Distros.tmp"; final String sSymbolsFile = "Symbols.tmp"; Chunker = new EntropyChunker(); int Levels = 2; sgOverallGraph = new SymbolicGraph(1, Levels); siIndex = new SemanticIndex(sgOverallGraph); try { siIndex.MeaningExtractor = new LocalWordNetMeaningExtractor(); } catch (IOException ioe) { siIndex.MeaningExtractor = null; } try { DocumentSet dsSet = new DocumentSet(FilePathEdt.getText(), 1.0); dsSet.createSets(true, (double) 100 / 100); int iCurCnt, iTotal; String sFile = ""; Iterator iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } appendToLog("Training chunker..."); Chunker.train(dsSet.toFilenameSet(DocumentSet.FROM_WHOLE_SET)); appendToLog("Setting delimiters..."); setDelimiters(Chunker.getDelimiters()); iCurCnt = 0; cdDoc = new DistributionDocument[Levels]; for (int iCnt = 0; iCnt < Levels; iCnt++) cdDoc[iCnt] = new DistributionDocument(1, MinLevel + iCnt); fStatus.setVisible(true); ThreadList t = new ThreadList(Runtime.getRuntime().availableProcessors() + 1); appendToLog("(Pass 1/3) Loading files..." + sFile); TreeSet tsOverallSymbols = new TreeSet(); while (iIter.hasNext()) { sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); fStatus.setStatus("(Pass 1/3) Loading file..." + sFile, (double) iCurCnt / iTotal); final DistributionDocument[] cdDocArg = cdDoc; final String sFileArg = sFile; for (int iCnt = 0; iCnt < cdDoc.length; iCnt++) { final int iCntArg = iCnt; while (!t.addThreadFor(new Runnable() { public void run() { if (!RightToLeftText) cdDocArg[iCntArg].loadDataStringFromFile(sFileArg, false); else { cdDocArg[iCntArg].setDataString(utils.reverseString(utils.loadFileToString(sFileArg)), iCntArg, false); } } })) Thread.yield(); } try { t.waitUntilCompletion(); } catch (InterruptedException ex) { ex.printStackTrace(System.err); appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } sgOverallGraph.setDataString(((new StringBuffer().append((char) StreamTokenizer.TT_EOF))).toString()); sgOverallGraph.loadFromFile(sFile); fStatus.setStatus("Loaded file..." + sFile, (double) ++iCurCnt / iTotal); Thread.yield(); } Set sSymbols = null; File fPreviousSymbols = new File(sSymbolsFile); boolean bSymbolsLoadedOK = false; if (fPreviousSymbols.exists()) { System.err.println("ATTENTION: Using previous symbols..."); try { FileInputStream fis = new FileInputStream(fPreviousSymbols); ObjectInputStream ois = new ObjectInputStream(fis); sSymbols = (Set) ois.readObject(); ois.close(); bSymbolsLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); } } if (!bSymbolsLoadedOK) sSymbols = getSymbolsByProbabilities(sgOverallGraph.getDataString(), fStatus); int iMinSymbolSize = Integer.MAX_VALUE; int iMaxSymbolSize = Integer.MIN_VALUE; Iterator iSymbol = sSymbols.iterator(); while (iSymbol.hasNext()) { String sCurSymbol = (String) iSymbol.next(); if (iMaxSymbolSize < sCurSymbol.length()) iMaxSymbolSize = sCurSymbol.length(); if (iMinSymbolSize > sCurSymbol.length()) iMinSymbolSize = sCurSymbol.length(); } try { FileOutputStream fos = new FileOutputStream(sSymbolsFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(sSymbols); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } appendToLog("(Pass 2/3) Determining symbol distros per n-gram size..."); iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } iCurCnt = 0; Distribution dSymbolsPerSize = new Distribution(); Distribution dNonSymbolsPerSize = new Distribution(); Distribution dSymbolSizes = new Distribution(); File fPreviousRun = new File(sDistrosFile); boolean bDistrosLoadedOK = false; if (fPreviousRun.exists()) { System.err.println("ATTENTION: Using previous distros..."); try { FileInputStream fis = new FileInputStream(fPreviousRun); ObjectInputStream ois = new ObjectInputStream(fis); dSymbolsPerSize = (Distribution) ois.readObject(); dNonSymbolsPerSize = (Distribution) ois.readObject(); dSymbolSizes = (Distribution) ois.readObject(); ois.close(); bDistrosLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } } if (!bDistrosLoadedOK) while (iIter.hasNext()) { fStatus.setStatus("(Pass 2/3) Parsing file..." + sFile, (double) iCurCnt++ / iTotal); sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); String sDataString = ""; try { ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); FileInputStream fiIn = new FileInputStream(sFile); int iData = 0; while ((iData = fiIn.read()) > -1) bsOut.write(iData); sDataString = bsOut.toString(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } final Distribution dSymbolsPerSizeArg = dSymbolsPerSize; final Distribution dNonSymbolsPerSizeArg = dNonSymbolsPerSize; final Distribution dSymbolSizesArg = dSymbolSizes; final String sDataStringArg = sDataString; final Set sSymbolsArg = sSymbols; for (int iSymbolSize = iMinSymbolSize; iSymbolSize <= iMaxSymbolSize; iSymbolSize++) { final int iSymbolSizeArg = iSymbolSize; while (!t.addThreadFor(new Runnable() { public void run() { NGramDocument ndCur = new NGramDocument(iSymbolSizeArg, iSymbolSizeArg, 1, iSymbolSizeArg, iSymbolSizeArg); ndCur.setDataString(sDataStringArg); int iSymbolCnt = 0; int iNonSymbolCnt = 0; Iterator iExtracted = ndCur.getDocumentGraph().getGraphLevel(0).getVertexSet().iterator(); while (iExtracted.hasNext()) { String sCur = ((Vertex) iExtracted.next()).toString(); if (sSymbolsArg.contains(sCur)) { iSymbolCnt++; synchronized (dSymbolSizesArg) { dSymbolSizesArg.setValue(sCur.length(), dSymbolSizesArg.getValue(sCur.length()) + 1.0); } } else iNonSymbolCnt++; } synchronized (dSymbolsPerSizeArg) { dSymbolsPerSizeArg.setValue(iSymbolSizeArg, dSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iSymbolCnt); } synchronized (dNonSymbolsPerSizeArg) { dNonSymbolsPerSizeArg.setValue(iSymbolSizeArg, dNonSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iNonSymbolCnt); } } })) Thread.yield(); } } if (!bDistrosLoadedOK) try { t.waitUntilCompletion(); try { FileOutputStream fos = new FileOutputStream(sDistrosFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(dSymbolsPerSize); oos.writeObject(dNonSymbolsPerSize); oos.writeObject(dSymbolSizes); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } } catch (InterruptedException ex) { appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } appendToLog("\n(Pass 3/3) Determining optimal n-gram range...\n"); NGramSizeEstimator nseEstimator = new NGramSizeEstimator(dSymbolsPerSize, dNonSymbolsPerSize); IntegerPair p = nseEstimator.getOptimalRange(); appendToLog("\nProposed n-gram sizes:" + p.first() + "," + p.second()); fStatus.setStatus("Determining optimal distance...", 0.0); DistanceEstimator de = new DistanceEstimator(dSymbolsPerSize, dNonSymbolsPerSize, nseEstimator); int iBestDist = de.getOptimalDistance(1, nseEstimator.getMaxRank() * 2, p.first(), p.second()); fStatus.setStatus("Determining optimal distance...", 1.0); appendToLog("\nOptimal distance:" + iBestDist); appendToLog("======DONE=====\n"); } finally { sgOverallGraph.removeNotificationListener(); } } Code Sample 2: public void writeOutput(String directory) throws IOException { File f = new File(directory); int i = 0; if (f.isDirectory()) { for (AppInventorScreen screen : screens.values()) { File screenFile = new File(getScreenFilePath(f.getAbsolutePath(), screen)); screenFile.getParentFile().mkdirs(); screenFile.createNewFile(); FileWriter out = new FileWriter(screenFile); String initial = files.get(i).toString(); Map<String, String> types = screen.getTypes(); String[] lines = initial.split("\n"); for (String key : types.keySet()) { if (!key.trim().equals(screen.getName().trim())) { String value = types.get(key); boolean varFound = false; boolean importFound = false; for (String line : lines) { if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*=.*;$")) varFound = true; if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*;$")) varFound = true; if (line.matches("^\\s*import\\s+.*" + value + "\\s*;$")) importFound = true; } if (!varFound) initial = initial.replaceFirst("(?s)(?<=\\{\n)", "\tprivate " + value + " " + key + ";\n"); if (!importFound) initial = initial.replaceFirst("(?=import)", "import com.google.devtools.simple.runtime.components.android." + value + ";\n"); } } out.write(initial); out.close(); i++; } File manifestFile = new File(getManifestFilePath(f.getAbsolutePath(), manifest)); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); FileWriter out = new FileWriter(manifestFile); out.write(manifest.toString()); out.close(); File projectFile = new File(getProjectFilePath(f.getAbsolutePath(), project)); projectFile.getParentFile().mkdirs(); projectFile.createNewFile(); out = new FileWriter(projectFile); out.write(project.toString()); out.close(); String[] copyResourceFilenames = { "proguard.cfg", "project.properties", "libSimpleAndroidRuntime.jar", "\\.classpath", "res/drawable/icon.png", "\\.settings/org.eclipse.jdt.core.prefs" }; for (String copyResourceFilename : copyResourceFilenames) { InputStream is = getClass().getResourceAsStream("/resources/" + copyResourceFilename.replace("\\.", "")); File outputFile = new File(f.getAbsoluteFile() + File.separator + copyResourceFilename.replace("\\.", ".")); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; if (is == null) System.out.println("/resources/" + copyResourceFilename.replace("\\.", "")); if (os == null) System.out.println(f.getAbsolutePath() + File.separator + copyResourceFilename.replace("\\.", ".")); while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } for (String assetName : assets) { InputStream is = new FileInputStream(new File(assetsDir.getAbsolutePath() + File.separator + assetName)); File outputFile = new File(f.getAbsoluteFile() + File.separator + assetName); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } File assetsOutput = new File(getAssetsFilePath(f.getAbsolutePath())); new File(assetsDir.getAbsoluteFile() + File.separator + "assets").renameTo(assetsOutput); } }
11
Code Sample 1: public void xtestFile1() throws Exception { InputStream inputStream = new FileInputStream(IOTest.FILE); OutputStream outputStream = new FileOutputStream("C:/Temp/testFile1.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); } Code Sample 2: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
00
Code Sample 1: public String getContentsFromVariant(SelectedVariant selected) { if (selected == null) { return null; } ActivatedVariablePolicy policy = selected.getPolicy(); Variant variant = selected.getVariant(); if (variant == null) { return null; } Content content = variant.getContent(); if (content instanceof EmbeddedContent) { EmbeddedContent embedded = (EmbeddedContent) content; return embedded.getData(); } else { MarinerURL marinerURL = computeURL((Asset) selected.getOldObject()); URL url; try { url = context.getAbsoluteURL(marinerURL); } catch (MalformedURLException e) { logger.warn("asset-mariner-url-retrieval-error", new Object[] { policy.getName(), ((marinerURL == null) ? "" : marinerURL.getExternalForm()) }, e); return null; } String text = null; try { if (logger.isDebugEnabled()) { logger.debug("Retrieving contents of URL " + url); } URLConnection connection = url.openConnection(); int contentLength = connection.getContentLength(); if (contentLength > 0) { String charset = connection.getContentEncoding(); if (charset == null) { charset = "UTF-8"; } InputStreamReader is = new InputStreamReader(connection.getInputStream(), charset); BufferedReader br = new BufferedReader(is); char[] buf = new char[contentLength]; int length = br.read(buf, 0, buf.length); text = String.copyValueOf(buf, 0, length); } } catch (IOException e) { logger.warn("asset-url-retrieval-error", new Object[] { policy.getName(), url }, e); } return text; } } Code Sample 2: public TreeMap getStrainMap() { TreeMap strainMap = new TreeMap(); String server = ""; try { Datasource[] ds = DatasourceManager.getDatasouce(alias, version, DatasourceManager.ALL_CONTAINS_GROUP); for (int i = 0; i < ds.length; i++) { if (ds[i].getDescription().startsWith(MOUSE_DBSNP)) { if (ds[i].getServer().length() == 0) { Connection con = ds[i].getConnection(); strainMap = Action.lineMode.regularSQL.GenotypeDataSearchAction.getStrainMap(con); break; } else { server = ds[i].getServer(); HashMap serverUrlMap = InitXml.getInstance().getServerMap(); String serverUrl = (String) serverUrlMap.get(server); URL url = new URL(serverUrl + servletName); URLConnection uc = url.openConnection(); uc.setDoOutput(true); OutputStream os = uc.getOutputStream(); StringBuffer buf = new StringBuffer(); buf.append("viewType=getstrains"); buf.append("&hHead=" + hHead); buf.append("&hCheck=" + version); PrintStream ps = new PrintStream(os); ps.print(buf.toString()); ps.close(); ObjectInputStream ois = new ObjectInputStream(uc.getInputStream()); strainMap = (TreeMap) ois.readObject(); ois.close(); } } } } catch (Exception e) { log.error("strain map", e); } return strainMap; }
00
Code Sample 1: public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } } Code Sample 2: private String doOAIQuery(String request) throws IOException, ProtocolException { DannoClient ac = getClient(); HttpGet get = new HttpGet(request); get.setHeader("Accept", "application/xml"); HttpResponse response = ac.execute(get); if (!ac.isOK()) { throw new DannoRequestFailureException("GET", response); } return massage(new BasicResponseHandler().handleResponse(response)); }
11
Code Sample 1: public synchronized void deleteDocument(final String file) throws IOException { SQLException ex = null; try { PreparedStatement findFileStmt = con.prepareStatement("SELECT ID AS \"ID\" FROM File_ WHERE Name = ?"); findFileStmt.setString(1, file); ResultSet rs = findFileStmt.executeQuery(); if (null != rs && rs.next()) { int fileId = rs.getInt("ID"); rs.close(); rs = null; PreparedStatement deleteTokensStmt = con.prepareStatement("DELETE FROM Token_ WHERE FieldID IN ( SELECT ID FROM Field_ WHERE FileID = ? )"); deleteTokensStmt.setInt(1, fileId); deleteTokensStmt.executeUpdate(); PreparedStatement deleteFieldsStmt = con.prepareStatement("DELETE FROM Field_ WHERE FileID = ?"); deleteFieldsStmt.setInt(1, fileId); deleteFieldsStmt.executeUpdate(); PreparedStatement deleteFileStmt = con.prepareStatement("DELETE FROM File_ WHERE ID = ?"); deleteFileStmt.setInt(1, fileId); deleteFileStmt.executeUpdate(); deleteFileStmt.close(); deleteFileStmt = null; deleteFieldsStmt.close(); deleteFieldsStmt = null; deleteTokensStmt.close(); deleteTokensStmt = null; } findFileStmt.close(); findFileStmt = null; } catch (SQLException e) { e.printStackTrace(); ex = e; try { this.con.rollback(); } catch (SQLException e2) { } } finally { try { this.con.setAutoCommit(true); } catch (SQLException e2) { } } if (null != ex) throw new IOException(ex.getMessage()); } Code Sample 2: public void modify(String strName, String strNewPass) { String str = "update jb_user set V_PASSWORD =? where V_USERNAME =?"; Connection con = null; PreparedStatement pstmt = null; try { con = DbForumFactory.getConnection(); con.setAutoCommit(false); pstmt = con.prepareStatement(str); pstmt.setString(1, SecurityUtil.md5ByHex(strNewPass)); pstmt.setString(2, strName); pstmt.executeUpdate(); con.commit(); } catch (Exception e) { e.printStackTrace(); try { con.rollback(); } catch (SQLException e1) { } } finally { try { DbForumFactory.closeDB(null, pstmt, null, con); } catch (Exception e) { } } }
11
Code Sample 1: public static void copyFile(String pathOrig, String pathDst) throws FileNotFoundException, IOException { InputStream in; OutputStream out; if (pathOrig == null || pathDst == null) { System.err.println("Error en path"); return; } File orig = new File(pathOrig); if (!orig.exists() || !orig.isFile() || !orig.canRead()) { System.err.println("Error en fichero de origen"); return; } File dest = new File(pathDst); String file = new File(pathOrig).getName(); if (dest.isDirectory()) pathDst += file; in = new FileInputStream(pathOrig); out = new FileOutputStream(pathDst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: public static void copyFile(File from, File to) throws IOException { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; } Code Sample 2: boolean copyFileStructure(File oldFile, File newFile) { if (oldFile == null || newFile == null) return false; File searchFile = newFile; do { if (oldFile.equals(searchFile)) return false; searchFile = searchFile.getParentFile(); } while (searchFile != null); if (oldFile.isDirectory()) { if (progressDialog != null) { progressDialog.setDetailFile(oldFile, ProgressDialog.COPY); } if (simulateOnly) { } else { if (!newFile.mkdirs()) return false; } File[] subFiles = oldFile.listFiles(); if (subFiles != null) { if (progressDialog != null) { progressDialog.addWorkUnits(subFiles.length); } for (int i = 0; i < subFiles.length; i++) { File oldSubFile = subFiles[i]; File newSubFile = new File(newFile, oldSubFile.getName()); if (!copyFileStructure(oldSubFile, newSubFile)) return false; if (progressDialog != null) { progressDialog.addProgress(1); if (progressDialog.isCancelled()) return false; } } } } else { if (simulateOnly) { } else { FileReader in = null; FileWriter out = null; try { in = new FileReader(oldFile); out = new FileWriter(newFile); int count; while ((count = in.read()) != -1) out.write(count); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { return false; } } } } return true; }
11
Code Sample 1: public void updateDb(int scriptNumber) throws SQLException, IOException { String pathName = updatesPackage.replace(".", "/"); InputStream in = getClass().getClassLoader().getResourceAsStream(pathName + "/" + scriptNumber + ".sql"); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); String script = out.toString("UTF-8"); String[] statements = script.split(";"); for (String statement : statements) { getJdbcTemplate().execute(statement); } } Code Sample 2: private void installBinaryFile(File source, File destination) { byte[] buffer = new byte[8192]; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); int read; while ((read = fis.read(buffer)) != -1) { fos.write(buffer, 0, read); } } catch (FileNotFoundException e) { } catch (IOException e) { new ProjectCreateException(e, "Failed to read binary file: %1$s", source.getAbsolutePath()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public void init(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8"), 0, password.length()); byte[] rawKey = md.digest(); skeySpec = new SecretKeySpec(rawKey, "AES"); ivSpec = new IvParameterSpec(rawKey); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: private String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
11
Code Sample 1: public void removeExifTag(File jpegImageFile, File dst) throws IOException, ImageReadException, ImageWriteException { OutputStream os = null; try { TiffOutputSet outputSet = null; IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile); JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata; if (null != jpegMetadata) { TiffImageMetadata exif = jpegMetadata.getExif(); if (null != exif) { outputSet = exif.getOutputSet(); } } if (null == outputSet) { IOUtils.copyFileNio(jpegImageFile, dst); return; } { outputSet.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); TiffOutputDirectory exifDirectory = outputSet.getExifDirectory(); if (null != exifDirectory) exifDirectory.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); } os = new FileOutputStream(dst); os = new BufferedOutputStream(os); new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet); os.close(); os = null; } finally { if (os != null) try { os.close(); } catch (IOException e) { } } } Code Sample 2: public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; }
00
Code Sample 1: public static String getMD5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes("ISO8859_1")); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (Exception ex) { } return res; } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
11
Code Sample 1: private void prepareJobFile(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.JOB, zer.getName(), fcopyName)); } Code Sample 2: public Parameters getParameters(HttpExchange http) throws IOException { ParametersImpl params = new ParametersImpl(); String query = null; if (http.getRequestMethod().equalsIgnoreCase("GET")) { query = http.getRequestURI().getRawQuery(); } else if (http.getRequestMethod().equalsIgnoreCase("POST")) { InputStream in = new MaxInputStream(http.getRequestBody()); if (in != null) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtils.copyTo(in, bytes); query = new String(bytes.toByteArray()); in.close(); } } else { throw new IOException("Method not supported " + http.getRequestMethod()); } if (query != null) { for (String s : query.split("[&]")) { s = s.replace('+', ' '); int eq = s.indexOf('='); if (eq > 0) { params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8")); } } } return params; }
11
Code Sample 1: public static String encryptPassword(String password) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { LOG.error(e); } try { md.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { LOG.error(e); } return (new BASE64Encoder()).encode(md.digest()); } Code Sample 2: public static String md5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(value.getBytes()); return bytesToString(messageDigest.digest()); } catch (Exception ex) { Tools.logException(Tools.class, ex, value); } return value; }
00
Code Sample 1: public void copy(File src, File dest) throws FileNotFoundException, IOException { FileInputStream srcStream = new FileInputStream(src); FileOutputStream destStream = new FileOutputStream(dest); FileChannel srcChannel = srcStream.getChannel(); FileChannel destChannel = destStream.getChannel(); srcChannel.transferTo(0, srcChannel.size(), destChannel); destChannel.close(); srcChannel.close(); destStream.close(); srcStream.close(); } Code Sample 2: private final String createMD5(String pwd) throws Exception { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(pwd.getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } return app.toString(); }
00
Code Sample 1: public ProjectDeploymentConfiguration deleteProjectDeploymentConfig(int id) throws AdaptationException { ProjectDeploymentConfiguration config = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProjectDeploymentConfigurations " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete project deployment " + "configuration failed."; log.error(msg); throw new AdaptationException(msg); } config = getProjectDeploymentConfiguration(resultSet); query = "DELETE FROM ProjectDeploymentConfigurations " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProjectDeploymentConfig"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return config; } Code Sample 2: private void copyFile(File orig, File dest) { byte[] buffer = new byte[1024]; try { FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(dest, true); int readBytes = 0; do { readBytes = fis.read(buffer); if (readBytes > 0) fos.write(buffer, 0, readBytes); } while (readBytes > 0); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private void performDownload() { List<String> selected = filesPane.getSelectedValuesList(); if (selected == null || selected.isEmpty() || selected.size() != 1) { JOptionPane.showMessageDialog(this, "Please select one path"); return; } RFile file = new RFile(selected.get(0)); if (!file.isFile()) { JOptionPane.showMessageDialog(this, "file does not exist anymore"); return; } chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), file.getName())); int ok = chooser.showSaveDialog(this); if (ok != JFileChooser.APPROVE_OPTION) { return; } FileOutputStream fout = null; RFileInputStream in = null; try { fout = new FileOutputStream(chooser.getSelectedFile()); in = new RFileInputStream(file); IOUtils.copy(in, fout); JOptionPane.showMessageDialog(this, "File downloaded to " + chooser.getSelectedFile(), "Download finished", JOptionPane.INFORMATION_MESSAGE); } catch (IOException iOException) { JOptionPane.showMessageDialog(this, "Error: " + iOException, "Error", JOptionPane.ERROR_MESSAGE); } finally { if (in != null) { try { in.close(); } catch (Throwable t) { } } if (fout != null) { try { fout.close(); } catch (Throwable t) { } } } } Code Sample 2: public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: private Map<String, DomAttr> getAttributesFor(final BaseFrame frame) throws IOException { final Map<String, DomAttr> map = createAttributesCopyWithClonedAttribute(frame, "src"); final DomAttr srcAttr = map.get("src"); if (srcAttr == null) { return map; } final Page enclosedPage = frame.getEnclosedPage(); final String suffix = getFileExtension(enclosedPage); final File file = createFile(srcAttr.getValue(), "." + suffix); if (enclosedPage instanceof HtmlPage) { file.delete(); ((HtmlPage) enclosedPage).save(file); } else { final InputStream is = enclosedPage.getWebResponse().getContentAsStream(); final FileOutputStream fos = new FileOutputStream(file); IOUtils.copyLarge(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } srcAttr.setValue(file.getParentFile().getName() + FILE_SEPARATOR + file.getName()); return map; }
11
Code Sample 1: @Override public Document duplicate() { BinaryDocument b = new BinaryDocument(this.name, this.content.getContentType()); try { IOUtils.copy(this.getContent().getInputStream(), this.getContent().getOutputStream()); return b; } catch (IOException e) { throw ManagedIOException.manage(e); } } Code Sample 2: private void collectImageFile(@NotNull final Progress progress, @NotNull final File collectedDirectory) throws IOException { final File file = new File(collectedDirectory, ActionBuilderUtils.getString(ACTION_BUILDER, "configSource.image.name")); final FileOutputStream fos = new FileOutputStream(file); try { final FileChannel outChannel = fos.getChannel(); try { final int numOfFaceObjects = faceObjects.size(); progress.setLabel(ActionBuilderUtils.getString(ACTION_BUILDER, "archCollectImages"), numOfFaceObjects); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); final Charset charset = Charset.forName("ISO-8859-1"); int i = 0; for (final FaceObject faceObject : faceObjects) { final String face = faceObject.getFaceName(); final String path = archFaceProvider.getFilename(face); try { final FileInputStream fin = new FileInputStream(path); try { final FileChannel inChannel = fin.getChannel(); final long imageSize = inChannel.size(); byteBuffer.clear(); byteBuffer.put(("IMAGE " + (faceObjects.isIncludeFaceNumbers() ? i + " " : "") + imageSize + " " + face + "\n").getBytes(charset)); byteBuffer.flip(); outChannel.write(byteBuffer); inChannel.transferTo(0L, imageSize, outChannel); } finally { fin.close(); } } catch (final FileNotFoundException ignored) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorFileNotFound", path); return; } catch (final IOException e) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorIOException", path, e); return; } if (i++ % 100 == 0) { progress.setValue(i); } } progress.setValue(faceObjects.size()); } finally { outChannel.close(); } } finally { fos.close(); } }
00
Code Sample 1: @Override public void run() { try { bitmapDrawable = new BitmapDrawable(new URL(url).openStream()); imageCache.put(id, new SoftReference<Drawable>(bitmapDrawable)); log("image::: put: id = " + id + " "); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } handler.post(new Runnable() { @Override public void run() { iv.setImageDrawable(bitmapDrawable); } }); } Code Sample 2: @Test public void test_blueprintDetailsForTypeName() throws Exception { URL url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar+Blueprint"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("{\"invBlueprintTypeDto\":{\"blueprintTypeID\":28849,\"blueprintTypeName\":\"Anshar Blueprint\",\"productTypeID\":28848,\"productTypeName\":\"Anshar\",\"productCategoryID\":6,\"parentBlueprintTypeID\":20188,\"parentBlueprintTypeName\":\"Obelisk Blueprint\",\"parentProductTypeID\":20187,\"parentProductTypeName\":\"Obelisk\",\"techLevel\":2,\"productionTime\":1920000,\"researchProductivityTime\":11520000,\"researchMaterialTime\":7680000,\"researchCopyTime\":2560000,\"researchTechTime\":3840000,\"productivityModifier\":384000,\"wasteFactor\":10,\"maxProductionLimit\":10,\"productVolume\":\"17550000\",\"productPortionSize\":1,\"dumpVersion\":\"cru16\"},\"materialDtos\":[{\"materialTypeID\":3828,\"materialTypeName\":\"Construction Blocks\",\"materialTypeCategoryID\":43,\"materialTypeIcon\":\"06_05\",\"materialVolume\":\"1.5\",\"quantity\":1500},{\"materialTypeID\":11399,\"materialTypeName\":\"Morphite\",\"materialTypeCategoryID\":4,\"materialTypeIcon\":\"35_02\",\"materialVolume\":\"0.01\",\"quantity\":2500},{\"materialTypeID\":21025,\"materialTypeName\":\"Capital Jump Drive\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"54_08\",\"materialVolume\":\"10000.0\",\"quantity\":20},{\"materialTypeID\":29041,\"materialTypeName\":\"Capital Crystalline Carbonide Armor Plate\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_14\",\"materialVolume\":\"10.0\",\"quantity\":1013},{\"materialTypeID\":29051,\"materialTypeName\":\"Capital Fusion Reactor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_02\",\"materialVolume\":\"10.0\",\"quantity\":518},{\"materialTypeID\":29061,\"materialTypeName\":\"Capital Ion Thruster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_02\",\"materialVolume\":\"10.0\",\"quantity\":422},{\"materialTypeID\":29069,\"materialTypeName\":\"Capital Magnetometric Sensor Cluster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_06\",\"materialVolume\":\"10.0\",\"quantity\":443},{\"materialTypeID\":29081,\"materialTypeName\":\"Capital Oscillator Capacitor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_06\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29085,\"materialTypeName\":\"Capital Photon Microprocessor\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_10\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29091,\"materialTypeName\":\"Capital Pulse Shield Emitter\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_10\",\"materialVolume\":\"10.0\",\"quantity\":449}],\"manufacturingRequirementDtos\":[{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":3380,\"requiredTypeName\":\"Industry\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":268,\"requiredTypeGroupName\":\"Industry\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11478,\"requiredTypeName\":\"R.A.M.- Starship Tech\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_02\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":20187,\"requiredTypeName\":\"Obelisk\",\"requiredTypeCategoryID\":6,\"requiredTypeGroupID\":513,\"requiredTypeGroupName\":\"Freighter\",\"damagePerJob\":\"1.0\",\"quantity\":1,\"requiredTypeVolume\":\"17550000\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":22242,\"requiredTypeName\":\"Capital Ship Construction\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":269,\"requiredTypeGroupName\":\"Mechanic\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"}],\"timeProductivityRequirementDtos\":[{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3403,\"requiredTypeName\":\"Research\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":120,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.8\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"materialProductivityRequirementDtos\":[{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3409,\"requiredTypeName\":\"Metallurgy\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":140,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.6\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"copyingRequirementDtos\":[{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":3812,\"requiredTypeName\":\"Data Sheets\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":600,\"requiredTypeVolume\":\"1.0\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"}],\"reverseEngineeringRequirementDtos\":[],\"inventionRequirementDtos\":[]}")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><blueprintDetailsDto><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>1.0</damagePerJob><quantity>600</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3812</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Data Sheets</requiredTypeName><requiredTypeVolume>1.0</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></copyingRequirementDtos><invBlueprintTypeDto><blueprintTypeID>28849</blueprintTypeID><blueprintTypeName>Anshar Blueprint</blueprintTypeName><dumpVersion>cru16</dumpVersion><maxProductionLimit>10</maxProductionLimit><parentBlueprintTypeID>20188</parentBlueprintTypeID><parentBlueprintTypeName>Obelisk Blueprint</parentBlueprintTypeName><parentProductTypeID>20187</parentProductTypeID><parentProductTypeName>Obelisk</parentProductTypeName><productCategoryID>6</productCategoryID><productPortionSize>1</productPortionSize><productTypeID>28848</productTypeID><productTypeName>Anshar</productTypeName><productVolume>17550000</productVolume><productionTime>1920000</productionTime><productivityModifier>384000</productivityModifier><researchCopyTime>2560000</researchCopyTime><researchMaterialTime>7680000</researchMaterialTime><researchProductivityTime>11520000</researchProductivityTime><researchTechTime>3840000</researchTechTime><techLevel>2</techLevel><wasteFactor>10</wasteFactor></invBlueprintTypeDto><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>268</requiredTypeGroupID><requiredTypeGroupName>Industry</requiredTypeGroupName><requiredTypeID>3380</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Industry</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11478</requiredTypeID><requiredTypeIcon>41_02</requiredTypeIcon><requiredTypeName>R.A.M.- Starship Tech</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>1.0</damagePerJob><quantity>1</quantity><requiredTypeCategoryID>6</requiredTypeCategoryID><requiredTypeGroupID>513</requiredTypeGroupID><requiredTypeGroupName>Freighter</requiredTypeGroupName><requiredTypeID>20187</requiredTypeID><requiredTypeName>Obelisk</requiredTypeName><requiredTypeVolume>17550000</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>269</requiredTypeGroupID><requiredTypeGroupName>Mechanic</requiredTypeGroupName><requiredTypeID>22242</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Capital Ship Construction</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><materialDtos><materialTypeCategoryID>43</materialTypeCategoryID><materialTypeID>3828</materialTypeID><materialTypeIcon>06_05</materialTypeIcon><materialTypeName>Construction Blocks</materialTypeName><materialVolume>1.5</materialVolume><quantity>1500</quantity></materialDtos><materialDtos><materialTypeCategoryID>4</materialTypeCategoryID><materialTypeID>11399</materialTypeID><materialTypeIcon>35_02</materialTypeIcon><materialTypeName>Morphite</materialTypeName><materialVolume>0.01</materialVolume><quantity>2500</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>21025</materialTypeID><materialTypeIcon>54_08</materialTypeIcon><materialTypeName>Capital Jump Drive</materialTypeName><materialVolume>10000.0</materialVolume><quantity>20</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29041</materialTypeID><materialTypeIcon>37_14</materialTypeIcon><materialTypeName>Capital Crystalline Carbonide Armor Plate</materialTypeName><materialVolume>10.0</materialVolume><quantity>1013</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29051</materialTypeID><materialTypeIcon>39_02</materialTypeIcon><materialTypeName>Capital Fusion Reactor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>518</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29061</materialTypeID><materialTypeIcon>37_02</materialTypeIcon><materialTypeName>Capital Ion Thruster</materialTypeName><materialVolume>10.0</materialVolume><quantity>422</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29069</materialTypeID><materialTypeIcon>37_06</materialTypeIcon><materialTypeName>Capital Magnetometric Sensor Cluster</materialTypeName><materialVolume>10.0</materialVolume><quantity>443</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29081</materialTypeID><materialTypeIcon>39_06</materialTypeIcon><materialTypeName>Capital Oscillator Capacitor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29085</materialTypeID><materialTypeIcon>37_10</materialTypeIcon><materialTypeName>Capital Photon Microprocessor</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29091</materialTypeID><materialTypeIcon>39_10</materialTypeIcon><materialTypeName>Capital Pulse Shield Emitter</materialTypeName><materialVolume>10.0</materialVolume><quantity>449</quantity></materialDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3409</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Metallurgy</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>140</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.6</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></materialProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3403</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Research</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>120</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.8</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></timeProductivityRequirementDtos></blueprintDetailsDto>")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/xml; charset=utf-8")); url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar%20Blueprint"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("{\"invBlueprintTypeDto\":{\"blueprintTypeID\":28849,\"blueprintTypeName\":\"Anshar Blueprint\",\"productTypeID\":28848,\"productTypeName\":\"Anshar\",\"productCategoryID\":6,\"parentBlueprintTypeID\":20188,\"parentBlueprintTypeName\":\"Obelisk Blueprint\",\"parentProductTypeID\":20187,\"parentProductTypeName\":\"Obelisk\",\"techLevel\":2,\"productionTime\":1920000,\"researchProductivityTime\":11520000,\"researchMaterialTime\":7680000,\"researchCopyTime\":2560000,\"researchTechTime\":3840000,\"productivityModifier\":384000,\"wasteFactor\":10,\"maxProductionLimit\":10,\"productVolume\":\"17550000\",\"productPortionSize\":1,\"dumpVersion\":\"cru16\"},\"materialDtos\":[{\"materialTypeID\":3828,\"materialTypeName\":\"Construction Blocks\",\"materialTypeCategoryID\":43,\"materialTypeIcon\":\"06_05\",\"materialVolume\":\"1.5\",\"quantity\":1500},{\"materialTypeID\":11399,\"materialTypeName\":\"Morphite\",\"materialTypeCategoryID\":4,\"materialTypeIcon\":\"35_02\",\"materialVolume\":\"0.01\",\"quantity\":2500},{\"materialTypeID\":21025,\"materialTypeName\":\"Capital Jump Drive\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"54_08\",\"materialVolume\":\"10000.0\",\"quantity\":20},{\"materialTypeID\":29041,\"materialTypeName\":\"Capital Crystalline Carbonide Armor Plate\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_14\",\"materialVolume\":\"10.0\",\"quantity\":1013},{\"materialTypeID\":29051,\"materialTypeName\":\"Capital Fusion Reactor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_02\",\"materialVolume\":\"10.0\",\"quantity\":518},{\"materialTypeID\":29061,\"materialTypeName\":\"Capital Ion Thruster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_02\",\"materialVolume\":\"10.0\",\"quantity\":422},{\"materialTypeID\":29069,\"materialTypeName\":\"Capital Magnetometric Sensor Cluster\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_06\",\"materialVolume\":\"10.0\",\"quantity\":443},{\"materialTypeID\":29081,\"materialTypeName\":\"Capital Oscillator Capacitor Unit\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_06\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29085,\"materialTypeName\":\"Capital Photon Microprocessor\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"37_10\",\"materialVolume\":\"10.0\",\"quantity\":704},{\"materialTypeID\":29091,\"materialTypeName\":\"Capital Pulse Shield Emitter\",\"materialTypeCategoryID\":17,\"materialTypeIcon\":\"39_10\",\"materialVolume\":\"10.0\",\"quantity\":449}],\"manufacturingRequirementDtos\":[{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":3380,\"requiredTypeName\":\"Industry\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":268,\"requiredTypeGroupName\":\"Industry\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":11478,\"requiredTypeName\":\"R.A.M.- Starship Tech\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_02\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":20187,\"requiredTypeName\":\"Obelisk\",\"requiredTypeCategoryID\":6,\"requiredTypeGroupID\":513,\"requiredTypeGroupName\":\"Freighter\",\"damagePerJob\":\"1.0\",\"quantity\":1,\"requiredTypeVolume\":\"17550000\"},{\"activityID\":1,\"activityName\":\"Manufacturing\",\"requiredTypeID\":22242,\"requiredTypeName\":\"Capital Ship Construction\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":269,\"requiredTypeGroupName\":\"Mechanic\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":4,\"requiredTypeVolume\":\"0.01\"}],\"timeProductivityRequirementDtos\":[{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3403,\"requiredTypeName\":\"Research\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":120,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":3,\"activityName\":\"Researching Time Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.8\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"materialProductivityRequirementDtos\":[{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3409,\"requiredTypeName\":\"Metallurgy\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":3814,\"requiredTypeName\":\"Reports\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":140,\"requiredTypeVolume\":\"0.1\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":9836,\"requiredTypeName\":\"Consumer Electronics\",\"requiredTypeCategoryID\":43,\"requiredTypeGroupID\":1034,\"requiredTypeGroupName\":\"Refined Commodities\",\"requiredTypeIcon\":\"24_08\",\"damagePerJob\":\"1.0\",\"quantity\":100,\"requiredTypeVolume\":\"1.5\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":4,\"activityName\":\"Researching Material Productivity\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.6\",\"quantity\":30,\"requiredTypeVolume\":\"4.0\"}],\"copyingRequirementDtos\":[{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":3812,\"requiredTypeName\":\"Data Sheets\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":280,\"requiredTypeGroupName\":\"General\",\"requiredTypeIcon\":\"10_16\",\"damagePerJob\":\"1.0\",\"quantity\":600,\"requiredTypeVolume\":\"1.0\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11450,\"requiredTypeName\":\"Gallentean Starship Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11452,\"requiredTypeName\":\"Mechanical Engineering\",\"requiredTypeCategoryID\":16,\"requiredTypeGroupID\":270,\"requiredTypeGroupName\":\"Science\",\"requiredTypeIcon\":\"50_11\",\"damagePerJob\":\"0.0\",\"quantity\":5,\"requiredTypeVolume\":\"0.01\"},{\"activityID\":5,\"activityName\":\"Copying\",\"requiredTypeID\":11466,\"requiredTypeName\":\"R.Db - CreoDron\",\"requiredTypeCategoryID\":17,\"requiredTypeGroupID\":332,\"requiredTypeGroupName\":\"Tool\",\"requiredTypeIcon\":\"41_01\",\"damagePerJob\":\"0.95\",\"quantity\":40,\"requiredTypeVolume\":\"4.0\"}],\"reverseEngineeringRequirementDtos\":[],\"inventionRequirementDtos\":[]}")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/json; charset=utf-8")); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(200)); assertThat(getResponse(connection), equalTo("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><blueprintDetailsDto><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>1.0</damagePerJob><quantity>600</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3812</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Data Sheets</requiredTypeName><requiredTypeVolume>1.0</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></copyingRequirementDtos><copyingRequirementDtos><activityID>5</activityID><activityName>Copying</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></copyingRequirementDtos><invBlueprintTypeDto><blueprintTypeID>28849</blueprintTypeID><blueprintTypeName>Anshar Blueprint</blueprintTypeName><dumpVersion>cru16</dumpVersion><maxProductionLimit>10</maxProductionLimit><parentBlueprintTypeID>20188</parentBlueprintTypeID><parentBlueprintTypeName>Obelisk Blueprint</parentBlueprintTypeName><parentProductTypeID>20187</parentProductTypeID><parentProductTypeName>Obelisk</parentProductTypeName><productCategoryID>6</productCategoryID><productPortionSize>1</productPortionSize><productTypeID>28848</productTypeID><productTypeName>Anshar</productTypeName><productVolume>17550000</productVolume><productionTime>1920000</productionTime><productivityModifier>384000</productivityModifier><researchCopyTime>2560000</researchCopyTime><researchMaterialTime>7680000</researchMaterialTime><researchProductivityTime>11520000</researchProductivityTime><researchTechTime>3840000</researchTechTime><techLevel>2</techLevel><wasteFactor>10</wasteFactor></invBlueprintTypeDto><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>268</requiredTypeGroupID><requiredTypeGroupName>Industry</requiredTypeGroupName><requiredTypeID>3380</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Industry</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.95</damagePerJob><quantity>40</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11478</requiredTypeID><requiredTypeIcon>41_02</requiredTypeIcon><requiredTypeName>R.A.M.- Starship Tech</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>1.0</damagePerJob><quantity>1</quantity><requiredTypeCategoryID>6</requiredTypeCategoryID><requiredTypeGroupID>513</requiredTypeGroupID><requiredTypeGroupName>Freighter</requiredTypeGroupName><requiredTypeID>20187</requiredTypeID><requiredTypeName>Obelisk</requiredTypeName><requiredTypeVolume>17550000</requiredTypeVolume></manufacturingRequirementDtos><manufacturingRequirementDtos><activityID>1</activityID><activityName>Manufacturing</activityName><damagePerJob>0.0</damagePerJob><quantity>4</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>269</requiredTypeGroupID><requiredTypeGroupName>Mechanic</requiredTypeGroupName><requiredTypeID>22242</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Capital Ship Construction</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></manufacturingRequirementDtos><materialDtos><materialTypeCategoryID>43</materialTypeCategoryID><materialTypeID>3828</materialTypeID><materialTypeIcon>06_05</materialTypeIcon><materialTypeName>Construction Blocks</materialTypeName><materialVolume>1.5</materialVolume><quantity>1500</quantity></materialDtos><materialDtos><materialTypeCategoryID>4</materialTypeCategoryID><materialTypeID>11399</materialTypeID><materialTypeIcon>35_02</materialTypeIcon><materialTypeName>Morphite</materialTypeName><materialVolume>0.01</materialVolume><quantity>2500</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>21025</materialTypeID><materialTypeIcon>54_08</materialTypeIcon><materialTypeName>Capital Jump Drive</materialTypeName><materialVolume>10000.0</materialVolume><quantity>20</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29041</materialTypeID><materialTypeIcon>37_14</materialTypeIcon><materialTypeName>Capital Crystalline Carbonide Armor Plate</materialTypeName><materialVolume>10.0</materialVolume><quantity>1013</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29051</materialTypeID><materialTypeIcon>39_02</materialTypeIcon><materialTypeName>Capital Fusion Reactor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>518</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29061</materialTypeID><materialTypeIcon>37_02</materialTypeIcon><materialTypeName>Capital Ion Thruster</materialTypeName><materialVolume>10.0</materialVolume><quantity>422</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29069</materialTypeID><materialTypeIcon>37_06</materialTypeIcon><materialTypeName>Capital Magnetometric Sensor Cluster</materialTypeName><materialVolume>10.0</materialVolume><quantity>443</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29081</materialTypeID><materialTypeIcon>39_06</materialTypeIcon><materialTypeName>Capital Oscillator Capacitor Unit</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29085</materialTypeID><materialTypeIcon>37_10</materialTypeIcon><materialTypeName>Capital Photon Microprocessor</materialTypeName><materialVolume>10.0</materialVolume><quantity>704</quantity></materialDtos><materialDtos><materialTypeCategoryID>17</materialTypeCategoryID><materialTypeID>29091</materialTypeID><materialTypeIcon>39_10</materialTypeIcon><materialTypeName>Capital Pulse Shield Emitter</materialTypeName><materialVolume>10.0</materialVolume><quantity>449</quantity></materialDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3409</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Metallurgy</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>140</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></materialProductivityRequirementDtos><materialProductivityRequirementDtos><activityID>4</activityID><activityName>Researching Material Productivity</activityName><damagePerJob>0.6</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></materialProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>3403</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Research</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>120</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>280</requiredTypeGroupID><requiredTypeGroupName>General</requiredTypeGroupName><requiredTypeID>3814</requiredTypeID><requiredTypeIcon>10_16</requiredTypeIcon><requiredTypeName>Reports</requiredTypeName><requiredTypeVolume>0.1</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>1.0</damagePerJob><quantity>100</quantity><requiredTypeCategoryID>43</requiredTypeCategoryID><requiredTypeGroupID>1034</requiredTypeGroupID><requiredTypeGroupName>Refined Commodities</requiredTypeGroupName><requiredTypeID>9836</requiredTypeID><requiredTypeIcon>24_08</requiredTypeIcon><requiredTypeName>Consumer Electronics</requiredTypeName><requiredTypeVolume>1.5</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11450</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Gallentean Starship Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.0</damagePerJob><quantity>5</quantity><requiredTypeCategoryID>16</requiredTypeCategoryID><requiredTypeGroupID>270</requiredTypeGroupID><requiredTypeGroupName>Science</requiredTypeGroupName><requiredTypeID>11452</requiredTypeID><requiredTypeIcon>50_11</requiredTypeIcon><requiredTypeName>Mechanical Engineering</requiredTypeName><requiredTypeVolume>0.01</requiredTypeVolume></timeProductivityRequirementDtos><timeProductivityRequirementDtos><activityID>3</activityID><activityName>Researching Time Productivity</activityName><damagePerJob>0.8</damagePerJob><quantity>30</quantity><requiredTypeCategoryID>17</requiredTypeCategoryID><requiredTypeGroupID>332</requiredTypeGroupID><requiredTypeGroupName>Tool</requiredTypeGroupName><requiredTypeID>11466</requiredTypeID><requiredTypeIcon>41_01</requiredTypeIcon><requiredTypeName>R.Db - CreoDron</requiredTypeName><requiredTypeVolume>4.0</requiredTypeVolume></timeProductivityRequirementDtos></blueprintDetailsDto>")); assertThat(connection.getHeaderField("Content-Type"), equalTo("application/xml; charset=utf-8")); url = new URL(baseUrl + "/blueprintDetailsForTypeName/Anshar Blueprint"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
11
Code Sample 1: public String control(final String allOptions) throws SQLException { connect(); final Statement stmt = connection.createStatement(); final ResultSet rst1 = stmt.executeQuery("SELECT versionId FROM versions WHERE version='" + Concrete.version() + "'"); final long versionId; if (rst1.next()) { versionId = rst1.getInt(1); } else { disconnect(); return ""; } rst1.close(); final MessageDigest msgDigest; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e1) { logger.throwing(SQLExecutionController.class.getSimpleName(), "control", e1); disconnect(); return ""; } msgDigest.update(allOptions.getBytes()); final ResultSet rst2 = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + Concrete.md5(msgDigest.digest()) + "'"); final long configId; if (rst2.next()) { configId = rst2.getInt(1); } else { disconnect(); return ""; } rst2.close(); final ResultSet rst4 = stmt.executeQuery("SELECT problems.md5 FROM executions " + "LEFT JOIN problems ON executions.problemId = problems.problemId WHERE " + "configId=" + configId + " AND versionId=" + versionId); final StringBuilder stb = new StringBuilder(); while (rst4.next()) { stb.append(rst4.getString(1)).append('\n'); } rst4.close(); stmt.close(); return stb.toString(); } Code Sample 2: public String getMD5(String data) { try { MessageDigest md5Algorithm = MessageDigest.getInstance("MD5"); md5Algorithm.update(data.getBytes(), 0, data.length()); byte[] digest = md5Algorithm.digest(); StringBuffer hexString = new StringBuffer(); String hexDigit = null; for (int i = 0; i < digest.length; i++) { hexDigit = Integer.toHexString(0xFF & digest[i]); if (hexDigit.length() < 2) { hexDigit = "0" + hexDigit; } hexString.append(hexDigit); } return hexString.toString(); } catch (NoSuchAlgorithmException ne) { return data; } }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static String crypt(String target) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(target.getBytes("UTF-16")); BigInteger res = new BigInteger(1, md.digest(key.getBytes())); return res.toString(16); }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void decompress(File apps,File f) throws IOException{ String filename=f.getName(); filename=filename.substring(0,filename.length()-PACK_FILE_SUFFIX.length()); File dir=new File(apps,filename); if(!dir.exists()){ dir.mkdirs(); } if(dir.isDirectory()){ JarFile jar=new JarFile(f); Enumeration<JarEntry> files=jar.entries(); while(files.hasMoreElements()){ JarEntry je=files.nextElement(); if(je.isDirectory()){ File item=new File(dir,je.getName()); item.mkdirs(); }else{ File item=new File(dir,je.getName()); item.getParentFile().mkdirs(); InputStream input=jar.getInputStream(je); FileOutputStream out=new FileOutputStream(item); IOUtils.copy(input, out); input.close(); out.close(); } //System.out.println(je.isDirectory() + je.getName()); } } }
00
Code Sample 1: public static void addProviders(URL url) { Reader reader = null; Properties prop = new Properties(); try { reader = new InputStreamReader(url.openStream()); prop.load(reader); } catch (Throwable t) { } finally { if (reader != null) { try { reader.close(); } catch (Throwable t) { } } } for (Map.Entry<Object, Object> entry : prop.entrySet()) { try { Class<?> cla = Class.forName((String) entry.getValue(), true, Thread.currentThread().getContextClassLoader()); providers.put(((String) entry.getKey()).toUpperCase(), (CharsetProvider) cla.newInstance()); } catch (Throwable t) { } } } Code Sample 2: public static String post(String strUrl, String strPostString) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(true); conn.setAllowUserInteraction(true); conn.setFollowRedirects(true); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(strPostString); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += s; } in.close(); return sRet; } catch (MalformedURLException e) { System.out.println("Internal Error. Malformed URL."); e.printStackTrace(); } catch (IOException e) { System.out.println("Internal I/O Error."); e.printStackTrace(); } return ""; }
11
Code Sample 1: public void handleRequestInternal(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws ServletException, IOException { final String servetPath = httpServletRequest.getServletPath(); final String previousToken = httpServletRequest.getHeader(IF_NONE_MATCH); final String currentToken = getETagValue(httpServletRequest); httpServletResponse.setHeader(ETAG, currentToken); final Date modifiedDate = new Date(httpServletRequest.getDateHeader(IF_MODIFIED_SINCE)); final Calendar calendar = Calendar.getInstance(); final Date now = calendar.getTime(); calendar.setTime(modifiedDate); calendar.add(Calendar.MINUTE, getEtagExpiration()); if (currentToken.equals(previousToken) && (now.getTime() < calendar.getTime().getTime())) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_MODIFIED); httpServletResponse.setHeader(LAST_MODIFIED, httpServletRequest.getHeader(IF_MODIFIED_SINCE)); if (LOG.isDebugEnabled()) { LOG.debug("ETag the same, will return 304"); } } else { httpServletResponse.setDateHeader(LAST_MODIFIED, (new Date()).getTime()); final String width = httpServletRequest.getParameter(Constants.WIDTH); final String height = httpServletRequest.getParameter(Constants.HEIGHT); final ImageNameStrategy imageNameStrategy = imageService.getImageNameStrategy(servetPath); String code = imageNameStrategy.getCode(servetPath); String fileName = imageNameStrategy.getFileName(servetPath); final String imageRealPathPrefix = getRealPathPrefix(httpServletRequest.getServerName().toLowerCase()); String original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); final File origFile = new File(original); if (!origFile.exists()) { code = Constants.NO_IMAGE; fileName = imageNameStrategy.getFileName(code); original = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code); } String resizedImageFileName = null; if (width != null && height != null && imageService.isSizeAllowed(width, height)) { resizedImageFileName = imageRealPathPrefix + imageNameStrategy.getFullFileNamePath(fileName, code, width, height); } final File imageFile = getImageFile(original, resizedImageFileName, width, height); final FileInputStream fileInputStream = new FileInputStream(imageFile); IOUtils.copy(fileInputStream, httpServletResponse.getOutputStream()); fileInputStream.close(); } } Code Sample 2: public static void main(String[] args) throws Exception { String uri = args[0]; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } }
11
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: public void process(String src, String dest) { try { KanjiDAO kanjiDAO = KanjiDAOFactory.getDAO(); MorphologicalAnalyzer mecab = MorphologicalAnalyzer.getInstance(); if (mecab.isActive()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), "UTF8")); String line; bw.write("// // // \r\n$title=\r\n$singer=\r\n$id=\r\n\r\n + _______ // 0 0 0 0 0 0 0\r\n\r\n"); while ((line = br.readLine()) != null) { System.out.println(line); String segment[] = line.split("//"); String japanese = null; String english = null; if (segment.length > 1) english = segment[1].trim(); if (segment.length > 0) japanese = segment[0].trim().replaceAll(" ", "_"); boolean first = true; if (japanese != null) { ArrayList<ExtractedWord> wordList = mecab.extractWord(japanese); Iterator<ExtractedWord> iter = wordList.iterator(); while (iter.hasNext()) { ExtractedWord word = iter.next(); if (first) { first = false; bw.write("*"); } else bw.write(" "); if (word.isParticle) bw.write("- "); else bw.write("+ "); if (!word.original.equals(word.reading)) { System.out.println("--> " + JapaneseString.toRomaji(word.original) + " / " + JapaneseString.toRomaji(word.reading)); KReading[] kr = ReadingAnalyzer.analyzeReadingStub(word.original, word.reading, kanjiDAO); if (kr != null) { for (int i = 0; i < kr.length; i++) { if (i > 0) bw.write(" "); bw.write(kr[i].kanji); if (kr[i].type != KReading.KANA) { bw.write("|"); bw.write(kr[i].reading); } } } else { bw.write(word.original); bw.write("|"); bw.write(word.reading); } } else { bw.write(word.original); } bw.write(" // \r\n"); } if (english != null) { bw.write(english); bw.write("\r\n"); } bw.write("\r\n"); } } br.close(); bw.close(); } else { System.out.println("Mecab couldn't be initialized"); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static Board readStream(InputStream is) throws IOException { StringWriter stringWriter = new StringWriter(); IOUtils.copy(is, stringWriter); String s = stringWriter.getBuffer().toString(); Board board = read(s); return board; } 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: 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; } Code Sample 2: public 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: public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("LOAD")) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JPEGFilter()); chooser.setMultiSelectionEnabled(false); if (chooser.showOpenDialog(getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(file)); ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length()); int read = is.read(); while (read != -1) { bos.write(read); read = is.read(); } is.close(); _changed = true; setImage(bos.toByteArray()); } catch (Exception e1) { _log.error("actionPerformed(ActionEvent)", e1); } } } else if (e.getActionCommand().equals("SAVE")) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new JPEGFilter()); chooser.setMultiSelectionEnabled(false); if (_data != null && chooser.showSaveDialog(getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) { try { File file = chooser.getSelectedFile(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); os.write(_data); os.flush(); os.close(); } catch (Exception e1) { _log.error("actionPerformed(ActionEvent)", e1); } } } else if (e.getActionCommand().equals("DELETE")) { if (_data != null) { int result = JOptionPane.showConfirmDialog(getTopLevelAncestor(), GuiStrings.getString("message.removeimg"), GuiStrings.getString("title.confirm"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { removeImage(); _changed = true; } } } } Code Sample 2: private void makeDailyBackup() throws CacheOperationException, ConfigurationException { final int MAX_DAILY_BACKUPS = 5; File cacheFolder = getBackupFolder(); cacheLog.debug("Making a daily backup of current Beehive archive..."); try { File oldestDaily = new File(DAILY_BACKUP_PREFIX + "." + MAX_DAILY_BACKUPS); if (oldestDaily.exists()) { moveToWeeklyBackup(oldestDaily); } for (int index = MAX_DAILY_BACKUPS - 1; index > 0; index--) { File daily = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + index); File target = new File(cacheFolder, DAILY_BACKUP_PREFIX + "." + (index + 1)); if (!daily.exists()) { cacheLog.debug("Daily backup file ''{0}'' was not present. Skipping...", daily.getAbsolutePath()); continue; } if (!daily.renameTo(target)) { sortBackups(); throw new CacheOperationException("There was an error moving ''{0}'' to ''{1}''.", daily.getAbsolutePath(), target.getAbsolutePath()); } else { cacheLog.debug("Moved " + daily.getAbsolutePath() + " to " + target.getAbsolutePath()); } } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied read/write access to daily backup files in ''{0}'' : {1}" + e, cacheFolder.getAbsolutePath(), e.getMessage()); } File beehiveArchive = getCachedArchive(); File tempBackupArchive = new File(cacheFolder, BEEHIVE_ARCHIVE_NAME + ".tmp"); BufferedInputStream archiveReader = null; BufferedOutputStream tempBackupWriter = null; try { archiveReader = new BufferedInputStream(new FileInputStream(beehiveArchive)); tempBackupWriter = new BufferedOutputStream(new FileOutputStream(tempBackupArchive)); int len, bytecount = 0; final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; while ((len = archiveReader.read(buffer, 0, BUFFER_SIZE)) != -1) { tempBackupWriter.write(buffer, 0, len); bytecount += len; } tempBackupWriter.flush(); long originalFileSize = beehiveArchive.length(); if (originalFileSize != bytecount) { throw new CacheOperationException("Original archive size was {0} bytes but only {1} were copied.", originalFileSize, bytecount); } cacheLog.debug("Finished copying ''{0}'' to ''{1}''.", beehiveArchive.getAbsolutePath(), tempBackupArchive.getAbsolutePath()); } catch (FileNotFoundException e) { throw new CacheOperationException("Files required for copying a backup of Beehive archive could not be found, opened " + "or created : {1}", e, e.getMessage()); } catch (IOException e) { throw new CacheOperationException("Error while making a copy of the Beehive archive : {0}", e, e.getMessage()); } finally { if (archiveReader != null) { try { archiveReader.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, beehiveArchive.getAbsolutePath(), t.getMessage()); } } if (tempBackupWriter != null) { try { tempBackupWriter.close(); } catch (Throwable t) { cacheLog.warn("Failed to close stream to ''{0}'' : {1}", t, tempBackupArchive.getAbsolutePath(), t.getMessage()); } } } validateArchive(tempBackupArchive); File newestDaily = getNewestDailyBackupFile(); try { if (!tempBackupArchive.renameTo(newestDaily)) { throw new CacheOperationException("Error moving ''{0}'' to ''{1}''.", tempBackupArchive.getAbsolutePath(), newestDaily.getAbsolutePath()); } else { cacheLog.info("Backup complete. Saved in ''{0}''", newestDaily.getAbsolutePath()); } } catch (SecurityException e) { throw new ConfigurationException("Security Manager has denied write access to ''{0}'' : {1}", e, newestDaily.getAbsolutePath(), e.getMessage()); } }
00
Code Sample 1: private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } Code Sample 2: private void sendToServer(String fichaID, String respostas) throws FileNotFoundException, ParserConfigurationException, SAXException, IOException, URISyntaxException { ArrayList params = new ArrayList(); params.add(new BasicNameValuePair("xml", respostas)); params.add(new BasicNameValuePair("idForm", fichaID)); URI uri = URIUtils.createURI("http", "172.20.9.144", 8080, "/PSFServer/SaveAnswers", URLEncodedUtils.format(params, "UTF-8"), null); HttpPost request = new HttpPost(uri); request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpClient client = new DefaultHttpClient(); HttpResponse httpResponse = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String resposta = sb.toString(); if (resposta != null || resposta != "") { new DatabaseManager(this).getWritableDatabase().execSQL("delete from " + DatabaseManager.getTableDados()); } backToMain(); }
00
Code Sample 1: public List<String[]> getCSV(String name) { return new ResourceLoader<List<String[]>>(name) { @Override protected List<String[]> get(URL url) throws Exception { CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(url.openStream())); return reader.readAll(); } finally { IOUtils.closeQuietly(reader); } } }.get(); } Code Sample 2: public InputSource resolveEntity(String pPublicId, String pSystemId) throws SAXException, IOException { getCisUtils().debug("Resolving entity publicId=" + pPublicId + ", systemId=" + pSystemId); final String res; if ("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN".equals(pPublicId)) { res = "resources/web-app_2_3.dtd"; } else { return null; } URL url = getClass().getResource(res); if (url == null) { throw new SAXException("Failed to locate resource: " + res); } InputSource isource = new InputSource(url.openStream()); isource.setSystemId(url.toExternalForm()); return isource; }
00
Code Sample 1: public static String md5(String str) { if (str == null) { System.err.println("Stringx.md5 (String) : null string."); return ""; } String rt = ""; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(str.getBytes("gb2312")); byte[] bt = md5.digest(); String s = null; int l = 0; for (int i = 0; i < bt.length; i++) { s = Integer.toHexString(bt[i]); l = s.length(); if (l > 2) s = s.substring(l - 2, l); else if (l == 1) s = "0" + s; rt += s; } } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return rt; } Code Sample 2: protected File downloadUpdate(String resource) throws AgentException { RESTCall call = makeRESTCall(resource); call.invoke(); File tmpFile; try { tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath)); } catch (IOException e) { throw new AgentException("Failed to create temporary file", e); } InputStream is; try { is = call.getInputStream(); } catch (IOException e) { throw new AgentException("Failed to open input stream", e); } try { FileOutputStream os; try { os = new FileOutputStream(tmpFile); } catch (FileNotFoundException e) { throw new AgentException("Failed to open temporary file for writing", e); } boolean success = false; try { IOUtils.copy(is, os); success = true; } catch (IOException e) { throw new AgentException("Failed to download update", e); } finally { try { os.flush(); os.close(); } catch (IOException e) { if (!success) throw new AgentException("Failed to flush to disk", e); } } } finally { try { is.close(); } catch (IOException e) { log.error("Failed to close input stream", e); } call.disconnect(); } return tmpFile; }
00
Code Sample 1: public void xtest12() throws Exception { PDFManager manager = new ITextManager(); InputStream pdf = new FileInputStream("/tmp/090237098008f637.pdf"); InputStream page1 = manager.cut(pdf, 36, 36); OutputStream outputStream = new FileOutputStream("/tmp/090237098008f637-1.pdf"); IOUtils.copy(page1, outputStream); outputStream.close(); pdf.close(); } Code Sample 2: private ScrollingGraphicalViewer createGraphicalViewer(final Composite parent) { final ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); _root = new ScalableRootEditPart(); viewer.setRootEditPart(_root); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getEditorInput().getAdapter(ScannedMap.class)); return viewer; }
00
Code Sample 1: public boolean ponerRivalxRonda(int idJugadorDiv, int idRonda, int dato) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = " + dato + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; 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 final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: public static String getRolesString(HttpServletRequest hrequest, HttpServletResponse hresponse, String username, String servicekey) { String registerapp = SSOFilter.getRegisterapp(); String u = SSOUtil.addParameter(registerapp + "/api/getroles", "username", username); u = SSOUtil.addParameter(u, "servicekey", servicekey); String roles = ""; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { roles = line.trim(); } reader.close(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } if ("error".equals(roles)) { return ""; } return roles.trim(); } Code Sample 2: protected String getLibJSCode() throws IOException { if (cachedLibJSCode == null) { InputStream is = getClass().getResourceAsStream(JS_LIB_FILE); StringWriter output = new StringWriter(); IOUtils.copy(is, output); cachedLibJSCode = output.toString(); } return cachedLibJSCode; }
11
Code Sample 1: private ChangeCapsule fetchServer(OWLOntology ontologyURI, Long sequenceNumber) throws IOException { String requestString = "http://" + InetAddress.getLocalHost().getHostName() + ":8080/ChangeServer"; requestString += "?fetch=" + URLEncoder.encode(ontologyURI.getURI().toString(), "UTF-8"); requestString += "&number" + sequenceNumber; URL url = new URL(requestString); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer returned = new StringBuffer(); String str; while (null != ((str = input.readLine()))) { returned.append(str); } input.close(); ChangeCapsule cp = new ChangeCapsule(returned.toString()); return cp; } Code Sample 2: private void initialize() { StringBuffer license = new StringBuffer(); URL url; InputStreamReader in; BufferedReader reader; String str; JTextArea textArea; JButton button; GridBagConstraints c; setTitle("mibible License"); setSize(600, 600); setDefaultCloseOperation(DISPOSE_ON_CLOSE); getContentPane().setLayout(new GridBagLayout()); url = getClass().getClassLoader().getResource("LICENSE.txt"); if (url == null) { license.append("Couldn't locate license file (LICENSE.txt)."); } else { try { in = new InputStreamReader(url.openStream()); reader = new BufferedReader(in); while ((str = reader.readLine()) != null) { if (!str.equals(" ")) { license.append(str); } license.append("\n"); } reader.close(); } catch (IOException e) { license.append("Error reading license file "); license.append("(LICENSE.txt):\n\n"); license.append(e.getMessage()); } } textArea = new JTextArea(license.toString()); textArea.setEditable(false); c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0d; c.weighty = 1.0d; c.insets = new Insets(4, 5, 4, 5); getContentPane().add(new JScrollPane(textArea), c); button = new JButton("Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); c = new GridBagConstraints(); c.gridy = 1; c.anchor = GridBagConstraints.CENTER; c.insets = new Insets(10, 10, 10, 10); getContentPane().add(button, c); }
00
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: public void testConnectionManagerGC() throws Exception { ThreadSafeClientConnManager mgr = createTSCCM(null, 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); EntityUtils.toByteArray(response.getEntity()); conn.markReusable(); mgr.releaseConnection(conn, -1, null); WeakReference<ThreadSafeClientConnManager> wref = new WeakReference<ThreadSafeClientConnManager>(mgr); mgr = null; System.gc(); Thread.sleep(1000); assertNull("TSCCM not garbage collected", wref.get()); }
11
Code Sample 1: public void onUpload$btnFileUpload(UploadEvent ue) { BufferedInputStream in = null; BufferedOutputStream out = null; if (ue == null) { System.out.println("unable to upload file"); return; } else { System.out.println("fileUploaded()"); } try { Media m = ue.getMedia(); System.out.println("m.getContentType(): " + m.getContentType()); System.out.println("m.getFormat(): " + m.getFormat()); try { InputStream is = m.getStreamData(); in = new BufferedInputStream(is); File baseDir = new File(UPLOAD_PATH); if (!baseDir.exists()) { baseDir.mkdirs(); } final File file = new File(UPLOAD_PATH + m.getName()); OutputStream fout = new FileOutputStream(file); out = new BufferedOutputStream(fout); IOUtils.copy(in, out); if (m.getFormat().equals("zip") || m.getFormat().equals("x-gzip")) { final String filename = m.getName(); Messagebox.show("Archive file detected. Would you like to unzip this file?", "ALA Spatial Portal", Messagebox.YES + Messagebox.NO, Messagebox.QUESTION, new EventListener() { @Override public void onEvent(Event event) throws Exception { try { int response = ((Integer) event.getData()).intValue(); if (response == Messagebox.YES) { System.out.println("unzipping file to: " + UPLOAD_PATH); boolean success = Zipper.unzipFile(filename, new FileInputStream(file), UPLOAD_PATH, false); if (success) { Messagebox.show("File unzipped: '" + filename + "'"); } else { Messagebox.show("Unable to unzip '" + filename + "' "); } } else { System.out.println("leaving archive file alone"); } } catch (NumberFormatException nfe) { System.out.println("Not a valid response"); } } }); } else { Messagebox.show("File '" + m.getName() + "' successfully uploaded"); } } catch (IOException e) { System.out.println("IO Exception while saving file: "); e.printStackTrace(System.out); } catch (Exception e) { System.out.println("General Exception: "); e.printStackTrace(System.out); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException e) { System.out.println("IO Exception while closing stream: "); e.printStackTrace(System.out); } } } catch (Exception e) { System.out.println("Error uploading file."); e.printStackTrace(System.out); } } Code Sample 2: private static void copy(File source, File target) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: public Certificate(URL url) throws CertificateException { try { URLConnection con = url.openConnection(); InputStream in2 = con.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(in2)); String inputLine; StringBuffer cert = new StringBuffer(); while ((inputLine = in.readLine()) != null) { cert.append(inputLine); cert.append("\n"); } in.close(); this.certificate = cert.toString(); } catch (IOException ex) { throw new CertificateException("Unable to read in credential: " + ex.getMessage(), ex); } loadCredential(this.certificate); } Code Sample 2: private static LaunchablePlugin[] findLaunchablePlugins(LoggerChannelListener listener) { List res = new ArrayList(); File app_dir = getApplicationFile("plugins"); if (!(app_dir.exists()) && app_dir.isDirectory()) { listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' not found"); return (new LaunchablePlugin[0]); } File[] plugins = app_dir.listFiles(); if (plugins == null || plugins.length == 0) { listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' empty"); return (new LaunchablePlugin[0]); } for (int i = 0; i < plugins.length; i++) { File plugin_dir = plugins[i]; if (!plugin_dir.isDirectory()) { continue; } try { ClassLoader classLoader = PluginLauncherImpl.class.getClassLoader(); ClassLoader root_cl = classLoader; File[] contents = plugin_dir.listFiles(); if (contents == null || contents.length == 0) { continue; } String[] plugin_version = { null }; String[] plugin_id = { null }; contents = getHighestJarVersions(contents, plugin_version, plugin_id, true); for (int j = 0; j < contents.length; j++) { classLoader = addFileToClassPath(root_cl, classLoader, contents[j]); } Properties props = new Properties(); File properties_file = new File(plugin_dir, "plugin.properties"); if (properties_file.exists()) { FileInputStream fis = null; try { fis = new FileInputStream(properties_file); props.load(fis); } finally { if (fis != null) { fis.close(); } } } else { if (classLoader instanceof URLClassLoader) { URLClassLoader current = (URLClassLoader) classLoader; URL url = current.findResource("plugin.properties"); if (url != null) { props.load(url.openStream()); } } } String plugin_class = (String) props.get("plugin.class"); if (plugin_class == null || plugin_class.indexOf(';') != -1) { continue; } Class c = classLoader.loadClass(plugin_class); Plugin plugin = (Plugin) c.newInstance(); if (plugin instanceof LaunchablePlugin) { preloaded_plugins.put(plugin_class, plugin); res.add(plugin); } } catch (Throwable e) { listener.messageLogged("Load of plugin in '" + plugin_dir + "' fails", e); } } LaunchablePlugin[] x = new LaunchablePlugin[res.size()]; res.toArray(x); return (x); }
11
Code Sample 1: public static void copyFile(File source, File dest) throws Exception { log.warn("File names are " + source.toString() + " and " + dest.toString()); if (!dest.getParentFile().exists()) dest.getParentFile().mkdir(); FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel destinationChannel = new FileOutputStream(dest).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: private static void backupFile(File file) { FileChannel in = null, out = null; try { if (!file.getName().endsWith(".bak")) { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } } catch (Exception e) { e.getMessage(); } finally { try { System.gc(); if (in != null) in.close(); if (out != null) out.close(); } catch (Exception e) { e.getMessage(); } } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public static String getHash(String uri) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(uri.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); } 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: public String encryptPassword(String password) { StringBuffer encPasswd = new StringBuffer(); try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } return encPasswd.toString(); } Code Sample 2: public String gerarHash(String frase) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(frase.getBytes()); byte[] bytes = md.digest(); StringBuilder s = new StringBuilder(0); for (int i = 0; i < bytes.length; i++) { int parteAlta = ((bytes[i] >> 4) & 0xf) << 4; int parteBaixa = bytes[i] & 0xf; if (parteAlta == 0) { s.append('0'); } s.append(Integer.toHexString(parteAlta | parteBaixa)); } return s.toString(); } catch (NoSuchAlgorithmException e) { return null; } }
00
Code Sample 1: public static boolean encodeFileToFile(final String infile, final 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)); final byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (final java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (final Exception exc) { } try { out.close(); } catch (final Exception exc) { } } return success; } Code Sample 2: public static byte[] generateHash(String strPassword, byte[] salt) { try { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(strPassword.getBytes(CHAR_ENCODING)); md.update(salt); return md.digest(); } catch (Exception e) { e.printStackTrace(); } return null; }
11
Code Sample 1: public static final void copyFile(String srcFilename, String dstFilename) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel ifc = null; FileChannel ofc = null; Util.copyBuffer.clear(); try { fis = new FileInputStream(srcFilename); ifc = fis.getChannel(); fos = new FileOutputStream(dstFilename); ofc = fos.getChannel(); int sz = (int) ifc.size(); int n = 0; while (n < sz) { if (ifc.read(Util.copyBuffer) < 0) { break; } Util.copyBuffer.flip(); n += ofc.write(Util.copyBuffer); Util.copyBuffer.compact(); } } finally { try { if (ifc != null) { ifc.close(); } else if (fis != null) { fis.close(); } } catch (IOException exc) { } try { if (ofc != null) { ofc.close(); } else if (fos != null) { fos.close(); } } catch (IOException exc) { } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, out); writer.setPdfVersion(PdfWriter.VERSION_1_3); writer.setFullCompression(); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STRENGTH128BITS, password, null, securityType); } final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } else if (base_url != null) { document.addTitle(base_url); } final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } else { document.addCreator(IHtmlToPdfTransformer.VERSION); } final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.addProducer(sproducer); } else { document.addProducer(IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer); } document.open(); } PdfImportedPage page; for (int j = 0; j < n; ) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } } document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext(); ) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i).replaceAll("<pagecount>", "" + n); final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } else { reader = new PdfReader(tmp2.getAbsolutePath()); } final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STRENGTH128BITS, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } if (reason != null) { sap.setReason(reason); } if (location != null) { sap.setLocation(location); } stp.close(); oldOut.flush(); } } catch (final Exception e) { throw new CConvertException("ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } finally { try { tmp.delete(); } catch (final Exception ignore) { } try { tmp2.delete(); } catch (final Exception ignore) { } } } Code Sample 2: public void run() { try { textUpdater.start(); int cnt; byte[] buf = new byte[4096]; File file = null; ZipInputStream zis = new ZipInputStream(new FileInputStream(new File(filename))); ZipEntry ze = zis.getNextEntry(); FileOutputStream fos; while (ze != null) { if (ze.isDirectory()) { file = new File(ze.getName()); if (!file.exists()) { textUpdater.appendText("Creating directory: " + ze.getName() + "\n"); file.mkdirs(); } } else { textUpdater.appendText("Extracting file: " + ze.getName() + "\n"); fos = new FileOutputStream(dstdir + File.separator + ze.getName()); while ((cnt = zis.read(buf, 0, buf.length)) != -1) fos.write(buf, 0, cnt); fos.close(); } zis.closeEntry(); ze = zis.getNextEntry(); } zis.close(); if (complete != null) textUpdater.appendText(complete + "\n"); } catch (Exception e) { e.printStackTrace(); } textUpdater.setFinished(true); }
00
Code Sample 1: private void parseUrl() { URLLexer lexer; URLParser parser; if (this.parent != null) { this.hops = ((HTTPFile) this.parent).hops - 1; } if (this.searchFilter.accept(this.url.getPath())) { if (!visited.contains(this.url.toExternalForm())) { if (this.hops > 0) { try { visited.add(this.url.toExternalForm()); InputStream in = this.url.openStream(); lexer = new URLLexer(this.url.openStream()); parser = new URLParser(lexer); URL[] urls = parser.htmlDocument(this.url); if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Found the following URLs in " + this.url.toExternalForm() + " : " + StringUtil.ArrayToString(urls, 10)); } for (int i = 0; i < urls.length; i++) { this.addInternal(urls[i]); } } catch (IOException e) { if (Debug.debug) { Debug.getInstance().error(e.getMessage()); } } catch (RecognitionException e) { if (Debug.debug) { Debug.getInstance().error("Problems while lexing " + this.url.toExternalForm() + " : " + e.getMessage(), e); } } catch (TokenStreamException e) { if (Debug.debug) { Debug.getInstance().error("Problems while parsing " + this.url.toExternalForm() + " : " + e.getMessage(), e); } } } } else { if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Skipping URL " + this.url.toExternalForm() + " : Maximum depth reached."); } } } else { if (Debug.debug) { Debug.getInstance().info(this.getClass().getName() + ".parseUrl(): Skipping URL " + this.url.toExternalForm() + " : Already parsed."); } } } Code Sample 2: private void initialize() { if (!initialized) { if (context.getJavadocLinks() != null) { for (String url : context.getJavadocLinks()) { if (!url.endsWith("/")) { url += "/"; } StringWriter writer = new StringWriter(); try { IOUtils.copy(new URL(url + "package-list").openStream(), writer); } catch (Exception e) { e.printStackTrace(); continue; } StringTokenizer tokenizer2 = new StringTokenizer(writer.toString()); while (tokenizer2.hasMoreTokens()) { javadocByPackage.put(tokenizer2.nextToken(), url); } } } initialized = true; } }
11
Code Sample 1: private void processOrder() { double neg = 0d; if (intMode == MODE_CHECKOUT) { if (round2Places(mBuf.getBufferTotal()) >= round2Places(order.getOrderTotal())) { double cash, credit, allowedCredit = 0d; allowedCredit = getStudentCredit(); if (settings.get(DBSettings.MAIN_ALLOWNEGBALANCES).compareTo("1") == 0) { try { neg = Double.parseDouble(settings.get(DBSettings.MAIN_MAXNEGBALANCE)); } catch (NumberFormatException ex) { System.err.println("NumberFormatException::Potential problem with setting MAIN_MAXNEGBALANCE"); System.err.println(" * Note: If you enable negative balances, please don't leave this"); System.err.println(" blank. At least set it to 0. For right now we are setting "); System.err.println(" the max negative balance to $0.00"); System.err.println(""); System.err.println("Exception Message:" + ex.getMessage()); } if (neg < 0) neg *= -1; allowedCredit += neg; } if (round2Places(mBuf.getCredit()) <= round2Places(allowedCredit)) { if (round2Places(mBuf.getCredit()) > round2Places(getStudentCredit()) && !student.isStudentSet()) { gui.setStatus("Can't allow negative balance on an anonymous student!", true); } else { if (round2Places(mBuf.getCredit()) > round2Places(order.getOrderTotal())) { credit = round2Places(order.getOrderTotal()); } else { credit = round2Places(mBuf.getCredit()); } if ((mBuf.getCash() + credit) >= order.getOrderTotal()) { cash = round2Places(order.getOrderTotal() - credit); double change = round2Places(mBuf.getCash() - cash); if (round2Places(cash + credit) == round2Places(order.getOrderTotal())) { Connection conn = null; Statement stmt = null; ResultSet rs = null; 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(); String strSql = "insert into " + strPOSPrefix + "trans_master ( tm_studentid, tm_total, tm_cashtotal, tm_credittotal, tm_building, tm_register, tm_cashier, tm_datetime, tm_change ) values( '" + stuId + "', '" + round2Places(order.getOrderTotal()) + "', '" + round2Places(cash) + "', '" + round2Places(credit) + "', '" + building + "', '" + host + "', '" + cashier + "', NOW(), '" + round2Places(change) + "')"; int intSqlReturnVal = -1; int masterID = -1; try { intSqlReturnVal = stmt.executeUpdate(strSql, Statement.RETURN_GENERATED_KEYS); ResultSet keys = stmt.getGeneratedKeys(); keys.next(); masterID = keys.getInt(1); keys.close(); stmt.close(); } catch (Exception exRetKeys) { System.err.println(exRetKeys.getMessage() + " (but pscafepos is attempting a work around)"); intSqlReturnVal = stmt.executeUpdate(strSql); masterID = dbMan.getLastInsertIDWorkAround(stmt, strPOSPrefix + "trans_master_tm_id_seq"); if (masterID == -1) System.err.println("It looks like the work around failed, please submit a bug report!"); else System.err.println("work around was successful!"); } if (intSqlReturnVal == 1) { if (masterID >= 0) { OrderItem[] itms = order.getOrderItems(); if (itms != null && itms.length > 0) { for (int i = 0; i < itms.length; i++) { if (itms[i] != null) { stmt = conn.createStatement(); int itemid = itms[i].getDBID(); double itemprice = round2Places(itms[i].getEffectivePrice()); int f, r, a; String strItemName, strItemBuilding, strItemCat; f = 0; r = 0; a = 0; if (itms[i].isSoldAsFree()) { f = 1; } if (itms[i].isSoldAsReduced()) { r = 1; } if (itms[i].isTypeA()) { a = 1; } strItemName = itms[i].getName(); strItemBuilding = (String) itms[i].getBuilding(); strItemCat = itms[i].getCategory(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "trans_item ( ti_itemid, ti_tmid, ti_pricesold, ti_registerid, ti_cashier, ti_studentid, ti_isfree, ti_isreduced, ti_datetime, ti_istypea, ti_itemname, ti_itembuilding, ti_itemcat ) values('" + itemid + "', '" + masterID + "', '" + round2Places(itemprice) + "', '" + host + "', '" + cashier + "', '" + stuId + "', '" + f + "', '" + r + "', NOW(), '" + a + "', '" + strItemName + "', '" + strItemBuilding + "', '" + strItemCat + "')") != 1) { gui.setCriticalMessage("Item insert failed"); conn.rollback(); } stmt.close(); stmt = conn.createStatement(); String sqlInv = "SELECT inv_id from " + strPOSPrefix + "inventory where inv_menuid = " + itemid + ""; if (stmt.execute(sqlInv)) { ResultSet rsInv = stmt.getResultSet(); int delId = -1; if (rsInv.next()) { delId = rsInv.getInt("inv_id"); } if (delId != -1) { stmt.executeUpdate("delete from " + strPOSPrefix + "inventory where inv_id = " + delId); } stmt.close(); } } else { gui.setCriticalMessage("Null Item"); conn.rollback(); } } boolean blOk = true; if (round2Places(credit) > 0d) { if (round2Places(allowedCredit) >= round2Places(credit)) { if (hasStudentCredit()) { stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "studentcredit set credit_amount = credit_amount - " + round2Places(credit) + " 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_transid, scl_datetime ) values( '" + stuId + "', '" + round2Places((-1) * credit) + "', '" + masterID + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { gui.setCriticalMessage("Unable to update student credit log."); blOk = false; } } else { gui.setCriticalMessage("Unable to update student credit account."); blOk = false; } } else { gui.setCriticalMessage("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((-1) * credit) + "','1','" + stuId + "', NOW())") == 1) { stmt.close(); stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "studentcredit_log ( scl_studentid, scl_action, scl_transid, scl_datetime ) values( '" + stuId + "', '" + round2Places((-1) * credit) + "', '" + masterID + "', NOW() )") == 1) { stmt.close(); blOk = true; } else { gui.setCriticalMessage("Unable to update student credit log."); blOk = false; } } else { gui.setCriticalMessage("Unable to create new student credit account."); blOk = false; } } } else { gui.setCriticalMessage("Student doesn't have enought credit."); blOk = false; } } if (blOk) { if (blDepositCredit && change > 0d) { try { if (doStudentCreditUpdate(change, stuId)) { change = 0d; } else blOk = false; } catch (Exception cExp) { blOk = false; } } } if (blOk) { boolean blHBOK = true; if (itms != null && itms.length > 0) { for (int i = 0; i < itms.length; i++) { stmt = conn.createStatement(); if (stmt.execute("select count(*) from " + strPOSPrefix + "hotbar where hb_itemid = '" + itms[i].getDBID() + "' and hb_building = '" + building + "' and hb_register = '" + host + "' and hb_cashier = '" + cashier + "'")) { rs = stmt.getResultSet(); rs.next(); int num = rs.getInt(1); stmt.close(); if (num == 1) { stmt = conn.createStatement(); if (stmt.executeUpdate("update " + strPOSPrefix + "hotbar set hb_count = hb_count + 1 where hb_itemid = '" + itms[i].getDBID() + "' and hb_building = '" + building + "' and hb_register = '" + host + "' and hb_cashier = '" + cashier + "'") != 1) blHBOK = false; } else { stmt = conn.createStatement(); if (stmt.executeUpdate("insert into " + strPOSPrefix + "hotbar ( hb_itemid, hb_building, hb_register, hb_cashier, hb_count ) values( '" + itms[i].getDBID() + "', '" + building + "', '" + host + "', '" + cashier + "', '1' )") != 1) blHBOK = false; } stmt.close(); } } } else blHBOK = false; if (blHBOK) { conn.commit(); gui.setStatus("Order Complete."); gui.disableUI(); summary = new PSOrderSummary(gui); if (cashDrawer != null) cashDrawer.openDrawer(); else summary.setPOSEventListener(this); summary.display(money.format(order.getOrderTotal()), money.format(mBuf.getCash()), money.format(credit), money.format(change), money.format(getStudentCredit())); } else { conn.rollback(); gui.setStatus("Failure during Hotbar update. Transaction has been rolled back.", true); } } else { conn.rollback(); } } else { gui.setCriticalMessage("Unable to fetch items."); conn.rollback(); } } else { gui.setCriticalMessage("Unable to retrieve autoid"); conn.rollback(); } } else { gui.setCriticalMessage("Error During Writting of Transaction Master Record."); conn.rollback(); } } catch (SQLException sqlEx) { System.err.println("SQLException: " + sqlEx.getMessage()); System.err.println("SQLState: " + sqlEx.getSQLState()); System.err.println("VendorError: " + sqlEx.getErrorCode()); try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); System.err.println(e); try { conn.rollback(); } catch (SQLException sqlEx2) { System.err.println("Rollback failed: " + sqlEx2.getMessage()); } } 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); } } } } } } else { gui.setStatus("Credit total + Cash total is less then the order total! ", true); } } } else { if (settings.get(DBSettings.MAIN_ALLOWNEGBALANCES).compareTo("1") == 0) { gui.setStatus("Sorry, maximum negative balance is " + money.format(neg) + "!", true); } else gui.setStatus("Student does not have enough credit to process this order.", true); } } else { gui.setStatus("Buffer total is less then the order total.", true); } } } Code Sample 2: private boolean delete() { boolean ret = false; try { Connection conn = ((JdbcRequestCycle) getRequestCycle()).getConnection(); if (conn == null) { throw new RestartResponseException(new OkErrorPage(OkErrorEnum.DATABASE)); } String query = "delete from revisions where entry=?"; PreparedStatement pstmt = conn.prepareStatement(query); pstmt.setInt(1, entry); int revisionsRowsAffected = pstmt.executeUpdate(); query = "delete from entry where id=?"; pstmt = conn.prepareStatement(query); pstmt.setInt(1, entry); int entryRowAffected = pstmt.executeUpdate(); if (entryRowAffected > 0) { ret = true; } else { conn.rollback(); } info(entryRowAffected + " entry with " + revisionsRowsAffected + " revisions was deleted."); } catch (SQLException ex) { ex.printStackTrace(); } return ret; }
00
Code Sample 1: protected void logout() { Session session = getConnection().getSession(); session.removeAttribute("usercookie.object"); String urlIn = GeoNetworkContext.url + "/" + GeoNetworkContext.logoutService; Element results = null; String cookie = (String) session.getAttribute("usercookie.object"); if (cookie != null) { try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); log.debug("CheckLogout to GeoNetwork returned " + Xml.getString(results)); } finally { in.close(); } } catch (Exception e) { throw new RuntimeException("User logout to GeoNetwork failed: ", e); } } log.debug("GeoNetwork logout done"); } Code Sample 2: PasswordTableWindow(String login) { super(login + ", tecle a senha de uso �nico"); this.login = login; Error.log(4001, "Autentica��o etapa 3 iniciada."); Container container = getContentPane(); container.setLayout(new FlowLayout()); btnNumber = new JButton[10]; btnOK = new JButton("OK"); btnClear = new JButton("Limpar"); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 10)); ResultSet rs; Statement stmt; String sql; Vector<Integer> result = new Vector<Integer>(); sql = "select key from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result.add(rs.getInt("key")); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r = rn.nextInt(); if (result.size() == 0) { rn = new Random(); Vector<Integer> passwordVector = new Vector<Integer>(); Vector<String> hashVector = new Vector<String>(); for (int i = 0; i < 10; i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < 10; i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < 10; i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "nova tabela de senhas criada para o usu�rio " + login + "."); Error.log(1002, "Sistema encerrado"); System.exit(0); } if (r < 0) r = r * (-1); int index = r % result.size(); if (index > result.size()) index = 0; key = result.get(index); labelKey = new JLabel("Chave n�mero " + key + " "); passwordField = new JPasswordField(12); ButtonHandler handler = new ButtonHandler(); for (int i = 0; i < 10; i++) { btnNumber[i] = new JButton("" + i); buttonPanel.add(btnNumber[i]); btnNumber[i].addActionListener(handler); } btnOK.addActionListener(handler); btnClear.addActionListener(handler); container.add(buttonPanel); container.add(passwordField); container.add(labelKey); container.add(btnOK); container.add(btnClear); setSize(325, 200); setVisible(true); }
00
Code Sample 1: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); } Code Sample 2: public static void fileCopy(String from_name, String to_name) throws IOException { File fromFile = new File(from_name); File toFile = new File(to_name); if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name); if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name); if (!fromFile.isFile()) abort("can't copy directory: " + from_name); if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name); } else { String parent = toFile.getParent(); if (parent == null) abort("destination directory doesn't exist: " + parent); File dir = new File(parent); if (!dir.exists()) abort("destination directory doesn't exist: " + parent); if (dir.isFile()) abort("destination is not a directory: " + parent); if (!dir.canWrite()) abort("destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
11
Code Sample 1: private void writeData(IBaseType dataType, Writer writer) throws XMLStreamException { InputStream isData; DataType data = (DataType) baseType; if (data.isSetInputStream()) { isData = data.getInputStream(); try { IOUtils.copy(isData, writer); } catch (IOException e) { throw new XMLStreamException("DataType fail writing streaming data ", e); } } else if (data.isSetOutputStream()) { throw new XMLStreamException("DataType only can write streaming input, its an output stream (only for reading) "); } else { new CharactersEventImpl(startElement.getLocation(), String.valueOf(baseType.asData()), false).writeAsEncodedUnicode(writer); } } Code Sample 2: public void testCodingBeyondContentLimitFromFile() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff; and a lot more stuff"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }