label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
protected static void copyDeleting(File source, File dest) throws ErrorCodeException { byte[] buf = new byte[8 * 1024]; FileInputStream in = null; try { in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { int count; while ((count = in.read(buf)) >= 0) out.write(buf, 0, count); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new ErrorCodeException(e); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public void fetchFile(String ID) { String url = "http://www.nal.usda.gov/cgi-bin/agricola-ind?bib=" + ID + "&conf=010000++++++++++++++&screen=MA"; System.out.println(url); try { PrintWriter pw = new PrintWriter(new FileWriter("MARC" + ID + ".txt")); if (!id.contains("MARC" + ID + ".txt")) { id.add("MARC" + ID + ".txt"); } in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); in.readLine(); String inputLine, stx = ""; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("<TR><TD><B>")) { String sts = (inputLine.substring(inputLine.indexOf("B>") + 2, inputLine.indexOf("</"))); int i = 0; try { i = Integer.parseInt(sts); } catch (NumberFormatException nfe) { } if (i > 0) { stx = stx + "\n" + sts + " - "; } else { stx += sts; } } if (!(inputLine.startsWith("<") || inputLine.startsWith(" <") || inputLine.startsWith(">"))) { String tx = inputLine.trim(); stx += tx; } } pw.println(stx); pw.close(); } catch (Exception e) { System.out.println("Couldn't open stream"); System.out.println(e); } }
Code Sample 2:
public static synchronized int registerVote(String IDVotazione, byte[] T1, byte[] sbT2, byte[] envelope, Config config) { if (IDVotazione == null) { LOGGER.error("registerVote::IDV null"); return C_addVote_BOH; } if (T1 == null) { LOGGER.error("registerVote::T1 null"); return C_addVote_BOH; } if (envelope == null) { LOGGER.error("registerVote::envelope null"); return C_addVote_BOH; } LOGGER.info("registering vote started"); Connection conn = null; PreparedStatement stmt = null; boolean autoCommitPresent = true; int ANSWER = C_addVote_BOH; try { ByteArrayInputStream tmpXMLStream = new ByteArrayInputStream(envelope); SAXReader tmpXMLReader = new SAXReader(); Document doc = tmpXMLReader.read(tmpXMLStream); if (LOGGER.isTraceEnabled()) LOGGER.trace(doc.asXML()); String sT1 = new String(Base64.encodeBase64(T1), "utf-8"); String ssbT2 = new String(Base64.encodeBase64(sbT2), "utf-8"); String sEnvelope = new String(Base64.encodeBase64(envelope), "utf-8"); LOGGER.trace("loading jdbc driver ..."); Class.forName("com.mysql.jdbc.Driver"); LOGGER.trace("... loaded"); conn = DriverManager.getConnection(config.getSconn()); autoCommitPresent = conn.getAutoCommit(); conn.setAutoCommit(false); String query = "" + " INSERT INTO votes(IDVotazione, T1, signByT2 , envelope) " + " VALUES (? , ? , ? , ? ) "; stmt = conn.prepareStatement(query); stmt.setString(1, IDVotazione); stmt.setString(2, sT1); stmt.setString(3, ssbT2); stmt.setString(4, sEnvelope); stmt.executeUpdate(); stmt.close(); LOGGER.debug("vote saved for references, now start the parsing"); query = "" + " INSERT INTO risposte (IDVotazione, T1, IDquestion , myrisposta,freetext) " + " VALUES (? , ? , ? , ? ,?) "; stmt = conn.prepareStatement(query); Element question, itemsElem, rispostaElem; List<Element> rispList; String id, rispostaText, risposta, freeText, questionType; Iterator<Element> questionIterator = doc.selectNodes("/poll/manifest/question").iterator(); while (questionIterator.hasNext()) { question = (Element) questionIterator.next(); risposta = freeText = ""; id = question.attributeValue("id"); itemsElem = question.element("items"); questionType = itemsElem == null ? "" : itemsElem.attributeValue("type"); rispostaElem = question.element("myrisposta"); rispostaText = rispostaElem == null ? "" : rispostaElem.getText(); if (rispostaText.equals(Votazione.C_TAG_WHITE_XML)) { risposta = C_TAG_WHITE; } else if (rispostaText.equals(Votazione.C_TAG_NULL_XML)) { risposta = C_TAG_NULL; } else { if (!rispostaText.equals("") && LOGGER.isDebugEnabled()) LOGGER.warn("Risposta text should be empty!: " + rispostaText); risposta = C_TAG_BUG; if (questionType.equals("selection")) { Element rispItem = rispostaElem.element("item"); String tmpRisposta = rispItem.attributeValue("index"); if (tmpRisposta != null) { risposta = tmpRisposta; if (risposta.equals("0")) freeText = rispItem.getText(); } } else if (questionType.equals("borda")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index, tokens; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); tokens = rispItem.attributeValue("tokens"); if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index + ":" + tokens; } } } else if (questionType.equals("ordering")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index, order; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); order = rispItem.attributeValue("order"); if (index == null) { continue; } if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index + ":" + order; } } } else if (questionType.equals("multiple")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index; } } } else if (questionType.equals("free")) { freeText = rispostaElem.element("item").getText(); risposta = ""; } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("ID_QUESTION: " + id); LOGGER.trace("question type: " + questionType); LOGGER.trace("risposta: " + risposta); LOGGER.trace("freetext: " + freeText); } if (risposta.equals(C_TAG_BUG)) { LOGGER.error("Invalid answer"); LOGGER.error("T1: " + sT1); LOGGER.error("ID_QUESTION: " + id); LOGGER.error("question type: " + questionType); } stmt.setString(1, IDVotazione); stmt.setString(2, sT1); stmt.setString(3, id); stmt.setString(4, risposta); stmt.setString(5, freeText); stmt.addBatch(); } stmt.executeBatch(); stmt.close(); conn.commit(); ANSWER = C_addVote_OK; LOGGER.info("registering vote end successfully"); } catch (SQLException e) { try { conn.rollback(); } catch (Exception ex) { } if (e.getErrorCode() == 1062) { ANSWER = C_addVote_DUPLICATE; LOGGER.error("error while registering vote (duplication)"); } else { ANSWER = C_addVote_BOH; LOGGER.error("error while registering vote", e); } } catch (UnsupportedEncodingException e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("encoding error", e); ANSWER = C_addVote_BOH; } catch (DocumentException e) { LOGGER.error("DocumentException", e); ANSWER = C_addVote_BOH; } catch (ClassNotFoundException e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("error while registering vote", e); ANSWER = C_addVote_BOH; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("Unexpected exception while registering vote", e); ANSWER = C_addVote_BOH; } finally { try { conn.setAutoCommit(autoCommitPresent); conn.close(); } catch (Exception e) { } ; } return ANSWER; }
|
11
|
Code Sample 1:
public Attributes getAttributes() throws SchemaViolationException, NoSuchAlgorithmException, UnsupportedEncodingException { BasicAttributes outAttrs = new BasicAttributes(true); BasicAttribute oc = new BasicAttribute("objectclass", "inetOrgPerson"); oc.add("organizationalPerson"); oc.add("person"); outAttrs.put(oc); if (lastName != null && firstName != null) { outAttrs.put("sn", lastName); outAttrs.put("givenName", firstName); outAttrs.put("cn", firstName + " " + lastName); } else { throw new SchemaViolationException("user must have surname"); } if (password != null) { MessageDigest sha = MessageDigest.getInstance("md5"); sha.reset(); sha.update(password.getBytes("utf-8")); byte[] digest = sha.digest(); String hash = Base64.encodeBase64String(digest); outAttrs.put("userPassword", "{MD5}" + hash); } if (email != null) { outAttrs.put("mail", email); } return (Attributes) outAttrs; }
Code Sample 2:
public static String encrypt(String text) { char[] toEncrypt = text.toCharArray(); StringBuffer hexString = new StringBuffer(); try { MessageDigest dig = MessageDigest.getInstance("MD5"); dig.reset(); String pw = ""; for (int i = 0; i < toEncrypt.length; i++) { pw += toEncrypt[i]; } dig.update(pw.getBytes()); byte[] digest = dig.digest(); int digestLength = digest.length; for (int i = 0; i < digestLength; i++) { hexString.append(hexDigit(digest[i])); } } catch (java.security.NoSuchAlgorithmException ae) { ae.printStackTrace(); } return hexString.toString(); }
|
11
|
Code Sample 1:
public Transaction() throws Exception { Connection Conn = null; Statement Stmt = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Conn = DriverManager.getConnection(DBUrl); Conn.setAutoCommit(true); Stmt = Conn.createStatement(); try { Stmt.executeUpdate("DROP TABLE trans_test"); } catch (SQLException sqlEx) { } Stmt.executeUpdate("CREATE TABLE trans_test (id int not null primary key, decdata double) type=BDB"); Conn.setAutoCommit(false); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.0)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Conn.rollback(); System.out.println("Roll Ok"); ResultSet RS = Stmt.executeQuery("SELECT * from trans_test"); if (!RS.next()) { System.out.println("Ok"); } else { System.out.println("Rollback failed"); } Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.485115)"); Conn.commit(); RS = Stmt.executeQuery("SELECT * from trans_test where id=2"); if (RS.next()) { System.out.println(RS.getDouble(2)); System.out.println("Ok"); } else { System.out.println("Rollback failed"); } } catch (Exception ex) { throw ex; } finally { if (Stmt != null) { try { Stmt.close(); } catch (SQLException SQLEx) { } } if (Conn != null) { try { Conn.close(); } catch (SQLException SQLEx) { } } } }
Code Sample 2:
public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("WITH_BOUI") + " [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (SCHEMA,OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
|
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 void main(String[] args) { FTPClient client = new FTPClient(); try { client.connect("192.168.1.10"); boolean login = client.login("a", "123456"); if (login) { System.out.println("Dang nhap thanh cong..."); boolean logout = client.logout(); if (logout) { System.out.println("Da Logout khoi FTP Server..."); } } else { System.out.println("Dang nhap that bai..."); } } catch (IOException e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
|
11
|
Code Sample 1:
protected static final void copyFile(String from, String to) throws SeleniumException { try { java.io.File fileFrom = new File(from); java.io.File fileTo = new File(to); FileReader in = new FileReader(fileFrom); FileWriter out = new FileWriter(fileTo); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { throw new SeleniumException("Failed to copy new file : " + from + " to : " + to, e); } }
Code Sample 2:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
protected static String fileName2md5(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes("iso-8859-1")); byte[] byteHash = md.digest(); md.reset(); StringBuffer resultString = new StringBuffer(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); } catch (Exception ex) { Logger.error(ex.getClass() + " " + ex.getMessage()); for (int i = 0; i < ex.getStackTrace().length; i++) Logger.error(" " + ex.getStackTrace()[i].toString()); ex.printStackTrace(); } return String.valueOf(Math.random() * Long.MAX_VALUE); }
Code Sample 2:
public Location getLocation(String ip) throws Exception { URL url = new URL("http://api.hostip.info/?ip=" + ip); SAXReader reader = new SAXReader(); Document doc = reader.read(url.openStream()); System.out.println(doc.asXML()); Location location = new Location(doc); return location; }
|
11
|
Code Sample 1:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
Code Sample 2:
private String choosePivotVertex() throws ProcessorExecutionException { String result = null; Graph src; Graph dest; Path tmpDir; System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex"); src = new Graph(Graph.defaultGraph()); src.setPath(_curr_path); dest = new Graph(Graph.defaultGraph()); try { tmpDir = _dirMgr.getTempDir(); } catch (IOException e) { throw new ProcessorExecutionException(e); } dest.setPath(tmpDir); GraphAlgorithm choose_pivot = new PivotChoose(); choose_pivot.setConf(context); choose_pivot.setSource(src); choose_pivot.setDestination(dest); choose_pivot.setMapperNum(getMapperNum()); choose_pivot.setReducerNum(getReducerNum()); choose_pivot.execute(); try { Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("##########> Chosen pivot id = " + result); } catch (IOException e) { throw new ProcessorExecutionException(e); } return result; }
|
11
|
Code Sample 1:
public static void importDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = output + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); createTablesDB(); } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); long tiempoInicio = System.currentTimeMillis(); String directoryPath = input + File.separator; File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(input + File.separator + G.imagesName); if (!fileXML.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE); } else { SAXBuilder builder = new SAXBuilder(false); Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); List<Element> globalLanguages = root.getChild("languages").getChildren("language"); Iterator<Element> langsI = globalLanguages.iterator(); HashMap<String, Integer> languageIDs = new HashMap<String, Integer>(); HashMap<String, Integer> typeIDs = new HashMap<String, Integer>(); Element e; int i = 0; int contTypes = 0; int contImages = 0; while (langsI.hasNext()) { e = langsI.next(); languageIDs.put(e.getText(), i); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)"); stmt.setInt(1, i); stmt.setString(2, e.getText()); stmt.executeUpdate(); stmt.close(); i++; } G.conn.setAutoCommit(false); while (j.hasNext()) { Element image = (Element) j.next(); String id = image.getAttributeValue("id"); List languages = image.getChildren("language"); Iterator k = languages.iterator(); if (exists(list, id)) { String pathSrc = directoryPath.concat(id); String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = output + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } while (k.hasNext()) { Element languageElement = (Element) k.next(); String language = languageElement.getAttributeValue("id"); List words = languageElement.getChildren("word"); Iterator l = words.iterator(); while (l.hasNext()) { Element wordElement = (Element) l.next(); String type = wordElement.getAttributeValue("type"); if (!typeIDs.containsKey(type)) { typeIDs.put(type, contTypes); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)"); stmt.setInt(1, contTypes); stmt.setString(2, type); stmt.executeUpdate(); stmt.close(); contTypes++; } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, wordElement.getText().toLowerCase()); stmt.setInt(2, languageIDs.get(language)); stmt.setInt(3, typeIDs.get(type)); stmt.setString(4, id); stmt.setString(5, id); stmt.executeUpdate(); stmt.close(); if (contImages == 5000) { G.conn.commit(); contImages = 0; } else contImages++; } } } else { } } G.conn.setAutoCommit(true); G.conn.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException("Expected arguments: fileName log"); String fileName = args[0]; String logFile = args[1]; LineNumberReader reader = null; PrintWriter writer = null; try { Reader reader0 = new FileReader(fileName); reader = new LineNumberReader(reader0); Writer writer0 = new FileWriter(logFile); BufferedWriter writer1 = new BufferedWriter(writer0); writer = new PrintWriter(writer1); String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.length() >= 81) { writer.println("Analyzing Sudoku #" + reader.getLineNumber()); System.out.println("Analyzing Sudoku #" + reader.getLineNumber()); Grid grid = new Grid(); for (int i = 0; i < 81; i++) { char ch = line.charAt(i); if (ch >= '1' && ch <= '9') { int value = (ch - '0'); grid.setCellValue(i % 9, i / 9, value); } } Solver solver = new Solver(grid); solver.rebuildPotentialValues(); try { Map<Rule, Integer> rules = solver.solve(null); Map<String, Integer> ruleNames = solver.toNamedList(rules); double difficulty = 0; String hardestRule = ""; for (Rule rule : rules.keySet()) { if (rule.getDifficulty() > difficulty) { difficulty = rule.getDifficulty(); hardestRule = rule.getName(); } } for (String rule : ruleNames.keySet()) { int count = ruleNames.get(rule); writer.println(Integer.toString(count) + " " + rule); System.out.println(Integer.toString(count) + " " + rule); } writer.println("Hardest technique: " + hardestRule); System.out.println("Hardest technique: " + hardestRule); writer.println("Difficulty: " + difficulty); System.out.println("Difficulty: " + difficulty); } catch (UnsupportedOperationException ex) { writer.println("Failed !"); System.out.println("Failed !"); } writer.println(); System.out.println(); writer.flush(); } else System.out.println("Skipping incomplete line: " + line); line = reader.readLine(); } writer.close(); reader.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException ex) { ex.printStackTrace(); } } System.out.print("Finished."); }
|
11
|
Code Sample 1:
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:
@Test(dependsOnMethods = { "getSize" }) public void download() throws IOException { FileObject typica = fsManager.resolveFile("s3://" + bucketName + "/jonny.zip"); File localCache = File.createTempFile("vfs.", ".s3-test"); FileOutputStream out = new FileOutputStream(localCache); IOUtils.copy(typica.getContent().getInputStream(), out); Assert.assertEquals(localCache.length(), typica.getContent().getSize()); localCache.delete(); }
|
11
|
Code Sample 1:
public static void extractZip(Resource zip, FileObject outputDirectory) { ZipInputStream zis = null; try { zis = new ZipInputStream(zip.getResourceURL().openStream()); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String[] pathElements = entry.getName().split("/"); FileObject extractDir = outputDirectory; for (int i = 0; i < pathElements.length - 1; i++) { String pathElementName = pathElements[i]; FileObject pathElementFile = extractDir.resolveFile(pathElementName); if (!pathElementFile.exists()) { pathElementFile.createFolder(); } extractDir = pathElementFile; } String fileName = entry.getName(); if (fileName.endsWith("/")) { fileName = fileName.substring(0, fileName.length() - 1); } if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf('/') + 1); } if (entry.isDirectory()) { extractDir.resolveFile(fileName).createFolder(); } else { FileObject file = extractDir.resolveFile(fileName); file.createFile(); int size = (int) entry.getSize(); byte[] unpackBuffer = new byte[size]; zis.read(unpackBuffer, 0, size); InputStream in = null; OutputStream out = null; try { in = new ByteArrayInputStream(unpackBuffer); out = file.getContent().getOutputStream(); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } } } catch (IOException e2) { throw new RuntimeException(e2); } finally { IOUtils.closeQuietly(zis); } }
Code Sample 2:
public static File extract(File source, String filename, File target) { if (source.exists() == false || filename == null || filename.trim().length() < 1 || target == null) return null; boolean isDirectory = (filename.lastIndexOf("/") == filename.length() - 1); try { Map contents = (Map) jarContents.get(source.getPath()); if (contents == null) { contents = new HashMap(); jarContents.put(source.getPath(), contents); ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; contents.put(zipEntry.getName(), zipEntry); } input.close(); } if (isDirectory) { Iterator it = contents.keySet().iterator(); while (it.hasNext()) { String next = (String) it.next(); if (next.startsWith(filename)) { ZipEntry zipEntry = (ZipEntry) contents.get(next); int n = filename.length(); File newTarget = new File(target, zipEntry.getName().substring(n)); extract(source, next, newTarget); } } return target; } ZipEntry entry = (ZipEntry) contents.get(filename); ZipFile input = new ZipFile(source); InputStream in = input.getInputStream(entry); target.getParentFile().mkdirs(); int bytesRead; byte[] buffer = new byte[1024]; FileOutputStream output = new FileOutputStream(target); while ((bytesRead = in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.close(); return target; } catch (Exception ex) { ex.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public File copyFile(File f) throws IOException { File t = createNewFile("fm", "cpy"); FileOutputStream fos = new FileOutputStream(t); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(f); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return t; }
Code Sample 2:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
|
00
|
Code Sample 1:
public void test() throws Exception { StringDocument doc = new StringDocument("Test", "UTF-8"); doc.open(); try { assertEquals("UTF-8", doc.getCharacterEncoding()); assertEquals("Test", doc.getText()); InputStream input = doc.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { writer.close(); } assertEquals("Test", writer.toString()); } finally { doc.close(); } }
Code Sample 2:
public static BufferedReader getUserInfoStream(String name) throws IOException { BufferedReader in; try { URL url = new URL("http://www.spoj.pl/users/" + name.toLowerCase() + "/"); in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (MalformedURLException e) { in = null; throw e; } return in; }
|
11
|
Code Sample 1:
public List<SysSequences> getSeqs() throws Exception { List<SysSequences> list = new ArrayList<SysSequences>(); Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("update ss_sys_sequences set next_value=next_value+step_value"); ps.executeUpdate(); ps.close(); ps = conn.prepareStatement("select * from ss_sys_sequences"); ResultSet rs = ps.executeQuery(); while (rs.next()) { SysSequences seq = new SysSequences(); seq.setTableName(rs.getString(1)); long nextValue = rs.getLong(2); long stepValue = rs.getLong(3); seq.setNextValue(nextValue - stepValue); seq.setStepValue(stepValue); list.add(seq); } rs.close(); ps.close(); conn.commit(); } catch (Exception e) { conn.rollback(); e.printStackTrace(); } finally { try { conn.setAutoCommit(true); } catch (Exception e) { } ConnectUtil.closeConn(conn); } return list; }
Code Sample 2:
public ProgramSymbol deleteProgramSymbol(int id) throws AdaptationException { ProgramSymbol programSymbol = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProgramSymbols " + "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 program symbol failed."; log.error(msg); throw new AdaptationException(msg); } programSymbol = getProgramSymbol(resultSet); query = "DELETE FROM ProgramSymbols " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProgramSymbol"; 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 programSymbol; }
|
11
|
Code Sample 1:
public static boolean downloadFile(String url, String destination) throws Exception { BufferedInputStream bi = null; BufferedOutputStream bo = null; File destfile; byte BUFFER[] = new byte[100]; java.net.URL fileurl; URLConnection conn; fileurl = new java.net.URL(url); conn = fileurl.openConnection(); long fullsize = conn.getContentLength(); long onepercent = fullsize / 100; MessageFrame.setTotalDownloadSize(fullsize); bi = new BufferedInputStream(conn.getInputStream()); destfile = new File(destination); if (!destfile.createNewFile()) { destfile.delete(); destfile.createNewFile(); } bo = new BufferedOutputStream(new FileOutputStream(destfile)); int read = 0; int sum = 0; long i = 0; while ((read = bi.read(BUFFER)) != -1) { bo.write(BUFFER, 0, read); sum += read; i += read; if (i > onepercent) { i = 0; MessageFrame.setDownloadProgress(sum); } } bi.close(); bo.close(); MessageFrame.setDownloadProgress(fullsize); return true; }
Code Sample 2:
public static URL getIconURLForUser(String id) { try { URL url = new URL("http://profiles.yahoo.com/" + id); BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream())); String input = null; while ((input = r.readLine()) != null) { if (input.indexOf("<a href=\"") < 0) continue; if (input.indexOf("<img src=\"") < 0) continue; if (input.indexOf("<a href=\"") > input.indexOf("<img src=\"")) continue; String href = input.substring(input.indexOf("<a href=\"") + 9); String src = input.substring(input.indexOf("<img src=\"") + 10); if (href.indexOf("\"") < 0) continue; if (src.indexOf("\"") < 0) continue; href = href.substring(0, href.indexOf("\"")); src = src.substring(0, src.indexOf("\"")); if (href.equals(src)) { return new URL(href); } } } catch (IOException e) { } URL toReturn = null; try { toReturn = new URL("http://us.i1.yimg.com/us.yimg.com/i/ppl/no_photo.gif"); } catch (MalformedURLException e) { Debug.assrt(false); } return toReturn; }
|
11
|
Code Sample 1:
public static void main(String args[]) throws Exception { File file = new File("D:/work/love.txt"); @SuppressWarnings("unused") ZipFile zipFile = new ZipFile("D:/work/test1.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("D:/work/test1.zip")); zos.setEncoding("GBK"); ZipEntry entry = null; if (file.isDirectory()) { entry = new ZipEntry(getAbsFileName(source, file) + "/"); } else { entry = new ZipEntry(getAbsFileName(source, file)); } entry.setSize(file.length()); entry.setTime(file.lastModified()); zos.putNextEntry(entry); int readLen = 0; byte[] buf = new byte[2048]; if (file.isFile()) { InputStream in = new BufferedInputStream(new FileInputStream(file)); while ((readLen = in.read(buf, 0, 2048)) != -1) { zos.write(buf, 0, readLen); } in.close(); } zos.close(); }
Code Sample 2:
public static void unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } }
|
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 static File unGzip(File infile, boolean deleteGzipfileOnSuccess) throws IOException { GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile)); File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", "")); FileOutputStream fos = new FileOutputStream(outFile); byte[] buf = new byte[100000]; int len; while ((len = gin.read(buf)) > 0) fos.write(buf, 0, len); gin.close(); fos.close(); if (deleteGzipfileOnSuccess) infile.delete(); return outFile; }
|
00
|
Code Sample 1:
@Override public void writeTo(final TrackRepresentation t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws WebApplicationException { if (mediaType.isCompatible(MediaType.APPLICATION_OCTET_STREAM_TYPE)) { InputStream is = null; try { httpHeaders.add("Content-Type", "audio/mp3"); IOUtils.copy(is = t.getInputStream(mediaType), entityStream); } catch (final IOException e) { LOG.warn("IOException : maybe remote client has disconnected"); } finally { IOUtils.closeQuietly(is); } } }
Code Sample 2:
protected int authenticate(long companyId, String login, String password, String authType, Map headerMap, Map parameterMap) throws PortalException, SystemException { login = login.trim().toLowerCase(); long userId = GetterUtil.getLong(login); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { if (!Validator.isEmailAddress(login)) { throw new UserEmailAddressException(); } } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { if (Validator.isNull(login)) { throw new UserScreenNameException(); } } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { if (Validator.isNull(login)) { throw new UserIdException(); } } if (Validator.isNull(password)) { throw new UserPasswordException(UserPasswordException.PASSWORD_INVALID); } int authResult = Authenticator.FAILURE; String[] authPipelinePre = PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_PRE); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { authResult = AuthPipeline.authenticateByEmailAddress(authPipelinePre, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { authResult = AuthPipeline.authenticateByScreenName(authPipelinePre, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { authResult = AuthPipeline.authenticateByUserId(authPipelinePre, companyId, userId, password, headerMap, parameterMap); } User user = null; try { if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { user = UserUtil.findByC_EA(companyId, login); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { user = UserUtil.findByC_SN(companyId, login); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { user = UserUtil.findByC_U(companyId, GetterUtil.getLong(login)); } } catch (NoSuchUserException nsue) { return Authenticator.DNE; } if (user.isDefaultUser()) { _log.error("The default user should never be allowed to authenticate"); return Authenticator.DNE; } if (!user.isPasswordEncrypted()) { user.setPassword(PwdEncryptor.encrypt(user.getPassword())); user.setPasswordEncrypted(true); UserUtil.update(user); } checkLockout(user); checkPasswordExpired(user); if (authResult == Authenticator.SUCCESS) { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK))) { String encPwd = PwdEncryptor.encrypt(password, user.getPassword()); if (user.getPassword().equals(encPwd)) { authResult = Authenticator.SUCCESS; } else if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.AUTH_MAC_ALLOW))) { try { MessageDigest digester = MessageDigest.getInstance(PropsUtil.get(PropsUtil.AUTH_MAC_ALGORITHM)); digester.update(login.getBytes("UTF8")); String shardKey = PropsUtil.get(PropsUtil.AUTH_MAC_SHARED_KEY); encPwd = Base64.encode(digester.digest(shardKey.getBytes("UTF8"))); if (password.equals(encPwd)) { authResult = Authenticator.SUCCESS; } else { authResult = Authenticator.FAILURE; } } catch (NoSuchAlgorithmException nsae) { throw new SystemException(nsae); } catch (UnsupportedEncodingException uee) { throw new SystemException(uee); } } else { authResult = Authenticator.FAILURE; } } } if (authResult == Authenticator.SUCCESS) { String[] authPipelinePost = PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_POST); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { authResult = AuthPipeline.authenticateByEmailAddress(authPipelinePost, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { authResult = AuthPipeline.authenticateByScreenName(authPipelinePost, companyId, login, password, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { authResult = AuthPipeline.authenticateByUserId(authPipelinePost, companyId, userId, password, headerMap, parameterMap); } } if (authResult == Authenticator.FAILURE) { try { String[] authFailure = PropsUtil.getArray(PropsUtil.AUTH_FAILURE); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { AuthPipeline.onFailureByEmailAddress(authFailure, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { AuthPipeline.onFailureByScreenName(authFailure, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { AuthPipeline.onFailureByUserId(authFailure, companyId, userId, headerMap, parameterMap); } if (!PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) { PasswordPolicy passwordPolicy = user.getPasswordPolicy(); int failedLoginAttempts = user.getFailedLoginAttempts(); int maxFailures = passwordPolicy.getMaxFailure(); if ((failedLoginAttempts >= maxFailures) && (maxFailures != 0)) { String[] authMaxFailures = PropsUtil.getArray(PropsUtil.AUTH_MAX_FAILURES); if (authType.equals(CompanyImpl.AUTH_TYPE_EA)) { AuthPipeline.onMaxFailuresByEmailAddress(authMaxFailures, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_SN)) { AuthPipeline.onMaxFailuresByScreenName(authMaxFailures, companyId, login, headerMap, parameterMap); } else if (authType.equals(CompanyImpl.AUTH_TYPE_ID)) { AuthPipeline.onMaxFailuresByUserId(authMaxFailures, companyId, userId, headerMap, parameterMap); } } } } catch (Exception e) { _log.error(e, e); } } return authResult; }
|
11
|
Code Sample 1:
private boolean copy_to_file_io(File src, File dst) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); is = new BufferedInputStream(is); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); byte buffer[] = new byte[1024 * 64]; int read; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } return true; } finally { try { if (is != null) is.close(); } catch (IOException e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (IOException e) { Debug.debug(e); } } }
Code Sample 2:
public static void copyFile(File srcFile, File desFile) throws IOException { AssertUtility.notNull(srcFile); AssertUtility.notNull(desFile); FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(desFile); try { FileChannel srcChannel = fis.getChannel(); FileChannel dstChannel = fos.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } finally { fis.close(); fos.close(); } }
|
00
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void run(IAction action) { Shell shell = new Shell(); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(shell); viewer.setEditDomain(new DefaultEditDomain(null)); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.setContents(getContents()); viewer.flush(); int printMode = new PrintModeDialog(shell).open(); if (printMode == -1) return; PrintDialog dialog = new PrintDialog(shell, SWT.NULL); PrinterData data = dialog.open(); if (data != null) { PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer); op.setPrintMode(printMode); op.run(selectedFile.getName()); } }
|
11
|
Code Sample 1:
public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) { ConvResult[] convs = acr.getConvResults(); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(nwbConvGraph)); writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("id*int")) { writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n"); } else if (line.matches(NODE_LINE)) { String[] parts = line.split(" "); String rawConvName = parts[1]; String convName = rawConvName.replaceAll("\"", ""); boolean wroteAttributes = false; for (int ii = 0; ii < convs.length; ii++) { ConvResult cr = convs[ii]; if (cr.getShortName().equals(convName)) { int trusted; if (cr.isTrusted()) { trusted = 1; } else { trusted = 0; } writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n"); wroteAttributes = true; break; } } if (!wroteAttributes) { writer.write(line + " 1 100.0 0" + "\r\n"); } } else { writer.write(line + "\r\n"); } } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e); try { if (reader != null) reader.close(); } catch (IOException e2) { this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e); } } finally { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } catch (IOException e) { this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e); e.printStackTrace(); } } }
Code Sample 2:
public boolean copy(String file, String target, int tag) { try { File file_in = new File(file); File file_out = new File(target); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } }
|
11
|
Code Sample 1:
public String getResourceAsString(String name) throws IOException { String content = null; InputStream stream = aClass.getResourceAsStream(name); if (stream != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(stream, buffer); content = buffer.toString(); } else { Assert.fail("Resource not available: " + name); } return content; }
Code Sample 2:
@SuppressWarnings("unchecked") protected void processDownloadAction(HttpServletRequest request, HttpServletResponse response) throws Exception { File transformationFile = new File(xslBase, "file-info.xsl"); HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); DataSourceIf dataSource = new NullSource(); Document fileInfoDoc = XmlUtils.getEmptyDOM(); DOMResult result = new DOMResult(fileInfoDoc); transformer.transform((Source) dataSource, result); Element documentElement = fileInfoDoc.getDocumentElement(); if (documentElement.getLocalName().equals("null")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } InputStream is = null; try { XPath xpath = XPathFactory.newInstance().newXPath(); String sourceType = XPathUtils.getStringValue(xpath, "source-type", documentElement, null); String location = XPathUtils.getStringValue(xpath, "location", documentElement, null); String fileName = XPathUtils.getStringValue(xpath, "file-name", documentElement, null); String mimeType = XPathUtils.getStringValue(xpath, "mime-type", documentElement, null); String encoding = XPathUtils.getStringValue(xpath, "encoding", documentElement, null); if (StringUtils.equals(sourceType, "cifsSource")) { String domain = XPathUtils.getStringValue(xpath, "domain", documentElement, null); String userName = XPathUtils.getStringValue(xpath, "username", documentElement, null); String password = XPathUtils.getStringValue(xpath, "password", documentElement, null); URI uri = new URI(location); if (StringUtils.isNotBlank(userName)) { String userInfo = ""; if (StringUtils.isNotBlank(domain)) { userInfo = userInfo + domain + ";"; } userInfo = userInfo + userName; if (StringUtils.isNotBlank(password)) { userInfo = userInfo + ":" + password; } uri = new URI(uri.getScheme(), userInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } SmbFile smbFile = new SmbFile(uri.toURL()); is = new SmbFileInputStream(smbFile); } else if (StringUtils.equals(sourceType, "localFileSystemSource")) { File file = new File(location); is = new FileInputStream(file); } else { logger.error("Source type \"" + ((sourceType != null) ? sourceType : "") + "\" not supported"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (StringUtils.isBlank(mimeType) && StringUtils.isBlank(encoding)) { response.setContentType(Definitions.MIMETYPE_BINARY); } else if (StringUtils.isBlank(encoding)) { response.setContentType(mimeType); } else { response.setContentType(mimeType + ";charset=" + encoding); } if (request.getParameterMap().containsKey(Definitions.REQUEST_PARAMNAME_DOWNLOAD)) { response.setHeader("Content-Disposition", "attachment; filename=" + fileName); } IOUtils.copy(new BufferedInputStream(is), response.getOutputStream()); } finally { if (is != null) { is.close(); } } }
|
11
|
Code Sample 1:
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { log.error(e, e); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
public ValidationReport validate(OriginalDeployUnitDescription unit) throws UnitValidationException { ValidationReport vr = new DefaultValidationReport(); errorHandler = new SimpleErrorHandler(vr); vr.setFileUri(unit.getAbsolutePath()); SAXParser parser; SAXReader reader = null; try { parser = factory.newSAXParser(); reader = new SAXReader(parser.getXMLReader()); reader.setValidation(false); reader.setErrorHandler(this.errorHandler); } catch (ParserConfigurationException e) { throw new UnitValidationException("The configuration of parser is illegal.", e); } catch (SAXException e) { String m = "Something is wrong when register schema"; logger.error(m, e); throw new UnitValidationException(m, e); } ZipInputStream zipInputStream; InputStream tempInput = null; try { tempInput = new FileInputStream(unit.getAbsolutePath()); } catch (FileNotFoundException e1) { String m = String.format("The file [%s] don't exist.", unit.getAbsolutePath()); logger.error(m, e1); throw new UnitValidationException(m, e1); } zipInputStream = new ZipInputStream(tempInput); ZipEntry zipEntry = null; try { zipEntry = zipInputStream.getNextEntry(); if (zipEntry == null) { String m = String.format("Error when get zipEntry. Maybe the [%s] is not zip file!", unit.getAbsolutePath()); logger.error(m); throw new UnitValidationException(m); } while (zipEntry != null) { if (configFiles.contains(zipEntry.getName())) { byte[] extra = new byte[(int) zipEntry.getSize()]; zipInputStream.read(extra); File file = File.createTempFile("temp", "extra"); file.deleteOnExit(); logger.info("[TempFile:]" + file.getAbsoluteFile()); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(extra); FileOutputStream tempFileOutputStream = new FileOutputStream(file); IOUtils.copy(byteInputStream, tempFileOutputStream); tempFileOutputStream.flush(); IOUtils.closeQuietly(tempFileOutputStream); InputStream inputStream = new FileInputStream(file); reader.read(inputStream, unit.getAbsolutePath() + ":" + zipEntry.getName()); IOUtils.closeQuietly(inputStream); } zipEntry = zipInputStream.getNextEntry(); } } catch (IOException e) { ValidationMessage vm = new XMLValidationMessage("IOError", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } catch (DocumentException e) { ValidationMessage vm = new XMLValidationMessage("Document Error.", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } finally { IOUtils.closeQuietly(tempInput); IOUtils.closeQuietly(zipInputStream); } return vr; }
|
00
|
Code Sample 1:
private void externalizeFiles(Document doc, File out) throws IOException { File[] files = doc.getImages(); if (files.length > 0) { File dir = new File(out.getParentFile(), out.getName() + ".images"); if (!dir.mkdirs()) throw new IOException("cannot create directory " + dir); if (dir.exists()) { for (int i = 0; i < files.length; i++) { File file = files[i]; File copy = new File(dir, file.getName()); FileChannel from = null, to = null; long count = -1; try { from = new FileInputStream(file).getChannel(); count = from.size(); to = new FileOutputStream(copy).getChannel(); from.transferTo(0, count, to); doc.setImage(file, dir.getName() + "/" + copy.getName()); } catch (Throwable t) { LOG.log(Level.WARNING, "Copying '" + file + "' to '" + copy + "' failed (size=" + count + ")", t); } finally { try { to.close(); } catch (Throwable t) { } try { from.close(); } catch (Throwable t) { } } } } } }
Code Sample 2:
public Constructor run() throws Exception { String path = "META-INF/services/" + ComponentApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = ComponentApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (ComponentApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new ComponentApplicationException("No " + "ComponentApplicationContext implementation " + "found."); }
|
11
|
Code Sample 1:
private String unzip(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
Code Sample 2:
static void cleanFile(File file) { final Counter cnt = new Counter(); final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned")); final SAMFileReader reader = new SAMFileReader(file); final SAMRecordIterator it = reader.iterator(); final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out); if (!it.hasNext()) return; log.info("Cleaning file " + file + " to " + out.getName()); SAMRecord last = it.next(); writer.addAlignment(last); while (it.hasNext()) { final SAMRecord now = it.next(); final int start1 = last.getAlignmentStart(); final int start2 = now.getAlignmentStart(); final int end1 = last.getAlignmentEnd(); final int end2 = now.getAlignmentEnd(); if (start1 == start2 && end1 == end2) { log.debug("Discarding record " + now.toString()); cnt.count(); continue; } writer.addAlignment(now); last = now; } writer.close(); reader.close(); log.info(file + " done, discarded " + cnt.getCount() + " reads"); exe.shutdown(); }
|
11
|
Code Sample 1:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
Code Sample 2:
public void testPreparedStatementRollback1() throws Exception { Connection localCon = getConnection(); Statement stmt = localCon.createStatement(); stmt.execute("CREATE TABLE #psr1 (data BIT)"); localCon.setAutoCommit(false); PreparedStatement pstmt = localCon.prepareStatement("INSERT INTO #psr1 (data) VALUES (?)"); pstmt.setBoolean(1, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); localCon.rollback(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psr1"); assertFalse(rs.next()); rs.close(); stmt.close(); localCon.close(); try { localCon.commit(); fail("Expecting commit to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } try { localCon.rollback(); fail("Expecting rollback to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } }
|
00
|
Code Sample 1:
private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "AND x.zulfilepath not in (?, ?, ?) " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); pstmt.setString(2, ACTIVITIES_PATH); pstmt.setString(3, FAVOURITES_PATH); pstmt.setString(4, VIEWS_PATH); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); }
Code Sample 2:
private BibtexDatabase parseBibtexDatabase(List<String> id, boolean abs) throws IOException { if (id.isEmpty()) { return null; } URL url; URLConnection conn; try { url = new URL(importUrl); conn = url.openConnection(); } catch (MalformedURLException e) { e.printStackTrace(); return null; } conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Referer", searchUrl); PrintWriter out = new PrintWriter(conn.getOutputStream()); String recordIds = ""; Iterator<String> iter = id.iterator(); while (iter.hasNext()) { recordIds += iter.next() + " "; } recordIds = recordIds.trim(); String citation = abs ? "citation-abstract" : "citation-only"; String content = "recordIds=" + recordIds.replaceAll(" ", "%20") + "&fromPageName=&citations-format=" + citation + "&download-format=download-bibtex"; System.out.println(content); out.write(content); out.flush(); out.close(); BufferedReader bufr = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); char[] buffer = new char[256]; while (true) { int bytesRead = bufr.read(buffer); if (bytesRead == -1) { break; } for (int i = 0; i < bytesRead; i++) { sb.append((char) buffer[i]); } } System.out.println(sb.toString()); ParserResult results = new BibtexParser(bufr).parse(); bufr.close(); return results.getDatabase(); }
|
11
|
Code Sample 1:
private String determineGuardedHtml() { StringBuffer buf = new StringBuffer(); if (m_guardedButtonPresent) { buf.append("\n<span id='" + getHtmlIdPrefix() + PUSH_PAGE_SUFFIX + "' style='display:none'>\n"); String location = m_guardedHtmlLocation != null ? m_guardedHtmlLocation : (String) Config.getProperty(Config.PROP_PRESENTATION_DEFAULT_GUARDED_HTML_LOCATION); String html = (String) c_guardedHtmlCache.get(location); if (html == null) { if (log.isDebugEnabled()) log.debug(this.NAME + ".determineGuardedHtml: Reading the Guarded Html Fragment: " + location); URL url = getUrl(location); if (url != null) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf1 = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { buf1.append(line); buf1.append('\n'); } html = buf1.toString(); } catch (IOException e) { log.warn(this.NAME + ".determineGuardedHtml: Failed to read the Guarded Html Fragment: " + location, e); } finally { try { if (in != null) in.close(); } catch (IOException ex) { log.warn(this.NAME + ".determineGuardedHtml: Failed to close the Guarded Html Fragment: " + location, ex); } } } else { log.warn("Failed to read the Guarded Html Fragment: " + location); } if (html == null) html = "Transaction in Progress"; c_guardedHtmlCache.put(location, html); } buf.append(html); buf.append("\n</span>\n"); } return buf.toString(); }
Code Sample 2:
public static ArrayList<Quote> fetchAllQuotes(String symbol, Date from, Date to) { try { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(from); String monthFrom = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayFrom = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearFrom = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); calendar.setTime(to); String monthTo = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayTo = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearTo = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + monthFrom + "&b=" + dayFrom + "&c=" + yearFrom + "&d=" + monthTo + "&e=" + dayTo + "&f=" + yearTo + "&g=d&ignore=.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; ArrayList<Quote> result = new ArrayList<Quote>(); reader.readLine(); while ((line = reader.readLine()) != null) { String[] values = line.split(","); String date = values[0]; Date dateQuote = new SimpleDateFormat("yyyy-MM-dd").parse(date); double open = Double.valueOf(values[1]); double high = Double.valueOf(values[2]); double low = Double.valueOf(values[3]); double close = Double.valueOf(values[4]); long volume = Long.valueOf(values[5]); double adjClose = Double.valueOf(values[6]); Quote q = new Quote(dateQuote, open, high, low, close, volume, adjClose); result.add(q); } reader.close(); Collections.reverse(result); return result; } catch (MalformedURLException e) { System.out.println("URL malformee"); } catch (IOException e) { System.out.println("Donnees illisibles"); } catch (ParseException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public static void copy(final File src, final File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
Code Sample 2:
public void writeToStream(String urlString, OutputStream os) { BufferedInputStream input = null; try { URL url = new URL(urlString); System.out.println("Opening stream:" + url.toString()); input = new BufferedInputStream(url.openStream(), 4 * 1024 * 1024); byte[] data = new byte[102400]; int read; while ((read = input.read(data)) != -1) { os.write(data, 0, read); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } }
|
00
|
Code Sample 1:
public void loadJar(final String extName, final String url, final String fileName, final IProgressListener pl) throws Exception { pl.setName(fileName); pl.setProgress(0); pl.setFinished(false); pl.setStarted(true); String installDirName = extDir + File.separator + extName; Log.log("extension installation directory: " + installDirName); File installDir = new File(installDirName); if (!installDir.exists()) { if (!installDir.mkdirs()) { throw new Exception("ExtensionLoader.loadJar: Cannot create install directory: " + installDirName); } } URL downloadURL = new URL(url + fileName); File jarFile = new File(installDirName, fileName); File indexFile = null; long urlTimeStamp = downloadURL.openConnection().getLastModified(); String indexFileName = ""; int idx = fileName.lastIndexOf("."); if (idx > 0) { indexFileName = fileName.substring(0, idx); } else { indexFileName = fileName; } indexFileName = indexFileName + ".idx"; Log.log("index filename: " + indexFileName); boolean isDirty = true; if (jarFile.exists()) { Log.log("extensionfile already exists: " + fileName); indexFile = new File(installDir, indexFileName); if (indexFile.exists()) { Log.log("indexfile already exists"); long cachedTimeStamp = readTimeStamp(indexFile); isDirty = !(cachedTimeStamp == urlTimeStamp); Log.log("cached file dirty: " + isDirty + ", url timestamp: " + urlTimeStamp + " cache stamp: " + cachedTimeStamp); } else { Log.log("indexfile doesn't exist, assume cache is dirty"); } } if (isDirty) { if (jarFile.exists()) { if (indexFile != null && indexFile.exists()) { Log.log("deleting old index file"); indexFile.delete(); } indexFile = new File(installDirName, indexFileName); Log.log("deleting old cached file"); jarFile.delete(); } downloadJar(downloadURL, jarFile, pl); indexFile = new File(installDir, indexFileName); Log.log("writing timestamp to index file"); writeTimeStamp(indexFile, urlTimeStamp); } addJar(jarFile); }
Code Sample 2:
private void getRdfResponse(StringBuilder sb, String url) { try { String inputLine = null; BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); while ((inputLine = reader.readLine()) != null) { sb.append(inputLine); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; String review = request.getParameter("review"); String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String inforId = request.getParameter("inforId"); request.setAttribute("id", inforId); String str_postFIX = ""; int i_p = 0; if (null == review) { FormFile file = vo.getFile(); if (file != null) { String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); String fullPath = realpath + "attach/" + strAppend + str_postFIX; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); return "editsave"; } else { String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); FormFile file = vo.getFile(); FormFile file2 = vo.getFile2(); FormFile file3 = vo.getFile3(); t_infor_review newreview = new t_infor_review(); String content = request.getParameter("content"); newreview.setContent(content); if (null != inforId) newreview.setInfor_id(Integer.parseInt(inforId)); newreview.setInsert_day(new Date()); UserDetails user = LoginUtils.getLoginUser(request); newreview.setCreate_name(user.getUsercode()); if (null != file.getFileName() && !"".equals(file.getFileName())) { newreview.setAttachname1(file.getFileName()); String strAppend1 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file.getFileName().lastIndexOf("."); str_postFIX = file.getFileName().substring(i_p, file.getFileName().length()); newreview.setAttachfullname1(realpath + "attach/" + strAppend1 + str_postFIX); saveFile(file.getInputStream(), realpath + "attach/" + strAppend1 + str_postFIX); } if (null != file2.getFileName() && !"".equals(file2.getFileName())) { newreview.setAttachname2(file2.getFileName()); String strAppend2 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file2.getFileName().lastIndexOf("."); str_postFIX = file2.getFileName().substring(i_p, file2.getFileName().length()); newreview.setAttachfullname2(realpath + "attach/" + strAppend2 + str_postFIX); saveFile(file2.getInputStream(), realpath + "attach/" + strAppend2 + str_postFIX); } if (null != file3.getFileName() && !"".equals(file3.getFileName())) { newreview.setAttachname3(file3.getFileName()); String strAppend3 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); i_p = file3.getFileName().lastIndexOf("."); str_postFIX = file3.getFileName().substring(i_p, file3.getFileName().length()); newreview.setAttachfullname3(realpath + "attach/" + strAppend3 + str_postFIX); saveFile(file3.getInputStream(), realpath + "attach/" + strAppend3 + str_postFIX); } t_infor_review_EditMap reviewEdit = new t_infor_review_EditMap(); reviewEdit.add(newreview); request.setAttribute("review", "1"); return "aftersave"; } }
Code Sample 2:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); getLog().info("Process request " + pathInfo); if (null != pathInfo) { String pathId = getPathId(pathInfo); JobResources res = ContextUtil.getJobResource(pathId); if (null != res) { RequestType requType = getRequestType(request); ResultAccess access = new ResultAccess(res); Collection<Long> uIdColl = res.getUniqIds(); boolean isFiltered = false; { List<String> postSeqIds = getSeqList(request); if (!postSeqIds.isEmpty()) { isFiltered = true; uIdColl = access.loadIds(postSeqIds); } } try { if ((requType.equals(RequestType.FASTA)) || (requType.equals(RequestType.SWISSPROT))) { OutputStreamWriter out = null; out = new OutputStreamWriter(response.getOutputStream()); for (Long uid : uIdColl) { if (requType.equals(RequestType.FASTA)) { SwissProt sw = access.getSwissprotEntry(uid); if (null != sw) { PrintFactory.instance().print(ConvertFactory.instance().SwissProt2fasta(sw), out); } else { System.err.println("Not able to read Swissprot entry " + uid + " in project " + res.getBaseDir()); } } else if (requType.equals(RequestType.SWISSPROT)) { File swissFile = res.getSwissprotFile(uid); if (swissFile.exists()) { InputStream in = null; try { in = new FileInputStream(swissFile); IOUtils.copy(in, out); } catch (IOException e) { e.printStackTrace(); System.err.println("Problems with reading file to output stream " + swissFile); } finally { IOUtils.closeQuietly(in); } } else { System.err.println("Swissprot file does not exist: " + swissFile); } } } out.flush(); } else { if (uIdColl.size() <= 2) { isFiltered = false; uIdColl = res.getUniqIds(); } Tree tree = access.getTreeByUniquId(uIdColl); if (requType.equals(RequestType.TREE)) { response.getWriter().write(tree.toNewHampshireX()); } else if (requType.equals(RequestType.PNG)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); ImageMap map = ImageFactory.instance().createProteinCard(sp, tree, true, res); response.setContentType("image/png"); response.addHeader("Content-Disposition", "filename=ProteinCards.png"); ImageFactory.instance().printPNG(map.getImage(), response.getOutputStream()); response.getOutputStream().flush(); } else if (requType.equals(RequestType.HTML)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); createHtml(res, access, tree, request, response, sp, isFiltered); } } } catch (Exception e) { e.printStackTrace(); getLog().error("Problem with Request: " + pathInfo + "; type " + requType, e); } } else { getLog().error("Resource is null: " + pathId + "; path " + pathInfo); } } else { getLog().error("PathInfo is null!!!"); } }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) { int len; byte[] buffer = new byte[1024]; try { FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len); fin.close(); fout.close(); } catch (IOException ex) { } }
Code Sample 2:
public ServiceAdapterIfc deploy(String session, String name, byte jarBytes[], String jarName, String serviceClass, String serviceInterface) throws RemoteException, MalformedURLException, StartServiceException, SessionException { try { File jarFile = new File(jarName); jarName = jarFile.getName(); String jarName2 = jarName; jarFile = new File(jarName2); int n = 0; while (jarFile.exists()) { jarName2 = jarName + n++; jarFile = new File(jarName2); } FileOutputStream fos = new FileOutputStream(jarName2); IOUtils.copy(new ByteArrayInputStream(jarBytes), fos); SCClassLoader cl = new SCClassLoader(new URL[] { new URL("file://" + jarFile.getAbsolutePath()) }, getMasterNode().getSCClassLoaderCounter()); return startService(session, name, serviceClass, serviceInterface, cl); } catch (SessionException e) { throw e; } catch (Exception e) { throw new StartServiceException("Could not deploy service: " + e.getMessage(), e); } }
|
00
|
Code Sample 1:
public void login(String a_username, String a_password) throws GB_SecurityException { Exception l_exception = null; try { if (clientFtp == null) { clientFtp = new FTPClient(); clientFtp.connect("ftp://" + ftp); } boolean b = clientFtp.login(a_username, a_password); if (b) { username = a_username; password = a_password; return; } } catch (Exception ex) { l_exception = ex; } String l_msg = "Cannot login to ftp server with user [{1}], {2}"; String[] l_replaces = new String[] { a_username, ftp }; l_msg = STools.replace(l_msg, l_replaces); throw new GB_SecurityException(l_msg, l_exception); }
Code Sample 2:
public void setDefaultMailBox(final int domainId, final int userId) { final EmailAddress defaultMailbox = cmDB.getDefaultMailbox(domainId); try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty(defaultMailbox == null ? "domain.setDefaultMailbox" : "domain.updateDefaultMailbox")); if (defaultMailbox == null) { psImpl.setInt(1, domainId); psImpl.setInt(2, userId); } else { psImpl.setInt(1, userId); psImpl.setInt(2, domainId); } psImpl.executeUpdate(); } }); connection.commit(); cmDB.updateDomains(null, null); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
|
00
|
Code Sample 1:
public Component loadComponent(URI uri, URI origuri) throws ComponentException { if (usePrivMan) PrivilegeManager.enablePrivilege("UniversalConnect"); ConzillaRDFModel model = factory.createModel(origuri, uri); RDFParser parser = new com.hp.hpl.jena.rdf.arp.StanfordImpl(); java.net.URL url = null; try { url = uri.getJavaURL(); } catch (java.net.MalformedURLException e) { throw new ComponentException("Invalid URL " + uri + " for component " + origuri + ":\n " + e.getMessage()); } try { InputSource source = new InputSource(url.openStream()); source.setSystemId(origuri.toString()); parser.parse(source, new ModelConsumer(model)); factory.getTotalModel().addModel(model); } catch (org.xml.sax.SAXException se) { se.getException().printStackTrace(); throw new ComponentException("Format error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } catch (java.io.IOException se) { throw new ComponentException("IO error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } catch (org.w3c.rdf.model.ModelException se) { throw new ComponentException("Model error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } return model; }
Code Sample 2:
public static void main(final String[] args) { final Runnable startDerby = new Runnable() { public void run() { try { final NetworkServerControl control = new NetworkServerControl(InetAddress.getByName("localhost"), 1527); control.start(new PrintWriter(System.out)); } catch (final Exception ex) { throw new RuntimeException(ex); } } }; new Thread(startDerby).start(); final Runnable startActiveMq = new Runnable() { public void run() { Main.main(new String[] { "start", "xbean:file:active-mq-config.xml" }); } }; new Thread(startActiveMq).start(); final Runnable startMailServer = new Runnable() { public void run() { final SimpleMessageListener listener = new SimpleMessageListener() { public final boolean accept(final String from, final String recipient) { return true; } public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } } }; final SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(listener)); smtpServer.start(); System.out.println("Started SMTP Server"); } }; new Thread(startMailServer).start(); }
|
00
|
Code Sample 1:
public StringBuffer getReturn(String url_address) { StringBuffer message = new StringBuffer(); try { URL url = new URL(url_address); try { HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.connect(); InputStreamReader insr = new InputStreamReader(httpConnection.getInputStream()); BufferedReader in = new BufferedReader(insr); String temp = in.readLine(); while (temp != null) { message.append(temp + "\n"); temp = in.readLine(); } in.close(); } catch (IOException e) { System.out.println("httpConnecter:Error[" + e + "]"); message.append("Connect error [" + url_address + "]"); } } catch (MalformedURLException e) { message.append("Connect error [" + url_address + "]"); System.out.println("httpConneter:Error[" + e.getMessage() + "]"); } catch (Exception e) { message.append("Connect error [" + url_address + "]"); System.out.println("httpConneter:Error[" + e.getMessage() + "]"); } return message; }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
11
|
Code Sample 1:
private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; }
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); } } } }
|
11
|
Code Sample 1:
public void fileCopy(File inFile, File outFile) { try { FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { System.err.println("Hubo un error de entrada/salida!!!"); } }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException { String zipPath = "C:\\test.zip"; CZipInputStream zip_in = null; try { byte[] c = new byte[1024]; int slen; zip_in = new CZipInputStream(new FileInputStream(zipPath), "utf-8"); do { ZipEntry file = zip_in.getNextEntry(); if (file == null) break; String fileName = file.getName(); System.out.println(fileName); String ext = fileName.substring(fileName.lastIndexOf(".")); long seed = new Date(System.currentTimeMillis()).getTime(); String newFileName = Long.toString(seed) + ext; FileOutputStream out = new FileOutputStream(newFileName); while ((slen = zip_in.read(c, 0, c.length)) != -1) out.write(c, 0, slen); out.close(); } while (true); } catch (ZipException zipe) { zipe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { zip_in.close(); } }
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()); }
|
00
|
Code Sample 1:
protected Ontology loadOntology(String ontologyIri) throws IOException, ParserException, InvalidModelException { assert ontologyIri != null; URL url = null; Ontology ontology = null; url = new URL(ontologyIri); InputStream is = url.openStream(); TopEntity[] identifiable = parser.parse(new InputStreamReader(is)); if (identifiable.length > 0 && identifiable[0] instanceof Ontology) { ontology = ((Ontology) identifiable[0]); } return ontology; }
Code Sample 2:
public static String getHashedPassword(String password) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); BigInteger hashedInt = new BigInteger(1, digest.digest()); return String.format("%1$032X", hashedInt); } catch (NoSuchAlgorithmException nsae) { System.err.println(nsae.getMessage()); } return ""; }
|
11
|
Code Sample 1:
public String getResource(String resourceName) throws IOException { InputStream resourceStream = resourceClass.getResourceAsStream(resourceName); ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); IOUtils.copyAndClose(resourceStream, baos); String expected = new String(baos.toByteArray()); return expected; }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
private int resourceToString(String aFile, StringBuffer aBuffer) { int cols = 0; URL url = getClass().getResource(aFile); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; do { line = in.readLine(); if (line != null) { if (line.length() > cols) cols = line.length(); aBuffer.append(line); aBuffer.append('\n'); } } while (line != null); } catch (IOException e) { e.printStackTrace(); } return cols; }
Code Sample 2:
public static Image getImage(URL url) throws IOException { InputStream is = null; try { is = url.openStream(); Image img = getImage(is); img.setUrl(url); return img; } finally { if (is != null) { is.close(); } } }
|
11
|
Code Sample 1:
public Object downloadFile(File destinationFile, URL[] urls, DownloadListener listener, Object checksum, long length, PRIORITY priority) throws DownloadException { URL url = urls[0]; if (!url.getProtocol().equalsIgnoreCase("http")) { throw new DownloadException(" Only HTTP is supported in this version "); } if (!destinationFile.exists()) { try { destinationFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); throw new DownloadException("Unable to download from URL : " + url.toString()); } } HeadMethod head = new HeadMethod(url.toString()); HttpClient httpClient = new HttpClient(); try { httpClient.executeMethod(head); Header[] headers = head.getResponseHeaders(); for (Header header : headers) { System.out.println(header); } Header header = head.getResponseHeader("Content-Length"); Object contentLength = header.getValue(); Long fileLength = Long.parseLong(contentLength.toString()); System.out.println(length + " : " + fileLength); GetMethod get = new GetMethod(url.toString()); httpClient.executeMethod(get); InputStream ins = get.getResponseBodyAsStream(); FileOutputStream fos = new FileOutputStream(destinationFile); IOUtils.copy(ins, fos); System.out.println(" DOWNLOADED FILE"); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
Code Sample 2:
@Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { String resourceDir = System.getProperty("resourceDir"); File resource = new File(resourceDir, filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (resource.exists()) { in = new FileInputStream(resource); } else { in = LOADER.getResourceAsStream(RES_PKG + filename); } IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
|
00
|
Code Sample 1:
public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
Code Sample 2:
@Override public void run() { String src = null; try { src = File.readText(srcFile); if (Char.isValidate(src)) { java.net.URL url = new java.net.URL(ConsEnv.HOMEPAGE + "code/code0001.ashx"); java.util.HashMap<String, String> params = new java.util.HashMap<String, String>(); String ext = File.getExtension(srcFile.getName()); if (Char.isValidate(ext) && ext.charAt(0) == '.') { ext = ext.substring(1); } params.put("l", ext); params.put("i", "1"); params.put("n", ck_LineNbr.isSelected() ? "1" : "0"); params.put("u", ck_LinkUri.isSelected() ? "1" : "0"); params.put("t", cb_TagStyle.getSelectedItem() + ""); String tab = tf_TabCount.getText().trim(); if (java.util.regex.Pattern.matches("^\\d+$", tab)) { tab = "4"; } params.put("s", tab); params.put("o", "html"); params.put("c", src); java.net.HttpURLConnection con = (java.net.HttpURLConnection) url.openConnection(); java.io.InputStream stream = Http.post(con, params); ep_CodeView.setContentType(con.getContentType()); src = File.readText(stream); stream.close(); con.disconnect(); java.io.File tmpFile = java.io.File.createTempFile("src_", ".html"); tmpFile.deleteOnExit(); File.saveText(tmpFile, src); ep_CodeView.setPage(tmpFile.toURI().toURL()); ep_CodeView.setFont(ep_CodeView.getFont().deriveFont(20f)); } } catch (Exception exp) { Logs.exception(exp); } }
|
00
|
Code Sample 1:
private static GSP loadGSP(URL url) { try { InputStream input = url.openStream(); int c; while ((c = input.read()) != -1) { result = result + (char) c; } Unmarshaller unmarshaller = getUnmarshaller(); unmarshaller.setValidation(false); GSP gsp = (GSP) unmarshaller.unmarshal(new InputSource()); return gsp; } catch (Exception e) { System.out.println("loadGSP " + e); e.printStackTrace(); return null; } }
Code Sample 2:
public static void 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 void testAddingEntries() throws Exception { DiskCache c = new DiskCache(); { c.setRoot(rootFolder.getAbsolutePath()); c.setHtmlExtension("htm"); c.setPropertiesExtension("txt"); assertEquals("htm", c.getHtmlExtension()); assertEquals("txt", c.getPropertiesExtension()); assertEquals(rootFolder.getAbsolutePath(), c.getRoot()); } String key1 = "cat1/key1"; String key2 = "cat1/key2"; try { try { { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(300005L); i.setTranslationCount(10); i.setEncoding("ISO-8859-7"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = new ByteArrayInputStream(greekTextBytes); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } c.storeInCache(key1, i); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key2, null); CacheItem i = c.getOrCreateCacheEntry(key2); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); i.setLastModified(350000L); i.setTranslationCount(11); i.setEncoding("ISO-8859-1"); i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" })); String englishText = "Hello this is another example"; { InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1")); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[29]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test3", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test4", h.getName()); assertEquals("[Value1]", Arrays.toString(h.getValues())); } } } c.storeInCache(key2, i); assertEquals("ISO-8859-1", i.getEncoding()); assertEquals(350000L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertTrue(i.isCached()); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-1"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(englishText, w.toString()); } } { CacheItem i = c.getOrCreateCacheEntry(key1); assertEquals("ISO-8859-7", i.getEncoding()); assertEquals(300005L, i.getLastModified()); assertEquals(10, i.getTranslationCount()); assertTrue(i.isCached()); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[97]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 }; String greekText = new String(greekTextBytes, "ISO-8859-7"); { InputStream input = i.getContentAsStream(); StringWriter w = new StringWriter(); IOUtils.copy(input, w, "ISO-8859-7"); IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); assertEquals(greekText, w.toString()); } } { c.removeCacheEntry(key1, null); CacheItem i = c.getOrCreateCacheEntry(key1); assertNull(i.getEncoding()); assertEquals(-1L, i.getLastModified()); assertEquals(-1, i.getTranslationCount()); assertFalse(i.isCached()); assertNull(i.getHeaders()); } } finally { c.removeCacheEntry(key1, null); } } finally { c.removeCacheEntry(key2, null); } }
Code Sample 2:
public Vector split() { File nextFile = new File(filename); long fileSize = nextFile.length(); long parts = fileSize / splitSize; Vector vec = new Vector(new Long(parts).intValue()); if (debug) { System.out.println("File: " + nextFile.getName() + "\nfileSize: " + fileSize + "\nsplitSize: " + splitSize + "\nparts: " + parts); } if (fileSize % splitSize > 0) { parts++; } try { FileInputStream fis = new FileInputStream(nextFile); DataInputStream dis = new DataInputStream(fis); long bytesRead = 0; File destinationDirectory = new File(nextFile.getParent()); if (!destinationDirectory.exists()) { destinationDirectory.mkdir(); } for (long k = 0; k < parts; k++) { if (debug) { System.out.println("Splitting parts: " + nextFile.getName() + " into part " + k); } String filePartName = nextFile.getName(); filePartName = filePartName + "." + String.valueOf(k); File outputFile = new File(destinationDirectory, filePartName); FileOutputStream fos = new FileOutputStream(outputFile); DataOutputStream dos = new DataOutputStream(fos); long bytesWritten = 0; while ((bytesWritten < splitSize) && (bytesRead < fileSize)) { dos.writeByte(dis.readByte()); bytesRead++; bytesWritten++; } dos.close(); vec.addElement(outputFile.getAbsolutePath()); if (debug) { System.out.println("Wrote " + bytesWritten + " bytes." + outputFile.getName() + " created."); } } } catch (FileNotFoundException fnfe) { System.err.println("FileNotFoundException: " + fnfe.getMessage()); vec = null; } catch (IOException ioe) { System.err.println("IOException: " + ioe.getMessage()); vec = null; } return vec; }
|
00
|
Code Sample 1:
@Override public Representation getRepresentation(Variant variant) { Representation representation = null; MediaType requestMediaType = variant.getMediaType(); if (MediaType.TEXT_XML.equals(requestMediaType)) { try { representation = new DomRepresentation(MediaType.TEXT_XML); } catch (IOException e) { e.printStackTrace(); return null; } } String strJobsUrl = ((ResourceApplication) getApplication()).getJobsUrl(); org.dom4j.Document reportDoc = null; try { SAXReader reader = new SAXReader(); reportDoc = reader.read(strJobsUrl + "/" + strJobId + "/report.xml"); } catch (DocumentException e) { String strErrMsg = "Unable to find job, " + strJobId + ": " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.CLIENT_ERROR_NOT_FOUND, null, "JobNotFound", strErrMsg, null); return rep; } if (MediaType.TEXT_XML.equals(requestMediaType)) { log.debug("XML Media Type requested"); try { reportDoc.removeProcessingInstruction("xml-stylesheet"); DOMWriter writer = new DOMWriter(); Document doc = writer.write(reportDoc); doc.normalizeDocument(); ((DomRepresentation) representation).setDocument(doc); return representation; } catch (DocumentException e) { String strErrMsg = "Error display job's report: " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.CLIENT_ERROR_CONFLICT, null, "ClientConflict", strErrMsg, null); return rep; } } else if (MediaType.TEXT_HTML.equals(requestMediaType)) { log.debug("HTML Media Type requested"); try { ProcessingInstruction pi = reportDoc.processingInstruction("xml-stylesheet"); if (pi != null) { String strXslHref = pi.getValue("href"); URL url = new URL(strXslHref); XSLTransformer reportDocTransformer = new XSLTransformer(); log.debug("constructed the reportDocTransformer"); reportDoc = reportDocTransformer.transform(reportDoc, url.openStream()); } } catch (MalformedURLException e) { String strErrMsg = "Error accessing referenced XSL-STYLESHEET: " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.SERVER_ERROR_INTERNAL, null, "InternalError", strErrMsg, null); return rep; } catch (IOException e) { String strErrMsg = "Error accessing referenced XSL-STYLESHEET: " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.SERVER_ERROR_INTERNAL, null, "InternalError", strErrMsg, null); return rep; } catch (FedoraAPIException e) { String strErrMsg = "Error accessing referenced XSL-STYLESHEET: " + e.getMessage(); log.debug(strErrMsg); Representation rep = SetRepositoryMessage(Status.SERVER_ERROR_INTERNAL, null, "InternalError", strErrMsg, null); return rep; } representation = new StringRepresentation(reportDoc.asXML(), MediaType.TEXT_HTML); return representation; } return null; }
Code Sample 2:
public void reqservmodif(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { try { System.err.println(req.getSession().getServletContext().getRealPath("WEB-INF/syncWork")); File tempFile = File.createTempFile("localmodif-", ".medoorequest"); OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); tempFile.delete(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } catch (ImogSerializationException ex) { logger.error(ex.getMessage()); } }
|
11
|
Code Sample 1:
protected boolean loadJarLibrary(final String jarLib) { final String tempLib = System.getProperty("java.io.tmpdir") + File.separator + jarLib; boolean copied = IOUtils.copyFile(jarLib, tempLib); if (!copied) { return false; } System.load(tempLib); return true; }
Code Sample 2:
private void writeInputStreamToFile(InputStream stream, File file) { try { FileOutputStream fOut = new FileOutputStream(file); IOUtils.copy(stream, fOut); fOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
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:
private void importSources() { InputOutput io = IOProvider.getDefault().getIO("Import Sources", false); io.select(); PrintWriter pw = new PrintWriter(io.getOut()); pw.println("Beginning transaction...."); pw.println("Processing selected files:"); String[][] selectedFiles = getSelectedFiles(pw); if (selectedFiles.length == 0) { pw.println("There are no files to process."); } else { pw.println(new StringBuilder("Importing ").append(selectedFiles.length).append(" files to ").append(group.getDisplayName()).append(" within project ").append(ProjectUtils.getInformation(project).getDisplayName()).toString()); FileObject destFO = group.getRootFolder(); try { String destRootDir = new File(destFO.getURL().toURI()).getAbsolutePath(); if (destFO.canWrite()) { for (String[] s : selectedFiles) { try { File parentDir = new File(new StringBuilder(destRootDir).append(File.separator).append(s[0]).toString()); if (!parentDir.exists()) { parentDir.mkdirs(); } File f = new File(new StringBuilder(destRootDir).append(s[0]).append(File.separator).append(s[1]).toString()); if (!f.exists()) { f.createNewFile(); } FileInputStream fin = null; FileOutputStream fout = null; byte[] b = new byte[1024]; int read = -1; try { File inputFile = new File(new StringBuilder(rootDir).append(s[0]).append(File.separator).append(s[1]).toString()); pw.print(new StringBuilder("\tImporting file:").append(inputFile.getAbsolutePath()).toString()); fin = new FileInputStream(inputFile); fout = new FileOutputStream(f); while ((read = fin.read(b)) != -1) { fout.write(b, 0, read); } pw.println(" ... done"); fin.close(); fout.close(); } catch (FileNotFoundException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } finally { if (fin != null) { try { fin.close(); } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } } if (fout != null) { try { fout.close(); } catch (IOException ex) { } } } } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } } pw.println("Import sources completed successfully."); } else { pw.println("Cannot write to the destination directory." + " Please check the priviledges and try again."); return; } } catch (FileStateInvalidException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); pw.println("Import failed!!"); } catch (URISyntaxException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); pw.println("Import failed!!"); } } }
|
00
|
Code Sample 1:
public static String encrypt(String plaintext) throws NoSuchAlgorithmException { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { logger.error("unable to encrypt password" + e.getMessage()); throw new NoSuchAlgorithmException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("unable to encrypt password" + e.getMessage()); throw new NoSuchAlgorithmException(e.getMessage()); } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
Code Sample 2:
protected void assignListeners() { groupsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent event) { refreshInfo(); } }); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showSaveDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); ReaderWriterGroup.write(out, writer); System.err.println("Wrote groups informations to output '" + fileName + "'."); out.close(); } catch (IOException e) { System.err.println("error while writing (GroupManager.saveClt):"); e.printStackTrace(); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showOpenDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); BufferedReader fileReader = null; try { fileReader = new BufferedReader(new FileReader(fileName)); ReaderWriterGroup.read(fileReader, writer); fileReader.close(); } catch (Exception e) { System.err.println("Exception while reading from file '" + fileName + "'."); System.err.println(e); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); ItemListener propItemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { int[] indices = groupsList.getSelectedIndices(); for (int index : indices) { Group group = getGroupFromListIndex(index); if (group != null) { if (event.getSource() instanceof JComboBox) { JComboBox eventSource = (JComboBox) event.getSource(); if (eventSource == colorComboBox) { Color color = colorComboBox.getSelectedColor(); assert (color != null); group.setColor(color); shapeComboBox.setColor(color); } else if (eventSource == shapeComboBox) { Shape shape = shapeComboBox.getSelectedShape(); assert (shape != null); group.setShape(shape); } } else if (event.getSource() instanceof JCheckBox) { JCheckBox eventSource = (JCheckBox) event.getSource(); if (eventSource == showGroupCheckBox) { group.visible = showGroupCheckBox.isSelected(); } else if (eventSource == showGraphicInfoCheckBox) { group.info = showGraphicInfoCheckBox.isSelected(); } } } } graph.notifyAboutGroupsChange(null); } }; colorComboBox.addItemListener(propItemListener); shapeComboBox.addItemListener(propItemListener); showGroupCheckBox.addItemListener(propItemListener); showGraphicInfoCheckBox.addItemListener(propItemListener); showGroupfreeNodesCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { graph.getGroup(0).visible = showGroupfreeNodesCheckBox.isSelected(); graph.notifyAboutGroupsChange(null); } }); ActionListener propActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton botton = (JButton) event.getSource(); Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { for (GraphVertex graphVertex : group) { if (botton == showLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, true); } else if (botton == hideLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, false); } } graph.notifyAboutGroupsChange(null); } } }; showLabelsButton.addActionListener(propActionListener); hideLabelsButton.addActionListener(propActionListener); newButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String newGroupName = JOptionPane.showInputDialog(null, "Enter a name", "Name of the new group", JOptionPane.QUESTION_MESSAGE); if (newGroupName != null) { if (graph.getGroup(newGroupName) == null) { graph.addGroup(new Group(newGroupName, graph)); } } } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { DialogEditGroup dialog = new DialogEditGroup(graph, group); dialog.setModal(true); dialog.setVisible(true); } } }); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index > 0 && index < graph.getNumberOfGroups() - 1) { graph.removeGroup(index); } } }); upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupUp(index); groupsList.setSelectedIndex(index - 1); } } }); downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupDown(index); groupsList.setSelectedIndex(index + 1); } } }); }
|
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:
private Document saveFile(Document document, File file) throws Exception { List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { preference = preferences.get(0); } SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File folder = new File(sbRepo.append(sbFolder).toString()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } return document; }
|
11
|
Code Sample 1:
public String calculateProjectMD5(String scenarioName) throws Exception { Scenario s = ScenariosManager.getInstance().getScenario(scenarioName); s.loadParametersAndValues(); String scenarioMD5 = calculateScenarioMD5(s); Map<ProjectComponent, String> map = getProjectMD5(new ProjectComponent[] { ProjectComponent.resources, ProjectComponent.classes, ProjectComponent.suts, ProjectComponent.libs }); map.put(ProjectComponent.currentScenario, scenarioMD5); MessageDigest md = MessageDigest.getInstance("MD5"); Iterator<String> iter = map.values().iterator(); while (iter.hasNext()) { md.update(iter.next().getBytes()); } byte[] hash = md.digest(); BigInteger result = new BigInteger(hash); String rc = result.toString(16); return rc; }
Code Sample 2:
private static String createBoundary(int number) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } digest.update(String.valueOf(Math.random()).getBytes()); digest.update(String.valueOf(System.currentTimeMillis()).getBytes()); digest.update(String.valueOf(digest.hashCode()).getBytes()); byte[] bytes = digest.digest(); String paddedNumber = Integer.toString(number); paddedNumber = ("0000000000".substring(0, 10 - paddedNumber.length()) + paddedNumber); StringBuffer buffer = new StringBuffer(); buffer.append("---------------------------------=__"); for (int i = 0; i < 8; i++) { String hex = Integer.toHexString((bytes[i] & 0xff) + 0x100).substring(1); buffer.append(hex); } buffer.append('_'); buffer.append(paddedNumber); return buffer.toString(); }
|
00
|
Code Sample 1:
public boolean consolidateCrossrefGet(BiblioItem bib, ArrayList<BiblioItem> bib2) throws Exception { boolean result = false; String doi = bib.getDOI(); String aut = bib.getFirstAuthorSurname(); String title = bib.getTitle(); String firstPage = null; String pageRange = bib.getPageRange(); int beginPage = bib.getBeginPage(); if (beginPage != -1) { firstPage = "" + beginPage; } else if (pageRange != null) { StringTokenizer st = new StringTokenizer(pageRange, "--"); if (st.countTokens() == 2) { firstPage = st.nextToken(); } else if (st.countTokens() == 1) firstPage = pageRange; } if (aut != null) { aut = TextUtilities.removeAccents(aut); } if (title != null) { title = TextUtilities.removeAccents(title); } if (doi != null) { if (doi.startsWith("doi:") | doi.startsWith("DOI:")) { doi.substring(4, doi.length()); doi = doi.trim(); } doi = doi.replace(" ", ""); String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL3); pstmt.setString(1, doi); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF CACHE"); throw new GROBIDServiceException("EXCEPTION HANDLING CROSSREF CACHE.", se); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { String subpath = String.format(DOI_BASE_QUERY, crossref_id, crossref_pw, doi); URL url = new URL("http://" + crossref_host + "/" + subpath); System.out.println("Sending: " + url.toString()); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { urlConn = null; throw new GROBIDServiceException("An exception occured while running Grobid.", e2); } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, " + "but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL3); pstmt2.setString(1, doi); pstmt2.setString(2, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } else if ((title != null) & (aut != null)) { String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL); pstmt.setString(1, aut); pstmt.setString(2, title); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { throw new GROBIDServiceException("EXCEPTION HANDLING CROSSREF CACHE", se); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { String subpath = String.format(TITLE_BASE_QUERY, crossref_id, crossref_pw, URLEncoder.encode(title), URLEncoder.encode(aut)); URL url = new URL("http://" + crossref_host + "/" + subpath); System.out.println("Sending: " + url.toString()); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { urlConn = null; throw new GROBIDServiceException("An exception occured while running Grobid.", e2); } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, " + "but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL); pstmt2.setString(1, aut); pstmt2.setString(2, bib.getTitle()); pstmt2.setString(3, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } else if ((firstPage != null) & (bib.getJournal() != null) & (bib.getVolume() != null)) { String subpath = String.format(JOURNAL_BASE_QUERY, crossref_id, crossref_pw, URLEncoder.encode(bib.getJournal()), URLEncoder.encode(bib.getVolume()), firstPage); URL url = new URL("http://" + crossref_host + "/" + subpath); String urlmsg = url.toString(); System.out.println(urlmsg); String xml = null; if (cCon != null) { PreparedStatement pstmt = null; try { pstmt = cCon.prepareStatement(QUERY_CROSSREF_SQL2); pstmt.setString(1, urlmsg); ResultSet res = pstmt.executeQuery(); if (res.next()) { xml = res.getString(1); } res.close(); pstmt.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF CACHE"); throw new GROBIDServiceException("EXCEPTION HANDLING CROSSREF CACHE.", se); } finally { try { if (pstmt != null) pstmt.close(); } catch (SQLException se) { } } if (xml != null) { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); parser.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } } } if (xml == null) { System.out.println("Sending: " + urlmsg); HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { this.setProxy(); try { urlConn = (HttpURLConnection) url.openConnection(); } catch (Exception e2) { urlConn = null; throw new GROBIDServiceException("An exception occured while running Grobid.", e2); } } if (urlConn != null) { try { urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); InputStream in = urlConn.getInputStream(); xml = TextUtilities.convertStreamToString(in); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); DefaultHandler crossref = new crossrefUnixrefSaxParser(bib2); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser p = spf.newSAXParser(); p.parse(is, crossref); if (bib2.size() > 0) { if (!bib2.get(0).getError()) result = true; } in.close(); urlConn.disconnect(); } catch (Exception e) { System.err.println("Warning: Consolidation set true, " + "but the online connection to Crossref fails."); } if (cCon != null) { PreparedStatement pstmt2 = null; try { pstmt2 = cCon.prepareStatement(INSERT_CROSSREF_SQL2); pstmt2.setString(1, urlmsg); pstmt2.setString(2, xml); pstmt2.executeUpdate(); pstmt2.close(); } catch (SQLException se) { System.err.println("EXCEPTION HANDLING CROSSREF UPDATE"); } finally { try { if (pstmt2 != null) pstmt2.close(); } catch (SQLException se) { } } } } } } return result; }
Code Sample 2:
private void setup() { env = new EnvAdvanced(); try { URL url = Sysutil.getURL("world.env"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[0].equalsIgnoreCase("skybox")) { env.setRoom(new EnvSkyRoom(fields[1])); } else if (fields[0].equalsIgnoreCase("camera")) { env.setCameraXYZ(Double.parseDouble(fields[1]), Double.parseDouble(fields[2]), Double.parseDouble(fields[3])); env.setCameraYaw(Double.parseDouble(fields[4])); env.setCameraPitch(Double.parseDouble(fields[5])); } else if (fields[0].equalsIgnoreCase("terrain")) { terrain = new EnvTerrain(fields[1]); terrain.setTexture(fields[2]); env.addObject(terrain); } else if (fields[0].equalsIgnoreCase("object")) { GameObject n = (GameObject) Class.forName(fields[10]).newInstance(); n.setX(Double.parseDouble(fields[1])); n.setY(Double.parseDouble(fields[2])); n.setZ(Double.parseDouble(fields[3])); n.setScale(Double.parseDouble(fields[4])); n.setRotateX(Double.parseDouble(fields[5])); n.setRotateY(Double.parseDouble(fields[6])); n.setRotateZ(Double.parseDouble(fields[7])); n.setTexture(fields[9]); n.setModel(fields[8]); n.setEnv(env); env.addObject(n); } } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
@Override public void alterar(QuestaoDiscursiva q) throws Exception { System.out.println("ALTERAR " + q.getIdQuestao()); PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoDiscursiva(q); } catch (SQLException e) { conexao.rollback(); throw e; } }
Code Sample 2:
private Element getXmlFromGeoNetwork(String urlIn, Session userSession) throws FailedActionException { Element results = null; try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); String cookie = (String) userSession.getAttribute("usercookie.object"); if (cookie != null) conn.setRequestProperty("Cookie", cookie); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); } finally { in.close(); } } catch (Exception e) { throw new FailedActionException(FailedActionReason.SYSTEM_ERROR); } return results; }
|
00
|
Code Sample 1:
public static InputStream downloadStream(URL url) { InputStream inputStream = null; try { URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setFollowRedirects(true); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) return null; } return urlConnection.getInputStream(); } catch (Exception ex) { try { inputStream.close(); } catch (Exception ex1) { } return null; } }
Code Sample 2:
private void extractSpecifications(String id, File specification) { Object resource = getClass().getResource(id + ".xml"); if (resource instanceof URL) { URL url = (URL) resource; try { InputStream istream = url.openStream(); try { OutputStream ostream = new FileOutputStream(specification); try { byte[] buffer = new byte[1024]; int length; while ((length = istream.read(buffer)) > 0) { ostream.write(buffer, 0, length); } } finally { ostream.close(); } } finally { istream.close(); } } catch (IOException ex) { throw new RuntimeException("Failed to open " + url, ex); } } }
|
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 boolean copyFile(File from, File to, byte[] buf) { if (buf == null) buf = new byte[BUFFER_SIZE]; FileInputStream from_s = null; FileOutputStream to_s = null; try { from_s = new FileInputStream(from); to_s = new FileOutputStream(to); for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead); from_s.close(); from_s = null; to_s.getFD().sync(); to_s.close(); to_s = null; } catch (IOException ioe) { return false; } finally { if (from_s != null) { try { from_s.close(); } catch (IOException ioe) { } } if (to_s != null) { try { to_s.close(); } catch (IOException ioe) { } } } return true; }
|
00
|
Code Sample 1:
public TestReport runImpl() throws Exception { DefaultTestReport report = new DefaultTestReport(this); ParsedURL purl; try { purl = new ParsedURL(base); } catch (Exception e) { StringWriter trace = new StringWriter(); e.printStackTrace(new PrintWriter(trace)); report.setErrorCode(ERROR_CANNOT_PARSE_URL); report.setDescription(new TestReport.Entry[] { new TestReport.Entry(TestMessages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null), TestMessages.formatMessage(ERROR_CANNOT_PARSE_URL, new String[] { "null", base, trace.toString() })) }); report.setPassed(false); return report; } byte[] data = new byte[5]; int num = 0; try { InputStream is = purl.openStream(); num = is.read(data); } catch (IOException ioe) { ioe.printStackTrace(); } StringBuffer sb = new StringBuffer(); for (int i = 0; i < num; i++) { int val = ((int) data[i]) & 0xFF; if (val < 16) { sb.append("0"); } sb.append(Integer.toHexString(val) + " "); } String info = ("CT: " + purl.getContentType() + " CE: " + purl.getContentEncoding() + " DATA: " + sb + "URL: " + purl); if (ref.equals(info)) { report.setPassed(true); return report; } report.setErrorCode(ERROR_WRONG_RESULT); report.setDescription(new TestReport.Entry[] { new TestReport.Entry(TestMessages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null), TestMessages.formatMessage(ERROR_WRONG_RESULT, new String[] { info, ref })) }); report.setPassed(false); return report; }
Code Sample 2:
private void removeSessionId(InputStream inputStream, Output output) throws IOException { String jsessionid = RewriteUtils.getSessionId(target); boolean textContentType = ResourceUtils.isTextContentType(httpClientResponse.getHeader(HttpHeaders.CONTENT_TYPE), target.getDriver().getConfiguration().getParsableContentTypes()); if (jsessionid == null || !textContentType) { IOUtils.copy(inputStream, output.getOutputStream()); } else { String charset = httpClientResponse.getContentCharset(); if (charset == null) { charset = "ISO-8859-1"; } String content = IOUtils.toString(inputStream, charset); content = removeSessionId(jsessionid, content); if (output.getHeader(HttpHeaders.CONTENT_LENGTH) != null) { output.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(content.length())); } OutputStream outputStream = output.getOutputStream(); IOUtils.write(content, outputStream, charset); } inputStream.close(); }
|
00
|
Code Sample 1:
static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } }
Code Sample 2:
public void run() { try { URL url = new URL("http://pokedev.org/time.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringTokenizer s = new StringTokenizer(in.readLine()); m_day = Integer.parseInt(s.nextToken()); m_hour = Integer.parseInt(s.nextToken()); m_minutes = Integer.parseInt(s.nextToken()); in.close(); } catch (Exception e) { System.out.println("ERROR: Cannot reach time server, reverting to local time"); Calendar cal = Calendar.getInstance(); m_hour = cal.get(Calendar.HOUR_OF_DAY); m_minutes = 0; m_day = 0; } while (m_isRunning) { m_minutes = m_minutes == 59 ? 0 : m_minutes + 1; if (m_minutes == 0) { if (m_hour == 23) { incrementDay(); m_hour = 0; } else { m_hour += 1; } } m_hour = m_hour == 23 ? 0 : m_hour + 1; if (System.currentTimeMillis() - m_lastWeatherUpdate >= 3600000) { generateWeather(); m_lastWeatherUpdate = System.currentTimeMillis(); } try { Thread.sleep(60000); } catch (Exception e) { } } System.out.println("INFO: Time Service stopped"); }
|
00
|
Code Sample 1:
public static Model downloadModel(String url) { Model model = ModelFactory.createDefaultModel(); try { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestProperty("Accept", "application/rdf+xml, */*;q=.1"); httpConnection.setRequestProperty("Accept-Language", "en"); } InputStream in = connection.getInputStream(); model.read(in, url); in.close(); return model; } catch (MalformedURLException e) { logger.debug("Unable to download model from " + url, e); throw new RuntimeException(e); } catch (IOException e) { logger.debug("Unable to download model from " + url, e); throw new RuntimeException(e); } }
Code Sample 2:
public boolean download(String url) { HttpGet httpGet = new HttpGet(url); String filename = FileUtils.replaceNonAlphanumericCharacters(url); String completePath = directory + File.separatorChar + filename; int retriesLeft = MAX_RETRIES; while (retriesLeft > 0) { try { HttpResponse response = httpClient.execute(httpGet); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { logger.info("Downloading file from " + url + " -> " + completePath); IOUtils.copy(resEntity.getContent(), new FileOutputStream(completePath)); logger.info("File " + filename + " was downloaded successfully."); setFileSize(new File(completePath).length()); setFilename(filename); return true; } else { logger.warn("Trouble downloading file from " + url + ". Status was: " + response.getStatusLine()); } } catch (ClientProtocolException e) { logger.error("Protocol error. This is probably serious, and there's no need " + "to continue trying to download this file.", e); return false; } catch (IOException e) { logger.warn("IO trouble: " + e.getMessage() + ". Retries left: " + retriesLeft); } retriesLeft--; } return false; }
|
00
|
Code Sample 1:
public TestReport runImpl() throws Exception { DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parserClassName); File f = (new File(testFileName)); URL url = f.toURL(); Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream()); Element e = doc.getElementById(targetId); if (e == null) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(ERROR_GET_ELEMENT_BY_ID_FAILED); report.addDescriptionEntry(ENTRY_KEY_ID, targetId); report.setPassed(false); return report; } e.setAttribute(targetAttribute, targetValue); if (targetValue.equals(e.getAttribute(targetAttribute))) { return reportSuccess(); } DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(TestReport.ERROR_TEST_FAILED); report.setPassed(false); return report; }
Code Sample 2:
public Object run() { if (type == GET_THEME_DIR) { String sep = File.separator; String[] dirs = new String[] { userHome + sep + ".themes", System.getProperty("swing.metacitythemedir"), "/usr/share/themes", "/usr/gnome/share/themes", "/opt/gnome2/share/themes" }; URL themeDir = null; for (int i = 0; i < dirs.length; i++) { if (dirs[i] == null) { continue; } File dir = new File(dirs[i] + sep + arg + sep + "metacity-1"); if (new File(dir, "metacity-theme-1.xml").canRead()) { try { themeDir = dir.toURL(); } catch (MalformedURLException ex) { themeDir = null; } break; } } if (themeDir == null) { String filename = "resources/metacity/" + arg + "/metacity-1/metacity-theme-1.xml"; URL url = getClass().getResource(filename); if (url != null) { String str = url.toString(); try { themeDir = new URL(str.substring(0, str.lastIndexOf('/')) + "/"); } catch (MalformedURLException ex) { themeDir = null; } } } return themeDir; } else if (type == GET_USER_THEME) { try { userHome = System.getProperty("user.home"); String theme = System.getProperty("swing.metacitythemename"); if (theme != null) { return theme; } URL url = new URL(new File(userHome).toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); Reader reader = new InputStreamReader(url.openStream(), "ISO-8859-1"); char[] buf = new char[1024]; StringBuffer strBuf = new StringBuffer(); int n; while ((n = reader.read(buf)) >= 0) { strBuf.append(buf, 0, n); } reader.close(); String str = strBuf.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); int i = strLowerCase.indexOf("<entry name=\"theme\""); if (i >= 0) { i = strLowerCase.indexOf("<stringvalue>", i); if (i > 0) { i += "<stringvalue>".length(); int i2 = str.indexOf("<", i); return str.substring(i, i2); } } } } catch (MalformedURLException ex) { } catch (IOException ex) { } return null; } else if (type == GET_IMAGE) { return new ImageIcon((URL) arg).getImage(); } else { return null; } }
|
00
|
Code Sample 1:
public void download() { try { URL url = new URL(srcURL + src); URLConnection urlc = url.openConnection(); InputStream is = urlc.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); FileOutputStream fos = new FileOutputStream(dest); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffer = new byte[1000000]; int readSize; readSize = bis.read(buffer); while (readSize > 0) { bos.write(buffer, 0, readSize); readSize = bis.read(buffer); } bos.close(); fos.close(); bis.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public boolean verifySignature() { try { byte[] data = readFile(name + ".tmp1.bin"); if (data == null) return false; if (data[data.length - 0x104] != 'N' || data[data.length - 0x103] != 'G' || data[data.length - 0x102] != 'I' || data[data.length - 0x101] != 'S') return false; byte[] signature = new byte[0x100]; byte[] module = new byte[data.length - 0x104]; System.arraycopy(data, data.length - 0x100, signature, 0, 0x100); System.arraycopy(data, 0, module, 0, data.length - 0x104); BigIntegerEx power = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { 0x01, 0x00, 0x01, 0x00 }); BigIntegerEx mod = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, new byte[] { (byte) 0x6B, (byte) 0xCE, (byte) 0xF5, (byte) 0x2D, (byte) 0x2A, (byte) 0x7D, (byte) 0x7A, (byte) 0x67, (byte) 0x21, (byte) 0x21, (byte) 0x84, (byte) 0xC9, (byte) 0xBC, (byte) 0x25, (byte) 0xC7, (byte) 0xBC, (byte) 0xDF, (byte) 0x3D, (byte) 0x8F, (byte) 0xD9, (byte) 0x47, (byte) 0xBC, (byte) 0x45, (byte) 0x48, (byte) 0x8B, (byte) 0x22, (byte) 0x85, (byte) 0x3B, (byte) 0xC5, (byte) 0xC1, (byte) 0xF4, (byte) 0xF5, (byte) 0x3C, (byte) 0x0C, (byte) 0x49, (byte) 0xBB, (byte) 0x56, (byte) 0xE0, (byte) 0x3D, (byte) 0xBC, (byte) 0xA2, (byte) 0xD2, (byte) 0x35, (byte) 0xC1, (byte) 0xF0, (byte) 0x74, (byte) 0x2E, (byte) 0x15, (byte) 0x5A, (byte) 0x06, (byte) 0x8A, (byte) 0x68, (byte) 0x01, (byte) 0x9E, (byte) 0x60, (byte) 0x17, (byte) 0x70, (byte) 0x8B, (byte) 0xBD, (byte) 0xF8, (byte) 0xD5, (byte) 0xF9, (byte) 0x3A, (byte) 0xD3, (byte) 0x25, (byte) 0xB2, (byte) 0x66, (byte) 0x92, (byte) 0xBA, (byte) 0x43, (byte) 0x8A, (byte) 0x81, (byte) 0x52, (byte) 0x0F, (byte) 0x64, (byte) 0x98, (byte) 0xFF, (byte) 0x60, (byte) 0x37, (byte) 0xAF, (byte) 0xB4, (byte) 0x11, (byte) 0x8C, (byte) 0xF9, (byte) 0x2E, (byte) 0xC5, (byte) 0xEE, (byte) 0xCA, (byte) 0xB4, (byte) 0x41, (byte) 0x60, (byte) 0x3C, (byte) 0x7D, (byte) 0x02, (byte) 0xAF, (byte) 0xA1, (byte) 0x2B, (byte) 0x9B, (byte) 0x22, (byte) 0x4B, (byte) 0x3B, (byte) 0xFC, (byte) 0xD2, (byte) 0x5D, (byte) 0x73, (byte) 0xE9, (byte) 0x29, (byte) 0x34, (byte) 0x91, (byte) 0x85, (byte) 0x93, (byte) 0x4C, (byte) 0xBE, (byte) 0xBE, (byte) 0x73, (byte) 0xA9, (byte) 0xD2, (byte) 0x3B, (byte) 0x27, (byte) 0x7A, (byte) 0x47, (byte) 0x76, (byte) 0xEC, (byte) 0xB0, (byte) 0x28, (byte) 0xC9, (byte) 0xC1, (byte) 0xDA, (byte) 0xEE, (byte) 0xAA, (byte) 0xB3, (byte) 0x96, (byte) 0x9C, (byte) 0x1E, (byte) 0xF5, (byte) 0x6B, (byte) 0xF6, (byte) 0x64, (byte) 0xD8, (byte) 0x94, (byte) 0x2E, (byte) 0xF1, (byte) 0xF7, (byte) 0x14, (byte) 0x5F, (byte) 0xA0, (byte) 0xF1, (byte) 0xA3, (byte) 0xB9, (byte) 0xB1, (byte) 0xAA, (byte) 0x58, (byte) 0x97, (byte) 0xDC, (byte) 0x09, (byte) 0x17, (byte) 0x0C, (byte) 0x04, (byte) 0xD3, (byte) 0x8E, (byte) 0x02, (byte) 0x2C, (byte) 0x83, (byte) 0x8A, (byte) 0xD6, (byte) 0xAF, (byte) 0x7C, (byte) 0xFE, (byte) 0x83, (byte) 0x33, (byte) 0xC6, (byte) 0xA8, (byte) 0xC3, (byte) 0x84, (byte) 0xEF, (byte) 0x29, (byte) 0x06, (byte) 0xA9, (byte) 0xB7, (byte) 0x2D, (byte) 0x06, (byte) 0x0B, (byte) 0x0D, (byte) 0x6F, (byte) 0x70, (byte) 0x9E, (byte) 0x34, (byte) 0xA6, (byte) 0xC7, (byte) 0x31, (byte) 0xBE, (byte) 0x56, (byte) 0xDE, (byte) 0xDD, (byte) 0x02, (byte) 0x92, (byte) 0xF8, (byte) 0xA0, (byte) 0x58, (byte) 0x0B, (byte) 0xFC, (byte) 0xFA, (byte) 0xBA, (byte) 0x49, (byte) 0xB4, (byte) 0x48, (byte) 0xDB, (byte) 0xEC, (byte) 0x25, (byte) 0xF3, (byte) 0x18, (byte) 0x8F, (byte) 0x2D, (byte) 0xB3, (byte) 0xC0, (byte) 0xB8, (byte) 0xDD, (byte) 0xBC, (byte) 0xD6, (byte) 0xAA, (byte) 0xA6, (byte) 0xDB, (byte) 0x6F, (byte) 0x7D, (byte) 0x7D, (byte) 0x25, (byte) 0xA6, (byte) 0xCD, (byte) 0x39, (byte) 0x6D, (byte) 0xDA, (byte) 0x76, (byte) 0x0C, (byte) 0x79, (byte) 0xBF, (byte) 0x48, (byte) 0x25, (byte) 0xFC, (byte) 0x2D, (byte) 0xC5, (byte) 0xFA, (byte) 0x53, (byte) 0x9B, (byte) 0x4D, (byte) 0x60, (byte) 0xF4, (byte) 0xEF, (byte) 0xC7, (byte) 0xEA, (byte) 0xAC, (byte) 0xA1, (byte) 0x7B, (byte) 0x03, (byte) 0xF4, (byte) 0xAF, (byte) 0xC7 }); byte[] result = new BigIntegerEx(BigIntegerEx.LITTLE_ENDIAN, signature).modPow(power, mod).toByteArray(); byte[] digest; byte[] properResult = new byte[0x100]; for (int i = 0; i < properResult.length; i++) properResult[i] = (byte) 0xBB; MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(module); md.update("MAIEV.MOD".getBytes()); digest = md.digest(); System.arraycopy(digest, 0, properResult, 0, digest.length); for (int i = 0; i < result.length; i++) if (result[i] != properResult[i]) return false; return true; } catch (Exception e) { System.out.println("Failed to verify signature: " + e.toString()); } return false; }
|
11
|
Code Sample 1:
public static String httpGetJson(final List<NameValuePair> nameValuePairs) { HttpClient httpclient = null; String data = ""; URI uri = null; try { final String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); if (HTTPS) { final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final HttpParams params = new BasicHttpParams(); final SingleClientConnManager mgr = new SingleClientConnManager(params, schemeRegistry); httpclient = new DefaultHttpClient(mgr, params); uri = new URI(DEADDROPS_SERVER_URL_HTTPS + "?" + paramString); } else { httpclient = new DefaultHttpClient(); uri = new URI(DEADDROPS_SERVER_URL + "?" + paramString); } final HttpGet request = new HttpGet(); request.setURI(uri); final HttpResponse response = httpclient.execute(request); final BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; while ((inputLine = in.readLine()) != null) data += inputLine; in.close(); } catch (final URISyntaxException e) { e.printStackTrace(); return null; } catch (final ClientProtocolException e) { e.printStackTrace(); return null; } catch (final IOException e) { e.printStackTrace(); return null; } return data; }
Code Sample 2:
public static ArrayList<Quote> fetchAllQuotes(String symbol, Date from, Date to) { try { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(from); String monthFrom = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayFrom = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearFrom = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); calendar.setTime(to); String monthTo = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString(); String dayTo = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString(); String yearTo = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString(); URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + monthFrom + "&b=" + dayFrom + "&c=" + yearFrom + "&d=" + monthTo + "&e=" + dayTo + "&f=" + yearTo + "&g=d&ignore=.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; ArrayList<Quote> result = new ArrayList<Quote>(); reader.readLine(); while ((line = reader.readLine()) != null) { String[] values = line.split(","); String date = values[0]; Date dateQuote = new SimpleDateFormat("yyyy-MM-dd").parse(date); double open = Double.valueOf(values[1]); double high = Double.valueOf(values[2]); double low = Double.valueOf(values[3]); double close = Double.valueOf(values[4]); long volume = Long.valueOf(values[5]); double adjClose = Double.valueOf(values[6]); Quote q = new Quote(dateQuote, open, high, low, close, volume, adjClose); result.add(q); } reader.close(); Collections.reverse(result); return result; } catch (MalformedURLException e) { System.out.println("URL malformee"); } catch (IOException e) { System.out.println("Donnees illisibles"); } catch (ParseException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public ProcessorOutput createOutput(String name) { ProcessorOutput output = new ProcessorImpl.CacheableTransformerOutputImpl(getClass(), name) { protected void readImpl(org.orbeon.oxf.pipeline.api.PipelineContext context, final ContentHandler contentHandler) { ProcessorInput i = getInputByName(INPUT_DATA); try { Grammar grammar = (Grammar) readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader() { public Object read(org.orbeon.oxf.pipeline.api.PipelineContext context, ProcessorInput input) { final Locator[] locator = new Locator[1]; GrammarReader grammarReader = new XMLSchemaReader(new GrammarReaderController() { public void error(Locator[] locators, String s, Exception e) { throw new ValidationException(s, e, new LocationData(locators[0])); } public void warning(Locator[] locators, String s) { throw new ValidationException(s, new LocationData(locators[0])); } public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { URL url = URLFactory.createURL((locator[0] != null && locator[0].getSystemId() != null) ? locator[0].getSystemId() : null, systemId); InputSource i = new InputSource(url.openStream()); i.setSystemId(url.toString()); return i; } }); readInputAsSAX(context, input, new ForwardingContentHandler(grammarReader) { public void setDocumentLocator(Locator loc) { super.setDocumentLocator(loc); locator[0] = loc; } }); return grammarReader.getResultAsGrammar(); } }); DocumentDeclaration vgm = new REDocumentDeclaration(grammar.getTopLevel(), new ExpressionPool()); Verifier verifier = new Verifier(vgm, new ErrorHandler()) { boolean stopDecorating = false; private void generateErrorElement(ValidationException ve) throws SAXException { if (decorateOutput && ve != null) { if (!stopDecorating) { AttributesImpl a = new AttributesImpl(); a.addAttribute("", ValidationProcessor.MESSAGE_ATTRIBUTE, ValidationProcessor.MESSAGE_ATTRIBUTE, "CDATA", ve.getSimpleMessage()); a.addAttribute("", ValidationProcessor.SYSTEMID_ATTRIBUTE, ValidationProcessor.SYSTEMID_ATTRIBUTE, "CDATA", ve.getLocationData().getSystemID()); a.addAttribute("", ValidationProcessor.LINE_ATTRIBUTE, ValidationProcessor.LINE_ATTRIBUTE, "CDATA", Integer.toString(ve.getLocationData().getLine())); a.addAttribute("", ValidationProcessor.COLUMN_ATTRIBUTE, ValidationProcessor.COLUMN_ATTRIBUTE, "CDATA", Integer.toString(ve.getLocationData().getCol())); contentHandler.startElement(ValidationProcessor.ORBEON_ERROR_NS, ValidationProcessor.ERROR_ELEMENT, ValidationProcessor.ORBEON_ERROR_PREFIX + ":" + ValidationProcessor.ERROR_ELEMENT, a); contentHandler.endElement(ValidationProcessor.ORBEON_ERROR_NS, ValidationProcessor.ERROR_ELEMENT, ValidationProcessor.ORBEON_ERROR_PREFIX + ":" + ValidationProcessor.ERROR_ELEMENT); stopDecorating = true; } } else { throw ve; } } public void characters(char[] chars, int i, int i1) throws SAXException { try { super.characters(chars, i, i1); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.characters(chars, i, i1); } public void endDocument() throws SAXException { try { super.endDocument(); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.endDocument(); } public void endElement(String s, String s1, String s2) throws SAXException { try { super.endElement(s, s1, s2); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.endElement(s, s1, s2); } public void startDocument() throws SAXException { try { super.startDocument(); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.startDocument(); } public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException { ((ErrorHandler) getErrorHandler()).setElement(s, s1); try { super.startElement(s, s1, s2, attributes); } catch (ValidationException e) { generateErrorElement(e); } contentHandler.startElement(s, s1, s2, attributes); } public void endPrefixMapping(String s) { try { super.endPrefixMapping(s); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.endPrefixMapping(s); } catch (SAXException se) { throw new OXFException(se.getException()); } } public void processingInstruction(String s, String s1) { try { super.processingInstruction(s, s1); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.processingInstruction(s, s1); } catch (SAXException e) { throw new OXFException(e.getException()); } } public void setDocumentLocator(Locator locator) { try { super.setDocumentLocator(locator); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } contentHandler.setDocumentLocator(locator); } public void skippedEntity(String s) { try { super.skippedEntity(s); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getMessage()); } } try { contentHandler.skippedEntity(s); } catch (SAXException e) { throw new OXFException(e.getException()); } } public void startPrefixMapping(String s, String s1) { try { super.startPrefixMapping(s, s1); } catch (ValidationException e) { try { generateErrorElement(e); } catch (SAXException se) { throw new OXFException(se.getException()); } } try { contentHandler.startPrefixMapping(s, s1); } catch (SAXException e) { throw new OXFException(e.getException()); } } }; readInputAsSAX(context, getInputByName(INPUT_DATA), verifier); } catch (Exception e) { throw new OXFException(e); } } }; addOutput(name, output); return output; }
Code Sample 2:
private ArrayList<IdLocation> doGet(String identifier) throws IdLocatorException { String openurl = baseurl.toString() + "?url_ver=Z39.88-2004&rft_id=" + identifier; URL url; SRUSearchRetrieveResponse sru; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { sru = SRUSearchRetrieveResponse.read(huc.getInputStream()); } else throw new IdLocatorException("cannot get " + url.toString()); } catch (MalformedURLException e) { throw new IdLocatorException("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new IdLocatorException("An IOException occurred attempting to connect to " + openurl); } catch (SRUException e) { throw new IdLocatorException("An SRUException occurred attempting to parse the response"); } ArrayList<IdLocation> ids = new ArrayList<IdLocation>(); for (SRUDC dc : sru.getRecords()) { IdLocation id = new IdLocation(); id.setId(dc.getKeys(SRUDC.Key.IDENTIFIER).firstElement()); id.setRepo(dc.getKeys(SRUDC.Key.SOURCE).firstElement()); id.setDate(dc.getKeys(SRUDC.Key.DATE).firstElement()); ids.add(id); } Collections.sort(ids); return ids; }
|
00
|
Code Sample 1:
public void processSaveHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_HOLDING " + "SET " + " full_name_HOLDING=?, " + " NAME_HOLDING=? " + "WHERE ID_HOLDING = ? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); RsetTools.setLong(ps, num++, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); processInsertRelatedCompany(dbDyn, holdingBean, authSession); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
Code Sample 2:
public void downloadTranslationsAndReload() { File languages = new File(this.translationsFile); try { URL languageURL = new URL(languageServer); InputStream is = languageURL.openStream(); OutputStream os = new FileOutputStream(languages); byte[] read = new byte[512000]; int bytesRead = 0; do { bytesRead = is.read(read); if (bytesRead > 0) { os.write(read, 0, bytesRead); } } while (bytesRead > 0); is.close(); os.close(); this.loadTranslations(); } catch (Exception e) { System.err.println("Remote languages file not found!"); if (languages.exists()) { try { XMLDecoder loader = new XMLDecoder(new FileInputStream(languages)); this.languages = (Hashtable) loader.readObject(); loader.close(); } catch (Exception ex) { ex.printStackTrace(); this.languages.put(naiveLanguage, new Hashtable()); } } else this.languages.put(naiveLanguage, new Hashtable()); } }
|
11
|
Code Sample 1:
public static void unzip(File zipInFile, File outputDir) throws Exception { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(zipInFile); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipInFile)); ZipEntry entry = (ZipEntry) zipInputStream.getNextEntry(); File curOutDir = outputDir; while (entry != null) { if (entry.isDirectory()) { curOutDir = new File(curOutDir, entry.getName()); curOutDir.mkdirs(); continue; } File outFile = new File(curOutDir, entry.getName()); File tempDir = outFile.getParentFile(); if (!tempDir.exists()) tempDir.mkdirs(); outFile.createNewFile(); BufferedOutputStream outstream = new BufferedOutputStream(new FileOutputStream(outFile)); int n; byte[] buf = new byte[1024]; while ((n = zipInputStream.read(buf, 0, 1024)) > -1) outstream.write(buf, 0, n); outstream.flush(); outstream.close(); zipInputStream.closeEntry(); entry = zipInputStream.getNextEntry(); } zipInputStream.close(); zipFile.close(); }
Code Sample 2:
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:
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; }
Code Sample 2:
@Override public String fetchElectronicEdition(Publication pub) { final String url = pub.getEe(); HttpMethod method = null; String responseBody = ""; method = new GetMethod(url); method.setFollowRedirects(true); try { if (StringUtils.isNotBlank(method.getURI().getScheme())) { InputStream is = null; StringWriter writer = new StringWriter(); try { client.executeMethod(method); Header contentType = method.getResponseHeader("Content-Type"); if (contentType != null && StringUtils.isNotBlank(contentType.getValue()) && contentType.getValue().indexOf("text/html") >= 0) { is = method.getResponseBodyAsStream(); IOUtils.copy(is, writer); responseBody = writer.toString(); } else { logger.info("ignoring non-text/html response from page: " + url + " content-type:" + contentType); } } catch (HttpException he) { logger.error("Http error connecting to '" + url + "'"); logger.error(he.getMessage()); } catch (IOException ioe) { logger.error("Unable to connect to '" + url + "'"); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(writer); } } } catch (URIException e) { logger.error(e); } finally { method.releaseConnection(); } return responseBody; }
|
00
|
Code Sample 1:
public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException { ChallengeAction challengeAction; ManagerResponse challengeResponse; String challenge; String key; LoginAction loginAction; ManagerResponse loginResponse; if (socket == null) { connect(); } if (!socket.isConnected()) { connect(); } synchronized (protocolIdentifier) { if (protocolIdentifier.value == null) { try { protocolIdentifier.wait(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (protocolIdentifier.value == null) { disconnect(); if (reader != null && reader.getTerminationException() != null) { throw reader.getTerminationException(); } else { throw new TimeoutException("Timeout waiting for protocol identifier"); } } } challengeAction = new ChallengeAction("MD5"); try { challengeResponse = sendAction(challengeAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send challenge action", e); } if (challengeResponse instanceof ChallengeResponse) { challenge = ((ChallengeResponse) challengeResponse).getChallenge(); } else { disconnect(); throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage()); } try { MessageDigest md; md = MessageDigest.getInstance("MD5"); if (challenge != null) { md.update(challenge.getBytes()); } if (password != null) { md.update(password.getBytes()); } key = ManagerUtil.toHexString(md.digest()); } catch (NoSuchAlgorithmException ex) { disconnect(); throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex); } loginAction = new LoginAction(username, "MD5", key, eventMask); try { loginResponse = sendAction(loginAction); } catch (Exception e) { disconnect(); throw new AuthenticationFailedException("Unable to send login action", e); } if (loginResponse instanceof ManagerError) { disconnect(); throw new AuthenticationFailedException(loginResponse.getMessage()); } version = determineVersion(); writer.setTargetVersion(version); ConnectEvent connectEvent = new ConnectEvent(this); connectEvent.setProtocolIdentifier(getProtocolIdentifier()); connectEvent.setDateReceived(DateUtil.getDate()); fireEvent(connectEvent); }
|
00
|
Code Sample 1:
private boolean streamDownload(URL url, File file) { try { InputStream in = url.openConnection().getInputStream(); BufferedInputStream bis = new BufferedInputStream(in); OutputStream out = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(out); int chunkSize = 63 * 1024; byte[] ba = new byte[chunkSize]; while (true) { int bytesRead = readBlocking(bis, ba, 0, chunkSize); if (bytesRead > 0) { if (bos != null) bos.write(ba, 0, bytesRead); } else { bos.close(); break; } } } catch (IOException e) { System.out.println("Error writing file " + file); return false; } System.out.println("OK writing file " + file); return true; }
Code Sample 2:
public void processSaveCompany(Company companyBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "UPDATE WM_LIST_COMPANY " + "SET " + " full_name = ?, " + " short_name = ?, " + " address = ?, " + " telefon_buh = ?, " + " telefon_chief = ?, " + " chief = ?, " + " buh = ?, " + " fax = ?, " + " email = ?, " + " icq = ?, " + " short_client_info = ?, " + " url = ?, " + " short_info = ? " + "WHERE ID_FIRM = ? and ID_FIRM in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedCompanyId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_FIRM from v$_read_list_firm z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); int num = 1; ps.setString(num++, companyBean.getName()); ps.setString(num++, companyBean.getShortName()); ps.setString(num++, companyBean.getAddress()); ps.setString(num++, ""); ps.setString(num++, ""); ps.setString(num++, companyBean.getCeo()); ps.setString(num++, companyBean.getCfo()); ps.setString(num++, ""); ps.setString(num++, ""); RsetTools.setLong(ps, num++, null); ps.setString(num++, ""); ps.setString(num++, companyBean.getWebsite()); ps.setString(num++, companyBean.getInfo()); RsetTools.setLong(ps, num++, companyBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(num++, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save company"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
|
00
|
Code Sample 1:
public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException { CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toByteArray(); }
Code Sample 2:
public void connect(String username, String passwordMd5) { this.username = username; this.passwordMd5 = passwordMd5; StringBuffer handshakeUrl = new StringBuffer(); handshakeUrl.append("http://ws.audioscrobbler.com/radio/handshake.php?version="); handshakeUrl.append(LastFM.VERSION); handshakeUrl.append("&platform=linux&username="); handshakeUrl.append(this.username); handshakeUrl.append("&passwordmd5="); handshakeUrl.append(this.passwordMd5); handshakeUrl.append("&language=en&player=aTunes"); URL url; try { url = new URL(handshakeUrl.toString()); URLConnection connection = url.openConnection(); InputStream inputStream = new BufferedInputStream(connection.getInputStream()); byte[] buffer = new byte[4069]; int read = 0; StringBuffer result = new StringBuffer(); while ((read = inputStream.read(buffer)) > -1) { result.append((new String(buffer, 0, read))); } String[] rows = result.toString().split("\n"); this.data = new HashMap<String, String>(); for (String row : rows) { row = row.trim(); int firstEquals = row.indexOf("="); data.put(row.substring(0, firstEquals), row.substring(firstEquals + 1)); } String streamingUrl = data.get("stream_url"); streamingUrl = streamingUrl.substring(7); int delimiter = streamingUrl.indexOf("/"); String hostname = streamingUrl.substring(0, delimiter); String path = streamingUrl.substring(delimiter + 1); String[] tokens = hostname.split(":"); hostname = tokens[0]; int port = Integer.parseInt(tokens[1]); this.lastFmSocket = new Socket(hostname, port); OutputStreamWriter osw = new OutputStreamWriter(this.lastFmSocket.getOutputStream()); osw.write("GET /" + path + " HTTP/1.0\r\n"); osw.write("Host: " + hostname + "\r\n"); osw.write("\r\n"); osw.flush(); this.lastFmInputStream = this.lastFmSocket.getInputStream(); result = new StringBuffer(); while ((read = this.lastFmInputStream.read(buffer)) > -1) { String line = new String(buffer, 0, read); result.append(line); if (line.contains("\r\n\r\n")) break; } String response = result.toString(); logger.info("Result: " + response); if (!response.startsWith("HTTP/1.0 200 OK")) { this.lastFmSocket.close(); throw new LastFmException("Could not handshake with lastfm. Check credential!"); } StringBuffer sb = new StringBuffer(); sb.append("http://"); sb.append(this.data.get("base_url")); sb.append(this.data.get("base_path")); sb.append("/xspf.php?sk="); sb.append(this.data.get("session")); sb.append("&discovery=1&desktop="); sb.append(LastFM.VERSION); logger.info(sb.toString()); this.playlistUrl = new URL(sb.toString()); this.playlist = this.playlistParser.fetchPlaylist(this.playlistUrl.toString()); Iterator<LastFmTrack> it = this.playlist.iterator(); while (it.hasNext()) { System.out.println(it.next().getCreator()); } this.connected = true; } catch (MalformedURLException e) { throw new LastFmException("Could not handshake with lastfm", e.getCause()); } catch (IOException e) { throw new LastFmException("Could not initialise lastfm", e.getCause()); } }
|
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: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
Code Sample 2:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, NULL_OUTPUT_STREAM); } finally { IOUtils.close(in); } return checksum; }
|
00
|
Code Sample 1:
private void loadTrustAnchors(final String keystoreLocation) { LOG.debug("keystore location: " + keystoreLocation); try { if (keystoreLocation == null) { throw new NullPointerException("No TrustAnchor KeyStore name is set"); } InputStream keyStoreStream = null; if (new File(keystoreLocation).exists()) { keyStoreStream = new FileInputStream(keystoreLocation); } else if (new File("../trust1.keystore").exists()) { keyStoreStream = new FileInputStream(new File("../trust1.keystore")); } else if (new File("trust1.keystore").exists()) { keyStoreStream = new FileInputStream(new File("../trust1.keystore")); } else { URL url = Thread.currentThread().getContextClassLoader().getResource("trust1.keystore"); if (url != null) keyStoreStream = new BufferedInputStream(url.openStream()); } KeyStore ks = KeyStore.getInstance(trustStoreType); ks.load(keyStoreStream, trustStorePassword.toCharArray()); Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); LOG.debug("inspecting alias " + alias); if (ks.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) { LOG.debug("Adding TrustAnchor: " + ((X509Certificate) ks.getCertificate(alias)).getSubjectX500Principal().getName()); TrustAnchor ta = new TrustAnchor((X509Certificate) (ks.getCertificate(alias)), null); this.trustAnchors.add(ta); } } } catch (Exception ex) { LOG.error("Error loading TrustAnchors", ex); this.trustAnchors = null; } }
Code Sample 2:
@SuppressWarnings("unchecked") protected void processDownloadAction(HttpServletRequest request, HttpServletResponse response) throws Exception { File transformationFile = new File(xslBase, "file-info.xsl"); HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); DataSourceIf dataSource = new NullSource(); Document fileInfoDoc = XmlUtils.getEmptyDOM(); DOMResult result = new DOMResult(fileInfoDoc); transformer.transform((Source) dataSource, result); Element documentElement = fileInfoDoc.getDocumentElement(); if (documentElement.getLocalName().equals("null")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } InputStream is = null; try { XPath xpath = XPathFactory.newInstance().newXPath(); String sourceType = XPathUtils.getStringValue(xpath, "source-type", documentElement, null); String location = XPathUtils.getStringValue(xpath, "location", documentElement, null); String fileName = XPathUtils.getStringValue(xpath, "file-name", documentElement, null); String mimeType = XPathUtils.getStringValue(xpath, "mime-type", documentElement, null); String encoding = XPathUtils.getStringValue(xpath, "encoding", documentElement, null); if (StringUtils.equals(sourceType, "cifsSource")) { String domain = XPathUtils.getStringValue(xpath, "domain", documentElement, null); String userName = XPathUtils.getStringValue(xpath, "username", documentElement, null); String password = XPathUtils.getStringValue(xpath, "password", documentElement, null); URI uri = new URI(location); if (StringUtils.isNotBlank(userName)) { String userInfo = ""; if (StringUtils.isNotBlank(domain)) { userInfo = userInfo + domain + ";"; } userInfo = userInfo + userName; if (StringUtils.isNotBlank(password)) { userInfo = userInfo + ":" + password; } uri = new URI(uri.getScheme(), userInfo, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } SmbFile smbFile = new SmbFile(uri.toURL()); is = new SmbFileInputStream(smbFile); } else if (StringUtils.equals(sourceType, "localFileSystemSource")) { File file = new File(location); is = new FileInputStream(file); } else { logger.error("Source type \"" + ((sourceType != null) ? sourceType : "") + "\" not supported"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (StringUtils.isBlank(mimeType) && StringUtils.isBlank(encoding)) { response.setContentType(Definitions.MIMETYPE_BINARY); } else if (StringUtils.isBlank(encoding)) { response.setContentType(mimeType); } else { response.setContentType(mimeType + ";charset=" + encoding); } if (request.getParameterMap().containsKey(Definitions.REQUEST_PARAMNAME_DOWNLOAD)) { response.setHeader("Content-Disposition", "attachment; filename=" + fileName); } IOUtils.copy(new BufferedInputStream(is), response.getOutputStream()); } finally { if (is != null) { is.close(); } } }
|
00
|
Code Sample 1:
public void GetList() throws Exception { Authenticator.setDefault(new MyAuth(this._user, this._pwd)); URL url = new URL(MyFanfou.PublicTimeLine); InputStream ins = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(ins)); String json = ""; String line; while ((line = reader.readLine()) != null) json += line; JSONArray array = new JSONArray(json); for (int i = 0; i < array.length(); i++) { JSONObject object = array.getJSONObject(i); String users = object.getString("user"); JSONObject user = new JSONObject(users); System.out.println(object.getString("id") + ":" + user.getString("birthday")); } }
Code Sample 2:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
|
11
|
Code Sample 1:
private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); }
Code Sample 2:
public BufferedImage process(final InputStream is, DjatokaDecodeParam params) throws DjatokaException { if (isWindows) return processUsingTemp(is, params); ArrayList<Double> dims = null; if (params.getRegion() != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyStream(is, baos); dims = getRegionMetadata(new ByteArrayInputStream(baos.toByteArray()), params); return process(new ByteArrayInputStream(baos.toByteArray()), dims, params); } else return process(is, dims, params); }
|
00
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public void importNotesFromServer() { boolean downloaded = true; try { makeBackupFile(); File f = new File(UserSettings.getInstance().getNotesFile()); FileOutputStream fos = new FileOutputStream(f); String urlString = protocol + "://" + UserSettings.getInstance().getServerAddress() + UserSettings.getInstance().getServerDir() + f.getName(); setDefaultAuthenticator(); URL url = new URL(urlString); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); InputStream is = urlc.getInputStream(); int nextByte = is.read(); while (nextByte != -1) { fos.write(nextByte); nextByte = is.read(); } fos.close(); if (urlc.getResponseCode() != HttpURLConnection.HTTP_OK) { downloaded = false; } } catch (SSLHandshakeException e) { JOptionPane.showMessageDialog(null, I18N.getInstance().getString("error.sslcertificateerror"), I18N.getInstance().getString("error.title"), JOptionPane.ERROR_MESSAGE); downloaded = false; } catch (Exception e) { downloaded = false; } if (downloaded) { deleteBackupFile(); JOptionPane.showMessageDialog(null, I18N.getInstance().getString("info.notesfiledownloaded"), I18N.getInstance().getString("info.title"), JOptionPane.INFORMATION_MESSAGE); } else { restoreFileFromBackup(); JOptionPane.showMessageDialog(null, I18N.getInstance().getString("error.notesfilenotdownloaded"), I18N.getInstance().getString("error.title"), JOptionPane.ERROR_MESSAGE); } }
|
11
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
|
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 SingularValueDecomposition(Matrix Arg) { double[][] A = Arg.getArrayCopy(); m = Arg.getRowDimension(); n = Arg.getColumnDimension(); int nu = Math.min(m, n); s = new double[Math.min(m + 1, n)]; U = new double[m][nu]; V = new double[n][n]; double[] e = new double[n]; double[] work = new double[m]; boolean wantu = true; boolean wantv = true; int nct = Math.min(m - 1, n); int nrt = Math.max(0, Math.min(n - 2, m)); for (int k = 0; k < Math.max(nct, nrt); k++) { if (k < nct) { s[k] = 0; for (int i = k; i < m; i++) { s[k] = Maths.hypot(s[k], A[i][k]); } if (s[k] != 0.0) { if (A[k][k] < 0.0) { s[k] = -s[k]; } for (int i = k; i < m; i++) { A[i][k] /= s[k]; } A[k][k] += 1.0; } s[k] = -s[k]; } for (int j = k + 1; j < n; j++) { if ((k < nct) & (s[k] != 0.0)) { double t = 0; for (int i = k; i < m; i++) { t += A[i][k] * A[i][j]; } t = -t / A[k][k]; for (int i = k; i < m; i++) { A[i][j] += t * A[i][k]; } } e[j] = A[k][j]; } if (wantu & (k < nct)) { for (int i = k; i < m; i++) { U[i][k] = A[i][k]; } } if (k < nrt) { e[k] = 0; for (int i = k + 1; i < n; i++) { e[k] = Maths.hypot(e[k], e[i]); } if (e[k] != 0.0) { if (e[k + 1] < 0.0) { e[k] = -e[k]; } for (int i = k + 1; i < n; i++) { e[i] /= e[k]; } e[k + 1] += 1.0; } e[k] = -e[k]; if ((k + 1 < m) & (e[k] != 0.0)) { for (int i = k + 1; i < m; i++) { work[i] = 0.0; } for (int j = k + 1; j < n; j++) { for (int i = k + 1; i < m; i++) { work[i] += e[j] * A[i][j]; } } for (int j = k + 1; j < n; j++) { double t = -e[j] / e[k + 1]; for (int i = k + 1; i < m; i++) { A[i][j] += t * work[i]; } } } if (wantv) { for (int i = k + 1; i < n; i++) { V[i][k] = e[i]; } } } } int p = Math.min(n, m + 1); if (nct < n) { s[nct] = A[nct][nct]; } if (m < p) { s[p - 1] = 0.0; } if (nrt + 1 < p) { e[nrt] = A[nrt][p - 1]; } e[p - 1] = 0.0; if (wantu) { for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) { U[i][j] = 0.0; } U[j][j] = 1.0; } for (int k = nct - 1; k >= 0; k--) { if (s[k] != 0.0) { for (int j = k + 1; j < nu; j++) { double t = 0; for (int i = k; i < m; i++) { t += U[i][k] * U[i][j]; } t = -t / U[k][k]; for (int i = k; i < m; i++) { U[i][j] += t * U[i][k]; } } for (int i = k; i < m; i++) { U[i][k] = -U[i][k]; } U[k][k] = 1.0 + U[k][k]; for (int i = 0; i < k - 1; i++) { U[i][k] = 0.0; } } else { for (int i = 0; i < m; i++) { U[i][k] = 0.0; } U[k][k] = 1.0; } } } if (wantv) { for (int k = n - 1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0.0)) { for (int j = k + 1; j < nu; j++) { double t = 0; for (int i = k + 1; i < n; i++) { t += V[i][k] * V[i][j]; } t = -t / V[k + 1][k]; for (int i = k + 1; i < n; i++) { V[i][j] += t * V[i][k]; } } } for (int i = 0; i < n; i++) { V[i][k] = 0.0; } V[k][k] = 1.0; } } int pp = p - 1; int iter = 0; double eps = Math.pow(2.0, -52.0); double tiny = Math.pow(2.0, -966.0); while (p > 0) { int k, kase; for (k = p - 2; k >= -1; k--) { if (k == -1) { break; } if (Math.abs(e[k]) <= tiny + eps * (Math.abs(s[k]) + Math.abs(s[k + 1]))) { e[k] = 0.0; break; } } if (k == p - 2) { kase = 4; } else { int ks; for (ks = p - 1; ks >= k; ks--) { if (ks == k) { break; } double t = (ks != p ? Math.abs(e[ks]) : 0.) + (ks != k + 1 ? Math.abs(e[ks - 1]) : 0.); if (Math.abs(s[ks]) <= tiny + eps * t) { s[ks] = 0.0; break; } } if (ks == k) { kase = 3; } else if (ks == p - 1) { kase = 1; } else { kase = 2; k = ks; } } k++; switch(kase) { case 1: { double f = e[p - 2]; e[p - 2] = 0.0; for (int j = p - 2; j >= k; j--) { double t = Maths.hypot(s[j], f); double cs = s[j] / t; double sn = f / t; s[j] = t; if (j != k) { f = -sn * e[j - 1]; e[j - 1] = cs * e[j - 1]; } if (wantv) { for (int i = 0; i < n; i++) { t = cs * V[i][j] + sn * V[i][p - 1]; V[i][p - 1] = -sn * V[i][j] + cs * V[i][p - 1]; V[i][j] = t; } } } } break; case 2: { double f = e[k - 1]; e[k - 1] = 0.0; for (int j = k; j < p; j++) { double t = Maths.hypot(s[j], f); double cs = s[j] / t; double sn = f / t; s[j] = t; f = -sn * e[j]; e[j] = cs * e[j]; if (wantu) { for (int i = 0; i < m; i++) { t = cs * U[i][j] + sn * U[i][k - 1]; U[i][k - 1] = -sn * U[i][j] + cs * U[i][k - 1]; U[i][j] = t; } } } } break; case 3: { double scale = Math.max(Math.max(Math.max(Math.max(Math.abs(s[p - 1]), Math.abs(s[p - 2])), Math.abs(e[p - 2])), Math.abs(s[k])), Math.abs(e[k])); double sp = s[p - 1] / scale; double spm1 = s[p - 2] / scale; double epm1 = e[p - 2] / scale; double sk = s[k] / scale; double ek = e[k] / scale; double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; double c = (sp * epm1) * (sp * epm1); double shift = 0.0; if ((b != 0.0) | (c != 0.0)) { shift = Math.sqrt(b * b + c); if (b < 0.0) { shift = -shift; } shift = c / (b + shift); } double f = (sk + sp) * (sk - sp) + shift; double g = sk * ek; for (int j = k; j < p - 1; j++) { double t = Maths.hypot(f, g); double cs = f / t; double sn = g / t; if (j != k) { e[j - 1] = t; } f = cs * s[j] + sn * e[j]; e[j] = cs * e[j] - sn * s[j]; g = sn * s[j + 1]; s[j + 1] = cs * s[j + 1]; if (wantv) { for (int i = 0; i < n; i++) { t = cs * V[i][j] + sn * V[i][j + 1]; V[i][j + 1] = -sn * V[i][j] + cs * V[i][j + 1]; V[i][j] = t; } } t = Maths.hypot(f, g); cs = f / t; sn = g / t; s[j] = t; f = cs * e[j] + sn * s[j + 1]; s[j + 1] = -sn * e[j] + cs * s[j + 1]; g = sn * e[j + 1]; e[j + 1] = cs * e[j + 1]; if (wantu && (j < m - 1)) { for (int i = 0; i < m; i++) { t = cs * U[i][j] + sn * U[i][j + 1]; U[i][j + 1] = -sn * U[i][j] + cs * U[i][j + 1]; U[i][j] = t; } } } e[p - 2] = f; iter = iter + 1; } break; case 4: { if (s[k] <= 0.0) { s[k] = (s[k] < 0.0 ? -s[k] : 0.0); if (wantv) { for (int i = 0; i <= pp; i++) { V[i][k] = -V[i][k]; } } } while (k < pp) { if (s[k] >= s[k + 1]) { break; } double t = s[k]; s[k] = s[k + 1]; s[k + 1] = t; if (wantv && (k < n - 1)) { for (int i = 0; i < n; i++) { t = V[i][k + 1]; V[i][k + 1] = V[i][k]; V[i][k] = t; } } if (wantu && (k < m - 1)) { for (int i = 0; i < m; i++) { t = U[i][k + 1]; U[i][k + 1] = U[i][k]; U[i][k] = t; } } k++; } iter = 0; p--; } break; } } }
|
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 boolean extract(File f, String folder) { Enumeration entries; ZipFile zipFile; try { zipFile = new ZipFile(f); entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement(); if (entry == null) continue; String path = folder + "/" + entry.getName().replace('\\', '/'); if (!entry.isDirectory()) { File destFile = new File(path); String parent = destFile.getParent(); if (parent != null) { File parentFile = new File(parent); if (!parentFile.exists()) { parentFile.mkdirs(); } } copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(destFile))); } } zipFile.close(); } catch (IOException ioe) { this.errMsg = ioe.getMessage(); Malgn.errorLog("{Zip.unzip} " + ioe.getMessage()); return false; } return true; }
|
11
|
Code Sample 1:
public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
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) { } } } }
|
00
|
Code Sample 1:
public Set<Plugin<?>> loadPluginImplementationMetaData() throws PluginRegistryException { try { final Enumeration<URL> urls = JavaSystemHelper.getResources(pluginImplementationMetaInfPath); pluginImplsSet.clear(); if (urls != null) { while (urls.hasMoreElements()) { final URL url = urls.nextElement(); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.found", "classes", url.getPath())); InputStream resourceInput = null; Reader reader = null; BufferedReader buffReader = null; String line; try { resourceInput = url.openStream(); reader = new InputStreamReader(resourceInput); buffReader = new BufferedReader(reader); line = buffReader.readLine(); while (line != null) { try { pluginImplsSet.add(inspectPluginImpl(Class.forName(line.trim()))); echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.processing", "class", line)); line = buffReader.readLine(); } catch (final ClassNotFoundException cnfe) { throw new PluginRegistryException("plugin.error.load.classnotfound", cnfe, pluginImplementationMetaInfPath, line); } catch (final LinkageError ncfe) { if (LOGGER.isDebugEnabled()) { echoMessages.add(PluginMessageBundle.getMessage("plugin.info.visitor.resource.linkageError", "class", line, ncfe.getMessage())); } line = buffReader.readLine(); } } } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, url.getFile(), ioe.getMessage()); } finally { if (buffReader != null) { buffReader.close(); } if (reader != null) { reader.close(); } if (resourceInput != null) { resourceInput.close(); } } } } return Collections.unmodifiableSet(pluginImplsSet); } catch (final IOException ioe) { throw new PluginRegistryException("plugin.error.load.ioe", ioe, pluginImplementationMetaInfPath, ioe.getMessage()); } }
Code Sample 2:
public static Font createTrueTypeFont(URL url, int style, float size) { Font f = null; try { f = Font.createFont(Font.TRUETYPE_FONT, url.openStream()); } catch (IOException e) { System.err.println("ERROR: " + url + " is not found or can not be read"); f = new Font("Verdana", 0, 0); } catch (FontFormatException e) { System.err.println("ERROR: " + url + " is not a valid true type font"); f = new Font("Verdana", 0, 0); } return f.deriveFont(style, size); }
|
11
|
Code Sample 1:
private void copy(File source, File target) throws IOException { FileChannel in = (new FileInputStream(source)).getChannel(); FileChannel out = (new FileOutputStream(target)).getChannel(); in.transferTo(0, source.length(), out); in.close(); out.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!"); }
|
00
|
Code Sample 1:
@Override public boolean connect(String host, String userName, String password) throws IOException, UnknownHostException { try { if (ftpClient != null) if (ftpClient.isConnected()) ftpClient.disconnect(); ftpClient = new FTPSClient("SSL", false); boolean success = false; ftpClient.connect(host); int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) success = ftpClient.login(userName, password); if (!success) ftpClient.disconnect(); return success; } catch (Exception ex) { throw new IOException(ex.getMessage()); } }
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:
protected long loadFromSource(long afterThisTime) { long startTime = System.currentTimeMillis(); QuoteDataSourceDescriptor quoteDataSourceDescriptor = (QuoteDataSourceDescriptor) dataSourceDescriptor; List<Quote> dataPool = dataPools.get(quoteDataSourceDescriptor.sourceSymbol); Calendar calendar = Calendar.getInstance(); calendar.clear(); SimpleDateFormat sdf = new SimpleDateFormat(quoteDataSourceDescriptor.dateFormat, Locale.US); Date fromDate = new Date(); Date toDate = new Date(); if (afterThisTime == FIRST_TIME_LOAD) { fromDate = quoteDataSourceDescriptor.fromDate; toDate = quoteDataSourceDescriptor.toDate; } else { calendar.setTimeInMillis(afterThisTime); fromDate = calendar.getTime(); } calendar.setTime(fromDate); int a = calendar.get(Calendar.MONTH); int b = calendar.get(Calendar.DAY_OF_MONTH); int c = calendar.get(Calendar.YEAR); calendar.setTime(toDate); int d = calendar.get(Calendar.MONTH); int e = calendar.get(Calendar.DAY_OF_MONTH); int f = calendar.get(Calendar.YEAR); BufferedReader dis; StringBuffer urlStr = new StringBuffer(); urlStr.append("http://table.finance.yahoo.com/table.csv").append("?s="); urlStr.append(quoteDataSourceDescriptor.sourceSymbol); urlStr.append("&a=" + a + "&b=" + b + "&c=" + c + "&d=" + d + "&e=" + e + "&f=" + f); urlStr.append("&g=d&ignore=.csv"); try { URL url = new URL(urlStr.toString()); System.out.println(url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setAllowUserInteraction(true); conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(true); InputStreamReader isr = new InputStreamReader(conn.getInputStream()); dis = new BufferedReader(isr); String s = dis.readLine(); int iDateTime = 0; int iOpen = 1; int iHigh = 2; int iLow = 3; int iClose = 4; int iVolume = 5; int iAdjClose = 6; count = 0; calendar.clear(); while ((s = dis.readLine()) != null) { String[] items; items = s.split(","); if (items.length < 6) { break; } Date date = null; try { date = sdf.parse(items[iDateTime].trim()); } catch (ParseException ex) { ex.printStackTrace(); continue; } calendar.clear(); calendar.setTime(date); long time = calendar.getTimeInMillis(); if (time <= afterThisTime) { continue; } Quote quote = new Quote(); quote.time = time; quote.open = Float.parseFloat(items[iOpen].trim()); quote.high = Float.parseFloat(items[iHigh].trim()); quote.low = Float.parseFloat(items[iLow].trim()); quote.close = Float.parseFloat(items[iClose].trim()); quote.volume = Float.parseFloat(items[iVolume].trim()) / 100f; quote.amount = -1; quote.close_adj = Float.parseFloat(items[iAdjClose].trim()); if (quote.high * quote.low * quote.close == 0) { quote = null; continue; } dataPool.add(quote); if (count == 0) { firstTime = time; } lastTime = time; setAscending((lastTime >= firstTime) ? true : false); count++; } } catch (Exception ex) { System.out.println("Error in Reading File: " + ex.getMessage()); } long newestTime = (lastTime >= firstTime) ? lastTime : firstTime; return newestTime; }
Code Sample 2:
public String getWebcontent(final String link, final String postdata) { final StringBuffer response = new StringBuffer(); try { DisableSSLCertificateCheckUtil.disableChecks(); final URL url = new URL(link); final URLConnection conn = url.openConnection(); conn.setDoOutput(true); final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postdata); wr.flush(); final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String content = ""; while ((content = rd.readLine()) != null) { response.append(content); response.append('\n'); } wr.close(); rd.close(); } catch (final Exception e) { LOG.error("getWebcontent(String link, String postdata): " + e.toString() + "\012" + link + "\012" + postdata); } return response.toString(); }
|
11
|
Code Sample 1:
public boolean copyTo(String targetFilePath) { try { FileInputStream srcFile = new FileInputStream(filePath); FileOutputStream target = new FileOutputStream(targetFilePath); byte[] buff = new byte[1024]; int readed = -1; while ((readed = srcFile.read(buff)) > 0) target.write(buff, 0, readed); srcFile.close(); target.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
@Test public void testCopy_inputStreamToWriter_Encoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, "UTF8"); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF8").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static String compressFile(String fileName) throws IOException { String newFileName = fileName + ".gz"; FileInputStream fis = new FileInputStream(fileName); FileOutputStream fos = new FileOutputStream(newFileName); GZIPOutputStream gzos = new GZIPOutputStream(fos); byte[] buf = new byte[10000]; int bytesRead; while ((bytesRead = fis.read(buf)) > 0) gzos.write(buf, 0, bytesRead); fis.close(); gzos.close(); return newFileName; }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, String myImagesBehaviour) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(directoryPath + "images.xml"); SAXBuilder builder = new SAXBuilder(false); try { Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); int i = 0; TIGDataBase.activateTransactions(); while (j.hasNext() && !stop && !cancel) { current = i; i++; Element image = (Element) j.next(); String name = image.getAttributeValue("name"); List categories = image.getChildren("category"); Iterator k = categories.iterator(); if (exists(list, name)) { String pathSrc = directoryPath.concat(name); String pathDst = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase() + File.separator; String folder = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase(); if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.REPLACE_IMAGES"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); TIGDataBase.deleteAsociatedOfImage(idImage); } pathDst = pathDst.concat(name); } if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.ADD_IMAGES"))) { Vector aux = new Vector(); aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); int fileCount = 0; if (aux.size() != 0) { while (aux.size() != 0) { fileCount++; aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.')) + "_" + fileCount); } pathDst = pathDst + name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); name = name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); } else { pathDst = pathDst.concat(name); } } String pathThumbnail = (pathDst.substring(0, pathDst.lastIndexOf("."))).concat("_th.jpg"); File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertImageDB(name.substring(0, name.lastIndexOf('.')), name); int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); while (k.hasNext()) { Element category = (Element) k.next(); int idCategory = TIGDataBase.insertConceptDB(category.getValue()); TIGDataBase.insertAsociatedDB(idCategory, idImage); } } else { errorImages = errorImages + System.getProperty("line.separator") + name; } } TIGDataBase.executeQueries(); current = lengthOfTask; } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public String readURL(URL url) throws JasenException { OutputStream out = new ByteArrayOutputStream(); InputStream in = null; String html = null; NonBlockingStreamReader reader = null; try { in = url.openStream(); reader = new NonBlockingStreamReader(); reader.read(in, out, readBufferSize, readTimeout, null); html = new String(((ByteArrayOutputStream) out).toByteArray()); } catch (IOException e) { throw new JasenException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } return html; }
Code Sample 2:
protected boolean validateCaptcha(HttpServletRequest request) { String captchaID = request.getSession().getId(); String challengeResponse = StringUtils.upperCase(request.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME)); try { String urlString = "eadefakiaHR0cDovL3d3dy5zaG9weHgubmV0L2NlcnRpZmljYXRlLmFjdGlvbj9zaG9wVXJsPQ"; BASE64Decoder bASE64Decoder = new BASE64Decoder(); urlString = new String(bASE64Decoder.decodeBuffer(StringUtils.substring(urlString, 8) + "==")); URL url = new URL(urlString + SystemConfigUtil.getSystemConfig().getShopUrl()); URLConnection urlConnection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; httpConnection.getResponseCode(); } catch (IOException e) { } return captchaService.validateResponseForID(captchaID, challengeResponse); }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public static void copyFile(File src, File dest) throws IOException { log.debug("Copying file: '" + src + "' to '" + dest + "'"); FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
11
|
Code Sample 1:
private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } }
Code Sample 2:
public static String calcolaMd5(String messaggio) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); md.update(messaggio.getBytes()); byte[] impronta = md.digest(); return new String(impronta); }
|
11
|
Code Sample 1:
private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; }
Code Sample 2:
public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); }
|
11
|
Code Sample 1:
protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } }
Code Sample 2:
public static void copy(String pstrFileFrom, String pstrFileTo) { try { FileChannel srcChannel = new FileInputStream(pstrFileFrom).getChannel(); FileChannel dstChannel = new FileOutputStream(pstrFileTo).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
private final void copyTargetFileToSourceFile(File sourceFile, File targetFile) throws MJProcessorException { if (!targetFile.exists()) { targetFile.getParentFile().mkdirs(); try { if (!targetFile.exists()) { targetFile.createNewFile(); } } catch (IOException e) { throw new MJProcessorException(e.getMessage(), e); } } FileChannel in = null, out = null; try { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(targetFile).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (IOException e) { log.error(e); } finally { if (in != null) try { in.close(); } catch (IOException e) { log.error(e); } if (out != null) try { out.close(); } catch (IOException e) { log.error(e); } } }
Code Sample 2:
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { PrintUtil.prt((char) buff.get()); } }
|
11
|
Code Sample 1:
protected void doRestoreOrganizeTypeRelation() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_RELATION_TABLE; String strSelQuery = "SELECT parent_organize_type,child_organize_type " + "FROM " + Common.ORGANIZE_TYPE_RELATION_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_RELATION_TABLE + " " + "(parent_organize_type,child_organize_type) " + "VALUES (?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("parent_organize_type")); ps.setString(2, result.getString("child_organize_type")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE_RELATION INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeTypeRelation(): SQLException while committing or rollback"); } }
Code Sample 2:
public boolean addSiteScore(ArrayList<InitScoreTable> siteScores, InitScoreTable scoreTable, String filePath, String strTime) { boolean bResult = false; String strSql = ""; Connection conn = null; Statement stm = null; try { conn = db.getConnection(); conn.setAutoCommit(false); stm = conn.createStatement(); strSql = "delete from t_siteScore where strTaskId = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); for (int i = 0; i < siteScores.size(); i++) { InitScoreTable temp = siteScores.get(i); String tempSql = "select * from t_tagConf where strTagName='" + temp.getStrSiteScoreTagName() + "' and strTagYear='" + temp.getStrSiteScoreYear() + "' "; System.out.println(tempSql); ResultSet rst = stm.executeQuery(tempSql); if (rst.next()) { temp.setStrSiteScoreTagId(rst.getString("strId")); temp.setStrSiteinfoScoreParentId(rst.getString("strParentId")); } rst = null; } Iterator<InitScoreTable> it = siteScores.iterator(); String strCreatedTime = com.siteeval.common.Format.getDateTime(); String taskId = ""; while (it.hasNext()) { InitScoreTable thebean = it.next(); taskId = thebean.getStrSiteScoreTaskId(); String strId = UID.getID(); strSql = "INSERT INTO " + strTableName3 + "(strId,strTaskId,strTagId," + "strTagType,strTagName,strParentId,flaTagScore,strYear,datCreatedTime,strCreator) " + "VALUES('" + strId + "','" + taskId + "','" + thebean.getStrSiteScoreTagId() + "','" + thebean.getStrSiteScoreTagType() + "','" + thebean.getStrSiteScoreTagName() + "','" + thebean.getStrSiteinfoScoreParentId() + "','" + thebean.getFlaSiteScoreTagScore() + "','" + thebean.getStrSiteScoreYear() + "','" + strCreatedTime + "','" + thebean.getStrSiteScoreCreator() + "')"; stm.executeUpdate(strSql); } strSql = "update t_siteTotalScore set strSiteState=1,flaSiteScore='" + scoreTable.getFlaSiteScore() + "',flaInfoDisclosureScore='" + scoreTable.getFlaInfoDisclosureScore() + "',flaOnlineServicesScore='" + scoreTable.getFlaOnlineServicesScore() + "',flaPublicParticipationSore='" + scoreTable.getFlaPublicParticipationSore() + "',flaWebDesignScore='" + scoreTable.getFlaWebDesignScore() + "',strSiteFeature='" + scoreTable.getStrTotalScoreSiteFeature() + "',strSiteAdvantage='" + scoreTable.getStrTotalScoreSiteAdvantage() + "',strSiteFailure='" + scoreTable.getStrTotalScoreSiteFailure() + "' where strTaskId='" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); strSql = "update " + strTableName1 + " set templateUrl='" + filePath + "',dTaskBeginTime='" + strTime + "',dTaskEndTime='" + strTime + "' where strid = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); conn.commit(); bResult = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception eee) { } System.out.println("������վ���ֱ���Ϣʱ���?"); } finally { try { conn.setAutoCommit(true); if (stm != null) { stm.close(); } if (conn != null) { conn.close(); } } catch (Exception ee) { } } return bResult; }
|
00
|
Code Sample 1:
public boolean backup() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/data/android.bluebox/databases/bluebox.db"; String backupDBPath = "/Android/bluebox.bak"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
Code Sample 2:
private void loadDBpediaOntology() { try { URL url = new URL("http://downloads.dbpedia.org/3.6/dbpedia_3.6.owl.bz2"); InputStream is = new BufferedInputStream(url.openStream()); CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); dbPediaOntology = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(in); reasoner = PelletReasonerFactory.getInstance().createNonBufferingReasoner(dbPediaOntology); reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (CompressorException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } }
Code Sample 2:
public static void copyFile(File oldPathFile, File newPathFile) throws IOException { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(oldPathFile)); out = new BufferedOutputStream(new FileOutputStream(newPathFile)); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while (in.read(buffer) > 0) out.write(buffer); } finally { if (null != in) in.close(); if (null != out) out.close(); } }
|
00
|
Code Sample 1:
public static String hash(final String text) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return Sha1.convertToHex(sha1hash); } catch (NoSuchAlgorithmException e) { return null; } catch (UnsupportedEncodingException e) { return null; } }
Code Sample 2:
public String getHtmlCodeUnCharset(String urlString) { StringBuffer result = new StringBuffer(); BufferedReader in = null; try { URL url = new URL((urlString)); URLConnection con = url.openConnection(); in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = null; while ((line = in.readLine()) != null) { result.append(line + "\r\n"); } in.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } finally { if (in != null) { try { in.close(); } catch (Exception ex) { System.out.println("Exception throws at finally close reader when connecting to URL: " + urlString); } } } return result.toString(); }
|
11
|
Code Sample 1:
public static void copyFile(File fileIn, File fileOut) throws IOException { FileChannel chIn = new FileInputStream(fileIn).getChannel(); FileChannel chOut = new FileOutputStream(fileOut).getChannel(); try { chIn.transferTo(0, chIn.size(), chOut); } catch (IOException e) { throw e; } finally { if (chIn != null) chIn.close(); if (chOut != null) chOut.close(); } }
Code Sample 2:
@Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } }
|
00
|
Code Sample 1:
public final InputSource getInputSource() { if (url == null) throw new RuntimeException("Cannot find table defs"); try { InputStream stream = url.openStream(); InputStreamReader reader = new InputStreamReader(stream); return new InputSource(reader); } catch (IOException e) { throw new RuntimeException(e); } }
Code Sample 2:
private String readWebpage() { BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { URI uri = new URI("file:///www.vogella.de"); IProxyService proxyService = getProxyService(); IProxyData[] proxyDataForHost = proxyService.select(uri); for (IProxyData data : proxyDataForHost) { if (data.getHost() != null) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", data.getHost()); } if (data.getHost() != null) { System.setProperty("http.proxyPort", String.valueOf(data.getPort())); } } proxyService = null; URL url; url = uri.toURL(); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); }
|
00
|
Code Sample 1:
private String read(URL url) throws IOException { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer text = new StringBuffer(); String line; while ((line = in.readLine()) != null) { text.append(line); } return text.toString(); } finally { in.close(); } }
Code Sample 2:
public SWORDEntry ingestDepost(final DepositCollection pDeposit, final ServiceDocument pServiceDocument) throws SWORDException { try { ZipFileAccess tZipFile = new ZipFileAccess(super.getTempDir()); LOG.debug("copying file"); String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp"; IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName)); Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName); _datastreamList.add(tDatastream); _datastreamList.addAll(tZipFile.getFiles(tZipTempFileName)); int i = 0; boolean found = false; for (i = 0; i < _datastreamList.size(); i++) { if (_datastreamList.get(i).getId().equalsIgnoreCase("mets")) { found = true; break; } } if (found) { SAXBuilder tBuilder = new SAXBuilder(); _mets = new METSObject(tBuilder.build(((LocalDatastream) _datastreamList.get(i)).getPath())); LocalDatastream tLocalMETSDS = (LocalDatastream) _datastreamList.remove(i); new File(tLocalMETSDS.getPath()).delete(); _datastreamList.add(_mets.getMETSDs()); _datastreamList.addAll(_mets.getMetadataDatastreams()); } else { throw new SWORDException("Couldn't find a METS document in the zip file, ensure it is named mets.xml or METS.xml"); } SWORDEntry tEntry = super.ingestDepost(pDeposit, pServiceDocument); tZipFile.removeLocalFiles(); return tEntry; } catch (IOException tIOExcpt) { String tMessage = "Couldn't retrieve METS from deposit: " + tIOExcpt.toString(); LOG.error(tMessage); tIOExcpt.printStackTrace(); throw new SWORDException(tMessage, tIOExcpt); } catch (JDOMException tJDOMExcpt) { String tMessage = "Couldn't build METS from deposit: " + tJDOMExcpt.toString(); LOG.error(tMessage); tJDOMExcpt.printStackTrace(); throw new SWORDException(tMessage, tJDOMExcpt); } }
|
00
|
Code Sample 1:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
Code Sample 2:
private EventSeries<PhotoEvent> loadIncomingEvents(long reportID) { EventSeries<PhotoEvent> events = new EventSeries<PhotoEvent>(); try { URL url = new URL(SERVER_URL + XML_PATH + "reports.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = reader.readLine()) != null) { String[] values = str.split(","); if (values.length == 2) { long id = Long.parseLong(values[0]); if (id == reportID) { long time = Long.parseLong(values[1]); events.addEvent(new PhotoEvent(time)); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return events; }
|
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 void fileCopy(File inFile, File outFile) { try { FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { System.err.println("Hubo un error de entrada/salida!!!"); } }
|
11
|
Code Sample 1:
private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, boolean absolute) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (File file2 : files) { recurseFiles(root, file2, taos, absolute); } } else if ((!file.getName().endsWith(".tar")) && (!file.getName().endsWith(".TAR"))) { String filename = null; if (absolute) { filename = file.getAbsolutePath().substring(root.getAbsolutePath().length()); } else { filename = file.getName(); } TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } }
Code Sample 2:
public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { log.error(e, e); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.