label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
|
Code Sample 1:
private JButton getButtonSonido() { if (buttonSonido == null) { buttonSonido = new JButton(); buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15")); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetree.png")); buttonSonido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonSonido; }
Code Sample 2:
public void openUrlActionPerformed(ActionEvent event) { RemoteFileChooser fileChooser = new RemoteFileChooser(this, getAppName()); fileChooser.getDialog().setVisible(true); if (fileChooser.getResult() == JOptionPane.OK_OPTION) { setCursorBusy(true); URL url = fileChooser.getSelectedUrl(); String filename = fileChooser.getSelectedFilename(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); openFile(filename, reader); } catch (IOException e) { handleException(e); } setCursorBusy(false); } checkActions(); }
|
00
|
Code Sample 1:
@SuppressWarnings("unchecked") private Map<String, Object> _request(String method, String path, Map<String, Object> body, JSONRecognizer... recognizers) throws IOException, TwinException { String uri = url + path; HttpRequest request; if (body == null) { BasicHttpRequest r = new BasicHttpRequest(method, uri); request = r; } else { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri); StringEntity entity; try { entity = new StringEntity(JSON.encode(body), "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } entity.setContentType("application/json; charset=utf-8"); r.setEntity(entity); request = r; } HttpClient client = getClient(); try { HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request); HttpEntity entity = response.getEntity(); if (entity == null) return null; String contentType = entity.getContentType().getValue(); boolean isJson = (contentType != null) && ("application/json".equals(contentType) || contentType.startsWith("application/json;")); String result = null; InputStream in = entity.getContent(); try { Reader r = new InputStreamReader(in, "UTF-8"); StringBuilder sb = new StringBuilder(); char[] buf = new char[256]; int read; while ((read = r.read(buf, 0, buf.length)) >= 0) sb.append(buf, 0, read); r.close(); result = sb.toString(); } finally { try { in.close(); } catch (Exception e) { } } int code = response.getStatusLine().getStatusCode(); if (code >= 400) { if (isJson) { try { throw deserializeException((Map<String, Object>) JSON.decode(result)); } catch (IllegalArgumentException e) { throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e); } } if (code == 404) throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri); else throw TwinError.UnknownError.create("Got server response " + code + " for request " + uri + "\nBody is " + result); } if (!isJson) throw TwinError.UnknownError.create("Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result); try { return (Map<String, Object>) JSON.decode(result, recognizers); } catch (Exception e) { throw TwinError.UnknownError.create("Malformed JSON result for request " + uri + ": \nBody is " + result, e); } } catch (ClientProtocolException e) { throw new IOException(e); } }
Code Sample 2:
public SSLContext getSSLContext() throws IOException { try { URL url = getClass().getClassLoader().getResource(keyStoreFile); KeyStore keystore = KeyStore.getInstance(type.name()); keystore.load(url.openStream(), keyPassword); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, keyPassword); KeyManager[] keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance(protocol.name()); sslcontext.init(keymanagers, TRUST_MANAGER, null); return sslcontext; } catch (Exception e) { throw new IOException(e); } }
|
00
|
Code Sample 1:
public URLStream(URL url) throws IOException { this.url = url; this.conn = this.url.openConnection(); contentType = conn.getContentType(); name = url.toExternalForm(); size = new Long(conn.getContentLength()); sourceInfo = "url"; }
Code Sample 2:
public static String doPostWithBasicAuthentication(URL url, String username, String password, String parameters, Map<String, String> headers) throws IOException { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoInput(true); con.setDoOutput(true); byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); con.setConnectTimeout(2000); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (parameters != null) con.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); }
|
00
|
Code Sample 1:
public static void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void test(TestHarness harness) { harness.checkPoint("TestOfMD4"); try { Security.addProvider(new JarsyncProvider()); algorithm = MessageDigest.getInstance("BrokenMD4", "JARSYNC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); throw new Error(x); } try { for (int i = 0; i < 64; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "755cd64425f260e356f5303ee82a2d5f"; harness.check(exp.equals(Util.toHexString(md)), "testSixtyFourA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { harness.verbose("NOTE: This test may take a while."); for (int i = 0; i < 536870913; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "b6cea9f528a85963f7529a9e3a2153db"; harness.check(exp.equals(Util.toHexString(md)), "test536870913A"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { byte[] md = algorithm.digest("a".getBytes()); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testA"); } try { byte[] md = algorithm.digest("abc".getBytes()); String exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testABC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testABC"); } try { byte[] md = algorithm.digest("message digest".getBytes()); String exp = "d9130a8164549fe818874806e1c7014b"; harness.check(exp.equals(Util.toHexString(md)), "testMessageDigest"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testMessageDigest"); } try { byte[] md = algorithm.digest("abcdefghijklmnopqrstuvwxyz".getBytes()); String exp = "d79e1c308aa5bbcdeea8ed63df412da9"; harness.check(exp.equals(Util.toHexString(md)), "testAlphabet"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAlphabet"); } try { byte[] md = algorithm.digest("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".getBytes()); String exp = "043f8582f241db351ce627e153e7f0e4"; harness.check(exp.equals(Util.toHexString(md)), "testAsciiSubset"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAsciiSubset"); } try { byte[] md = algorithm.digest("12345678901234567890123456789012345678901234567890123456789012345678901234567890".getBytes()); String exp = "e33b4ddc9c38f2199c3e7b164fcc0536"; harness.check(exp.equals(Util.toHexString(md)), "testEightyNumerics"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testEightyNumerics"); } try { algorithm.update("a".getBytes(), 0, 1); clone = (MessageDigest) algorithm.clone(); byte[] md = algorithm.digest(); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #1"); clone.update("bc".getBytes(), 0, 2); md = clone.digest(); exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #2"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testCloning"); } }
|
11
|
Code Sample 1:
public String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
Code Sample 2:
public static String crypt(String target) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(target.getBytes("UTF-16")); BigInteger res = new BigInteger(1, md.digest(key.getBytes())); return res.toString(16); }
|
00
|
Code Sample 1:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
Code Sample 2:
public String[] doGeoQuery(String query) throws IOException { String baseURL = "http://maps.google.com/maps/geo?output=csv&keyABQIAAAAct2NN7QKbyiMr1rfhB6UGBQn1DChMmG6tCCZd3aXbcL03vlL5hSUZpyoaGCXRwjbRTSBi0L89DeYeg&q="; URL url = new URL(baseURL + URLEncoder.encode(query, "UTF-8")); URLConnection connection = url.openConnection(); StringBuffer buf = new StringBuffer(); InputStream is = (InputStream) connection.getContent(); int b = -1; while ((b = is.read()) != -1) { buf.append((char) b); } log.info("Geo Query " + url.toExternalForm() + " => " + buf.toString()); return buf.toString().split(","); }
|
00
|
Code Sample 1:
public static String MD5(String text) { try { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (Exception e) { System.out.println(e.toString()); } return null; }
Code Sample 2:
@Override public void create(DisciplinaDTO disciplina) { try { this.criaConexao(false); } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } String sql = "insert into Disciplina select nextval('sq_Disciplina') as id, ? as nome"; PreparedStatement stmt = null; try { stmt = this.getConnection().prepareStatement(sql); stmt.setString(1, disciplina.getNome()); int retorno = stmt.executeUpdate(); if (retorno == 0) { this.getConnection().rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de inserir dados de Disciplina no banco!"); } this.getConnection().commit(); } catch (SQLException e) { try { this.getConnection().rollback(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { try { throw e; } catch (SQLException ex) { java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex); } } } }
|
11
|
Code Sample 1:
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 void uploadFile(String filename) throws RQLException { checkFtpClient(); OutputStream out = null; try { out = ftpClient.storeFileStream(filename); IOUtils.copy(new FileReader(filename), out); out.close(); ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Upload of local file with name " + filename + " via FTP to server " + server + " failed.", ex); } }
|
11
|
Code Sample 1:
public static void s_copy(FileInputStream fis, FileOutputStream fos) throws Exception { FileChannel in = fis.getChannel(); FileChannel out = fos.getChannel(); in.transferTo(0, in.size(), out); if (in != null) in.close(); if (out != null) out.close(); }
Code Sample 2:
public static void main(String[] args) { paraProc(args); CanonicalGFF cgff = new CanonicalGFF(gffFilename); CanonicalGFF geneModel = new CanonicalGFF(modelFilename); CanonicalGFF transcriptGff = new CanonicalGFF(transcriptFilename); TreeMap ksTable1 = getKsTable(ksTable1Filename); TreeMap ksTable2 = getKsTable(ksTable2Filename); Map intronReadCntMap = new TreeMap(); Map intronSplicingPosMap = new TreeMap(); try { BufferedReader fr = new BufferedReader(new FileReader(inFilename)); while (fr.ready()) { String line = fr.readLine(); if (line.startsWith("#")) continue; String tokens[] = line.split("\t"); String chr = tokens[0]; int start = Integer.parseInt(tokens[1]); int stop = Integer.parseInt(tokens[2]); GenomeInterval intron = new GenomeInterval(chr, start, stop); int readCnt = Integer.parseInt(tokens[3]); intronReadCntMap.put(intron, readCnt); String splicingMapStr = tokens[4]; Map splicingMap = getSplicingMap(splicingMapStr); intronSplicingPosMap.put(intron, splicingMap); } fr.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } double[] hdCDF = getHdCdf(readLength, minimumOverlap); try { FileWriter fw = new FileWriter(outFilename); for (Iterator intronIterator = intronReadCntMap.keySet().iterator(); intronIterator.hasNext(); ) { GenomeInterval intron = (GenomeInterval) intronIterator.next(); int readCnt = ((Integer) intronReadCntMap.get(intron)).intValue(); TreeMap splicingMap = (TreeMap) intronSplicingPosMap.get(intron); Object ksInfoArray[] = distributionAccepter((TreeMap) splicingMap.clone(), readCnt, hdCDF, ksTable1, ksTable2); boolean ksAccepted = (Boolean) ksInfoArray[0]; double testK = (Double) ksInfoArray[1]; double standardK1 = (Double) ksInfoArray[2]; double standardK2 = (Double) ksInfoArray[3]; int positionCnt = splicingMap.size(); Object modelInfoArray[] = getModelAgreedSiteCnt(intron, cgff, geneModel, transcriptGff); int modelAgreedSiteCnt = (Integer) modelInfoArray[0]; int maxAgreedTransSiteCnt = (Integer) modelInfoArray[1]; boolean containedBySomeGene = (Boolean) modelInfoArray[2]; int numIntersectingGenes = (Integer) modelInfoArray[3]; int distance = intron.getStop() - intron.getStart(); fw.write(intron.getChr() + ":" + intron.getStart() + ".." + intron.getStop() + "\t" + distance + "\t" + readCnt + "\t" + splicingMap + "\t" + probabilityEvaluation(readLength, distance, readCnt, splicingMap, positionCnt) + "\t" + ksAccepted + "\t" + testK + "\t" + standardK1 + "\t" + standardK2 + "\t" + positionCnt + "\t" + modelAgreedSiteCnt + "\t" + maxAgreedTransSiteCnt + "\t" + containedBySomeGene + "\t" + numIntersectingGenes + "\n"); } fw.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } }
|
00
|
Code Sample 1:
public static InputStream download_file(String sessionid, String key) { InputStream is = null; String urlString = "https://s2.cloud.cm/rpc/raw?c=Storage&m=download_file&key=" + key; try { String apple = ""; URL url = new URL(urlString); Log.d("current running function name:", "download_file"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Cookie", "PHPSESSID=" + sessionid); conn.setRequestMethod("POST"); conn.setDoInput(true); is = conn.getInputStream(); return is; } catch (Exception e) { e.printStackTrace(); Log.d("download problem", "download problem"); } return is; }
Code Sample 2:
public String drive() { logger.info("\n"); logger.info("==========================================================="); logger.info("========== Start drive method ============================="); logger.info("==========================================================="); logger.entering(cl, "drive"); xstream = new XStream(new JsonHierarchicalStreamDriver()); xstream.setMode(XStream.NO_REFERENCES); xstream.alias("AuditDiffFacade", AuditDiffFacade.class); File auditSchemaFile = null; File auditSchemaXsdFile = null; try { if (configFile == null) { logger.severe("Request Failed: configFile is null"); return null; } else { if (configFile.getAuditSchemaFile() != null) { logger.info("auditSchemaFile=" + configFile.getAuditSchemaFile()); logger.info("auditSchemaXsdFile=" + configFile.getAuditSchemaXsdFile()); logger.info("plnXpathFile=" + configFile.getPlnXpathFile()); logger.info("auditSchemaFileDir=" + configFile.getAuditSchemaFileDir()); logger.info("auditReportFile=" + configFile.getAuditReportFile()); logger.info("auditReportXsdFile=" + configFile.getAuditReportXsdFile()); } else { logger.severe("Request Failed: auditSchemaFile is null"); return null; } } File test = new File(configFile.getAuditSchemaFileDir() + File.separator + "temp.xml"); auditSchemaFile = new File(configFile.getAuditSchemaFile()); if (!auditSchemaFile.exists() || auditSchemaFile.length() == 0L) { logger.severe("Request Failed: the audit schema file does not exist or empty"); return null; } auditSchemaXsdFile = null; if (configFile.getAuditSchemaXsdFile() != null) { auditSchemaXsdFile = new File(configFile.getAuditSchemaXsdFile()); } else { logger.severe("Request Failed: the audit schema xsd file is null"); return null; } if (!auditSchemaXsdFile.exists() || auditSchemaXsdFile.length() == 0L) { logger.severe("Request Failed: the audit schema xsd file does not exist or empty"); return null; } SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(auditSchemaXsdFile); Validator validator = schema.newValidator(); Source source = new StreamSource(auditSchemaFile); validator.validate(source); } catch (SAXException e) { logger.warning("SAXException caught trying to validate input Schema Files: "); e.printStackTrace(); } catch (IOException e) { logger.warning("IOException caught trying to read input Schema File: "); e.printStackTrace(); } String xPathFile = null; if (configFile.getPlnXpathFile() != null) { xPathFile = configFile.getPlnXpathFile(); logger.info("Attempting to retrieve xpaths from file: '" + xPathFile + "'"); XpathUtility.readFile(xPathFile); } else { logger.severe("Configuration file does not have a value for the Xpath Filename"); return null; } Properties xpathProps = XpathUtility.getXpathsProps(); if (xpathProps == null) { logger.severe("No Xpaths could be extracted from file: '" + xPathFile + "' - xpath properties object is null"); return null; } if (xpathProps.isEmpty()) { logger.severe("No Xpaths could be extracted from file: '" + xPathFile + "' - xpath properties object is empty"); return null; } logger.info(xpathProps.size() + " xpaths retrieved."); for (String key : xpathProps.stringPropertyNames()) { logger.info("Key=" + key + " Value=" + xpathProps.getProperty(key)); } logger.info("\n"); logger.info("==========================================================="); logger.info("========== Process XML Schema File BEGIN =================="); logger.info("==========================================================="); SchemaSAXReader sax = new SchemaSAXReader(); ArrayList<String> key_matches = new ArrayList<String>(sax.parseDocument(auditSchemaFile, xpathProps)); logger.info("Check Input xpath hash against xpaths found in Schema."); Comparison comp_keys = new Comparison(); ArrayList<String> in_xpath_not_in_schema = new ArrayList<String>(comp_keys.keys_not_in_both_hashes(xpathProps, Utility.arraylist_to_map(key_matches, "key_matches"), "xpath Properties", "hm_key_matches")); if (in_xpath_not_in_schema.size() > 0) { logger.severe("All XPaths in Input xpath Properties list were not found in Schema."); logger.severe("Xpaths in xpath Properties list missing from schema file:" + xstream.toXML(in_xpath_not_in_schema)); logger.severe("Quitting."); return null; } Map<String, Map> schema_audit_hashbox = sax.get_audit_hashbox(); logger.info("schema_audit_hashbox\n" + xstream.toXML(schema_audit_hashbox)); Map<String, Map> schema_network_hashbox = sax.get_net_hashbox(); logger.info("schema_network_hashbox\n" + xstream.toXML(schema_network_hashbox)); Map<String, Map> schema_host_hashbox = sax.get_host_hashbox(); Map<String, Map> schema_au_hashbox = sax.get_au_hashbox(); logger.info("schema_au_hashbox\n" + xstream.toXML(schema_au_hashbox)); Hasherator hr = new Hasherator(); Set<String> s_host_hb_additions = new HashSet<String>(); s_host_hb_additions.add("/SSP/network/@network_id"); schema_host_hashbox = hr.copy_hashbox_entries(schema_network_hashbox, schema_host_hashbox, s_host_hb_additions); logger.info("schema_host_hashbox(after adding network name)\n" + xstream.toXML(schema_host_hashbox)); Map<String, String> transforms_s_au_hb = new HashMap<String, String>(); transforms_s_au_hb.put("/SSP/archivalUnits/au/auCapabilities/storageRequired/@max_size", "s_gigabytes_to_string_bytes_unformatted()"); schema_au_hashbox = hr.convert_hashbox_vals(schema_au_hashbox, transforms_s_au_hb); Map<String, String> transforms_s_host_hb = new HashMap<String, String>(); transforms_s_host_hb.put("/SSP/hosts/host/hostCapabilities/storageAvailable/@max_size", "s_gigabytes_to_string_bytes_unformatted()"); schema_host_hashbox = hr.convert_hashbox_vals(schema_host_hashbox, transforms_s_host_hb); logger.info("schema_host_hashbox(after transformations)\n" + xstream.toXML(schema_host_hashbox)); logger.info("\n"); logger.info("========== Process Schema END ============================"); logger.info("\n"); logger.info("========== Database Operations ============================"); MYSQLWorkPlnHostSummaryDAO daowphs = new MYSQLWorkPlnHostSummaryDAO(); daowphs.drop(); daowphs.create(); daowphs.updateTimestamp(); CachedRowSet rs_q0_N = daowphs.query_0_N(); double d_space_total = DBUtil.get_single_db_double_value(rs_q0_N, "net_sum_repo_size"); double d_space_used = DBUtil.get_single_db_double_value(rs_q0_N, "net_sum_used_space"); double d_space_free = d_space_total - d_space_used; double d_avg_uptime = DBUtil.get_single_db_double_value(rs_q0_N, "net_avg_uptime"); long space_total = (long) d_space_total; long space_used = (long) d_space_used; long space_free = space_total - space_used; String f_space_total = Utility.l_bytes_to_other_units_formatted(space_total, 3, "T"); String f_space_used = Utility.l_bytes_to_other_units_formatted(space_used, 3, "G"); String f_space_free = Utility.l_bytes_to_other_units_formatted(space_free, 3, "T"); String f_space_free2 = Utility.l_bytes_to_other_units_formatted(space_free, 3, null); logger.info("d_space_total: " + d_space_total + "\n" + "d_space_used: " + d_space_used + "\n" + "space_total: " + space_total + "\n" + "space_used: " + space_used + "\n" + "space_free: " + space_free + "\n\n" + "Double.toString( d_space_total ): " + Double.toString(d_space_total) + "\n\n" + "f_space_total: " + f_space_total + "\n" + "f_space_used: " + f_space_used + "\n" + "f_space_free: " + f_space_free + "\n" + "f_space_free2: " + f_space_free2); rprtCnst = new ReportData(); logger.info("\n"); logger.info("========== Load Report Constants from Calculations ==========="); rprtCnst.addKV("REPORT_HOSTS_TOTAL_DISKSPACE", f_space_total); rprtCnst.addKV("REPORT_HOSTS_TOTAL_DISKSPACE_USED", f_space_used); rprtCnst.addKV("REPORT_HOSTS_TOTAL_DISKSPACE_FREE", f_space_free); rprtCnst.addKV("REPORT_HOSTS_MEAN_UPTIME", Utility.ms_to_dd_hh_mm_ss_formatted((long) d_avg_uptime)); logger.info("r=\n" + rprtCnst.toString()); logger.info("\n"); logger.info("========== Load Report Constants from ConfigFile ============="); rprtCnst.addKV("REPORT_FILENAME_SCHEMA_FILENAME", configFile.getAuditSchemaFile()); rprtCnst.addKV("REPORT_FILENAME_SCHEMA_FILE_XSD_FILENAME", configFile.getAuditSchemaXsdFile()); rprtCnst.addKV("REPORT_FILENAME_XML_DIFF_FILENAME", configFile.getAuditReportFile()); rprtCnst.addKV("REPORT_FILENAME_XML_DIFF_FILE_XSD_FILENAME", configFile.getAuditReportXsdFile()); logger.info("\n"); logger.info("========== Load Report Constants from Hashboxes =============="); Set auditHBKeySet = hr.getMapKeyset(schema_audit_hashbox, "schema_audit_hashbox"); String audit_id = hr.singleKeysetEntryToString(auditHBKeySet); logger.info("audit_id: " + audit_id); Set networkHBKeySet = hr.getMapKeyset(schema_network_hashbox, "schema_network_hashbox"); String network_id = hr.singleKeysetEntryToString(networkHBKeySet); logger.info("network_id: " + network_id); rprtCnst.addKV("REPORT_AUDIT_ID", audit_id); rprtCnst.addKV("REPORT_AUDIT_REPORT_EMAIL", hr.extractSingleValueFromHashbox(schema_audit_hashbox, "schema_audit_hashbox", audit_id, "/SSP/audit/auditReportEmail")); rprtCnst.addKV("REPORT_AUDIT_INTERVAL", hr.extractSingleValueFromHashbox(schema_audit_hashbox, "schema_audit_hashbox", audit_id, "/SSP/audit/auditReportInterval/@maxDays")); rprtCnst.addKV("REPORT_SCHEMA_VERSION", hr.extractSingleValueFromHashbox(schema_audit_hashbox, "schema_audit_hashbox", audit_id, "/SSP/audit/schemaVersion")); rprtCnst.addKV("REPORT_CLASSIFICATION_GEOGRAPHIC_SUMMARY_SCHEME", hr.extractSingleValueFromHashbox(schema_audit_hashbox, "schema_audit_hashbox", audit_id, "/SSP/audit/geographicSummaryScheme")); rprtCnst.addKV("REPORT_CLASSIFICATION_SUBJECT_SUMMARY_SCHEME", hr.extractSingleValueFromHashbox(schema_audit_hashbox, "schema_audit_hashbox", audit_id, "/SSP/audit/subjectSummaryScheme")); rprtCnst.addKV("REPORT_CLASSIFICATION_OWNER_INSTITUTION_SUMMARY_SCHEME", hr.extractSingleValueFromHashbox(schema_audit_hashbox, "schema_audit_hashbox", audit_id, "/SSP/audit/ownerInstSummaryScheme")); rprtCnst.addKV("REPORT_NETWORK_ID", network_id); rprtCnst.addKV("REPORT_NETWORK_ADMIN_EMAIL", hr.extractSingleValueFromHashbox(schema_network_hashbox, "schema_network_hashbox", network_id, "/SSP/network/networkIdentity/accessBase/@adminEmail")); rprtCnst.addKV("REPORT_GEOGRAPHIC_CODING", hr.extractSingleValueFromHashbox(schema_network_hashbox, "schema_network_hashbox", network_id, "/SSP/network/networkIdentity/geographicCoding")); logger.info("\n"); logger.info("==========================================================="); logger.info("========== Process Network Data BEGIN======================"); logger.info("==========================================================="); Set<String> tableSet0 = reportAuOverviewFacade.findAllTables(); String reportAuOverviewTable = "report_au_overview"; int n_tabs = 0; if (tableSet0 != null && !tableSet0.isEmpty()) { logger.fine("Table List N=" + tableSet0.size()); for (String tableName : tableSet0) { n_tabs++; if (tableName.equalsIgnoreCase(reportAuOverviewTable)) { logger.fine(n_tabs + " " + tableName + " <--"); } else { logger.fine(n_tabs + " " + tableName); } } } else { logger.fine("No tables found in DB."); } if (!tableSet0.contains(reportAuOverviewTable)) { logger.info("Database does not contain table '" + reportAuOverviewTable + "'"); } List<ReportAuOverview> repAuOvTabAllData = null; repAuOvTabAllData = reportAuOverviewFacade.findAll(); if (repAuOvTabAllData != null && !(repAuOvTabAllData.isEmpty())) { logger.fine("\n" + reportAuOverviewTable + " table has " + repAuOvTabAllData.size() + " rows."); int n_rows = 0; for (ReportAuOverview row : repAuOvTabAllData) { n_rows++; logger.fine(n_rows + " " + row.toString()); } } else { logger.fine(reportAuOverviewTable + " is null, empty, or nonexistent."); } logger.fine("report_au_overview Table xstream Dump:\n" + xstream.toXML(repAuOvTabAllData)); logger.fine("\n"); logger.fine("Iterate over repAuOvTabAllData 2"); Iterator it = repAuOvTabAllData.iterator(); int n_el = 0; while (it.hasNext()) { ++n_el; String el = it.next().toString(); logger.fine(n_el + ". " + el); } Class aClass = edu.harvard.iq.safe.saasystem.entities.ReportAuOverview.class; String reportAuOverviewTableName = reportAuOverviewFacade.getTableName(); logger.fine("\n"); logger.fine("EntityManager Tests"); logger.fine("Table: " + reportAuOverviewTableName); logger.fine("\n"); logger.fine("Schema: " + reportAuOverviewFacade.getSchema()); logger.fine("\n"); Set columnList = reportAuOverviewFacade.getColumnList(reportAuOverviewFacade.getTableName()); logger.fine("Columns (fields) in table '" + reportAuOverviewTableName + "' (N=" + columnList.size() + ")"); Set<String> colList = new HashSet(); Iterator colNames = columnList.iterator(); int n_el2 = 0; while (colNames.hasNext()) { ++n_el2; String el = colNames.next().toString(); logger.fine(n_el2 + ". " + el); colList.add(el); } logger.fine(colList.size() + " entries in Set 'colList' "); logger.info("========== Query 'au_overview_table'============="); MySQLAuOverviewDAO daoao = new MySQLAuOverviewDAO(); CachedRowSet rs_q1_A = daoao.query_q1_A(); int[] au_table_rc = DBUtil.get_rs_dims(rs_q1_A); logger.info("Au Table Query ResultSet has " + au_table_rc[0] + " rows and " + au_table_rc[1] + " columns."); rprtCnst.addKV("REPORT_N_AUS_IN_NETWORK", Integer.toString(au_table_rc[0])); logger.info("========== Create 'network_au_hashbox' =========="); Map<String, Map> network_au_hashbox = new TreeMap<String, Map>(DBUtil.rs_to_hashbox(rs_q1_A, null, "au_id")); logger.info("network_au_hashbox before transformations\n" + xstream.toXML(network_au_hashbox)); Map<String, String> transforms_n_au_hb = new HashMap<String, String>(); transforms_n_au_hb.put("last_s_crawl_end", "ms_to_decimal_days_elapsed()"); transforms_n_au_hb.put("last_s_poll_end", "ms_to_decimal_days_elapsed()"); transforms_n_au_hb.put("crawl_duration", "ms_to_decimal_days()"); network_au_hashbox = hr.convert_hashbox_vals(network_au_hashbox, transforms_n_au_hb); Map<String, String> auNVerifiedRegions = reportAuOverviewFacade.getAuNVerifiedRegions(); logger.fine("auNVerifiedRegions\n" + xstream.toXML(auNVerifiedRegions)); network_au_hashbox = hr.addNewInnerHashEntriesToHashbox(network_au_hashbox, auNVerifiedRegions, "au_n_verified_regions"); logger.info("network_au_hashbox after Transformations and Addition of 'au_n_verified_regions'" + xstream.toXML(network_au_hashbox)); logger.info("========== Compare AUs BEGIN =============================="); ArrayList<String> al_aus_in_schema_not_in_network = new ArrayList<String>(comp_keys.keys_not_in_both_hashes(schema_au_hashbox, network_au_hashbox, "schema_aus", "network_aus")); Map<String, String> h_aus_in_schema_not_in_network = hr.get_names_from_id_list(schema_au_hashbox, al_aus_in_schema_not_in_network, "/SSP/archivalUnits/au/auIdentity/name"); rprtCnst.addKV("REPORT_N_AUS_IN_SCHEMA_NOT_IN_NETWORK", Integer.toString(al_aus_in_schema_not_in_network.size())); rprtCnst.set_h_aus_in_schema_not_in_network(h_aus_in_schema_not_in_network); MYSQLReportAusInSchemaNotInNetworkDAO daoraisnin = new MYSQLReportAusInSchemaNotInNetworkDAO(); daoraisnin.create(); daoraisnin.update(h_aus_in_schema_not_in_network); ArrayList<String> al_aus_in_network_not_in_schema = new ArrayList<String>(comp_keys.keys_not_in_both_hashes(network_au_hashbox, schema_au_hashbox, "network_aus", "schema_aus")); Utility.print_arraylist(al_aus_in_network_not_in_schema, "aus in_network_not_in_schema"); Map<String, String> h_aus_in_network_not_in_schema = hr.get_names_from_id_list(network_au_hashbox, al_aus_in_network_not_in_schema, "au_name"); rprtCnst.addKV("REPORT_N_AUS_IN_NETWORK_NOT_IN_SCHEMA", Integer.toString(al_aus_in_network_not_in_schema.size())); rprtCnst.set_h_aus_in_network_not_in_schema(h_aus_in_network_not_in_schema); MYSQLReportAusInNetworkNotInSchemaDAO daorainnis = new MYSQLReportAusInNetworkNotInSchemaDAO(); daorainnis.create(); daorainnis.update(h_aus_in_network_not_in_schema); Comparison comp_au = new Comparison(schema_au_hashbox, "Schema_AU", network_au_hashbox, "Network_AU", XpathUtility.getXpathToDbColumnMap(), XpathUtility.getXpathToCompOpMap()); comp_au.init(); logger.info("Attempting to create DB table 'lockss_audit.audit_results_au'"); MYSQLAuditResultsAuDAO daoara = new MYSQLAuditResultsAuDAO(); daoara.create(); String results_table_au = "audit_results_au"; String sql_vals_au_schema = comp_au.iterate_hbs_au(daoara, results_table_au, "au", h_aus_in_network_not_in_schema); CachedRowSet rs_RA2 = daoara.query_q1_RA(); String n_aus_not_verified = DBUtil.get_single_count_from_rs(rs_RA2); rprtCnst.addKV("REPORT_N_AUS_NOT_VERIFIED", DBUtil.get_single_count_from_rs(rs_RA2)); logger.info("\nInstantiating Result Class from main()"); DiffResult result = new DiffResult(); Map au_comp_host = result.get_result_hash("au"); logger.info("========== Compare AUs END ================================"); logger.info("========== Process Network Host Table ====================="); logger.info("========== Query 'lockss_box_table' and ========="); logger.info("================ 'repository_space_table' =======\n"); MySQLLockssBoxRepositorySpaceDAO daolbrs = new MySQLLockssBoxRepositorySpaceDAO(); CachedRowSet rs_q1_H = daolbrs.query_q1_H(); int[] host_table_rc = DBUtil.get_rs_dims(rs_q1_H); logger.info("Host Table Query ResultSet has " + host_table_rc[0] + " rows and " + host_table_rc[1] + " columns."); rprtCnst.addKV("REPORT_N_HOSTS_IN_NETWORK", Integer.toString(host_table_rc[0])); Long numberOfMemberHosts; if (StringUtils.isNotBlank(saasConfigurationRegistry.getSaasConfigProperties().getProperty("saas.ip.fromlockssxml"))) { numberOfMemberHosts = Long.parseLong(Integer.toString(saasConfigurationRegistry.getSaasConfigProperties().getProperty("saas.ip.fromlockssxml").split(",").length)); } else { if (StringUtils.isNotBlank(saasConfigurationRegistry.getSaasAuditConfigProperties().getProperty("saas.targetIp"))) { numberOfMemberHosts = Long.parseLong(Integer.toString(saasConfigurationRegistry.getSaasAuditConfigProperties().getProperty("saas.targetIp").split(",").length)); } else { numberOfMemberHosts = 0L; } } rprtCnst.addKV("REPORT_N_HOSTS_IN_NETWORK_2", Long.toString(numberOfMemberHosts)); Long numberOfReachableHosts; numberOfReachableHosts = lockssBoxFacade.getTotalHosts(); rprtCnst.addKV("REPORT_N_HOSTS_IN_NETWORK_REACHABLE", Long.toString(numberOfReachableHosts)); Map<String, Map> network_host_hashbox = new TreeMap<String, Map>(DBUtil.rs_to_hashbox(rs_q1_H, null, "ip_address")); logger.info("network_host_hashbox before transformations\n" + xstream.toXML(network_host_hashbox)); Map<String, String> transforms_n_host_hb = new HashMap<String, String>(); transforms_n_host_hb.put("repo_size", "SciToStr2()"); transforms_n_host_hb.put("used_space", "SciToStr2()"); network_host_hashbox = hr.convert_hashbox_vals(network_host_hashbox, transforms_n_host_hb); logger.info("network_host_hashbox(after transformations)\n" + xstream.toXML(network_host_hashbox)); Map<String, String> network_host_hb_sel_used_space = hr.join_hash_pk_to_inner_hash_value(network_host_hashbox, "used_space"); Map<String, String> schema_host_hb_sel_size = hr.join_hash_pk_to_inner_hash_value(schema_host_hashbox, "/SSP/hosts/host/hostCapabilities/storageAvailable/@max_size"); logger.info("\n========== Process Network END ==========================="); logger.info("========== Compare Key Sets (IDs)=========================="); Set<String> sa_hb_keys = hr.gen_hash_keyset(schema_au_hashbox, "schema_au_hashbox"); hr.set_hash_keyset(sa_hb_keys, "s_au_hb"); Set<String> sh_hb_keys = hr.gen_hash_keyset(schema_host_hashbox, "schema_host_hashbox"); hr.set_hash_keyset(sh_hb_keys, "s_h_hb"); Set<String> na_hb_keys = hr.gen_hash_keyset(network_au_hashbox, "network_au_hashbox"); hr.set_hash_keyset(na_hb_keys, "n_au_hb"); Set<String> nh_hb_keys = hr.gen_hash_keyset(network_host_hashbox, "network_host_hashbox"); hr.set_hash_keyset(nh_hb_keys, "n_h_hb"); Set<String> aus_in_schema_not_in_network = new TreeSet<String>(hr.get_hash_keyset("s_au_hb")); aus_in_schema_not_in_network.removeAll(hr.get_hash_keyset("n_au_hb")); Set<String> aus_in_network_not_in_schema = new TreeSet<String>(hr.get_hash_keyset("n_au_hb")); aus_in_network_not_in_schema.removeAll(hr.get_hash_keyset("s_au_hb")); Set<String> symmetricDiff = new HashSet<String>(hr.get_hash_keyset("s_au_hb")); symmetricDiff.addAll(hr.get_hash_keyset("n_au_hb")); Set<String> tmp = new HashSet<String>(hr.get_hash_keyset("s_au_hb")); tmp.retainAll(hr.get_hash_keyset("n_au_hb")); symmetricDiff.removeAll(tmp); Set<String> hosts_in_network_not_in_schema = new TreeSet<String>(hr.get_hash_keyset("n_h_hb")); hosts_in_network_not_in_schema.removeAll(hr.get_hash_keyset("s_h_hb")); Set<String> hosts_in_schema_not_in_network = new TreeSet<String>(hr.get_hash_keyset("s_h_hb")); hosts_in_schema_not_in_network.removeAll(hr.get_hash_keyset("n_h_hb")); ArrayList<String> al_hosts_in_schema_not_in_network = new ArrayList<String>(comp_keys.keys_not_in_both_hashes(schema_host_hashbox, network_host_hashbox, "schema_hosts", "network_hosts")); Map<String, String> h_hosts_in_schema_not_in_network = hr.get_names_from_id_list(schema_host_hashbox, al_hosts_in_schema_not_in_network, "/SSP/hosts/host/hostIdentity/name"); rprtCnst.addKV("REPORT_N_HOSTS_IN_SCHEMA_NOT_IN_NETWORK", Integer.toString(al_hosts_in_schema_not_in_network.size())); rprtCnst.set_h_hosts_in_schema_not_in_network(h_hosts_in_schema_not_in_network); MYSQLReportHostsInSchemaNotInNetworkDAO daorhisnin = new MYSQLReportHostsInSchemaNotInNetworkDAO(); daorhisnin.create(); daorhisnin.update(h_hosts_in_schema_not_in_network); ArrayList<String> al_hosts_in_network_not_in_schema = new ArrayList<String>(comp_keys.keys_not_in_both_hashes(network_host_hashbox, schema_host_hashbox, "network_hosts", "schema_hosts")); Map<String, String> h_hosts_in_network_not_in_schema = hr.get_names_from_id_list(network_host_hashbox, al_hosts_in_network_not_in_schema, "host_name"); rprtCnst.addKV("REPORT_N_HOSTS_IN_NETWORK_NOT_IN_SCHEMA", Integer.toString(al_hosts_in_network_not_in_schema.size())); rprtCnst.set_h_hosts_in_network_not_in_schema(h_hosts_in_network_not_in_schema); MYSQLReportHostsInNetworkNotInSchemaDAO rhinnis = new MYSQLReportHostsInNetworkNotInSchemaDAO(); rhinnis.create(); rhinnis.update(h_hosts_in_network_not_in_schema); logger.info("========== Compare Hosts BEGIN ============================"); Comparison comp_host = new Comparison(schema_host_hashbox, "Schema_Host", network_host_hashbox, "Network_Host", XpathUtility.getXpathToDbColumnMap(), XpathUtility.getXpathToCompOpMap()); comp_host.init(); MYSQLAuditResultsHostDAO daoarh = new MYSQLAuditResultsHostDAO(); daoarh.create(); String sql_vals_host_schema = comp_host.iterate_hbs_host(daoarh, "audit_results_host", "host", h_hosts_in_network_not_in_schema); CachedRowSet rs_RH = daoarh.query_q1_RH(); String n_hosts_not_meeting_storage = DBUtil.get_single_count_from_rs(rs_RH); rprtCnst.addKV("REPORT_N_HOSTS_NOT_MEETING_STORAGE", n_hosts_not_meeting_storage); logger.info("Calling result.get_result_hash( \"host\" ) from main()"); Map host_comp_hash = result.get_result_hash("host"); Map au_comp_hash2 = result.get_result_hash("au"); logger.info("========== Compare Hosts END =============================="); Map<String, String> map_host_ip_to_host_name = hr.make_id_hash(schema_host_hashbox, "/SSP/hosts/host/hostIdentity/name"); rprtCnst.addKV("REPORT_N_HOSTS_IN_SCHEMA", Integer.toString(map_host_ip_to_host_name.size())); String[] host_ip_list = hr.hash_keys_to_array(schema_host_hashbox); String[][] col2 = Utility.add_column_to_array1(map_host_ip_to_host_name.values().toArray(new String[0]), host_ip_list, null); Map<String, String> map_au_key_string_to_au_name = hr.make_id_hash(schema_au_hashbox, "/SSP/archivalUnits/au/auIdentity/name"); logger.info("Length map_au_key_string_to_au_name.values().toArray(new String[0]: " + map_au_key_string_to_au_name.values().toArray(new String[0]).length); rprtCnst.addKV("REPORT_N_AUS_IN_SCHEMA", Integer.toString(map_au_key_string_to_au_name.size())); MySQLLockssBoxArchivalUnitStatusDAO daolbaus = new MySQLLockssBoxArchivalUnitStatusDAO(); int[] rc = daolbaus.getResultSetDimensions(); int n_rs_rows = rc[0]; int n_rs_cols = rc[1]; logger.info("\n" + n_rs_rows + " rows (Host-AU's). " + n_rs_cols + " columns."); rprtCnst.addKV("REPORT_N_HOST_AUS_IN_NETWORK", Integer.toString(n_rs_rows)); logger.info("================== Query 'audit_results_host' Table =========="); CachedRowSet NNonCompliantAUsCRS = daoara.getNNonCompliantAUs(); String NNonCompliantAUs = DBUtil.get_single_count_from_rs(NNonCompliantAUsCRS); rprtCnst.addKV("REPORT_N_AUS_NONCOMPLIANT", NNonCompliantAUs); logger.info("================== Query 'audit_results_host' Table END ======"); logger.info("========== Output Report =================================="); MYSQLReportConstantsDAO daorc = new MYSQLReportConstantsDAO(); daorc.create(); daorc.update(rprtCnst.getBox()); MYSQLReportHostSummaryDAO daorhs = new MYSQLReportHostSummaryDAO(); daorhs.create(); CachedRowSet crsarh = daoarh.queryAll(); daorhs.update(crsarh); daorhs.update_new_column("space_offered", schema_host_hb_sel_size); daorhs.update_new_column("space_used", network_host_hb_sel_used_space); Map<String, String> computation_cols_in_net_host_summary = new HashMap<String, String>(); computation_cols_in_net_host_summary.put("space_total", "1"); computation_cols_in_net_host_summary.put("space_used", "2"); daorhs.update_compute_column("space_free", computation_cols_in_net_host_summary); logger.info("========== Audit Report Writer ======================================"); AuditReportXMLWriter arxw = new AuditReportXMLWriter(rprtCnst, configFile.getAuditReportFile()); Set<String> tableSet = tracAuditChecklistDataFacade.findAllTables(); String tracResultTable = "trac_audit_checklist_data"; List<TracAuditChecklistData> evidenceList = null; if (tableSet.contains(tracResultTable)) { evidenceList = tracAuditChecklistDataFacade.findAll(); logger.info("TRAC evidence list is size:" + evidenceList.size()); } else { logger.info("Database does not contain table 'trac_audit_checklist_data'"); } Map<String, String> tracDataMap = new LinkedHashMap<String, String>(); for (TracAuditChecklistData tracdata : evidenceList) { tracDataMap.put(tracdata.getAspectId(), tracdata.getEvidence()); } String writeTimestamp = arxw.write(daoarh, daoara, daorc, tracDataMap); File target = new File(configFile.getAuditReportFileDir() + File.separator + configFile.getAuditSchemaFileName() + "." + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(auditSchemaFile).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } logger.info("\n========== EXIT drive() ==========================================="); return writeTimestamp; }
|
00
|
Code Sample 1:
private boolean doDelete(String identifier) throws IOException, MalformedURLException { URL url = new URL(baseurl.toString() + "/" + identifier); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); huc.setRequestMethod("DELETE"); huc.connect(); if (huc.getResponseCode() == 200) { return true; } else return false; }
Code Sample 2:
public void test(TestHarness harness) { harness.checkPoint("TestOfMD4"); try { Security.addProvider(new JarsyncProvider()); algorithm = MessageDigest.getInstance("BrokenMD4", "JARSYNC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); throw new Error(x); } try { for (int i = 0; i < 64; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "755cd64425f260e356f5303ee82a2d5f"; harness.check(exp.equals(Util.toHexString(md)), "testSixtyFourA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { harness.verbose("NOTE: This test may take a while."); for (int i = 0; i < 536870913; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "b6cea9f528a85963f7529a9e3a2153db"; harness.check(exp.equals(Util.toHexString(md)), "test536870913A"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { byte[] md = algorithm.digest("a".getBytes()); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testA"); } try { byte[] md = algorithm.digest("abc".getBytes()); String exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testABC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testABC"); } try { byte[] md = algorithm.digest("message digest".getBytes()); String exp = "d9130a8164549fe818874806e1c7014b"; harness.check(exp.equals(Util.toHexString(md)), "testMessageDigest"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testMessageDigest"); } try { byte[] md = algorithm.digest("abcdefghijklmnopqrstuvwxyz".getBytes()); String exp = "d79e1c308aa5bbcdeea8ed63df412da9"; harness.check(exp.equals(Util.toHexString(md)), "testAlphabet"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAlphabet"); } try { byte[] md = algorithm.digest("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".getBytes()); String exp = "043f8582f241db351ce627e153e7f0e4"; harness.check(exp.equals(Util.toHexString(md)), "testAsciiSubset"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAsciiSubset"); } try { byte[] md = algorithm.digest("12345678901234567890123456789012345678901234567890123456789012345678901234567890".getBytes()); String exp = "e33b4ddc9c38f2199c3e7b164fcc0536"; harness.check(exp.equals(Util.toHexString(md)), "testEightyNumerics"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testEightyNumerics"); } try { algorithm.update("a".getBytes(), 0, 1); clone = (MessageDigest) algorithm.clone(); byte[] md = algorithm.digest(); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #1"); clone.update("bc".getBytes(), 0, 2); md = clone.digest(); exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #2"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testCloning"); } }
|
00
|
Code Sample 1:
private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
Code Sample 2:
public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
|
11
|
Code Sample 1:
private static void addFolderToZip(File folder, ZipOutputStream zip, String baseName) throws IOException { File[] files = folder.listFiles(); for (File file : files) { if (file.isDirectory()) { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(name + "/"); zip.putNextEntry(zipEntry); zip.closeEntry(); addFolderToZip(file, zip, baseName); } else { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(updateFilename(name)); zip.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(file), zip); zip.closeEntry(); } } }
Code Sample 2:
public String upload() throws IOException { int idx = docIndex.incrementAndGet(); String tmpName = "namefinder/doc_" + idx + "__" + fileFileName; File tmpFile = tmpFile(tmpName); if (tmpFile.exists()) { org.apache.commons.io.FileUtils.deleteQuietly(tmpFile); } org.apache.commons.io.FileUtils.touch(tmpFile); InputStream fileStream = new FileInputStream(file); OutputStream bos = new FileOutputStream(tmpFile); IOUtils.copy(fileStream, bos); bos.close(); fileStream.close(); return tmpUrl(tmpName); }
|
11
|
Code Sample 1:
public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
Code Sample 2:
private void initialize() { if (!initialized) { if (context.getJavadocLinks() != null) { for (String url : context.getJavadocLinks()) { if (!url.endsWith("/")) { url += "/"; } StringWriter writer = new StringWriter(); try { IOUtils.copy(new URL(url + "package-list").openStream(), writer); } catch (Exception e) { e.printStackTrace(); continue; } StringTokenizer tokenizer2 = new StringTokenizer(writer.toString()); while (tokenizer2.hasMoreTokens()) { javadocByPackage.put(tokenizer2.nextToken(), url); } } } initialized = true; } }
|
00
|
Code Sample 1:
public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } }
Code Sample 2:
@Override public User login(String username, String password) { User user = null; try { user = (User) em.createQuery("Select o from User o where o.username = :username").setParameter("username", username).getSingleResult(); } catch (NoResultException e) { throw new NestedException(e.getMessage(), e); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(password.getBytes("UTF-8")); byte[] hash = digest.digest(); BigInteger bigInt = new BigInteger(1, hash); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } if (hashtext.equals(user.getPassword())) return user; } catch (Exception e) { throw new NestedException(e.getMessage(), e); } return null; }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } }
|
00
|
Code Sample 1:
public Boolean connect() throws Exception { try { _ftpClient = new FTPClient(); _ftpClient.connect(_url); _ftpClient.login(_username, _password); _rootPath = _ftpClient.printWorkingDirectory(); return true; } catch (Exception ex) { throw new Exception("Cannot connect to server."); } }
Code Sample 2:
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { long startTime = System.currentTimeMillis(); boolean validClient = true; boolean validSession = false; String sessionKey = req.getParameter("sid"); String storedKey = CLIENT_SESSION_KEYS.get(req.getRemoteAddr()); if (sessionKey != null && storedKey != null && sessionKey.equals(storedKey)) validSession = true; DataStore ds = DataStore.getConnection(); if (IPV6_DETECTED) { boolean doneWarning; synchronized (SJQServlet.class) { doneWarning = IPV6_WARNED; if (!IPV6_WARNED) IPV6_WARNED = true; } if (!doneWarning) LOG.warn("IPv6 interface detected; client restriction settings ignored [restrictions do not support IPv6 addresses]"); } else { String[] clntRestrictions = ds.getSetting("ValidClients", "").split(";"); List<IPMatcher> matchers = new ArrayList<IPMatcher>(); if (clntRestrictions.length == 1 && clntRestrictions[0].trim().length() == 0) { LOG.warn("All client connections are being accepted and processed, please consider setting up client restrictions in SJQ settings"); } else { for (String s : clntRestrictions) { s = s.trim(); try { matchers.add(new IPMatcher(s)); } catch (IPMatcherException e) { LOG.error("Invalid client restriction settings; client restrictions ignored!", e); matchers.clear(); break; } } validClient = matchers.size() > 0 ? false : true; for (IPMatcher m : matchers) { try { if (m.match(req.getRemoteAddr())) { validClient = true; break; } } catch (IPMatcherException e) { LOG.error("IPMatcherException", e); } } } } String clntProto = req.getParameter("proto"); if (clntProto == null || Integer.parseInt(clntProto) != SJQ_PROTO) throw new RuntimeException("Server is speaking protocol '" + SJQ_PROTO + "', but client is speaking protocol '" + clntProto + "'; install a client version that matches the server protocol version!"); resp.setHeader("Content-Type", "text/plain"); resp.setDateHeader("Expires", 0); resp.setDateHeader("Last-Modified", System.currentTimeMillis()); resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); resp.setHeader("Pragma", "no-cache"); String cmd = req.getParameter("cmd"); if (cmd == null) { DataStore.returnConnection(ds); return; } ActiveClientList list = ActiveClientList.getInstance(); BufferedWriter bw = new BufferedWriter(resp.getWriter()); if (cmd.equals("pop")) { if (!validClient) { LOG.warn("Client IP rejected: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { list.add(req.getRemoteHost()); ClientParser clnt = new ClientParser(new StringReader(ds.getClientConf(req.getRemoteHost()))); String offDay = clnt.getGlobalOption("OFFDAY"); String offHour = clnt.getGlobalOption("OFFHOUR"); Calendar now = Calendar.getInstance(); if (RangeInterpreter.inRange(now.get(Calendar.DAY_OF_WEEK), 1, 7, offDay) || RangeInterpreter.inRange(now.get(Calendar.HOUR_OF_DAY), 0, 23, offHour)) { LOG.warn("Client '" + req.getRemoteAddr() + "' currently disabled via OFFDAY/OFFHOUR settings."); bw.write("null"); } else { Task t = TaskQueue.getInstance().pop(req.getRemoteHost(), getPopCandidates(req.getRemoteHost(), clnt)); if (t == null) bw.write("null"); else { t.setResourcesUsed(Integer.parseInt(clnt.getTask(t.getTaskId()).getOption("RESOURCES"))); Object obj = null; if (t.getObjType().equals("media")) obj = Butler.SageApi.mediaFileAPI.GetMediaFileForID(Integer.parseInt(t.getObjId())); else if (t.getObjType().equals("sysmsg")) obj = SystemMessageUtils.getSysMsg(t.getObjId()); ClientTask cTask = clnt.getTask(t.getTaskId()); JSONObject jobj = cTask.toJSONObject(obj); String objType = null; try { if (jobj != null) objType = jobj.getString(Task.JSON_OBJ_TYPE); } catch (JSONException e) { throw new RuntimeException("Invalid ClienTask JSON object conversion!"); } if (obj == null || jobj == null) { LOG.error("Source object has disappeared! [" + t.getObjType() + "/" + t.getObjId() + "]"); TaskQueue.getInstance().updateTask(t.getObjId(), t.getTaskId(), Task.State.FAILED, t.getObjType()); bw.write("null"); } else if (objType.equals("media")) { try { long ratio = calcRatio(jobj.getString(Task.JSON_OBJ_ID), jobj.getString(Task.JSON_NORECORDING)); if (ratio > 0 && new FieldTimeUntilNextRecording(null, "<=", ratio + "S").run()) { LOG.info("Client '" + req.getRemoteAddr() + "' cannot pop task '" + t.getObjType() + "/" + t.getTaskId() + "/" + t.getObjId() + "'; :NORECORDING option prevents running of this task"); TaskQueue.getInstance().pushBack(t); bw.write("null"); } else bw.write(jobj.toString()); } catch (JSONException e) { throw new RuntimeException(e); } } else bw.write(jobj.toString()); } } } } else if (cmd.equals("update")) { if (!validClient) { LOG.warn("Client IP rejected: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { list.add(req.getRemoteHost()); try { Task t = new Task(new JSONObject(req.getParameter("data"))); TaskQueue.getInstance().updateTask(t); } catch (JSONException e) { throw new RuntimeException("Input error; client '" + req.getRemoteHost() + "', CMD: update", e); } } } else if (cmd.equals("showQ")) { if (validSession) bw.write(TaskQueue.getInstance().toJSONArray().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("log")) { if (validSession) { String mediaId = req.getParameter("m"); String taskId = req.getParameter("t"); String objType = req.getParameter("o"); if ((mediaId != null && !mediaId.equals("0")) && (taskId != null && !taskId.equals("0"))) bw.write(ds.readLog(mediaId, taskId, objType)); else { BufferedReader r = new BufferedReader(new FileReader("sjq.log")); String line; while ((line = r.readLine()) != null) bw.write(line + "\n"); r.close(); } } else notAuthorized(resp, bw); } else if (cmd.equals("appState")) { if (validSession) bw.write(Butler.dumpAppTrace()); else notAuthorized(resp, bw); } else if (cmd.equals("writeLog")) { if (!validClient) { LOG.warn("Client IP reject: " + req.getRemoteAddr()); notAuthorized(resp, bw); } else { String mediaId = req.getParameter("m"); String taskId; if (!mediaId.equals("-1")) taskId = req.getParameter("t"); else taskId = req.getRemoteHost(); String objType = req.getParameter("o"); if (!mediaId.equals("0") && Boolean.parseBoolean(ds.getSetting("IgnoreTaskOutput", "false"))) { LOG.info("Dropping task output as per settings"); DataStore.returnConnection(ds); return; } String data = req.getParameter("data"); String[] msg = StringUtils.splitByWholeSeparator(data, "\r\n"); if (msg == null || msg.length == 1) msg = StringUtils.split(data, '\r'); if (msg == null || msg.length == 1) msg = StringUtils.split(data, '\n'); long now = System.currentTimeMillis(); for (String line : msg) ds.logForTaskClient(mediaId, taskId, line, now, objType); if (msg.length > 0) ds.flushLogs(); } } else if (cmd.equals("ruleset")) { if (validSession) bw.write(ds.getSetting("ruleset", "")); else notAuthorized(resp, bw); } else if (cmd.equals("saveRuleset")) { if (validSession) { ds.setSetting("ruleset", req.getParameter("data")); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("getClients")) { if (validSession) bw.write(ActiveClientList.getInstance().toJSONArray().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("loadClnt")) { if (validSession) bw.write(ds.getClientConf(req.getParameter("id"))); else notAuthorized(resp, bw); } else if (cmd.equals("saveClnt")) { if (validSession) { if (ds.saveClientConf(req.getParameter("id"), req.getParameter("data"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("history")) { if (validSession) { int start, limit; try { start = Integer.parseInt(req.getParameter("start")); limit = Integer.parseInt(req.getParameter("limit")); } catch (NumberFormatException e) { start = 0; limit = -1; } bw.write(ds.getJobHistory(Integer.parseInt(req.getParameter("t")), start, limit, req.getParameter("sort")).toString()); } else notAuthorized(resp, bw); } else if (cmd.equals("getSrvSetting")) { if (validSession) bw.write(ds.getSetting(req.getParameter("var"), "")); else notAuthorized(resp, bw); } else if (cmd.equals("setSrvSetting")) { if (validSession) { ds.setSetting(req.getParameter("var"), req.getParameter("val")); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("setFileCleaner")) { if (validSession) { ds.setSetting("DelRegex", req.getParameter("orphan")); ds.setSetting("IfRegex", req.getParameter("parent")); ds.setSetting("IgnoreRegex", req.getParameter("ignore")); new Thread(new FileCleaner()).start(); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("getFileCleanerSettings")) { if (validSession) { bw.write(ds.getSetting("DelRegex", "") + "\n"); bw.write(ds.getSetting("IfRegex", "") + "\n"); bw.write(ds.getSetting("IgnoreRegex", "")); } else notAuthorized(resp, bw); } else if (cmd.equals("writeSrvSettings")) { if (validSession) { try { ds.setSettings(new JSONObject(req.getParameter("data"))); } catch (JSONException e) { throw new RuntimeException(e); } bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("readSrvSettings")) { if (validSession) bw.write(ds.readSettings().toString()); else notAuthorized(resp, bw); } else if (cmd.equals("login")) { String pwd = ds.getSetting("password", ""); try { MessageDigest msg = MessageDigest.getInstance("MD5"); msg.update(req.getParameter("password").getBytes()); String userPwd = new String(msg.digest()); if (pwd.length() > 0 && pwd.equals(userPwd)) { bw.write("Success"); int key = new java.util.Random().nextInt(); resp.addHeader("SJQ-Session-Token", Integer.toString(key)); CLIENT_SESSION_KEYS.put(req.getRemoteAddr(), Integer.toString(key)); } else bw.write("BadPassword"); } catch (NoSuchAlgorithmException e) { bw.write(e.getLocalizedMessage()); } } else if (cmd.equals("editPwd")) { try { MessageDigest msg = MessageDigest.getInstance("MD5"); String curPwd = ds.getSetting("password", ""); String oldPwd = req.getParameter("old"); msg.update(oldPwd.getBytes()); oldPwd = new String(msg.digest()); msg.reset(); String newPwd = req.getParameter("new"); String confPwd = req.getParameter("conf"); if (!curPwd.equals(oldPwd)) bw.write("BadOld"); else if (!newPwd.equals(confPwd) || newPwd.length() == 0) bw.write("BadNew"); else { msg.update(newPwd.getBytes()); newPwd = new String(msg.digest()); ds.setSetting("password", newPwd); bw.write("Success"); } } catch (NoSuchAlgorithmException e) { bw.write(e.getLocalizedMessage()); } } else if (cmd.equals("runStats")) { if (validSession) { JSONObject o = new JSONObject(); try { o.put("last", Long.parseLong(ds.getSetting("LastRun", "0"))); o.put("next", Long.parseLong(ds.getSetting("NextRun", "0"))); bw.write(o.toString()); } catch (JSONException e) { bw.write(e.getLocalizedMessage()); } } else notAuthorized(resp, bw); } else if (cmd.equals("runQLoader")) { if (validSession) { Butler.wakeQueueLoader(); bw.write("Success"); } else notAuthorized(resp, bw); } else if (cmd.equals("delActiveQ")) { if (validSession) { if (TaskQueue.getInstance().delete(req.getParameter("m"), req.getParameter("t"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("clearActiveQ")) { if (validSession) { if (TaskQueue.getInstance().clear()) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("editPri")) { if (validSession) { try { int priority = Integer.parseInt(req.getParameter("p")); if (TaskQueue.getInstance().editPriority(req.getParameter("m"), req.getParameter("t"), priority)) bw.write("Success"); else bw.write("Failed"); } catch (NumberFormatException e) { bw.write("Failed"); } } else notAuthorized(resp, bw); } else if (cmd.equals("clearHistory")) { if (validSession) { if (ds.clear(Integer.parseInt(req.getParameter("t")))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("delHistRow")) { if (validSession) { if (ds.delTask(req.getParameter("m"), req.getParameter("t"), Integer.parseInt(req.getParameter("y")), req.getParameter("o"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("rmLog")) { if (validSession) { String mid = req.getParameter("m"); String tid = req.getParameter("t"); String oid = req.getParameter("o"); if (mid.equals("0") && tid.equals("0") && oid.equals("null")) { bw.write("Failed: Can't delete server log file (sjq.log) while SageTV is running!"); } else if (ds.clearLog(mid, tid, oid)) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("qryMediaFile")) { if (validSession) { JSONArray jarr = new JSONArray(); MediaFileAPI.List mediaList = Butler.SageApi.mediaFileAPI.GetMediaFiles(ds.getMediaMask()); String qry = req.getParameter("q"); int max = Integer.parseInt(req.getParameter("m")); for (MediaFileAPI.MediaFile mf : mediaList) { if ((qry.matches("\\d+") && Integer.toString(mf.GetMediaFileID()).startsWith(qry)) || mf.GetMediaTitle().matches(".*" + Pattern.quote(qry) + ".*") || fileSegmentMatches(mf, qry)) { JSONObject o = new JSONObject(); try { o.put("value", mf.GetFileForSegment(0).getAbsolutePath()); String subtitle = null; if (mf.GetMediaFileAiring() != null && mf.GetMediaFileAiring().GetShow() != null) subtitle = mf.GetMediaFileAiring().GetShow().GetShowEpisode(); String display; if (subtitle != null && subtitle.length() > 0) display = mf.GetMediaTitle() + ": " + subtitle; else display = mf.GetMediaTitle(); o.put("display", mf.GetMediaFileID() + " - " + display); jarr.put(o); if (jarr.length() >= max) break; } catch (JSONException e) { e.printStackTrace(System.out); } } } bw.write(jarr.toString()); } else notAuthorized(resp, bw); } else if (cmd.equals("debugMediaFile")) { if (validSession) { if (Butler.debugQueueLoader(req.getParameter("f"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("killTask")) { if (validSession) { if (TaskQueue.getInstance().killTask(req.getParameter("m"), req.getParameter("t"), req.getParameter("o"))) bw.write("Success"); else bw.write("Failed"); } else notAuthorized(resp, bw); } else if (cmd.equals("keepAlive")) { bw.write(Boolean.toString(!TaskQueue.getInstance().isTaskKilled(req.getParameter("m"), req.getParameter("t"), req.getParameter("o")))); } bw.close(); DataStore.returnConnection(ds); LOG.info("Servlet POST request completed [" + (System.currentTimeMillis() - startTime) + "ms]"); return; }
|
00
|
Code Sample 1:
public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.deleteSQL); ps.setString(1, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
Code Sample 2:
@SuppressWarnings("unchecked") private int syncCustomers() throws RemoteException, BasicException { dlintegration.syncCustomersBefore(); ArrayList<String> notToSync = new ArrayList<String>(); int step = 0; User[] remoteUsers; int cpt = 0; do { remoteUsers = externalsales.getUsersBySteps(step); step++; if (remoteUsers == null) { throw new BasicException(AppLocal.getIntString("message.returnnull") + " > Customers null"); } if (remoteUsers.length > 0) { String perms; for (User remoteUser : remoteUsers) { if (notToSync.contains(remoteUser.getLogin())) continue; cpt++; String name = externalsales.encodeString((remoteUser.getFirstname().trim() + " " + remoteUser.getLastname()).trim()); String firstname = externalsales.encodeString(remoteUser.getFirstname()); String lastname = externalsales.encodeString(remoteUser.getLastname()); String description = externalsales.encodeString(remoteUser.getDescription()); String address = externalsales.encodeString(remoteUser.getAddress()); String address2 = externalsales.encodeString(remoteUser.getAddress2()); String city = externalsales.encodeString(remoteUser.getCity()); String country = externalsales.encodeString(remoteUser.getCountry()); String phone = externalsales.encodeString(remoteUser.getPhone()); String mobile = externalsales.encodeString(remoteUser.getMobile()); String zipcode = externalsales.encodeString(remoteUser.getZipcode()); CustomerSync copyCustomer = new CustomerSync(remoteUser.getId()); if (firstname == null || firstname.equals("")) firstname = " "; copyCustomer.setFirstname(firstname.toUpperCase()); if (lastname == null || lastname.equals("")) lastname = " "; copyCustomer.setLastname(lastname.toUpperCase()); copyCustomer.setTaxid(remoteUser.getLogin()); copyCustomer.setSearchkey(remoteUser.getLogin() + name.toUpperCase()); if (name == null || name.equals("")) name = " "; copyCustomer.setName(name.toUpperCase()); if (description == null || description.equals("")) description = " "; copyCustomer.setNotes(description); copyCustomer.setEmail(remoteUser.getEmail()); if (address == null || address.equals("")) address = " "; copyCustomer.setAddress(address); if (address2 == null || address2.equals("")) address2 = " "; copyCustomer.setAddress2(address2); if (city == null || city.equals("")) city = "Brussels"; copyCustomer.setCity(city); if (country == null || country.equals("")) country = "Belgium"; copyCustomer.setCountry(country); copyCustomer.setMaxdebt(10000.0); if (phone == null || phone.equals("")) phone = " "; copyCustomer.setPhone(phone); if (mobile == null || mobile.equals("")) mobile = " "; copyCustomer.setPhone2(mobile); if (zipcode == null || zipcode.equals("")) zipcode = " "; copyCustomer.setPostal(zipcode); if (TicketInfo.isWS() && TicketInfo.getPayID() == 2 && remoteUser.getEmail().contains("@DONOTSENDME")) { notToSync.add(copyCustomer.getTaxid()); continue; } dlintegration.syncCustomer(copyCustomer); notToSync.add(copyCustomer.getTaxid()); } } } while (remoteUsers.length > 0); List<CustomerSync> localList = dlintegration.getCustomers(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (CustomerSync localCustomer : localList) { Date now = new Date(); if (notToSync.contains(localCustomer.getTaxid())) { continue; } cpt++; User userAdd = new User(); userAdd.setLogin(localCustomer.getTaxid()); userAdd.setId(localCustomer.getTaxid()); userAdd.setFirstname(" "); String tmpName = localCustomer.getName().trim(); tmpName = tmpName.replace("'", ""); while (tmpName.charAt(0) == ' ') { tmpName = tmpName.substring(1); } userAdd.setLastname(tmpName); char[] pw = new char[8]; int c = 'A'; int r1 = 0; for (int i = 0; i < 8; i++) { r1 = (int) (Math.random() * 3); switch(r1) { case 0: c = '0' + (int) (Math.random() * 10); break; case 1: c = 'a' + (int) (Math.random() * 26); break; case 2: c = 'A' + (int) (Math.random() * 26); break; } pw[i] = (char) c; } String clave = new String(pw); byte[] password = { 00 }; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(clave.getBytes()); password = md5.digest(); userAdd.setPassword(password.toString()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UsersSync.class.getName()).log(Level.SEVERE, null, ex); userAdd.setPassword(clave); } userAdd.setTitle("M"); if (localCustomer.getEmail() == null || localCustomer.getEmail().trim().equals("") || localCustomer.getEmail().indexOf('@') <= 0) userAdd.setEmail(localCustomer.getTaxid() + defaultEmail); else userAdd.setEmail(localCustomer.getEmail()); userAdd.setDescription(localCustomer.getNotes() + ""); userAdd.setAddress(localCustomer.getAddress() + ""); userAdd.setAddress2(localCustomer.getAddress2() + ""); userAdd.setState_region(localCustomer.getRegion() + ""); userAdd.setCity(localCustomer.getCity() + ""); userAdd.setCountry(localCustomer.getCountry() + ""); userAdd.setZipcode(localCustomer.getPostal() + ""); userAdd.setPhone(localCustomer.getPhone() + ""); userAdd.setMobile(localCustomer.getPhone2() + ""); userAdd.setFax(" "); try { userAdd.setCdate(df.format(localCustomer.getCurdate())); } catch (NullPointerException nu) { userAdd.setCdate(df.format(now)); } userAdd.setPerms("shopper"); userAdd.setBank_account_nr(""); userAdd.setBank_account_holder(""); userAdd.setBank_account_type(""); userAdd.setBank_iban(""); userAdd.setBank_name(""); userAdd.setBank_sort_code(""); userAdd.setMdate(df.format(now)); userAdd.setShopper_group_id("1"); externalsales.addUser(userAdd); } return cpt; }
|
00
|
Code Sample 1:
private static long saveAndClosePDFDocument(PDDocument document, OutputStreamProvider outProvider) throws IOException, COSVisitorException { File tempFile = null; InputStream in = null; OutputStream out = null; try { tempFile = File.createTempFile("temp", "pdf"); OutputStream tempFileOut = new FileOutputStream(tempFile); tempFileOut = new BufferedOutputStream(tempFileOut); document.save(tempFileOut); document.close(); tempFileOut.close(); long length = tempFile.length(); in = new BufferedInputStream(new FileInputStream(tempFile)); out = new BufferedOutputStream(outProvider.getOutputStream()); IOUtils.copy(in, out); return length; } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } if (tempFile != null && !FileUtils.deleteQuietly(tempFile)) { tempFile.deleteOnExit(); } } }
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:
public void notifyIterationEnds(final IterationEndsEvent event) { log.info("moving files..."); File source = new File("deqsim.log"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log to its iteration directory."); } } int parallelCnt = 0; source = new File("deqsim.log." + parallelCnt); while (source.exists()) { File destination = new File(Controler.getIterationFilename("deqsim.log." + parallelCnt)); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move deqsim.log." + parallelCnt + " to its iteration directory."); } parallelCnt++; source = new File("deqsim.log." + parallelCnt); } source = new File("loads_out.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("loads_out.txt")); try { IOUtils.copyFile(source, destination); } catch (FileNotFoundException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } catch (IOException e) { log.info("WARNING: Could not copy loads_out.txt to its iteration directory."); } destination = new File("loads_in.txt"); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move loads_out.txt to loads_in.txt."); } } source = new File("linkprocs.txt"); if (source.exists()) { File destination = new File(Controler.getIterationFilename("linkprocs.txt")); if (!IOUtils.renameFile(source, destination)) { log.info("WARNING: Could not move linkprocs.txt to its iteration directory."); } } }
Code Sample 2:
public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(inputLocation); outputStream = new FileOutputStream(outputLocation); byte buffer[] = new byte[1024]; while (inputStream.available() > 0) { int read = inputStream.read(buffer); outputStream.write(buffer, 0, read); } inputLocation.delete(); } finally { IOUtil.closeAndIgnoreErrors(inputStream); IOUtil.closeAndIgnoreErrors(outputStream); } }
|
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:
private void copyFile(File srcFile, File destFile) throws IOException { if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath()); if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath()); FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
|
00
|
Code Sample 1:
public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); }
Code Sample 2:
private static String connect(String apiURL, boolean secure) throws IOException { String baseUrl; if (secure) baseUrl = "https://todoist.com/API/"; else baseUrl = "http://todoist.com/API/"; URL url = new URL(baseUrl + apiURL); URLConnection c = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder toReturn = new StringBuilder(""); String toAppend; while ((toAppend = in.readLine()) != null) toReturn.append(toAppend); return toReturn.toString(); }
|
00
|
Code Sample 1:
public static void processRequest(byte[] b) throws Exception { URL url = new URL("http://localhost:8080/instantsoap-ws-echotest-1.0/services/instantsoap/applications"); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction", ""); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }
Code Sample 2:
public static String md5It(String data) { MessageDigest digest; String output = ""; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); byte[] hash = digest.digest(); for (byte b : hash) { output = output + String.format("%02X", b); } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Authenticator.class.getName()).log(Level.SEVERE, null, ex); } return output; }
|
00
|
Code Sample 1:
public static String getTextFromUrl(final String url) { InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(HtmlUtil.quoteHtml(line)).append("\r"); } return result.toString(); } catch (final IOException exception) { return exception.getMessage(); } finally { InputOutputUtil.close(bufferedReader); InputOutputUtil.close(inputStreamReader); } }
Code Sample 2:
byte[] makeIDPFXORMask() { if (idpfMask == null) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); String temp = strip(getPrimaryIdentifier()); sha.update(temp.getBytes("UTF-8"), 0, temp.length()); idpfMask = sha.digest(); } catch (NoSuchAlgorithmException e) { System.err.println("No such Algorithm (really, did I misspell SHA-1?"); System.err.println(e.toString()); return null; } catch (IOException e) { System.err.println("IO Exception. check out mask.write..."); System.err.println(e.toString()); return null; } } return idpfMask; }
|
00
|
Code Sample 1:
private static void _readAllRegionMDFiles(ClassLoader loader, RegionMetadata bean, String regionMDFile) { if (_LOG.isFinest()) { _LOG.finest("searching for region-metadata with resource:{0}", regionMDFile); } try { Enumeration<URL> files = loader.getResources(regionMDFile); while (files.hasMoreElements()) { URL url = files.nextElement(); String publicId = url.toString(); try { InputStream in = url.openStream(); _readRegionMetadata(bean, in, publicId); in.close(); } catch (IOException e) { _error(publicId, e); } } } catch (IOException e) { _LOG.warning("ERR_GET_REGION_METADATA_FILE", __CONFIG_FILE_OTHER); _LOG.warning(e); } }
Code Sample 2:
public static Debugger getDebugger(InetAddress host, int port, String password) throws IOException { try { Socket s = new Socket(host, port); try { ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream in = new ObjectInputStream(s.getInputStream()); int protocolVersion = in.readInt(); if (protocolVersion > 220) { throw new IOException("Incompatible protocol version " + protocolVersion + ". At most 220 was expected."); } byte[] challenge = (byte[]) in.readObject(); MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); md.update(challenge); out.writeObject(md.digest()); return new LocalDebuggerProxy((Debugger) in.readObject()); } finally { s.close(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new UndeclaredThrowableException(e); } }
|
11
|
Code Sample 1:
public static String extractIconPath(String siteURL) throws IOException { siteURL = siteURL.trim(); if (!siteURL.startsWith("http://")) { siteURL = "http://" + siteURL; } URL url = new URL(siteURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String iconURL = null; String iconPath = null; String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("type=\"image/x-icon\"") || inputLine.toLowerCase().contains("rel=\"shortcut icon\"")) { String tmp = new String(inputLine); String[] smallLines = inputLine.replace(">", ">\n").split("\n"); for (String smallLine : smallLines) { if (smallLine.contains("type=\"image/x-icon\"") || smallLine.toLowerCase().contains("rel=\"shortcut icon\"")) { tmp = smallLine; break; } } iconURL = tmp.replaceAll("^.*href=\"", ""); iconURL = iconURL.replaceAll("\".*", ""); tmp = null; String originalSiteURL = new String(siteURL); siteURL = getHome(siteURL); if (iconURL.charAt(0) == '/') { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL.substring(1); } else { iconURL = siteURL + iconURL; } } else if (!iconURL.startsWith("http://")) { if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } siteURL = originalSiteURL; break; } if (inputLine.contains("</head>".toLowerCase())) { break; } } in.close(); siteURL = getHome(siteURL); if (iconURL == null || "".equals(iconURL.trim())) { iconURL = "favicon.ico"; if (siteURL.charAt(siteURL.length() - 1) == '/') { iconURL = siteURL + iconURL; } else { iconURL = siteURL + "/" + iconURL; } } try { String iconFileName = siteURL; if (iconFileName.startsWith("http://")) { iconFileName = iconFileName.substring(7); } iconFileName = iconFileName.replaceAll("\\W", " ").trim().replace(" ", "_").concat(".ico"); iconPath = JReader.getConfig().getShortcutIconsDir() + File.separator + iconFileName; InputStream inIcon = new URL(iconURL).openStream(); OutputStream outIcon = new FileOutputStream(iconPath); byte[] buf = new byte[1024]; int len; while ((len = inIcon.read(buf)) > 0) { outIcon.write(buf, 0, len); } inIcon.close(); outIcon.close(); } catch (Exception e) { } return iconPath; }
Code Sample 2:
@Override public String getLatestApplicationVersion() { String latestVersion = null; String latestVersionInfoURL = "http://movie-browser.googlecode.com/svn/site/latest"; LOGGER.info("Checking latest version info from: " + latestVersionInfoURL); BufferedReader in = null; try { LOGGER.info("Fetcing latest version info from: " + latestVersionInfoURL); URL url = new URL(latestVersionInfoURL); in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { latestVersion = str; } } catch (Exception ex) { LOGGER.error("Error fetching latest version info from: " + latestVersionInfoURL, ex); } finally { try { in.close(); } catch (Exception ex) { LOGGER.error("Could not close inputstream", ex); } } return latestVersion; }
|
11
|
Code Sample 1:
public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) abort("FileCopy: no such source file: " + from_file.getName()); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_file.getName()); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_file.getName()); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("FileCopy: destination file is unwriteable: " + to_file.getName()); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { try { from.close(); } catch (IOException e) { e.printStackTrace(); } } if (to != null) { try { to.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Code Sample 2:
public final void saveAsCopy(String current_image, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; String source = temp_dir + key + current_image; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } }
|
00
|
Code Sample 1:
private void copia(FileInputStream input, FileOutputStream output) throws ErrorException { if (input == null || output == null) { throw new ErrorException("Param null"); } FileChannel inChannel = input.getChannel(); FileChannel outChannel = output.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (IOException e) { throw new ErrorException("Casino nella copia del file"); } }
Code Sample 2:
private void startOpening(final URL url) { final WebAccessor wa = this; openerThread = new Thread() { public void run() { iStream = null; try { tryProxy = false; URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection htc = (HttpURLConnection) connection; contentLength = htc.getContentLength(); } InputStream i = connection.getInputStream(); iStream = new LoggedInputStream(i, wa); } catch (ConnectException x) { tryProxy = true; exception = x; } catch (Exception x) { exception = x; } finally { if (dialog != null) { Thread.yield(); dialog.setVisible(false); } } } }; openerThread.start(); }
|
11
|
Code Sample 1:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
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 (FileNotFoundException fnfe) { Log.debug(fnfe); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
00
|
Code Sample 1:
public void importarHistoricoDoPIB(Andamento pAndamento) throws FileNotFoundException, SQLException, Exception { pAndamento.delimitarIntervaloDeVariacao(0, 49); PIB[] valoresPendentesDoPIB = obterValoresPendentesDoPIB(pAndamento); pAndamento.delimitarIntervaloDeVariacao(50, 100); if (valoresPendentesDoPIB != null && valoresPendentesDoPIB.length > 0) { String sql = "INSERT INTO tmp_TB_PIB(ULTIMO_DIA_DO_MES, PIB_ACUM_12MESES_REAL, PIB_ACUM_12MESES_DOLAR) VALUES(:ULTIMO_DIA_DO_MES, :PIB_ACUM_12MESES_REAL, :PIB_ACUM_12MESES_DOLAR)"; OraclePreparedStatement stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosASeremImportados = valoresPendentesDoPIB.length; try { int quantidadeDeRegistrosImportados = 0; int numeroDoRegistro = 0; final BigDecimal MILHAO = new BigDecimal("1000000"); for (PIB valorPendenteDoPIB : valoresPendentesDoPIB) { ++numeroDoRegistro; stmtDestino.clearParameters(); java.sql.Date vULTIMO_DIA_DO_MES = new java.sql.Date(obterUltimoDiaDoMes(valorPendenteDoPIB.mesEAno).getTime()); BigDecimal vPIB_ACUM_12MESES_REAL = valorPendenteDoPIB.valorDoPIBEmReais.multiply(MILHAO).setScale(0, RoundingMode.DOWN); BigDecimal vPIB_ACUM_12MESES_DOLAR = valorPendenteDoPIB.valorDoPIBEmDolares.multiply(MILHAO).setScale(0, RoundingMode.DOWN); stmtDestino.setDateAtName("ULTIMO_DIA_DO_MES", vULTIMO_DIA_DO_MES); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_REAL", vPIB_ACUM_12MESES_REAL); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_DOLAR", vPIB_ACUM_12MESES_DOLAR); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosASeremImportados * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); throw ex; } finally { if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } } pAndamento.setPercentualCompleto(100); }
Code Sample 2:
public boolean pollLocation(int device) { if (device < numDevices) { try { HttpResponse response = client.execute(post); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); JSONObject object = (JSONObject) JSONValue.parse(reader); JSONArray array = ((JSONArray) object.get("content")); object = (JSONObject) array.get(device); IPhoneLocation iPhoneLocation = getLocation(object); if (iPhoneLocation != null) { iPhoneRouteList.get(device).addLocation(iPhoneLocation); } } catch (ClientProtocolException ex) { logger.log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return false; } } else { logger.log(Level.WARNING, "Device {0} is out of range ({1} max)", new Object[] { (device + 1), numDevices }); return false; } return true; }
|
00
|
Code Sample 1:
protected final void connectFtp() throws IOException { try { if (!this.ftpClient.isConnected()) { this.ftpClient.connect(getHost(), getPort()); getLog().write(Level.INFO, String.format(getMessages().getString("FtpSuccessfullyConnected"), getHost())); int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { this.ftpClient.disconnect(); throw new IOException(String.format(getMessages().getString("FtpErrorConnectingRefused"), getHost())); } if (getUsername() != null) { if (!this.ftpClient.login(getUsername(), getPassword())) { this.ftpClient.logout(); disconnectFtp(); throw new IOException(String.format(getMessages().getString("FtpErrorAuthorizing"), getHost())); } } this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE); this.ftpClient.enterLocalPassiveMode(); getLog().write(Level.INFO, String.format(getMessages().getString("FtpSuccessfullyAuthorized"), getHost())); } } catch (IOException ex) { disconnectFtp(); throw new IOException(String.format(getMessages().getString("FtpErrorConnecting"), getHost(), ex.toString())); } }
Code Sample 2:
private void removeCollection(long oid, Connection conn) throws XMLDBException { try { String sql = "DELETE FROM X_DOCUMENT WHERE X_DOCUMENT.XDB_COLLECTION_OID = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); sql = "DELETE FROM XDB_COLLECTION WHERE XDB_COLLECTION.XDB_COLLECTION_OID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); removeChildCollection(oid, conn); } catch (java.sql.SQLException se) { try { conn.rollback(); } catch (java.sql.SQLException se2) { se2.printStackTrace(); } se.printStackTrace(); } }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private boolean downloadFile() { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.server); ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + this.server); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection."); return false; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { return false; } } ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server."); ResourcePool.LogException(e, this); return false; } try { if (!ftp.login(this.user, this.password)) { ftp.logout(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed."); return false; } ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName()); if ((this.transferType != null) && (this.transferType.compareTo(FTPWorkerThread.ASCII) == 0)) { ftp.setFileType(FTP.ASCII_FILE_TYPE); } else { ftp.setFileType(FTP.BINARY_FILE_TYPE); } if ((this.passiveMode != null) && this.passiveMode.equalsIgnoreCase(FTPWorkerThread.FALSE)) { ftp.enterLocalActiveMode(); } else { ftp.enterLocalPassiveMode(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection."); ResourcePool.LogException(e, this); return false; } catch (IOException e) { ResourcePool.LogException(e, this); return false; } OutputStream output; try { java.util.Date startDate = new java.util.Date(); output = new FileOutputStream(this.destFileName); ftp.retrieveFile(this.fileName, output); File f = new File(this.destFileName); if (f.exists() && (this.lastModifiedDate != null)) { f.setLastModified(this.lastModifiedDate.longValue()); } java.util.Date endDate = new java.util.Date(); this.downloadTime = endDate.getTime() - startDate.getTime(); double iDownLoadTime = ((this.downloadTime + 1) / 1000) + 1; ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Download Complete, Rate = " + (this.fileSize / (iDownLoadTime * 1024)) + " Kb/s, Seconds = " + iDownLoadTime); this.downloadTime = (this.downloadTime + 1) / 1000; if (ftp.isConnected()) { ftp.disconnect(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, e.getMessage()); ResourcePool.LogException(e, this); return false; } catch (IOException e) { ResourcePool.LogException(e, this); return false; } return true; }
|
11
|
Code Sample 1:
public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
protected boolean writeFile(Interest outstandingInterest) throws IOException { File fileToWrite = ccnNameToFilePath(outstandingInterest.name()); Log.info("CCNFileProxy: extracted request for file: " + fileToWrite.getAbsolutePath() + " exists? ", fileToWrite.exists()); if (!fileToWrite.exists()) { Log.warning("File {0} does not exist. Ignoring request.", fileToWrite.getAbsoluteFile()); return false; } FileInputStream fis = null; try { fis = new FileInputStream(fileToWrite); } catch (FileNotFoundException fnf) { Log.warning("Unexpected: file we expected to exist doesn't exist: {0}!", fileToWrite.getAbsolutePath()); return false; } CCNTime modificationTime = new CCNTime(fileToWrite.lastModified()); ContentName versionedName = VersioningProfile.addVersion(new ContentName(_prefix, outstandingInterest.name().postfix(_prefix).components()), modificationTime); CCNFileOutputStream ccnout = new CCNFileOutputStream(versionedName, _handle); ccnout.addOutstandingInterest(outstandingInterest); byte[] buffer = new byte[BUF_SIZE]; int read = fis.read(buffer); while (read >= 0) { ccnout.write(buffer, 0, read); read = fis.read(buffer); } fis.close(); ccnout.close(); return true; }
|
11
|
Code Sample 1:
private void analyseCorpus(final IStatusDisplayer fStatus) { final String sDistrosFile = "Distros.tmp"; final String sSymbolsFile = "Symbols.tmp"; Chunker = new EntropyChunker(); int Levels = 2; sgOverallGraph = new SymbolicGraph(1, Levels); siIndex = new SemanticIndex(sgOverallGraph); try { siIndex.MeaningExtractor = new LocalWordNetMeaningExtractor(); } catch (IOException ioe) { siIndex.MeaningExtractor = null; } try { DocumentSet dsSet = new DocumentSet(FilePathEdt.getText(), 1.0); dsSet.createSets(true, (double) 100 / 100); int iCurCnt, iTotal; String sFile = ""; Iterator iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } appendToLog("Training chunker..."); Chunker.train(dsSet.toFilenameSet(DocumentSet.FROM_WHOLE_SET)); appendToLog("Setting delimiters..."); setDelimiters(Chunker.getDelimiters()); iCurCnt = 0; cdDoc = new DistributionDocument[Levels]; for (int iCnt = 0; iCnt < Levels; iCnt++) cdDoc[iCnt] = new DistributionDocument(1, MinLevel + iCnt); fStatus.setVisible(true); ThreadList t = new ThreadList(Runtime.getRuntime().availableProcessors() + 1); appendToLog("(Pass 1/3) Loading files..." + sFile); TreeSet tsOverallSymbols = new TreeSet(); while (iIter.hasNext()) { sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); fStatus.setStatus("(Pass 1/3) Loading file..." + sFile, (double) iCurCnt / iTotal); final DistributionDocument[] cdDocArg = cdDoc; final String sFileArg = sFile; for (int iCnt = 0; iCnt < cdDoc.length; iCnt++) { final int iCntArg = iCnt; while (!t.addThreadFor(new Runnable() { public void run() { if (!RightToLeftText) cdDocArg[iCntArg].loadDataStringFromFile(sFileArg, false); else { cdDocArg[iCntArg].setDataString(utils.reverseString(utils.loadFileToString(sFileArg)), iCntArg, false); } } })) Thread.yield(); } try { t.waitUntilCompletion(); } catch (InterruptedException ex) { ex.printStackTrace(System.err); appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } sgOverallGraph.setDataString(((new StringBuffer().append((char) StreamTokenizer.TT_EOF))).toString()); sgOverallGraph.loadFromFile(sFile); fStatus.setStatus("Loaded file..." + sFile, (double) ++iCurCnt / iTotal); Thread.yield(); } Set sSymbols = null; File fPreviousSymbols = new File(sSymbolsFile); boolean bSymbolsLoadedOK = false; if (fPreviousSymbols.exists()) { System.err.println("ATTENTION: Using previous symbols..."); try { FileInputStream fis = new FileInputStream(fPreviousSymbols); ObjectInputStream ois = new ObjectInputStream(fis); sSymbols = (Set) ois.readObject(); ois.close(); bSymbolsLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); } } if (!bSymbolsLoadedOK) sSymbols = getSymbolsByProbabilities(sgOverallGraph.getDataString(), fStatus); int iMinSymbolSize = Integer.MAX_VALUE; int iMaxSymbolSize = Integer.MIN_VALUE; Iterator iSymbol = sSymbols.iterator(); while (iSymbol.hasNext()) { String sCurSymbol = (String) iSymbol.next(); if (iMaxSymbolSize < sCurSymbol.length()) iMaxSymbolSize = sCurSymbol.length(); if (iMinSymbolSize > sCurSymbol.length()) iMinSymbolSize = sCurSymbol.length(); } try { FileOutputStream fos = new FileOutputStream(sSymbolsFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(sSymbols); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } appendToLog("(Pass 2/3) Determining symbol distros per n-gram size..."); iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } iCurCnt = 0; Distribution dSymbolsPerSize = new Distribution(); Distribution dNonSymbolsPerSize = new Distribution(); Distribution dSymbolSizes = new Distribution(); File fPreviousRun = new File(sDistrosFile); boolean bDistrosLoadedOK = false; if (fPreviousRun.exists()) { System.err.println("ATTENTION: Using previous distros..."); try { FileInputStream fis = new FileInputStream(fPreviousRun); ObjectInputStream ois = new ObjectInputStream(fis); dSymbolsPerSize = (Distribution) ois.readObject(); dNonSymbolsPerSize = (Distribution) ois.readObject(); dSymbolSizes = (Distribution) ois.readObject(); ois.close(); bDistrosLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } } if (!bDistrosLoadedOK) while (iIter.hasNext()) { fStatus.setStatus("(Pass 2/3) Parsing file..." + sFile, (double) iCurCnt++ / iTotal); sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); String sDataString = ""; try { ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); FileInputStream fiIn = new FileInputStream(sFile); int iData = 0; while ((iData = fiIn.read()) > -1) bsOut.write(iData); sDataString = bsOut.toString(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } final Distribution dSymbolsPerSizeArg = dSymbolsPerSize; final Distribution dNonSymbolsPerSizeArg = dNonSymbolsPerSize; final Distribution dSymbolSizesArg = dSymbolSizes; final String sDataStringArg = sDataString; final Set sSymbolsArg = sSymbols; for (int iSymbolSize = iMinSymbolSize; iSymbolSize <= iMaxSymbolSize; iSymbolSize++) { final int iSymbolSizeArg = iSymbolSize; while (!t.addThreadFor(new Runnable() { public void run() { NGramDocument ndCur = new NGramDocument(iSymbolSizeArg, iSymbolSizeArg, 1, iSymbolSizeArg, iSymbolSizeArg); ndCur.setDataString(sDataStringArg); int iSymbolCnt = 0; int iNonSymbolCnt = 0; Iterator iExtracted = ndCur.getDocumentGraph().getGraphLevel(0).getVertexSet().iterator(); while (iExtracted.hasNext()) { String sCur = ((Vertex) iExtracted.next()).toString(); if (sSymbolsArg.contains(sCur)) { iSymbolCnt++; synchronized (dSymbolSizesArg) { dSymbolSizesArg.setValue(sCur.length(), dSymbolSizesArg.getValue(sCur.length()) + 1.0); } } else iNonSymbolCnt++; } synchronized (dSymbolsPerSizeArg) { dSymbolsPerSizeArg.setValue(iSymbolSizeArg, dSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iSymbolCnt); } synchronized (dNonSymbolsPerSizeArg) { dNonSymbolsPerSizeArg.setValue(iSymbolSizeArg, dNonSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iNonSymbolCnt); } } })) Thread.yield(); } } if (!bDistrosLoadedOK) try { t.waitUntilCompletion(); try { FileOutputStream fos = new FileOutputStream(sDistrosFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(dSymbolsPerSize); oos.writeObject(dNonSymbolsPerSize); oos.writeObject(dSymbolSizes); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } } catch (InterruptedException ex) { appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } appendToLog("\n(Pass 3/3) Determining optimal n-gram range...\n"); NGramSizeEstimator nseEstimator = new NGramSizeEstimator(dSymbolsPerSize, dNonSymbolsPerSize); IntegerPair p = nseEstimator.getOptimalRange(); appendToLog("\nProposed n-gram sizes:" + p.first() + "," + p.second()); fStatus.setStatus("Determining optimal distance...", 0.0); DistanceEstimator de = new DistanceEstimator(dSymbolsPerSize, dNonSymbolsPerSize, nseEstimator); int iBestDist = de.getOptimalDistance(1, nseEstimator.getMaxRank() * 2, p.first(), p.second()); fStatus.setStatus("Determining optimal distance...", 1.0); appendToLog("\nOptimal distance:" + iBestDist); appendToLog("======DONE=====\n"); } finally { sgOverallGraph.removeNotificationListener(); } }
Code Sample 2:
public void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPathFile); FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { message = ("���Ƶ����ļ���������"); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
11
|
Code Sample 1:
protected byte[] computeHash() { try { final MessageDigest inputHash = MessageDigest.getInstance("SHA"); inputHash.update(bufferFileData().getBytes()); return inputHash.digest(); } catch (final NoSuchAlgorithmException nsae) { lastException = nsae; return new byte[0]; } catch (final IOException ioe) { lastException = ioe; return new byte[0]; } }
Code Sample 2:
public BigInteger calculateMd5(String input) throws FileSystemException { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes()); byte[] messageDigest = digest.digest(); BigInteger bigInt = new BigInteger(1, messageDigest); return bigInt; } catch (Exception e) { throw new FileSystemException(e); } }
|
00
|
Code Sample 1:
public static boolean insereCapitulo(final Connection con, Capitulo cap, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodCapitulo(con, cap); String text = desc.getTexto().replaceAll("[']", "\""); String titulo = cap.getTitulo().replaceAll("['\"]", ""); String coment = cap.getComentario().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + text + "')"); smt.executeUpdate("INSERT INTO capitulo VALUES(" + cap.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO cap_aut VALUES(" + cap.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "CAPITULO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } }
Code Sample 2:
public static long writePropertiesInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, Map<String, String> properties) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } for (Map.Entry<String, String> property : properties.entrySet()) { CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (property.getKey().equals(Metadata.TITLE)) { coreProperties.setTitle(property.getValue()); } else if (property.getKey().equals(Metadata.AUTHOR)) { coreProperties.setCreator(property.getValue()); } else if (property.getKey().equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMMENTS)) { coreProperties.setDescription(property.getValue()); } else if (property.getKey().equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(property.getValue()); } else if (property.getKey().equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(property.getValue()); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(property.getKey())) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(property.getKey())) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } customProperties.addProperty(property.getKey(), property.getValue()); } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } }
|
11
|
Code Sample 1:
public void createResource(String resourceUri, boolean publish, User user) throws IOException { PermissionAPI perAPI = APILocator.getPermissionAPI(); Logger.debug(this.getClass(), "createResource"); resourceUri = stripMapping(resourceUri); String hostName = getHostname(resourceUri); String path = getPath(resourceUri); String folderName = getFolderName(path); String fileName = getFileName(path); fileName = deleteSpecialCharacter(fileName); if (fileName.startsWith(".")) { return; } Host host = HostFactory.getHostByHostName(hostName); Folder folder = FolderFactory.getFolderByPath(folderName, host); boolean hasPermission = perAPI.doesUserHavePermission(folder, PERMISSION_WRITE, user, false); if (hasPermission) { if (!checkFolderFilter(folder, fileName)) { throw new IOException("The file doesn't comply the folder's filter"); } if (host.getInode() != 0 && folder.getInode() != 0) { File file = new File(); file.setTitle(fileName); file.setFileName(fileName); file.setShowOnMenu(false); file.setLive(publish); file.setWorking(true); file.setDeleted(false); file.setLocked(false); file.setModDate(new Date()); String mimeType = FileFactory.getMimeType(fileName); file.setMimeType(mimeType); String author = user.getFullName(); file.setAuthor(author); file.setModUser(author); file.setSortOrder(0); file.setShowOnMenu(false); try { Identifier identifier = null; if (!isResource(resourceUri)) { WebAssetFactory.createAsset(file, user.getUserId(), folder, publish); identifier = IdentifierCache.getIdentifierFromIdentifierCache(file); } else { File actualFile = FileFactory.getFileByURI(path, host, false); identifier = IdentifierCache.getIdentifierFromIdentifierCache(actualFile); WebAssetFactory.createAsset(file, user.getUserId(), folder, identifier, false, false); WebAssetFactory.publishAsset(file); String assetsPath = FileFactory.getRealAssetsRootPath(); new java.io.File(assetsPath).mkdir(); java.io.File workingIOFile = FileFactory.getAssetIOFile(file); DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingIOFile.getPath()); if (file != null && file.getInode() > 0) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(workingIOFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); java.io.File newVersionFile = FileFactory.getAssetIOFile(file); vc.remove(ResourceManager.RESOURCE_TEMPLATE + newVersionFile.getPath()); FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); } java.util.List<Tree> parentTrees = TreeFactory.getTreesByChild(file); for (Tree tree : parentTrees) { Tree newTree = TreeFactory.getTree(tree.getParent(), file.getInode()); if (newTree.getChild() == 0) { newTree.setParent(tree.getParent()); newTree.setChild(file.getInode()); newTree.setRelationType(tree.getRelationType()); newTree.setTreeOrder(0); TreeFactory.saveTree(newTree); } } } List<Permission> permissions = perAPI.getPermissions(folder); for (Permission permission : permissions) { Permission filePermission = new Permission(); filePermission.setPermission(permission.getPermission()); filePermission.setRoleId(permission.getRoleId()); filePermission.setInode(identifier.getInode()); perAPI.save(filePermission); } } catch (Exception ex) { Logger.debug(this, ex.toString()); } } } else { throw new IOException("You don't have access to add that folder/host"); } }
Code Sample 2:
public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
00
|
Code Sample 1:
public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; }
Code Sample 2:
private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
|
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:
@SuppressWarnings("unchecked") private void doService(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String url = request.getRequestURL().toString(); if (url.endsWith("/favicon.ico")) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (url.contains("/delay")) { final String delay = StringUtils.substringBetween(url, "/delay", "/"); final int ms = Integer.parseInt(delay); if (LOG.isDebugEnabled()) { LOG.debug("Sleeping for " + ms + " before to deliver " + url); } Thread.sleep(ms); } final URL requestedUrl = new URL(url); final WebRequest webRequest = new WebRequest(requestedUrl); webRequest.setHttpMethod(HttpMethod.valueOf(request.getMethod())); for (final Enumeration<String> en = request.getHeaderNames(); en.hasMoreElements(); ) { final String headerName = en.nextElement(); final String headerValue = request.getHeader(headerName); webRequest.setAdditionalHeader(headerName, headerValue); } final List<NameValuePair> requestParameters = new ArrayList<NameValuePair>(); for (final Enumeration<String> paramNames = request.getParameterNames(); paramNames.hasMoreElements(); ) { final String name = paramNames.nextElement(); final String[] values = request.getParameterValues(name); for (final String value : values) { requestParameters.add(new NameValuePair(name, value)); } } if ("PUT".equals(request.getMethod()) && request.getContentLength() > 0) { final byte[] buffer = new byte[request.getContentLength()]; request.getInputStream().readLine(buffer, 0, buffer.length); webRequest.setRequestBody(new String(buffer)); } else { webRequest.setRequestParameters(requestParameters); } final WebResponse resp = MockConnection_.getResponse(webRequest); response.setStatus(resp.getStatusCode()); for (final NameValuePair responseHeader : resp.getResponseHeaders()) { response.addHeader(responseHeader.getName(), responseHeader.getValue()); } if (WriteContentAsBytes_) { IOUtils.copy(resp.getContentAsStream(), response.getOutputStream()); } else { final String newContent = getModifiedContent(resp.getContentAsString()); final String contentCharset = resp.getContentCharset(); response.setCharacterEncoding(contentCharset); response.getWriter().print(newContent); } response.flushBuffer(); }
|
11
|
Code Sample 1:
public void runDynusT() { final String[] exeFiles = new String[] { "DynusT.exe", "DLL_ramp.dll", "Ramp_Meter_Fixed_CDLL.dll", "Ramp_Meter_Feedback_CDLL.dll", "Ramp_Meter_Feedback_FDLL.dll", "libifcoremd.dll", "libmmd.dll", "Ramp_Meter_Fixed_FDLL.dll", "libiomp5md.dll" }; final String[] modelFiles = new String[] { "network.dat", "scenario.dat", "control.dat", "ramp.dat", "incident.dat", "movement.dat", "vms.dat", "origin.dat", "destination.dat", "StopCap4Way.dat", "StopCap2Way.dat", "YieldCap.dat", "WorkZone.dat", "GradeLengthPCE.dat", "leftcap.dat", "system.dat", "output_option.dat", "bg_demand_adjust.dat", "xy.dat", "TrafficFlowModel.dat", "parameter.dat" }; log.info("Creating iteration-directory..."); File iterDir = new File(this.tmpDir); if (!iterDir.exists()) { iterDir.mkdir(); } log.info("Copying application files to iteration-directory..."); for (String filename : exeFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.dynusTDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } log.info("Copying model files to iteration-directory..."); for (String filename : modelFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.modelDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } String logfileName = this.tmpDir + "/dynus-t.log"; String cmd = this.tmpDir + "/DynusT.exe"; log.info("running command: " + cmd); int timeout = 14400; int exitcode = ExeRunner.run(cmd, logfileName, timeout); if (exitcode != 0) { throw new RuntimeException("There was a problem running Dynus-T. exit code: " + exitcode); } }
Code Sample 2:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
private void getLines(PackageManager pm) throws PackageManagerException { final Pattern p = Pattern.compile("\\s*deb\\s+(ftp://|http://)(\\S+)\\s+((\\S+\\s*)*)(./){0,1}"); Matcher m; if (updateUrlAndFile == null) updateUrlAndFile = new ArrayList<UrlAndFile>(); BufferedReader f; String protocol; String host; String shares; String adress; try { f = new BufferedReader(new FileReader(sourcesList)); while ((protocol = f.readLine()) != null) { m = p.matcher(protocol); if (m.matches()) { protocol = m.group(1); host = m.group(2); if (m.group(3).trim().equalsIgnoreCase("./")) shares = ""; else shares = m.group(3).trim(); if (shares == null) adress = protocol + host; else { shares = shares.replace(" ", "/"); if (!host.endsWith("/") && !shares.startsWith("/")) host = host + "/"; adress = host + shares; while (adress.contains("//")) adress = adress.replace("//", "/"); adress = protocol + adress; } if (!adress.endsWith("/")) adress = adress + "/"; String changelogdir = adress; changelogdir = changelogdir.substring(changelogdir.indexOf("//") + 2); if (changelogdir.endsWith("/")) changelogdir = changelogdir.substring(0, changelogdir.lastIndexOf("/")); changelogdir = changelogdir.replace('/', '_'); changelogdir = changelogdir.replaceAll("\\.", "_"); changelogdir = changelogdir.replaceAll("-", "_"); changelogdir = changelogdir.replaceAll(":", "_COLON_"); adress = adress + "Packages.gz"; final String serverFileLocation = adress.replaceAll(":", "_COLON_"); final NameFileLocation nfl = new NameFileLocation(); try { final GZIPInputStream in = new GZIPInputStream(new ConnectToServer(pm).getInputStream(adress)); final String rename = new File(nfl.rename(serverFileLocation, listsDir)).getCanonicalPath(); final FileOutputStream out = new FileOutputStream(rename); final byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); final File file = new File(rename); final UrlAndFile uaf = new UrlAndFile(protocol + host, file, changelogdir); updateUrlAndFile.add(uaf); } catch (final Exception e) { final String message = "URL: " + adress + " caused exception"; if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } } } f.close(); } catch (final FileNotFoundException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("sourcesList.corrupt", "Entry not found sourcesList.corrupt"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } catch (final IOException e) { final String message = PreferenceStoreHolder.getPreferenceStoreByName("Screen").getPreferenceAsString("SearchForServerFile.getLines.IOException", "Entry not found SearchForServerFile.getLines.IOException"); if (null != pm) { logger.warn(message, e); pm.addWarning(message + "\n" + e.toString()); } else logger.warn(message, e); e.printStackTrace(); } }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public Blowfish(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA1"); digest.update(password.getBytes()); } catch (Exception e) { System.out.println(e); } m_bfish = new BlowfishCBC(digest.digest(), 0); digest.reset(); }
Code Sample 2:
public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
|
00
|
Code Sample 1:
public void loadSourceCode() { int length = MAX_SOURCE_LENGTH; try { File file = new File(filename); length = (int) file.length(); } catch (SecurityException ex) { } char[] buff = new char[length]; InputStream is; InputStreamReader isr; CodeViewer cv = new CodeViewer(); URL url; try { url = getClass().getResource(filename); is = url.openStream(); isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); sourceCode = new String("<html><pre>"); String line = reader.readLine(); while (line != null) { sourceCode += cv.syntaxHighlight(line) + " \n "; line = reader.readLine(); } sourceCode += "</pre></html>"; } catch (Exception ex) { sourceCode = getString("SourceCode.error"); } }
Code Sample 2:
protected InputStream openInputStream(String filename) throws FileNotFoundException { InputStream in = null; try { URL url = new URL(filename); in = url.openConnection().getInputStream(); logger.info("Opening file " + filename); } catch (FileNotFoundException e) { logger.error("Resource file not found: " + filename); throw e; } catch (IOException e) { logger.error("Resource file can not be readed: " + filename); throw new FileNotFoundException("Resource file can not be readed: " + filename); } if (in == null) { logger.error("Resource file not found: " + filename); throw new FileNotFoundException(filename); } return in; }
|
11
|
Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
private void addPNMLFileToLibrary(File selected) { try { FileChannel srcChannel = new FileInputStream(selected.getAbsolutePath()).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(matchingOrderXML).getParent() + "/" + selected.getName()).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); order.add(new ComponentDescription(false, selected.getName().replaceAll(".pnml", ""), 1.0)); updateComponentList(); } catch (IOException ioe) { JOptionPane.showMessageDialog(dialog, "Could not add the PNML file " + selected.getName() + " to the library!"); } }
|
11
|
Code Sample 1:
public static boolean copy(File source, File dest) { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
public void sendResponse(DjdocRequest req, HttpServletResponse res) throws IOException { File file = (File) req.getResult(); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) { in.close(); } } }
|
00
|
Code Sample 1:
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: HashCalculator <Algorithm> <Input>"); System.out.println("The preferred algorithm is SHA."); } else { MessageDigest md; try { md = MessageDigest.getInstance(args[0]); md.update(args[1].getBytes()); System.out.print("Hashed value of " + args[1] + " is: "); System.out.println((new BASE64Encoder()).encode(md.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } }
Code Sample 2:
public static String submitURLRequest(String url) throws HttpException, IOException, URISyntaxException { HttpClient httpclient = new DefaultHttpClient(); InputStream stream = null; user_agents = new LinkedList<String>(); user_agents.add("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); String response_text = ""; URI uri = new URI(url); HttpGet post = new HttpGet(uri); int MAX = user_agents.size() - 1; int index = (int) Math.round(((double) Math.random() * (MAX))); String agent = user_agents.get(index); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, agent); httpclient.getParams().setParameter("User-Agent", agent); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.ACCEPT_NONE); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { stream = entity.getContent(); response_text = convertStreamToString(stream); } httpclient.getConnectionManager().shutdown(); if (stream != null) { stream.close(); } return response_text; }
|
11
|
Code Sample 1:
private void trainSRLParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractSRLParser labeler = null; AbstractDecoder[] decoder = null; if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); labeler = new SRLParser(flag, s_featureXml); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); labeler = new SRLParser(flag, t_xml, s_lexiconFiles); } else if (flag == SRLParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train boost"); decoder = new AbstractDecoder[m_model.length]; for (int i = 0; i < decoder.length; i++) decoder[i] = new OneVsAllDecoder((OneVsAllModel) m_model[i]); labeler = new SRLParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = new SRLReader(s_trainFile, true); DepTree tree; int n; labeler.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { labeler.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- labeling: " + n); if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("- labeling"); labeler.saveTags(s_lexiconFiles); t_xml = labeler.getSRLFtrXml(); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE || flag == SRLParser.FLAG_TRAIN_BOOST) { a_yx = labeler.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); for (String lexicaFile : s_lexiconFiles) { zout.putArchiveEntry(new JarArchiveEntry(lexicaFile)); IOUtils.copy(new FileInputStream(lexicaFile), zout); zout.closeArchiveEntry(); } if (flag == SRLParser.FLAG_TRAIN_INSTANCE) t_map = labeler.getSRLFtrMap(); } }
Code Sample 2:
public static void copyClassPathResource(String classPathResourceName, String fileSystemDirectoryName) { InputStream resourceInputStream = null; OutputStream fileOutputStream = null; try { resourceInputStream = FileUtils.class.getResourceAsStream(classPathResourceName); String fileName = StringUtils.substringAfterLast(classPathResourceName, "/"); File fileSystemDirectory = new File(fileSystemDirectoryName); fileSystemDirectory.mkdirs(); fileOutputStream = new FileOutputStream(fileSystemDirectoryName + "/" + fileName); IOUtils.copy(resourceInputStream, fileOutputStream); } catch (IOException e) { throw new UnitilsException(e); } finally { closeQuietly(resourceInputStream); closeQuietly(fileOutputStream); } }
|
11
|
Code Sample 1:
public void delete(String name) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); AttributeTable attribute = new AttributeTable(); attribute.deleteAllForType(stmt, name); String sql = "delete from AttributeCategories " + "where CategoryName = '" + name + "'"; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(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()); } }
|
11
|
Code Sample 1:
public static void testclass(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.emptyClass(ClassWriter.ACC_PUBLIC, "TestClass", "java/lang/Object"); MethodInfo newMethod = writer.addMethod(ClassWriter.ACC_PUBLIC | ClassWriter.ACC_STATIC, "main", "([Ljava/lang/String;)V"); CodeAttribute attribute = newMethod.getCodeAttribute(); int constantIndex = writer.getStringConstantIndex("It's alive! It's alive!!"); int fieldRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Fieldref, "java/lang/System", "out", "Ljava/io/PrintStream;"); int methodRefIndex = writer.getReferenceIndex(ClassWriter.CONSTANT_Methodref, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); ArrayList instructions = new ArrayList(); byte[] operands; operands = new byte[2]; NetByte.intToPair(fieldRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("getstatic"), 0, operands, false)); operands = new byte[1]; operands[0] = (byte) constantIndex; instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("ldc"), 0, operands, false)); operands = new byte[2]; NetByte.intToPair(methodRefIndex, operands, 0); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("invokevirtual"), 0, operands, false)); instructions.add(new Instruction(OpCode.getOpCodeByMnemonic("return"), 0, null, false)); attribute.insertInstructions(0, 0, instructions); attribute.setMaxLocals(1); attribute.codeCheck(); System.out.println("constantIndex=" + constantIndex + " fieldRef=" + fieldRefIndex + " methodRef=" + methodRefIndex); writer.writeClass(new FileOutputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); writer.readClass(new FileInputStream("c:/cygnus/home/javaodb/classes/TestClass.class")); }
Code Sample 2:
public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
|
00
|
Code Sample 1:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); HttpClient client = new DefaultHttpClient(); HttpGet httpGetRequest = new HttpGet("http://www.google.com/"); String line = "", responseString = ""; try { HttpResponse response = client.execute(httpGetRequest); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while ((line = br.readLine()) != null) { responseString += line; } br.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } tv.setText(responseString); setContentView(tv); }
Code Sample 2:
public String encrypt(String pstrPlainText) throws Exception { if (pstrPlainText == null) { return ""; } MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pstrPlainText.getBytes("UTF-8")); byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); }
|
11
|
Code Sample 1:
private void checkForNewVersion() { try { org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(net.xan.taskstack.TaskStackApp.class).getContext().getResourceMap(NewTaskDialog.class); String versionUrl = resourceMap.getString("Application.versionFileUrl"); long startTime = System.currentTimeMillis(); System.out.println("Retrieving version file from\n" + versionUrl); URL url = new URL(versionUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.startsWith("LastVersion")) { String remoteVersion = str.substring(str.indexOf("=") + 1); String localVersion = resourceMap.getString("Application.version"); System.out.println("Version file found"); System.out.println("Local version: " + localVersion); System.out.println("Remote version: " + remoteVersion); if (remoteVersion.compareTo(localVersion) > 0) { askDownloadNewVersion(remoteVersion, localVersion); } break; } } long endTime = System.currentTimeMillis(); System.out.println("Elapsed time " + (endTime - startTime) + "ms"); in.close(); } catch (MalformedURLException e) { System.err.println(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private List getPluginClassList(List pluginFileList) { ArrayList l = new ArrayList(); for (Iterator i = pluginFileList.iterator(); i.hasNext(); ) { URL url = (URL) i.next(); log.debug("Trying file " + url.toString()); try { BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.length() == 0 || line.charAt(0) == '#') continue; l.add(line); } } catch (Exception e) { log.warn("Could not load " + url, e); } } return l; }
|
11
|
Code Sample 1:
public void service(Request req, Response resp) { PrintStream out = null; try { out = resp.getPrintStream(8192); String env = req.getParameter("env"); String regex = req.getParameter("regex"); String deep = req.getParameter("deep"); String term = req.getParameter("term"); String index = req.getParameter("index"); String refresh = req.getParameter("refresh"); String searcher = req.getParameter("searcher"); String grep = req.getParameter("grep"); String fiServerDetails = req.getParameter("fi_server_details"); String serverDetails = req.getParameter("server_details"); String hostDetails = req.getParameter("host_details"); String name = req.getParameter("name"); String show = req.getParameter("show"); String path = req.getPath().getPath(); int page = req.getForm().getInteger("page"); if (path.startsWith("/fs")) { String fsPath = path.replaceAll("^/fs", ""); File realPath = new File("C:\\", fsPath.replace('/', File.separatorChar)); if (realPath.isDirectory()) { out.write(FileSystemDirectory.getContents(new File("c:\\"), fsPath, "/fs")); } else { resp.set("Cache", "no-cache"); FileInputStream fin = new FileInputStream(realPath); FileChannel channel = fin.getChannel(); WritableByteChannel channelOut = resp.getByteChannel(); channel.transferTo(0, realPath.length(), channelOut); channel.close(); fin.close(); System.err.println("Serving " + path + " as " + realPath.getCanonicalPath()); } } else if (path.startsWith("/files/")) { String[] segments = req.getPath().getSegments(); boolean done = false; if (segments.length > 1) { String realPath = req.getPath().getPath(1); File file = context.getFile(realPath); if (file.isFile()) { resp.set("Content-Type", context.getContentType(realPath)); FileInputStream fin = new FileInputStream(file); FileChannel channel = fin.getChannel(); WritableByteChannel channelOut = resp.getByteChannel(); long start = System.currentTimeMillis(); channel.transferTo(0, realPath.length(), channelOut); channel.close(); fin.close(); System.err.println("Time take to write [" + realPath + "] was [" + (System.currentTimeMillis() - start) + "] of size [" + file.length() + "]"); done = true; } } if (!done) { resp.set("Content-Type", "text/plain"); out.println("Can not serve directory: path"); } } else if (path.startsWith("/upload")) { FileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); RequestAdapter adapter = new RequestAdapter(req); List<FileItem> list = upload.parseRequest(adapter); Map<String, FileItem> map = new HashMap<String, FileItem>(); for (FileItem entry : list) { String fileName = entry.getFieldName(); map.put(fileName, entry); } resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body>"); for (int i = 0; i < 10; i++) { Part file = req.getPart("datafile" + (i + 1)); if (file != null && file.isFile()) { String partName = file.getName(); String partFileName = file.getFileName(); File partFile = new File(partFileName); FileItem item = map.get(partName); InputStream in = file.getInputStream(); String fileName = file.getFileName().replaceAll("\\\\", "_").replaceAll(":", "_"); File filePath = new File(fileName); OutputStream fileOut = new FileOutputStream(filePath); byte[] chunk = new byte[8192]; int count = 0; while ((count = in.read(chunk)) != -1) { fileOut.write(chunk, 0, count); } fileOut.close(); in.close(); out.println("<table border='1'>"); out.println("<tr><td><b>File</b></td><td>"); out.println(filePath.getCanonicalPath()); out.println("</tr></td>"); out.println("<tr><td><b>Size</b></td><td>"); out.println(filePath.length()); out.println("</tr></td>"); out.println("<tr><td><b>MD5</b></td><td>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, file.getInputStream())); out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, item.getInputStream())); if (partFile.exists()) { out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.MD5, new FileInputStream(partFile))); } out.println("</tr></td>"); out.println("<tr><td><b>SHA1</b></td><td>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, file.getInputStream())); out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, item.getInputStream())); if (partFile.exists()) { out.println("<br>"); out.println(Digest.getSignature(Digest.Algorithm.SHA1, new FileInputStream(partFile))); } out.println("</tr></td>"); out.println("<tr><td><b>Header</b></td><td><pre>"); out.println(file.toString().trim()); out.println("</pre></tr></td>"); if (partFileName.toLowerCase().endsWith(".xml")) { String xml = file.getContent(); String formatted = format(xml); String fileFormatName = fileName + ".formatted"; File fileFormatOut = new File(fileFormatName); FileOutputStream formatOut = new FileOutputStream(fileFormatOut); formatOut.write(formatted.getBytes("UTF-8")); out.println("<tr><td><b>Formatted XML</b></td><td><pre>"); out.println("<a href='/" + (fileFormatName) + "'>" + partFileName + "</a>"); out.println("</pre></tr></td>"); formatOut.close(); } out.println("<table>"); } } out.println("</body>"); out.println("</html>"); } else if (path.startsWith("/sql/") && index != null && searcher != null) { String file = req.getPath().getPath(1); File root = searchEngine.index(searcher).getRoot(); SearchEngine engine = searchEngine.index(searcher); File indexFile = getStoredProcIndexFile(engine.getRoot(), index); File search = new File(root, "cpsql"); File source = new File(root, file.replace('/', File.separatorChar)); FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(search, indexFile); FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(source.getName()); resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body><pre>"); for (String procName : proc.getReferences()) { FindStoredProcs.StoredProc theProc = storedProcProj.getStoredProc(procName); if (theProc != null) { String url = getRelativeURL(root, theProc.getFile()); out.println("<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'><b>" + theProc.getName() + "</b>"); } } out.println("</pre></body>"); out.println("</html>"); } else if (show != null && index != null && searcher != null) { String authentication = req.getValue("Authorization"); if (authentication == null) { resp.setCode(401); resp.setText("Authorization Required"); resp.set("Content-Type", "text/html"); resp.set("WWW-Authenticate", "Basic realm=\"DTS Subversion Repository\""); out.println("<html>"); out.println("<head>"); out.println("401 Authorization Required"); out.println("</head>"); out.println("<body>"); out.println("<h1>401 Authorization Required</h1>"); out.println("</body>"); out.println("</html>"); } else { resp.set("Content-Type", "text/html"); Principal principal = new PrincipalParser(authentication); String file = show; SearchEngine engine = searchEngine.index(searcher); File root = engine.getRoot(); File javaIndexFile = getJavaIndexFile(root, index); File storedProcIndexFile = getStoredProcIndexFile(root, index); File sql = new File(root, "cpsql"); File source = new File(root, file.replace('/', File.separatorChar)); File javaSource = new File(root, file.replace('/', File.separatorChar)); File canonical = source.getCanonicalFile(); Repository repository = Subversion.login(Scheme.HTTP, principal.getName(), principal.getPassword()); Info info = null; try { info = repository.info(canonical); } catch (Exception e) { e.printStackTrace(); } List<Change> logMessages = new ArrayList<Change>(); try { logMessages = repository.log(canonical); } catch (Exception e) { e.printStackTrace(); } FileInputStream in = new FileInputStream(canonical); List<String> lines = LineStripper.stripLines(in); out.println("<html>"); out.println("<head>"); out.println("<!-- username='" + principal.getName() + "' password='" + principal.getPassword() + "' -->"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); if (info != null) { out.println("<table border='1'>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Author</tt></td><td><tt>" + info.author + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Version</tt></td><td><tt>" + info.version + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>URL</tt></td><td><tt>" + info.location + "</tt></td></tr>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Path</tt></td><td><tt>" + canonical + "</tt></td></tr>"); out.println("</table>"); } out.println("<table border='1''>"); out.println("<tr>"); out.println("<td valign='top' bgcolor=\"#C4C4C4\"><pre>"); FindStoredProcs.StoredProcProject storedProcProj = FindStoredProcs.getStoredProcProject(sql, storedProcIndexFile); FindStoredProcs.StoredProc storedProc = null; FindJavaSources.JavaProject project = null; FindJavaSources.JavaClass javaClass = null; List<FindJavaSources.JavaClass> importList = null; if (file.endsWith(".sql")) { storedProc = storedProcProj.getStoredProc(canonical.getName()); } else if (file.endsWith(".java")) { project = FindJavaSources.getProject(root, javaIndexFile); javaClass = project.getClass(source); importList = project.getImports(javaSource); } for (int i = 0; i < lines.size(); i++) { out.println(i); } out.println("</pre></td>"); out.print("<td valign='top'><pre"); out.print(getJavaScript(file)); out.println(">"); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String escaped = escapeHtml(line); if (project != null) { for (FindJavaSources.JavaClass entry : importList) { String className = entry.getClassName(); String fullyQualifiedName = entry.getFullyQualifiedName(); if (line.startsWith("import") && line.indexOf(fullyQualifiedName) > -1) { File classFile = entry.getSourceFile(); String url = getRelativeURL(root, classFile); escaped = escaped.replaceAll(fullyQualifiedName + ";", "<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + fullyQualifiedName + "</a>;"); } else if (line.indexOf(className) > -1) { File classFile = entry.getSourceFile(); String url = getRelativeURL(root, classFile); escaped = escaped.replaceAll("\\s" + className + ",", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("\\s" + className + "\\{", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>{"); escaped = escaped.replaceAll("," + className + ",", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll("," + className + "\\{", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>{"); escaped = escaped.replaceAll("\\s" + className + "\\s", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("\\(" + className + "\\s", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll("\\s" + className + "\\.", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>."); escaped = escaped.replaceAll("\\(" + className + "\\.", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>."); escaped = escaped.replaceAll("\\s" + className + "\\(", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>("); escaped = escaped.replaceAll("\\(" + className + "\\(", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>("); escaped = escaped.replaceAll(">" + className + ",", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>,"); escaped = escaped.replaceAll(">" + className + "\\s", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a> "); escaped = escaped.replaceAll(">" + className + "<", "><a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a><"); escaped = escaped.replaceAll("\\(" + className + "\\);", "(<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + className + "</a>)"); } } } else if (storedProc != null) { Set<String> procSet = storedProc.getTopReferences(); List<String> sortedProcs = new ArrayList(procSet); Collections.sort(sortedProcs, LONGEST_FIRST); for (String procFound : sortedProcs) { if (escaped.indexOf(procFound) != -1) { File nameFile = storedProcProj.getLocation(procFound); if (nameFile != null) { String url = getRelativeURL(root, nameFile); escaped = escaped.replaceAll("\\s" + procFound + "\\s", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("\\s" + procFound + ",", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("\\s" + procFound + ";", " <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("," + procFound + "\\s", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("," + procFound + ",", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("," + procFound + ";", ",<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("=" + procFound + "\\s", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("=" + procFound + ",", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("=" + procFound + ";", "=<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); escaped = escaped.replaceAll("." + procFound + "\\s", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a> "); escaped = escaped.replaceAll("." + procFound + ",", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>,"); escaped = escaped.replaceAll("." + procFound + ";", ".<a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + procFound + "</a>;"); } else { System.err.println("NOT FOUND: " + procFound); } } } } out.println(escaped); } out.println("</pre></td>"); out.println("</tr>"); out.println("</table>"); out.println("<table border='1'>"); out.printf("<tr><td bgcolor=\"#C4C4C4\"><tt>Revision</tt></td><td bgcolor=\"#C4C4C4\"><tt>Date</tt></td><td bgcolor=\"#C4C4C4\"><tt>Author</tt></td><td bgcolor=\"#C4C4C4\"><tt>Comment</tt></td></tr>"); DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); for (Change message : logMessages) { out.printf("<tr><td><tt>%s</tt></td><td><tt>%s</tt></td><td><tt>%s</tt></td><td><tt>%s</tt></td></tr>%n", message.version, format.format(message.date).replaceAll("\\s", " "), message.author, message.message); } out.println("</table>"); if (project != null) { out.println("<pre>"); for (FindJavaSources.JavaClass entry : importList) { String url = getRelativeURL(root, entry.getSourceFile()); out.println("import <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + entry.getFullyQualifiedName() + "</a> as " + entry.getClassName()); } out.println("</pre>"); } if (storedProc != null) { out.println("<pre>"); for (String procName : storedProc.getReferences()) { FindStoredProcs.StoredProc proc = storedProcProj.getStoredProc(procName); if (proc != null) { String url = getRelativeURL(root, proc.getFile()); out.println("using <a href='/?show=" + url + "&index=" + index + "&searcher=" + searcher + "'>" + proc.getName() + "</a>"); } } out.println("</pre>"); } out.println("</form>"); out.println("</body>"); out.println("</html>"); } } else if (path.endsWith(".js") || path.endsWith(".css") || path.endsWith(".formatted")) { path = path.replace('/', File.separatorChar); if (path.endsWith(".formatted")) { resp.set("Content-Type", "text/plain"); } else if (path.endsWith(".js")) { resp.set("Content-Type", "application/javascript"); } else { resp.set("Content-Type", "text/css"); } resp.set("Cache", "no-cache"); WritableByteChannel channelOut = resp.getByteChannel(); File file = new File(".", path).getCanonicalFile(); System.err.println("Serving " + path + " as " + file.getCanonicalPath()); FileChannel sourceChannel = new FileInputStream(file).getChannel(); sourceChannel.transferTo(0, file.length(), channelOut); sourceChannel.close(); channelOut.close(); } else if (env != null && regex != null) { ServerDetails details = config.getEnvironment(env).load(persister, serverDetails != null, fiServerDetails != null, hostDetails != null); List<String> tokens = new ArrayList<String>(); List<Searchable> list = details.search(regex, deep != null, tokens); Collections.sort(tokens, LONGEST_FIRST); for (String token : tokens) { System.out.println("TOKEN: " + token); } resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<head>"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); writeSearchBox(out, searcher, null, null, regex); out.println("<br>Found " + list.size() + " hits for <b>" + regex + "</b>"); out.println("<table border='1''>"); int countIndex = 1; for (Searchable value : list) { out.println(" <tr><td>" + countIndex++ + " <a href='" + value.getSource() + "'><b>" + value.getSource() + "</b></a></td></tr>"); out.println(" <tr><td><pre class='sh_xml'>"); StringWriter buffer = new StringWriter(); persister.write(value, buffer); String text = buffer.toString(); text = escapeHtml(text); for (String token : tokens) { text = text.replaceAll(token, "<font style='BACKGROUND-COLOR: yellow'>" + token + "</font>"); } out.println(text); out.println(" </pre></td></tr>"); } out.println("</table>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } else if (index != null && term != null && term.length() > 0) { out.println("<html>"); out.println("<head>"); out.println("<link rel='stylesheet' type='text/css' href='style.css'>"); out.println("<script src='highlight.js'></script>"); out.println("</head>"); out.println("<body onload=\"sh_highlightDocument('lang/', '.js')\">"); writeSearchBox(out, searcher, term, index, null); if (searcher == null) { searcher = searchEngine.getDefaultSearcher(); } if (refresh != null) { SearchEngine engine = searchEngine.index(searcher); File root = engine.getRoot(); File searchIndex = getJavaIndexFile(root, index); FindJavaSources.deleteProject(root, searchIndex); } boolean isRefresh = refresh != null; boolean isGrep = grep != null; boolean isSearchNames = name != null; SearchQuery query = new SearchQuery(index, term, page, isRefresh, isGrep, isSearchNames); List<SearchResult> results = searchEngine.index(searcher).search(query); writeSearchResults(query, searcher, results, out); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<body>"); writeSearchBox(out, searcher, null, null, null); out.println("</body>"); out.println("</html>"); } out.close(); } catch (Exception e) { try { e.printStackTrace(); resp.reset(); resp.setCode(500); resp.setText("Internal Server Error"); resp.set("Content-Type", "text/html"); out.println("<html>"); out.println("<body><h1>Internal Server Error</h1><pre>"); e.printStackTrace(out); out.println("</pre></body>"); out.println("</html>"); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
Code Sample 2:
public GetMessages(String messageType) { String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMessages"; String rvalue = ""; String filename = dms_home + FS + "temp" + FS + username + "messages.xml"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&messagetype=" + messageType + "&filename=" + URLEncoder.encode(username, "UTF-8") + "messages.xml"; ; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("message"); int num = nodelist.getLength(); messages = new String[num][7]; for (int i = 0; i < num; i++) { messages[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageid")); messages[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "subject")); messages[i][2] = (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "firstname"))) + " " + (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "lastname"))); messages[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagedatetime")); messages[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagefrom")); messages[i][5] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageto")); messages[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } }
|
00
|
Code Sample 1:
public boolean update(int idPartida, partida partidaModificada) { int intResult = 0; String sql = "UPDATE partida " + "SET torneo_idTorneo = ?, " + " jugador_idJugadorNegras = ?, jugador_idJugadorBlancas = ?, " + " fecha = ?, " + " resultado = ?, " + " nombreBlancas = ?, nombreNegras = ?, eloBlancas = ?, eloNegras = ?, idApertura = ? " + " WHERE idPartida = " + idPartida; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement2(partidaModificada); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
Code Sample 2:
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try { boolean isMultipart = FileUpload.isMultipartContent(request); Store storeInstance = getStoreInstance(request); if (isMultipart) { Map fields = new HashMap(); Vector files = new Vector(); List items = diskFileUpload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString()); } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); files.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } if (files.size() > 0) { storeInstance.send(files, 0, Charset.defaultCharset().displayName()); } } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
|
00
|
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:
public void generateHtmlPage(String real_filename, String url_filename) { String str_content = ""; URL m_url = null; URLConnection m_urlcon = null; try { m_url = new URL(url_filename); m_urlcon = m_url.openConnection(); InputStream in_stream = m_urlcon.getInputStream(); byte[] bytes = new byte[1]; Vector v_bytes = new Vector(); while (in_stream.read(bytes) != -1) { v_bytes.add(bytes); bytes = new byte[1]; } byte[] all_bytes = new byte[v_bytes.size()]; for (int i = 0; i < v_bytes.size(); i++) all_bytes[i] = ((byte[]) v_bytes.get(i))[0]; str_content = new String(all_bytes, "GBK"); } catch (Exception urle) { } try { oaFileOperation file_control = new oaFileOperation(); file_control.writeFile(str_content, real_filename, true); String strPath = url_filename.substring(0, url_filename.lastIndexOf("/") + 1); String strUrlFileName = url_filename.substring(url_filename.lastIndexOf("/") + 1); if (strUrlFileName.indexOf(".jsp") > 0) { strUrlFileName = strUrlFileName.substring(0, strUrlFileName.indexOf(".jsp")) + "_1.jsp"; m_url = new URL(strPath + strUrlFileName); m_url.openConnection(); } intWriteFileCount++; intWriteFileCount = (intWriteFileCount > 100000) ? 0 : intWriteFileCount; } catch (Exception e) { } m_urlcon = null; }
|
00
|
Code Sample 1:
public void run() { result.setValid(false); try { final HttpResponse response = client.execute(method, context); result.setValid(ArrayUtils.contains(validCodes, response.getStatusLine().getStatusCode())); result.setResult(response.getStatusLine().getStatusCode()); } catch (final ClientProtocolException e) { LOGGER.error(e); result.setValid(false); } catch (final IOException e) { LOGGER.error(e); result.setValid(false); } }
Code Sample 2:
public InputStream open(String filename) throws IOException { URL url = TemplateLoader.resolveURL("cms/" + filename); if (url != null) return url.openStream(); url = TemplateLoader.resolveURL(filename); if (url != null) return url.openStream(); return null; }
|
11
|
Code Sample 1:
private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
Code Sample 2:
public String encodePassword(String rawPass, Object salt) { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (java.security.NoSuchAlgorithmException e) { throw new LdapDataAccessException("No SHA implementation available!"); } sha.update(rawPass.getBytes()); if (salt != null) { Assert.isInstanceOf(byte[].class, salt, "Salt value must be a byte array"); sha.update((byte[]) salt); } byte[] hash = combineHashAndSalt(sha.digest(), (byte[]) salt); return (salt == null ? SHA_PREFIX : SSHA_PREFIX) + new String(Base64.encodeBase64(hash)); }
|
11
|
Code Sample 1:
public void testRevcounter() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } String testSourceUri = BASE_URL + "users/lars.trieloff?revision=1.1"; JCRNodeSource secondSource = (JCRNodeSource) resolveSource(testSourceUri); System.out.println("Created at: " + secondSource.getSourceRevision()); for (int i = 0; i < 3; i++) { OutputStream sourceOut = emptySource.getOutputStream(); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } System.out.println(emptySource.getLatestSourceRevision()); } System.out.println("Read again at:" + secondSource.getSourceRevision()); assertNotNull(emptySource.getSourceRevision()); }
Code Sample 2:
public void guardarRecordatorio() { try { if (espaciosLlenos()) { guardarCantidad(); String dat = ""; String filenametxt = String.valueOf("recordatorio" + cantidadArchivos + ".txt"); String filenamezip = String.valueOf("recordatorio" + cantidadArchivos + ".zip"); cantidadArchivos++; dat += identificarDato(datoSeleccionado) + "\n"; dat += String.valueOf(mesTemporal) + "\n"; dat += String.valueOf(anoTemporal) + "\n"; dat += horaT.getText() + "\n"; dat += lugarT.getText() + "\n"; dat += actividadT.getText() + "\n"; File archivo = new File(filenametxt); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(dat); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filenamezip); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File(filenametxt); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry(filenametxt); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); JOptionPane.showMessageDialog(null, "El recordatorio ha sido guardado con exito", "Recordatorio Guardado", JOptionPane.INFORMATION_MESSAGE); marco.hide(); marco.dispose(); establecerMarca(); table.clearSelection(); } else JOptionPane.showMessageDialog(null, "Debe llenar los espacios de Hora, Lugar y Actividad", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
|
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 SendFile(File testfile) { try { SocketChannel sock = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1234)); sock.configureBlocking(true); while (!sock.finishConnect()) { System.out.println("NOT connected!"); } System.out.println("CONNECTED!"); FileInputStream fis = new FileInputStream(testfile); FileChannel fic = fis.getChannel(); long len = fic.size(); Buffer.clear(); Buffer.putLong(len); Buffer.flip(); sock.write(Buffer); long cnt = 0; while (cnt < len) { Buffer.clear(); int add = fic.read(Buffer); cnt += add; Buffer.flip(); while (Buffer.hasRemaining()) { sock.write(Buffer); } } fic.close(); File tmpfile = getTmp().createNewFile("tmp", "tmp"); FileOutputStream fos = new FileOutputStream(tmpfile); FileChannel foc = fos.getChannel(); int mlen = -1; do { Buffer.clear(); mlen = sock.read(Buffer); Buffer.flip(); if (mlen > 0) { foc.write(Buffer); } } while (mlen > 0); foc.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void delete(Channel channel) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] selfDefinePath = getSelfDefinePath(channel.getPath(), "1", connection, preparedStatement, resultSet); selfDefineDelete(selfDefinePath, connection, preparedStatement); String sqlStr = "delete from t_ip_channel where channel_path=?"; preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); sqlStr = "delete from t_ip_channel_order where channel_order_site = ?"; preparedStatement.setString(1, channel.getPath()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException ex) { connection.rollback(); log.error("ɾ��Ƶ��ʧ�ܣ�channelPath=" + channel.getPath(), ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } }
Code Sample 2:
public void testClickToCallOutDirection() throws Exception { init(); SipCall[] receiverCalls = new SipCall[receiversCount]; receiverCalls[0] = sipPhoneReceivers[0].createSipCall(); receiverCalls[1] = sipPhoneReceivers[1].createSipCall(); receiverCalls[0].listenForIncomingCall(); receiverCalls[1].listenForIncomingCall(); logger.info("Trying to reach url : " + CLICK2DIAL_URL + CLICK2DIAL_PARAMS); URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS); InputStream in = url.openConnection().getInputStream(); byte[] buffer = new byte[10000]; int len = in.read(buffer); String httpResponse = ""; for (int q = 0; q < len; q++) httpResponse += (char) buffer[q]; logger.info("Received the follwing HTTP response: " + httpResponse); receiverCalls[0].waitForIncomingCall(timeout); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.OK, "OK", 0)); receiverCalls[1].waitForIncomingCall(timeout); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.OK, "OK", 0)); assertTrue(receiverCalls[1].waitForAck(timeout)); assertTrue(receiverCalls[0].waitForAck(timeout)); assertTrue(receiverCalls[0].disconnect()); assertTrue(receiverCalls[1].waitForDisconnect(timeout)); assertTrue(receiverCalls[1].respondToDisconnect()); }
|
11
|
Code Sample 1:
public File createReadmeFile(File dir, MavenProject mavenProject) throws IOException { InputStream is = getClass().getResourceAsStream("README.template"); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw); String content = sw.getBuffer().toString(); content = StringUtils.replace(content, "{project_name}", mavenProject.getArtifactId()); File readme = new File(dir, "README.TXT"); FileUtils.writeStringToFile(readme, content); return readme; }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
private static void readAndWriteFile(File source, File target) { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
private File unzipArchive(File zipArchive, File outDir, String nameInZipArchive) throws IOException { File mainFile = null; ZipEntry entry = null; ZipInputStream zis = new ZipInputStream(new FileInputStream((zipArchive))); FileOutputStream fos = null; byte buffer[] = new byte[4096]; int bytesRead; while ((entry = zis.getNextEntry()) != null) { File outFile = new File(outDir, entry.getName()); if (entry.getName().equals(nameInZipArchive)) mainFile = outFile; fos = new FileOutputStream(outFile); while ((bytesRead = zis.read(buffer)) != -1) fos.write(buffer, 0, bytesRead); fos.close(); } zis.close(); return mainFile; }
|
00
|
Code Sample 1:
public static void saveDigraph(mainFrame parentFrame, DigraphView digraphView, File tobeSaved) { DigraphFile digraphFile = new DigraphFile(); DigraphTextFile digraphTextFile = new DigraphTextFile(); try { if (!DigraphFile.DIGRAPH_FILE_EXTENSION.equals(getExtension(tobeSaved))) { tobeSaved = new File(tobeSaved.getPath() + "." + DigraphFile.DIGRAPH_FILE_EXTENSION); } File dtdFile = new File(tobeSaved.getParent() + "/" + DigraphFile.DTD_FILE); if (!dtdFile.exists()) { File baseDigraphDtdFile = parentFrame.getDigraphDtdFile(); if (baseDigraphDtdFile != null && baseDigraphDtdFile.exists()) { try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dtdFile)); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(baseDigraphDtdFile)); while (bis.available() > 1) { bos.write(bis.read()); } bis.close(); bos.close(); } catch (IOException ex) { System.out.println("Unable to Write Digraph DTD File: " + ex.getMessage()); } } else { System.out.println("Unable to Find Base Digraph DTD File: "); } } Digraph digraph = digraphView.getDigraph(); digraphFile.saveDigraph(tobeSaved, digraph); String fileName = tobeSaved.getName(); int extensionIndex = fileName.lastIndexOf("."); if (extensionIndex > 0) { fileName = fileName.substring(0, extensionIndex + 1) + "txt"; } else { fileName = fileName + ".txt"; } File textFile = new File(tobeSaved.getParent() + "/" + fileName); digraphTextFile.saveDigraph(textFile, digraph); digraphView.setDigraphDirty(false); parentFrame.setFilePath(tobeSaved.getPath()); parentFrame.setSavedOnce(true); } catch (DigraphFileException exep) { JOptionPane.showMessageDialog(parentFrame, "Error Saving File:\n" + exep.getMessage(), "Save Error", JOptionPane.ERROR_MESSAGE); } catch (DigraphException exep) { JOptionPane.showMessageDialog(parentFrame, "Error Retrieving Digraph from View:\n" + exep.getMessage(), "Save Error", JOptionPane.ERROR_MESSAGE); } }
Code Sample 2:
public void testGetWithKeepAlive() throws Exception { HttpGet request = new HttpGet(baseUri + "/test"); HttpResponse response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("test", TestUtil.getResponseAsString(response)); response = client.execute(request); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals("test", TestUtil.getResponseAsString(response)); }
|
00
|
Code Sample 1:
public static String readFromURL(String url_) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(url_); System.setProperty("http.agent", ""); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); connection.setDoInput(true); InputStream inStream = connection.getInputStream(); BufferedReader input = new BufferedReader(new InputStreamReader(inStream, "utf8")); String line = ""; while ((line = input.readLine()) != null) { buffer.append(line + "\n"); } } catch (Exception e) { System.out.println(e.toString()); } return buffer.toString(); }
Code Sample 2:
public static void copyAssetFile(Context ctx, String srcFileName, String targetFilePath) { AssetManager assetManager = ctx.getAssets(); try { InputStream is = assetManager.open(srcFileName); File out = new File(targetFilePath); if (!out.exists()) { out.getParentFile().mkdirs(); out.createNewFile(); } OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } catch (IOException e) { AIOUtils.log("error when copyAssetFile", e); } }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public List<PathObject> fetchPath(BoardObject board) throws NetworkException { if (boardPathMap.containsKey(board.getId())) { return boardPathMap.get(board.getId()).getChildren(); } HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_0AN_BOARD + board.getId()); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); Document doc = XmlOperator.readDocument(entity.getContent()); PathObject parent = new PathObject(); BBSBodyParseHelper.parsePathList(doc, parent); parent = searchAndCreatePathFromRoot(parent); boardPathMap.put(board.getId(), parent); return parent.getChildren(); } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } }
|
11
|
Code Sample 1:
private String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public boolean check(Object credentials) { String password = (credentials instanceof String) ? (String) credentials : credentials.toString(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] ha1; if (credentials instanceof Credential.MD5) { ha1 = ((Credential.MD5) credentials).getDigest(); } else { md.update(username.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(realm.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(password.getBytes(StringUtil.__ISO_8859_1)); ha1 = md.digest(); } md.reset(); md.update(method.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(uri.getBytes(StringUtil.__ISO_8859_1)); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(nc.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(cnonce.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(qop.getBytes(StringUtil.__ISO_8859_1)); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes(StringUtil.__ISO_8859_1)); byte[] digest = md.digest(); return (TypeUtil.toString(digest, 16).equalsIgnoreCase(response)); } catch (Exception e) { Log.warn(e); } return false; }
|
11
|
Code Sample 1:
char[] DigestCalcHA1(String algorithm, String userName, String realm, String password, String nonce, String clientNonce) throws SaslException { byte[] hash; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userName.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(realm.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(password.getBytes("UTF-8")); hash = md.digest(); if ("md5-sess".equals(algorithm)) { md.update(hash); md.update(":".getBytes("UTF-8")); md.update(nonce.getBytes("UTF-8")); md.update(":".getBytes("UTF-8")); md.update(clientNonce.getBytes("UTF-8")); hash = md.digest(); } } catch (NoSuchAlgorithmException e) { throw new SaslException("No provider found for MD5 hash", e); } catch (UnsupportedEncodingException e) { throw new SaslException("UTF-8 encoding not supported by platform.", e); } return convertToHex(hash); }
Code Sample 2:
public synchronized String decrypt(String plaintext) throws Exception { MessageDigest md = null; String strhash = new String((new BASE64Decoder()).decodeBuffer(plaintext)); System.out.println("strhash1122 " + strhash); try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); } byte raw[] = md.digest(); try { md.update(new String(raw).getBytes("UTF-8")); } catch (Exception e) { e.printStackTrace(); } System.out.println("plain text " + strhash); String strcode = new String(raw); System.out.println("strcode.." + strcode); return strcode; }
|
00
|
Code Sample 1:
private void trainSRLParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractSRLParser labeler = null; AbstractDecoder[] decoder = null; if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); labeler = new SRLParser(flag, s_featureXml); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); labeler = new SRLParser(flag, t_xml, s_lexiconFiles); } else if (flag == SRLParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train boost"); decoder = new AbstractDecoder[m_model.length]; for (int i = 0; i < decoder.length; i++) decoder[i] = new OneVsAllDecoder((OneVsAllModel) m_model[i]); labeler = new SRLParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = new SRLReader(s_trainFile, true); DepTree tree; int n; labeler.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { labeler.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- labeling: " + n); if (flag == SRLParser.FLAG_TRAIN_LEXICON) { System.out.println("- labeling"); labeler.saveTags(s_lexiconFiles); t_xml = labeler.getSRLFtrXml(); } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE || flag == SRLParser.FLAG_TRAIN_BOOST) { a_yx = labeler.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); for (String lexicaFile : s_lexiconFiles) { zout.putArchiveEntry(new JarArchiveEntry(lexicaFile)); IOUtils.copy(new FileInputStream(lexicaFile), zout); zout.closeArchiveEntry(); } if (flag == SRLParser.FLAG_TRAIN_INSTANCE) t_map = labeler.getSRLFtrMap(); } }
Code Sample 2:
public void initializeWebInfo() throws MalformedURLException, IOException, DOMException { Tidy tidy = new Tidy(); URL url = new URL(YOUTUBE_URL + videoId); InputStream in = url.openConnection().getInputStream(); Document doc = tidy.parseDOM(in, null); Element e = doc.getDocumentElement(); String title = null; if (e != null && e.hasChildNodes()) { NodeList children = e.getElementsByTagName("title"); if (children != null) { for (int i = 0; i < children.getLength(); i++) { try { Element childE = (Element) children.item(i); if (childE.getTagName().equals("title")) { NodeList titleChildren = childE.getChildNodes(); for (int n = 0; n < titleChildren.getLength(); n++) { if (titleChildren.item(n).getNodeType() == childE.TEXT_NODE) { title = titleChildren.item(n).getNodeValue(); } } } } catch (Exception exp) { exp.printStackTrace(); } } } } if (title == null || title.equals("")) { throw new DOMException(DOMException.NOT_FOUND_ERR, "no title found"); } else { setTitle(title); } }
|
00
|
Code Sample 1:
public static URLConnection createConnection(URL url) throws java.io.IOException { URLConnection urlConn = url.openConnection(); if (urlConn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setRequestMethod("POST"); } urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setDefaultUseCaches(false); return urlConn; }
Code Sample 2:
@Override protected ActionForward executeAction(ActionMapping mapping, ActionForm form, User user, HttpServletRequest request, HttpServletResponse response) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); String attributeIdentifier = request.getParameter("identifier"); if (resourceId != 0L && StringUtils.hasText(attributeIdentifier)) { try { BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, attributeIdentifier, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; } catch (DataRetrievalFailureException e) { addGlobalError(request, "errors.notFound"); } catch (Exception e) { addGlobalError(request, e); } } return mapping.getInputForward(); }
|
11
|
Code Sample 1:
public static String getPasswordHash(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); byte[] byteData = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Unknow error in hashing password", e); return "Unknow error, check system log"; } }
Code Sample 2:
public static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("UTF-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
|
00
|
Code Sample 1:
private void sendLocal() throws Exception { if (validParameters()) { URL url = new URL(storageUrlString); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); RequestUtils requestUtils = new RequestUtils(); requestUtils.preRequestAddParameter("senderObj", "QuotaSender"); requestUtils.preRequestAddParameter("beanNumbers", new String().valueOf(quotaBeans.size())); for (int vPos = 0; vPos < quotaBeans.size(); vPos++) { QuotaBean bean = (QuotaBean) quotaBeans.get(vPos); requestUtils.preRequestAddParameter("" + vPos + "#portalID", bean.getPortalID()); requestUtils.preRequestAddParameter("" + vPos + "#userID", bean.getUserID()); requestUtils.preRequestAddParameter("" + vPos + "#workflowID", bean.getWorkflowID()); requestUtils.preRequestAddParameter("" + vPos + "#runtimeID", bean.getRuntimeID()); requestUtils.preRequestAddParameter("" + vPos + "#plussQuotaSize", bean.getPlussQuotaSize().toString()); } requestUtils.preRequestAddFile("zipFileName", "dummyZipFileName.zip"); requestUtils.createPostRequest(); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary()); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); try { httpURLConnection.connect(); OutputStream out = httpURLConnection.getOutputStream(); byte[] preBytes = requestUtils.getPreRequestStringBytes(); out.write(preBytes); out.flush(); out.write(new String("dummyFile").getBytes()); byte[] postBytes = requestUtils.getPostRequestStringBytes(); out.write(postBytes); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); in.readLine(); in.close(); if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) { throw new Exception("response not HTTP_OK !"); } } catch (Exception e) { e.printStackTrace(); throw new Exception("Cannot connect to: " + storageUrlString, e); } } else { throw new Exception("Not valid parameters: quotaBeans !"); } }
Code Sample 2:
public Point getCoordinates(String address, String city, String state, String country) { StringBuilder queryString = new StringBuilder(); StringBuilder urlString = new StringBuilder(); StringBuilder response = new StringBuilder(); if (address != null) { queryString.append(address.trim().replaceAll(" ", "+")); queryString.append("+"); } if (city != null) { queryString.append(city.trim().replaceAll(" ", "+")); queryString.append("+"); } if (state != null) { queryString.append(state.trim().replaceAll(" ", "+")); queryString.append("+"); } if (country != null) { queryString.append(country.replaceAll(" ", "+")); } urlString.append("http://maps.google.com/maps/geo?key="); urlString.append(key); urlString.append("&sensor=false&output=json&oe=utf8&q="); urlString.append(queryString.toString()); try { URL url = new URL(urlString.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); JSONObject root = (JSONObject) JSONValue.parse(response.toString()); JSONObject placemark = (JSONObject) ((JSONArray) root.get("Placemark")).get(0); JSONArray coordinates = (JSONArray) ((JSONObject) placemark.get("Point")).get("coordinates"); Point point = new Point(); point.setLatitude((Double) coordinates.get(1)); point.setLongitude((Double) coordinates.get(0)); return point; } catch (MalformedURLException ex) { return null; } catch (NullPointerException ex) { return null; } catch (IOException ex) { return null; } }
|
11
|
Code Sample 1:
public void compressImage(InputStream input, String output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile; try { inputFile = File.createTempFile("tmp", ".tif"); inputFile.deleteOnExit(); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } compressImage(inputFile.getAbsolutePath(), output, params); if (inputFile != null) inputFile.delete(); }
Code Sample 2:
@Override public void run() { long timeout = 10 * 1000L; long start = (new Date()).getTime(); try { InputStream is = socket.getInputStream(); boolean available = false; while (!available && !socket.isClosed()) { try { if (is.available() != 0) { available = true; } else { Thread.sleep(100); } } catch (Exception e) { LOG.error("Error checking socket", e); } long curr = (new Date()).getTime(); if ((curr - start) >= timeout) { break; } } if (socket.isClosed()) { } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); baos.flush(); baos.close(); data = baos.toByteArray(); } String msg = FtpResponse.ReadComplete.asString() + ClientCommand.SP + "Read Complete" + ClientCommand.CRLF; List<String> list = new ArrayList<String>(); list.add(msg); ClientResponse response = new ClientResponse(list); ftpClient.notifyListeners(response); } catch (Exception e) { LOG.error("Error reading server response", e); } }
|
11
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
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(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
11
|
Code Sample 1:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.close(output); } } finally { IOUtils.close(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
Code Sample 2:
public Controller(String m_hostname, String team, boolean m_shouldexit) throws InternalException { m_received_messages = new ConcurrentLinkedQueue<ReceivedMessage>(); m_fragmsgs = new ArrayList<String>(); m_customizedtaunts = new HashMap<Integer, String>(); m_nethandler = new CachingNetHandler(); m_drawingpanel = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities()); m_user = System.getProperty("user.name"); m_chatbuffer = new StringBuffer(); this.m_shouldexit = m_shouldexit; isChatPaused = false; isRunning = true; m_lastbullet = 0; try { BufferedReader in = new BufferedReader(new FileReader(HogsConstants.FRAGMSGS_FILE)); String str; while ((str = in.readLine()) != null) { m_fragmsgs.add(str); } in.close(); } catch (IOException e) { e.printStackTrace(); } String newFile = PathFinder.getCustsFile(); boolean exists = (new File(newFile)).exists(); Reader reader = null; if (exists) { try { reader = new FileReader(newFile); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } else { Object[] options = { "Yes, create a .hogsrc file", "No, use default taunts" }; int n = JOptionPane.showOptionDialog(m_window, "You do not have customized taunts in your home\n " + "directory. Would you like to create a customizable file?", "Hogs Customization", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]); if (n == 0) { try { FileChannel srcChannel = new FileInputStream(HogsConstants.CUSTS_TEMPLATE).getChannel(); FileChannel dstChannel; dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); reader = new FileReader(newFile); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { reader = new FileReader(HogsConstants.CUSTS_TEMPLATE); } catch (FileNotFoundException e3) { e3.printStackTrace(); } } } try { m_netengine = NetEngine.forHost(m_user, m_hostname, 1820, m_nethandler); m_netengine.start(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (NetException e) { e.printStackTrace(); } m_gamestate = m_netengine.getCurrentState(); m_gamestate.setInChatMode(false); m_gamestate.setController(this); try { readFromFile(reader); } catch (NumberFormatException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } catch (InternalException e3) { e3.printStackTrace(); } GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice m_graphicsdevice = ge.getDefaultScreenDevice(); m_window = new GuiFrame(m_drawingpanel, m_gamestate); m_graphics = null; try { m_graphics = new GraphicsEngine(m_drawingpanel, m_gamestate); } catch (InternalException e1) { e1.printStackTrace(); System.exit(0); } m_drawingpanel.addGLEventListener(m_graphics); m_physics = new Physics(); if (team == null) { team = HogsConstants.TEAM_NONE; } if (!(team.toLowerCase().equals(HogsConstants.TEAM_NONE) || team.toLowerCase().equals(HogsConstants.TEAM_RED) || team.toLowerCase().equals(HogsConstants.TEAM_BLUE))) { throw new InternalException("Invalid team name!"); } String orig_team = team; Craft local_craft = m_gamestate.getLocalCraft(); if (m_gamestate.getNumCrafts() == 0) { local_craft.setTeamname(team); } else if (m_gamestate.isInTeamMode()) { if (team == HogsConstants.TEAM_NONE) { int red_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_RED); int blue_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_BLUE); String new_team; if (red_craft > blue_craft) { new_team = HogsConstants.TEAM_BLUE; } else if (red_craft < blue_craft) { new_team = HogsConstants.TEAM_RED; } else { new_team = Math.random() > 0.5 ? HogsConstants.TEAM_BLUE : HogsConstants.TEAM_RED; } m_gamestate.getLocalCraft().setTeamname(new_team); } else { local_craft.setTeamname(team); } } else { local_craft.setTeamname(HogsConstants.TEAM_NONE); if (orig_team != null) { m_window.displayText("You cannot join a team, this is an individual game."); } } if (!local_craft.getTeamname().equals(HogsConstants.TEAM_NONE)) { m_window.displayText("You are joining the " + local_craft.getTeamname() + " team."); } m_drawingpanel.setSize(m_drawingpanel.getWidth(), m_drawingpanel.getHeight()); m_middlepos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); m_curpos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2); GuiKeyListener k_listener = new GuiKeyListener(); GuiMouseListener m_listener = new GuiMouseListener(); m_window.addKeyListener(k_listener); m_drawingpanel.addKeyListener(k_listener); m_window.addMouseListener(m_listener); m_drawingpanel.addMouseListener(m_listener); m_window.addMouseMotionListener(m_listener); m_drawingpanel.addMouseMotionListener(m_listener); m_drawingpanel.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { m_window.setMouseTrapped(false); m_window.returnMouseToCenter(); } }); m_window.requestFocus(); }
|
11
|
Code Sample 1:
private String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
public static String encode(String plaintext) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not encrypt password for ISA db verification"); } }
|
11
|
Code Sample 1:
public void create(File target) { if ("dir".equals(type)) { File dir = new File(target, name); dir.mkdirs(); for (Resource c : children) { c.create(dir); } } else if ("package".equals(type)) { String[] dirs = name.split("\\."); File parent = target; for (String d : dirs) { parent = new File(parent, d); } parent.mkdirs(); for (Resource c : children) { c.create(parent); } } else if ("file".equals(type)) { InputStream is = getInputStream(); File file = new File(target, name); try { if (is != null) { FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(is, fos); fos.flush(); fos.close(); } else { PrintStream ps = new PrintStream(file); ps.print(content); ps.flush(); ps.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else if ("zip".equals(type)) { try { unzip(target); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { throw new RuntimeException("unknown resource type: " + type); } }
Code Sample 2:
public static boolean copy(File source, File target) { try { if (!source.exists()) return false; target.getParentFile().mkdirs(); InputStream input = new FileInputStream(source); OutputStream output = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = input.read(buf)) > 0) output.write(buf, 0, len); input.close(); output.close(); return true; } catch (Exception exc) { exc.printStackTrace(); return false; } }
|
11
|
Code Sample 1:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); 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) { ; } } }
|
00
|
Code Sample 1:
public static String gerarDigest(String mensagem) { String mensagemCriptografada = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); System.out.println("Mensagem original: " + mensagem); md.update(mensagem.getBytes()); byte[] digest = md.digest(); mensagemCriptografada = converterBytesEmHexa(digest); } catch (Exception e) { e.printStackTrace(); } return mensagemCriptografada; }
Code Sample 2:
public static final boolean zipUpdate(String zipfile, String name, String oldname, byte[] contents, boolean delete) { try { File temp = File.createTempFile("atf", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); OutputStream os = new BufferedOutputStream(new FileOutputStream(temp)); ZipInputStream zin = new ZipInputStream(in); ZipOutputStream zout = new ZipOutputStream(os); ZipEntry e; ZipEntry e2; byte buffer[] = new byte[TEMP_FILE_BUFFER_SIZE]; int bytesRead; boolean found = false; boolean rename = false; String oname = name; if (oldname != null) { name = oldname; rename = true; } while ((e = zin.getNextEntry()) != null) { if (!e.isDirectory()) { String ename = e.getName(); if (delete && ename.equals(name)) continue; e2 = new ZipEntry(rename ? oname : ename); zout.putNextEntry(e2); if (ename.equals(name)) { found = true; zout.write(contents); } else { while ((bytesRead = zin.read(buffer)) != -1) zout.write(buffer, 0, bytesRead); } zout.closeEntry(); } } if (!found && !delete) { e = new ZipEntry(name); zout.putNextEntry(e); zout.write(contents); zout.closeEntry(); } zin.close(); zout.close(); File fp = new File(zipfile); fp.delete(); MLUtil.copyFile(temp, fp); temp.delete(); return (true); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "updateZip " + zipfile + " " + name); } return (false); }
|
11
|
Code Sample 1:
private void foundNewVersion() { updater = new UpdaterView(); updater.setLabelText("Initiating Updater..."); updater.setProgress(0); updater.setLocationRelativeTo(null); updater.setVisible(true); URL pathUrl = ClassLoader.getSystemResource("img/icon.png"); String path = pathUrl.toString(); path = path.substring(4, path.length() - 14); try { file = new File(new URI(path)); updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar")); if (updaterFile.exists()) { updaterFile.delete(); } updater.setProgress(25); SwingUtilities.invokeLater(new Runnable() { public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } }); } catch (URISyntaxException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public static boolean copy(InputStream is, File file) { try { IOUtils.copy(is, new FileOutputStream(file)); return true; } catch (Exception e) { logger.severe(e.getMessage()); return false; } }
Code Sample 2:
private static void copyFile(File source, File destination) throws IOException, SecurityException { if (!destination.exists()) destination.createNewFile(); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); long count = 0; long size = sourceChannel.size(); while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ; } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); } }
|
00
|
Code Sample 1:
private IMolecule readMolecule() throws Exception { String xpath = ""; if (index.equals("ichi")) { xpath = URLEncoder.encode("//molecule[./identifier/basic='" + query + "']", UTF8); } else if (index.equals("kegg")) { xpath = URLEncoder.encode("//molecule[./@name='" + query + "' and ./@dictRef='KEGG']", UTF8); } else if (index.equals("nist")) { xpath = URLEncoder.encode("//molecule[../@id='" + query + "']", UTF8); } else { logger.error("Did not recognize index type: " + index); return null; } String colname = URLEncoder.encode("/" + this.collection, UTF8); logger.info("Doing query: " + xpath + " in collection " + colname); URL url = new URL("http://" + server + "/Bob/QueryXindice"); logger.info("Connection to server: " + url.toString()); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.print("detailed=on"); out.print("&"); out.print("xmlOnly=on"); out.print("&"); out.print("colName=" + colname); out.print("&"); out.print("xpathString=" + xpath); out.print("&"); out.println("query=Query"); out.close(); InputStream stream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(stream)); in.mark(1000000); in.readLine(); String comment = in.readLine(); logger.debug("The comment is: " + comment); Pattern p = Pattern.compile("<!-- There are (\\d{1,6}) results! -->"); Matcher match = p.matcher(comment); if (match.find()) { resultNum = match.group(1); } else { resultNum = "0"; } logger.debug("The number of result is " + resultNum); in.reset(); CMLReader reader = new CMLReader(stream); ChemFile cf = (ChemFile) reader.read((ChemObject) new ChemFile()); logger.debug("#sequences: " + cf.getChemSequenceCount()); IMolecule m = null; if (cf.getChemSequenceCount() > 0) { org.openscience.cdk.interfaces.IChemSequence chemSequence = cf.getChemSequence(0); logger.debug("#models in sequence: " + chemSequence.getChemModelCount()); if (chemSequence.getChemModelCount() > 0) { org.openscience.cdk.interfaces.IChemModel chemModel = chemSequence.getChemModel(0); org.openscience.cdk.interfaces.IMoleculeSet setOfMolecules = chemModel.getMoleculeSet(); logger.debug("#mols in model: " + setOfMolecules.getMoleculeCount()); if (setOfMolecules.getMoleculeCount() > 0) { m = setOfMolecules.getMolecule(0); } else { logger.warn("No molecules in the model"); } } else { logger.warn("No models in the sequence"); } } else { logger.warn("No sequences in the file"); } in.close(); return m; }
Code Sample 2:
public String translate(String before, int translateType) throws CoreException { if (before == null) throw new IllegalArgumentException("before is null."); if ((translateType != ENGLISH_TO_JAPANESE) && (translateType != JAPANESE_TO_ENGLISH)) { throw new IllegalArgumentException("Invalid translateType. value=" + translateType); } try { URL url = new URL(config.getTranslatorSiteUrl()); URLConnection connection = url.openConnection(); sendTranslateRequest(before, translateType, connection); String afterContents = receiveTranslatedResponse(connection); String afterStartKey = config.getTranslationResultStart(); String afterEndKey = config.getTranslationResultEnd(); int startLength = afterStartKey.length(); int startPos = afterContents.indexOf(afterStartKey); if (startPos != -1) { int endPos = afterContents.indexOf(afterEndKey, startPos); if (endPos != -1) { String after = afterContents.substring(startPos + startLength, endPos); after = replaceEntities(after); return after; } else { throwCoreException(ERROR_END_KEYWORD_NOT_FOUND, "End keyword not found.", null); } } else { throwCoreException(ERROR_START_KEYWORD_NOT_FOUND, "Start keyword not found.", null); } } catch (IOException e) { throwCoreException(ERROR_IO, e.getMessage(), e); } throw new IllegalStateException("CoreException not occurd."); }
|
11
|
Code Sample 1:
public static String md5(final String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[FOUR_BYTES]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); }
Code Sample 2:
public static String getDigest(String input) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(input.getBytes()); byte[] outDigest = md5.digest(); StringBuffer outBuf = new StringBuffer(33); for (int i = 0; i < outDigest.length; i++) { byte b = outDigest[i]; int hi = (b >> 4) & 0x0f; outBuf.append(MD5Digest.hexTab[hi]); int lo = b & 0x0f; outBuf.append(MD5Digest.hexTab[lo]); } return outBuf.toString(); }
|
11
|
Code Sample 1:
private void foundNewVersion() { updater = new UpdaterView(); updater.setLabelText("Initiating Updater..."); updater.setProgress(0); updater.setLocationRelativeTo(null); updater.setVisible(true); URL pathUrl = ClassLoader.getSystemResource("img/icon.png"); String path = pathUrl.toString(); path = path.substring(4, path.length() - 14); try { file = new File(new URI(path)); updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar")); if (updaterFile.exists()) { updaterFile.delete(); } updater.setProgress(25); SwingUtilities.invokeLater(new Runnable() { public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } }); } catch (URISyntaxException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE); } }
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:
public long copyFileWithPaths(String userBaseDir, String sourcePath, String destinPath) throws Exception { if (userBaseDir.endsWith(sep)) { userBaseDir = userBaseDir.substring(0, userBaseDir.length() - sep.length()); } String file1FullPath = new String(); if (sourcePath.startsWith(sep)) { file1FullPath = new String(userBaseDir + sourcePath); } else { file1FullPath = new String(userBaseDir + sep + sourcePath); } String file2FullPath = new String(); if (destinPath.startsWith(sep)) { file2FullPath = new String(userBaseDir + destinPath); } else { file2FullPath = new String(userBaseDir + sep + destinPath); } long plussQuotaSize = 0; BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File fileordir = new File(file1FullPath); if (fileordir.exists()) { if (fileordir.isFile()) { File file2 = new File(file2FullPath); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (fileordir.isDirectory()) { String[] entryList = fileordir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String file1FullPathEntry = new String(file1FullPath.concat(entryList[pos])); String file2FullPathEntry = new String(file2FullPath.concat(entryList[pos])); File file2 = new File(file2FullPathEntry); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPathEntry), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPathEntry), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Source file or dir not exist ! file1FullPath = (" + file1FullPath + ")"); } return plussQuotaSize; }
Code Sample 2:
private void copyEntries() { if (zipFile != null) { Enumeration<? extends ZipEntry> enumerator = zipFile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); if (!entry.isDirectory() && !toIgnore.contains(normalizePath(entry.getName()))) { ZipEntry originalEntry = new ZipEntry(entry.getName()); try { zipOutput.putNextEntry(originalEntry); IOUtils.copy(getInputStream(entry.getName()), zipOutput); zipOutput.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } } }
|
11
|
Code Sample 1:
public long copyFile(String baseDirStr, String fileName, String file2FullPath) throws Exception { long plussQuotaSize = 0; if (!baseDirStr.endsWith(sep)) { baseDirStr += sep; } BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; String file1FullPath = new String(baseDirStr + fileName); if (!file1FullPath.equalsIgnoreCase(file2FullPath)) { File file1 = new File(file1FullPath); if (file1.exists() && (file1.isFile())) { File file2 = new File(file2FullPath); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } else { throw new Exception("Source file not exist ! file1FullPath = (" + file1FullPath + ")"); } } return plussQuotaSize; }
Code Sample 2:
@Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { in = LOADER.getResourceAsStream(RES_PKG + filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
|
00
|
Code Sample 1:
public static File doRequestPost(URL url, String req, String fName, boolean override) throws ArcImsException { File f = null; URL virtualUrl = getVirtualRequestUrlFromUrlAndRequest(url, req); if ((f = getPreviousDownloadedURL(virtualUrl, override)) == null) { File tempDirectory = new File(tempDirectoryPath); if (!tempDirectory.exists()) { tempDirectory.mkdir(); } String nfName = normalizeFileName(fName); f = new File(tempDirectoryPath + "/" + nfName); f.deleteOnExit(); logger.info("downloading '" + url.toString() + "' to: " + f.getAbsolutePath()); try { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-length", "" + req.length()); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(req); wr.flush(); DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(f))); byte[] buffer = new byte[1024 * 256]; InputStream is = conn.getInputStream(); long readed = 0; for (int i = is.read(buffer); i > 0; i = is.read(buffer)) { dos.write(buffer, 0, i); readed += i; } dos.close(); is.close(); wr.close(); addDownloadedURL(virtualUrl, f.getAbsolutePath()); } catch (ConnectException ce) { logger.error("Timed out error", ce); throw new ArcImsException("arcims_server_timeout"); } catch (FileNotFoundException fe) { logger.error("FileNotFound Error", fe); throw new ArcImsException("arcims_server_error"); } catch (IOException e) { logger.error("IO Error", e); throw new ArcImsException("arcims_server_error"); } } if (!f.exists()) { downloadedFiles.remove(virtualUrl); f = doRequestPost(url, req, fName, override); } return f; }
Code Sample 2:
public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
|
11
|
Code Sample 1:
private static void copyFile(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); FileChannel inc = in.getChannel(); FileChannel outc = out.getChannel(); inc.transferTo(0, inc.size(), outc); inc.close(); outc.close(); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } }
|
11
|
Code Sample 1:
public void copyFile(File s, File t) { try { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
@Override public int onPut(Operation operation) { synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections++; if (logger.isDebugEnabled()) { logger.debug("Connection accepted, total number of connections: " + MuleObexRequestHandler.connections); } } int result = ResponseCodes.OBEX_HTTP_OK; try { headers = operation.getReceivedHeaders(); if (!this.maxFileSize.equals(ObexServer.UNLIMMITED_FILE_SIZE)) { Long fileSize = (Long) headers.getHeader(HeaderSet.LENGTH); if (fileSize == null) { result = ResponseCodes.OBEX_HTTP_LENGTH_REQUIRED; } if (fileSize > this.maxFileSize) { result = ResponseCodes.OBEX_HTTP_REQ_TOO_LARGE; } } if (result != ResponseCodes.OBEX_HTTP_OK) { InputStream in = operation.openInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); data = out.toByteArray(); if (interrupted) { data = null; result = ResponseCodes.OBEX_HTTP_GONE; } } return result; } catch (IOException e) { return ResponseCodes.OBEX_HTTP_UNAVAILABLE; } finally { synchronized (this) { this.notify(); } synchronized (MuleObexRequestHandler.connections) { MuleObexRequestHandler.connections--; if (logger.isDebugEnabled()) { logger.debug("Connection closed, total number of connections: " + MuleObexRequestHandler.connections); } } } }
|
00
|
Code Sample 1:
public void render(final HttpServletRequest request, final HttpServletResponse response, final byte[] bytes, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } response.setContentLength(bytes.length); IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream()); }
Code Sample 2:
public int print(String type, String url, String attrs) throws PrinterException { try { return print(type, (new URL(url)).openStream(), attrs); } catch (Exception e) { e.printStackTrace(); throw new PrinterException(e); } }
|
11
|
Code Sample 1:
public static String getDocumentAsString(URL url) throws IOException { StringBuffer result = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8")); String line = ""; while (line != null) { result.append(line); line = in.readLine(); } return result.toString(); }
Code Sample 2:
public static String createRecoveryContent(String password) { try { password = encryptGeneral1(password); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recovery_file"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String textContent = root.getTextContent(); return textContent; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
|
11
|
Code Sample 1:
private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException { if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]"); response.setContentLength(mediaBean.getContentLength()); response.setContentType(mediaBean.getContentType()); response.addHeader("Last-Modified", mediaBean.getLastMod()); response.addHeader("Cache-Control", "must-revalidate"); response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName()); byte[] content = mediaBean.getContent(); InputStream is = null; OutputStream os = null; try { os = response.getOutputStream(); is = new ByteArrayInputStream(content); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e, e); } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.close(); } catch (IOException e) { } } }
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(); } } }
|
11
|
Code Sample 1:
private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException { final boolean stripHtmlEnabled = true; final boolean injectSecretTokensEnabled = true; final boolean encryptQueryStringsEnabled = true; final boolean protectParamsAndFormsEnabled = true; final boolean applyExtraProtectionForDisabledFormFields = true; final boolean applyExtraProtectionForReadonlyFormFields = false; final boolean applyExtraProtectionForRequestParamValueCount = false; final ContentInjectionHelper helper = new ContentInjectionHelper(); final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader(); ruleFileLoaderModificationExcludes.setPath(RuleParameter.MODIFICATION_EXCLUDES_DEFAULT.getValue()); final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes); containerModExcludes.parseDefinitions(); helper.setContentModificationExcludeDefinitions(containerModExcludes); final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true, new AttackMailHandler()); final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", ""); final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true); final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader(); ruleFileLoaderResponseModifications.setPath(RuleParameter.RESPONSE_MODIFICATIONS_DEFAULT.getValue()); final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications); container.parseDefinitions(); final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions()); final List<Pattern> tmpPatternsToExcludeCompleteTag = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeCompleteScript = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeLinksWithinScripts = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToExcludeLinksWithinTags = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToCaptureLinksWithinScripts = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<Pattern> tmpPatternsToCaptureLinksWithinTags = new ArrayList<Pattern>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeCompleteTag = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeCompleteScript = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToExcludeLinksWithinTags = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<WordDictionary> tmpPrefiltersToCaptureLinksWithinTags = new ArrayList<WordDictionary>(responseModificationDefinitions.length); final List<Integer[]> tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList<Integer[]>(responseModificationDefinitions.length); final List<Integer[]> tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList<Integer[]>(responseModificationDefinitions.length); for (int i = 0; i < responseModificationDefinitions.length; i++) { final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i]; if (responseModificationDefinition.isMatchesScripts()) { tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern()); tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter()); tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } if (responseModificationDefinition.isMatchesTags()) { tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern()); tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter()); tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern()); tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter()); tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern()); tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter()); tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers())); } } final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag); final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript); final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts); final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags); final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts); final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags); final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]); final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]); final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts); final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags); final Cipher cipher = CryptoUtils.getCipher(); final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false); Cipher.getInstance("AES"); MessageDigest.getInstance("SHA-1"); final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false); final List durations = new ArrayList(); for (int i = 0; i < executionCount; i++) { final long start = System.currentTimeMillis(); Reader reader = null; Writer writer = null; try { reader = new BufferedReader(new FileReader(this.htmlFile)); writer = new FileWriter(this.outputFile); if (applyFilter) { writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false); writer = new BufferedWriter(writer); } char[] chars = new char[16 * 1024]; int read; while ((read = reader.read(chars)) != -1) { if (read > 0) { writer.write(chars, 0, read); } } durations.add(new Long(System.currentTimeMillis() - start)); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } if (writer != null) { try { writer.close(); } catch (IOException ignored) { } } } } long sum = 0; for (final Iterator iter = durations.iterator(); iter.hasNext(); ) { Long value = (Long) iter.next(); sum += value.longValue(); } return sum / durations.size(); }
Code Sample 2:
public void writeToFile(File out) throws IOException, DocumentException { FileChannel inChannel = new FileInputStream(pdf_file).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
public static void createModelZip(String filename, String tempdir) throws EDITSException { try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); } catch (Exception e) { throw new EDITSException("Can not create a model in file " + filename + " from folder " + tempdir); } }
Code Sample 2:
public HashMap parseFile(File newfile) throws IOException { String s; String[] tokens; int nvalues = 0; double num1, num2, num3; boolean baddata = false; URL url = newfile.toURL(); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); HashMap data = new HashMap(); while ((s = br.readLine()) != null) { tokens = s.split("\\s+"); nvalues = tokens.length; if (nvalues == 2) { data.put(new String(tokens[0]), new Double(Double.parseDouble(tokens[1]))); } else { System.out.println("Sorry, trouble reading reference file."); } } return data; }
|
00
|
Code Sample 1:
public static void main(String[] args) { try { FTPClient p = new FTPClient(); p.connect("url"); p.login("login", "pass"); int sendCommand = p.sendCommand("SYST"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PWD"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("NOOP"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PASV"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); p.changeWorkingDirectory("/"); try { printDir(p, "/"); } catch (Exception e) { e.printStackTrace(); } p.logout(); p.disconnect(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public void deleteProposal(String id) throws Exception { String tmp = ""; PreparedStatement prepStmt = null; try { if (id == null || id.length() == 0) throw new Exception("Invalid parameter"); con = database.getConnection(); String delProposal = "delete from proposal where PROPOSAL_ID='" + id + "'"; prepStmt = con.prepareStatement(delProposal); prepStmt.executeUpdate(); con.commit(); prepStmt.close(); con.close(); } catch (Exception e) { if (!con.isClosed()) { con.rollback(); prepStmt.close(); con.close(); } throw e; } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
@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); } } }
|
00
|
Code Sample 1:
public void readHTMLFromURL(URL url) throws IOException { InputStream in = url.openStream(); try { readHTMLFromStream(new InputStreamReader(in)); } finally { try { in.close(); } catch (IOException ex) { Logger.getLogger(HTMLTextAreaModel.class.getName()).log(Level.SEVERE, "Exception while closing InputStream", 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 static void copyFromOffset(long offset, File exe, File cab) throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(exe)); FileOutputStream out = new FileOutputStream(cab); byte[] buffer = new byte[4096]; int bytes_read; in.skipBytes((int) offset); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); in = null; out = null; }
Code Sample 2:
public static byte[] sendParamPost(String urlString, String param) { try { URL url = new URL(urlString + "?" + param); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setDefaultUseCaches(false); urlConn.setDoInput(true); urlConn.setRequestMethod("POST"); urlConn.connect(); OutputStream ops = urlConn.getOutputStream(); ops.close(); InputStream is = urlConn.getInputStream(); byte[] resultBytes = new byte[urlConn.getContentLength()]; byte[] tempByte = new byte[1024]; int length = 0; int index = 0; while ((length = is.read(tempByte)) != -1) { System.arraycopy(tempByte, 0, resultBytes, index, length); index += length; } is.close(); return resultBytes; } catch (Exception e) { e.printStackTrace(); return null; } }
|
00
|
Code Sample 1:
static Object loadPersistentRepresentationFromFile(URL url) throws PersistenceException { PersistenceManager.persistenceURL.get().addFirst(url); ObjectInputStream ois = null; HierarchicalStreamReader reader = null; XStream xstream = null; try { Reader inputReader = new java.io.InputStreamReader(url.openStream()); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader xsr = inputFactory.createXMLStreamReader(url.toExternalForm(), inputReader); reader = new StaxReader(new QNameMap(), xsr); } catch (XMLStreamException xse) { throw new PersistenceException("Error creating reader", xse); } xstream = new XStream(new StaxDriver()); xstream.setClassLoader(Gate.getClassLoader()); ois = xstream.createObjectInputStream(reader); Object res = null; Iterator urlIter = ((Collection) PersistenceManager.getTransientRepresentation(ois.readObject())).iterator(); while (urlIter.hasNext()) { URL anUrl = (URL) urlIter.next(); try { Gate.getCreoleRegister().registerDirectories(anUrl); } catch (GateException ge) { Err.prln("Could not reload creole directory " + anUrl.toExternalForm()); } } res = ois.readObject(); ois.close(); return res; } catch (PersistenceException pe) { throw pe; } catch (Exception e) { throw new PersistenceException("Error loading GAPP file", e); } finally { PersistenceManager.persistenceURL.get().removeFirst(); if (PersistenceManager.persistenceURL.get().isEmpty()) { PersistenceManager.persistenceURL.remove(); } } }
Code Sample 2:
public static String rename_file(String sessionid, String key, String newFileName) { String jsonstring = ""; try { Log.d("current running function name:", "rename_file"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "rename_file")); nameValuePairs.add(new BasicNameValuePair("new_name", newFileName)); nameValuePairs.add(new BasicNameValuePair("key", key)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); jsonstring = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", jsonstring); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
|
11
|
Code Sample 1:
public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); }
Code Sample 2:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.