label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: protected BufferedReader getBufferedReader(InputSource input) throws IOException, SAXException { BufferedReader br = null; if (input.getCharacterStream() != null) { br = new BufferedReader(input.getCharacterStream()); } else if (input.getByteStream() != null) { br = new BufferedReader(new InputStreamReader(input.getByteStream())); } else if (input.getSystemId() != null) { URL url = new URL(input.getSystemId()); br = new BufferedReader(new InputStreamReader(url.openStream())); } else { throw new SAXException("Invalid InputSource!"); } return br; } Code Sample 2: private void criarQuestaoMultiplaEscolha(QuestaoMultiplaEscolha q) throws SQLException { PreparedStatement stmt = null; String sql = "INSERT INTO multipla_escolha (id_questao, texto, gabarito) VALUES (?,?,?)"; try { for (Alternativa alternativa : q.getAlternativa()) { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.setString(2, alternativa.getTexto()); stmt.setBoolean(3, alternativa.getGabarito()); stmt.executeUpdate(); conexao.commit(); } } catch (SQLException e) { conexao.rollback(); throw e; } }
00
Code Sample 1: public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); byte[] hash = (new Base64()).encode(raw); return new String(hash); } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } } Code Sample 2: private static HttpURLConnection getConnection(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Accept", "application/zip;text/html"); return conn; }
00
Code Sample 1: public ResponseStatus submit(Collection<SubmissionData> data) throws IOException { if (sessionId == null) throw new IllegalStateException("Perform successful handshake first."); if (data.size() > 50) throw new IllegalArgumentException("Max 50 submissions at once"); StringBuilder builder = new StringBuilder(data.size() * 100); int index = 0; for (SubmissionData submissionData : data) { builder.append(submissionData.toString(sessionId, index)); builder.append('\n'); index++; } String body = builder.toString(); if (Caller.getInstance().isDebugMode()) System.out.println("submit: " + body); HttpURLConnection urlConnection = Caller.getInstance().openConnection(submissionUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(body); writer.close(); InputStream is = urlConnection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); r.close(); int statusCode = ResponseStatus.codeForStatus(status); if (statusCode == ResponseStatus.FAILED) { return new ResponseStatus(statusCode, status.substring(status.indexOf(' ') + 1)); } return new ResponseStatus(statusCode); } Code Sample 2: @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + httpServletRequest.getQueryString()); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + baos.toString()); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); }
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: @Override public final byte[] getDigest() { try { final MessageDigest hashing = MessageDigest.getInstance("SHA-256"); final Charset utf16 = Charset.forName("UTF-16"); for (final CollationKey wordKey : this.words) { hashing.update(wordKey.toByteArray()); } hashing.update(this.locale.toString().getBytes(utf16)); hashing.update(ByteUtils.toBytesLE(this.collator.getStrength())); hashing.update(ByteUtils.toBytesLE(this.collator.getDecomposition())); return hashing.digest(); } catch (final NoSuchAlgorithmException e) { FileBasedDictionary.LOG.severe(e.toString()); return new byte[0]; } }
11
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public static void unzipModel(String filename, String tempdir) throws Exception { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(filename); int BUFFER = 2048; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { int count; byte data[] = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(tempdir + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); throw new Exception("Can not expand model in \"" + tempdir + "\" because:\n" + e.getMessage()); } }
11
Code Sample 1: public static String md5Encode16(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes("utf-8")); byte b[] = md.digest(); int i; StringBuilder buf = new StringBuilder(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } return buf.toString().substring(8, 24); } catch (Exception e) { throw new RuntimeException(e); } } Code Sample 2: private static byte[] calcMd5(String pass) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pass.getBytes(), 0, pass.length()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm found"); throw new RuntimeException(e); } }
11
Code Sample 1: public static void copyResourceToFile(Class owningClass, String resourceName, File destinationDir) { final byte[] resourceBytes = readResource(owningClass, resourceName); final ByteArrayInputStream inputStream = new ByteArrayInputStream(resourceBytes); final File destinationFile = new File(destinationDir, resourceName); final FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(destinationFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new RuntimeException(e); } } Code Sample 2: private void copyValidFile(File file, int cviceni) { try { String filename = String.format("%s%s%02d%s%s", validovane, File.separator, cviceni, File.separator, file.getName()); boolean copy = false; File newFile = new File(filename); if (newFile.exists()) { if (file.lastModified() > newFile.lastModified()) copy = true; else copy = false; } else { newFile.createNewFile(); copy = true; } if (copy) { String EOL = "" + (char) 0x0D + (char) 0x0A; FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); FileWriter fw = new FileWriter(newFile); String line; while ((line = br.readLine()) != null) fw.write(line + EOL); br.close(); fw.close(); newFile.setLastModified(file.lastModified()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copy(File source, File dest) throws Exception { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: @Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("sort :: WORKDIR not given."); return 3; } if (args.size() == 1) { System.err.println("sort :: INPATH not given."); return 3; } final String wrkDir = args.get(0), out = (String) parser.getOptionValue(outputFileOpt); final List<String> strInputs = args.subList(1, args.size()); final List<Path> inputs = new ArrayList<Path>(strInputs.size()); for (final String in : strInputs) inputs.add(new Path(in)); final boolean verbose = parser.getBoolean(verboseOpt); final String intermediateOutName = out == null ? inputs.get(0).getName() : out; final Configuration conf = getConf(); conf.setStrings(INPUT_PATHS_PROP, strInputs.toArray(new String[0])); conf.set(SortOutputFormat.OUTPUT_NAME_PROP, intermediateOutName); final Path wrkDirPath = new Path(wrkDir); final Timer t = new Timer(); try { for (final Path in : inputs) Utils.configureSampling(in, conf); @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); final Job job = new Job(conf); job.setJarByClass(Sort.class); job.setMapperClass(Mapper.class); job.setReducerClass(SortReducer.class); job.setMapOutputKeyClass(LongWritable.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(SAMRecordWritable.class); job.setInputFormatClass(BAMInputFormat.class); job.setOutputFormatClass(SortOutputFormat.class); for (final Path in : inputs) FileInputFormat.addInputPath(job, in); FileOutputFormat.setOutputPath(job, wrkDirPath); job.setPartitionerClass(TotalOrderPartitioner.class); System.out.println("sort :: Sampling..."); t.start(); InputSampler.<LongWritable, SAMRecordWritable>writePartitionFile(job, new InputSampler.IntervalSampler<LongWritable, SAMRecordWritable>(0.01, 100)); System.out.printf("sort :: Sampling complete in %d.%03d s.\n", t.stopS(), t.fms()); job.submit(); System.out.println("sort :: Waiting for job completion..."); t.start(); if (!job.waitForCompletion(verbose)) { System.err.println("sort :: Job failed."); return 4; } System.out.printf("sort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Hadoop error: %s\n", e); return 4; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } if (out != null) try { System.out.println("sort :: Merging output..."); t.start(); final Path outPath = new Path(out); final FileSystem srcFS = wrkDirPath.getFileSystem(conf); FileSystem dstFS = outPath.getFileSystem(conf); if (dstFS instanceof LocalFileSystem && dstFS instanceof ChecksumFileSystem) dstFS = ((LocalFileSystem) dstFS).getRaw(); final BAMFileWriter w = new BAMFileWriter(dstFS.create(outPath), new File("")); w.setSortOrder(SAMFileHeader.SortOrder.coordinate, true); w.setHeader(getHeaderMerger(conf).getMergedHeader()); w.close(); final OutputStream outs = dstFS.append(outPath); final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, conf.get(SortOutputFormat.OUTPUT_NAME_PROP) + "-[0-9][0-9][0-9][0-9][0-9][0-9]*")); { int i = 0; final Timer t2 = new Timer(); for (final FileStatus part : parts) { t2.start(); final InputStream ins = srcFS.open(part.getPath()); IOUtils.copyBytes(ins, outs, conf, false); ins.close(); System.out.printf("sort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms()); } } for (final FileStatus part : parts) srcFS.delete(part.getPath(), false); outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK); outs.close(); System.out.printf("sort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms()); } catch (IOException e) { System.err.printf("sort :: Output merging failed: %s\n", e); return 5; } return 0; }
00
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 OAuthResponseMessage access(OAuthMessage request, net.oauth.ParameterStyle style) throws IOException { HttpMessage httpRequest = HttpMessage.newRequest(request, style); HttpResponseMessage httpResponse = http.execute(httpRequest, httpParameters); httpResponse = HttpMessageDecoder.decode(httpResponse); return new OAuthResponseMessage(httpResponse); }
11
Code Sample 1: public void compressFile(String filePath) { String outPut = filePath + ".zip"; try { FileInputStream in = new FileInputStream(filePath); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outPut)); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); out.close(); } catch (Exception c) { c.printStackTrace(); } } Code Sample 2: public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
00
Code Sample 1: private File prepareFileForUpload(File source, String s3key) throws IOException { File tmp = File.createTempFile("dirsync", ".tmp"); tmp.deleteOnExit(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = new DeflaterOutputStream(new CryptOutputStream(new FileOutputStream(tmp), cipher, getDataEncryptionKey())); IOUtils.copy(in, out); in.close(); out.close(); return tmp; } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } Code Sample 2: private void loadProperties() { if (properties == null) { properties = new Properties(); try { URL url = getClass().getResource(propsFile); properties.load(url.openStream()); } catch (IOException ioe) { ioe.printStackTrace(); } } }
11
Code Sample 1: private void add(Hashtable applicantInfo) throws Exception { String mode = "".equals(getParam("applicant_id_gen").trim()) ? "update" : "insert"; String applicant_id = getParam("applicant_id"); String password = getParam("password"); if ("".equals(applicant_id)) applicant_id = getParam("applicant_id_gen"); if ("".equals(getParam("applicant_name"))) throw new Exception("Can not have empty fields!"); applicantInfo.put("id", applicant_id); applicantInfo.put("password", password); applicantInfo.put("name", getParam("applicant_name")); applicantInfo.put("address1", getParam("address1")); applicantInfo.put("address2", getParam("address2")); applicantInfo.put("address3", getParam("address3")); applicantInfo.put("city", getParam("city")); applicantInfo.put("state", getParam("state")); applicantInfo.put("poscode", getParam("poscode")); applicantInfo.put("country_code", getParam("country_list")); applicantInfo.put("email", getParam("email")); applicantInfo.put("phone", getParam("phone")); String birth_year = getParam("birth_year"); String birth_month = getParam("birth_month"); String birth_day = getParam("birth_day"); applicantInfo.put("birth_year", birth_year); applicantInfo.put("birth_month", birth_month); applicantInfo.put("birth_day", birth_day); applicantInfo.put("gender", getParam("gender")); String birth_date = birth_year + "-" + fmt(birth_month) + "-" + fmt(birth_day); applicantInfo.put("birth_date", birth_date); Db db = null; String sql = ""; Connection conn = null; try { db = new Db(); conn = db.getConnection(); conn.setAutoCommit(false); Statement stmt = db.getStatement(); SQLRenderer r = new SQLRenderer(); boolean found = false; { r.add("applicant_id"); r.add("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLSelect("adm_applicant"); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) found = true; else found = false; } if (found && !"update".equals(mode)) throw new Exception("Applicant Id was invalid!"); { r.clear(); r.add("password", (String) applicantInfo.get("password")); r.add("applicant_name", (String) applicantInfo.get("name")); r.add("address1", (String) applicantInfo.get("address1")); r.add("address2", (String) applicantInfo.get("address2")); r.add("address3", (String) applicantInfo.get("address3")); r.add("city", (String) applicantInfo.get("city")); r.add("state", (String) applicantInfo.get("state")); r.add("poscode", (String) applicantInfo.get("poscode")); r.add("country_code", (String) applicantInfo.get("country_code")); r.add("phone", (String) applicantInfo.get("phone")); r.add("birth_date", (String) applicantInfo.get("birth_date")); r.add("gender", (String) applicantInfo.get("gender")); } if (!found) { r.add("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLInsert("adm_applicant"); stmt.executeUpdate(sql); } else { r.update("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLUpdate("adm_applicant"); stmt.executeUpdate(sql); } conn.commit(); } catch (DbException dbex) { throw dbex; } catch (SQLException sqlex) { try { conn.rollback(); } catch (SQLException rollex) { } throw sqlex; } finally { if (db != null) db.close(); } } Code Sample 2: public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("WITH_BOUI") + " [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (SCHEMA,OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
00
Code Sample 1: public int deleteFile(Integer[] fileID) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; Connection conn = null; int nbrow = 0; try { DataSource ds = getDataSource(DEFAULT_DATASOURCE); conn = ds.getConnection(); conn.setAutoCommit(false); if (log.isDebugEnabled()) { log.debug("FileDAOImpl.deleteFile() " + DELETE_FILES_LOGIC); } for (int i = 0; i < fileID.length; i++) { pstmt = conn.prepareStatement(DELETE_FILES_LOGIC); pstmt.setInt(1, fileID[i].intValue()); nbrow = pstmt.executeUpdate(); } } catch (SQLException e) { conn.rollback(); log.error("FileDAOImpl.deleteFile() : erreur technique", e); throw e; } finally { conn.commit(); closeRessources(conn, pstmt, rs); } return nbrow; } Code Sample 2: public static String calculateHash(String data, String algorithm) { if (data == null) { return null; } algorithm = (algorithm == null ? INTERNAL : algorithm.toUpperCase()); if (algorithm.equals(PLAIN)) { return data; } if (algorithm.startsWith("{RSA}")) { return encode(data, algorithm.substring(5), "RSA"); } try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(data.getBytes("UTF-8")); return getHashString(md.digest()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { logger.error(nsae.getMessage()); return null; } }
00
Code Sample 1: public void testTransactions0010() throws Exception { Statement stmt = con.createStatement(); stmt.executeUpdate("create table #t0010 " + " (i integer not null, " + " s char(10) not null) "); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement("insert into #t0010 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.rollback(); ResultSet rs = stmt.executeQuery("select s, i from #t0010"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertEquals(rs.getString(1).trim().length(), rs.getInt(2)); } assertEquals(count, 0); rowsToAdd = 6; for (int j = 1; j <= 2; j++) { count = 0; for (int i = 1; i <= rowsToAdd; i++) { pstmt.setInt(1, i + ((j - 1) * rowsToAdd)); pstmt.setString(2, theString.substring(0, i)); count += pstmt.executeUpdate(); } assertEquals(count, rowsToAdd); con.commit(); } rs = stmt.executeQuery("select s, i from #t0010"); count = 0; while (rs.next()) { count++; int i = rs.getInt(2); if (i > rowsToAdd) { i -= rowsToAdd; } assertEquals(rs.getString(1).trim().length(), i); } assertEquals(count, (2 * rowsToAdd)); stmt.close(); pstmt.close(); con.setAutoCommit(true); } Code Sample 2: private boolean Try(URL url, Metafile mf) throws Throwable { InputStream is = null; HttpURLConnection con = null; boolean success = false; try { con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.connect(); is = con.getInputStream(); Response r = new Response(is); responses.add(r); peers.addAll(r.peers); Main.log.info("got " + r.peers.size() + " peers from " + url); success = true; } finally { if (is != null) is.close(); if (con != null) con.disconnect(); } return success; }
11
Code Sample 1: public static byte[] readFile(String filePath) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); FileInputStream is = new FileInputStream(filePath); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } } 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(); } } } } }
00
Code Sample 1: protected synchronized Class findClass(String className) { LOG.info("FIND class:" + className); String urlName = className.replace('.', '/'); byte buf[]; Class currentClass; SecurityManager sm = System.getSecurityManager(); if (sm != null) { int i = className.lastIndexOf('.'); if (i >= 0) sm.checkPackageDefinition(className.substring(0, i)); } buf = cache.get(urlName); if (buf != null) { LOG.info("Get class from cache:" + className); currentClass = defineClass(className, buf, 0, buf.length, (CodeSource) null); return currentClass; } try { URL url = new URL(urlBase, urlName + ".class"); LOG.info("Loading " + url); InputStream is = url.openConnection().getInputStream(); buf = getClassBytes(is); currentClass = defineClass(className, buf, 0, buf.length, (CodeSource) null); return currentClass; } catch (MalformedURLException mE) { LOG.warn("Bad url detected", mE); return null; } catch (IOException e) { buf = downloadClass(className); if (buf != null) { return defineClass(className, buf, 0, buf.length); } else { LOG.warn("no class found: " + className); return null; } } } Code Sample 2: public static String sha256(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] data = new byte[64]; md.update(str.getBytes("iso-8859-1"), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.sha256} " + e.getMessage()); } return buf.toString(); }
00
Code Sample 1: public static void logout4www() throws NetworkException { HttpClient client = HttpUtil.newInstance(); HttpGet get = new HttpGet(HttpUtil.KAIXIN_WWW_LOGOUT_URL); HttpUtil.setHeader(get); try { HttpResponse response = client.execute(get); if (response != null && response.getEntity() != null) { HTTPUtil.consume(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); throw new NetworkException(e); } } Code Sample 2: @Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } }
00
Code Sample 1: private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; ClassdiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((ClassdiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } } Code Sample 2: private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment) throws IOException, MessagingException { writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\""); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName + "\";" + "\n size=" + Long.toString(attachment.mSize)); writeHeader(writer, "Content-ID", attachment.mContentId); writer.append("\r\n"); InputStream inStream = null; try { Uri fileUri = Uri.parse(attachment.mContentUri); inStream = context.getContentResolver().openInputStream(fileUri); writer.flush(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(inStream, base64Out); base64Out.close(); } catch (FileNotFoundException fnfe) { } catch (IOException ioe) { throw new MessagingException("Invalid attachment.", ioe); } }
00
Code Sample 1: private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { try { int id = 0; String sql = "SELECT MAX(ID) as MAX_ID from CORE_USER_GROUPS"; PreparedStatement pStmt = Database.getMyConnection().prepareStatement(sql); ResultSet rs = pStmt.executeQuery(); if (rs.next()) { id = rs.getInt("MAX_ID") + 1; } else { id = 1; } Database.close(pStmt); sql = "INSERT INTO CORE_USER_GROUPS" + " (ID, GRP_NAME, GRP_DESC, DATE_INITIAL, DATE_FINAL, IND_STATUS)" + " VALUES (?, ?, ?, ?, ?, ?)"; pStmt = Database.getMyConnection().prepareStatement(sql); pStmt.setInt(1, id); pStmt.setString(2, txtGrpName.getText()); pStmt.setString(3, txtGrpDesc.getText()); pStmt.setDate(4, Utils.getTodaySql()); pStmt.setDate(5, Date.valueOf("9999-12-31")); pStmt.setString(6, "A"); pStmt.executeUpdate(); Database.getMyConnection().commit(); Database.close(pStmt); MessageBox.ok("New group added successfully", this); rs = getGroups(); tblGroups.setModel(new GroupsTableModel(rs)); Database.close(rs); } catch (SQLException e) { log.error("Failed with update operation \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } catch (IllegalArgumentException e) { log.error("Illegal argument for the DATE_FINAL \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } finally { txtGrpName.setEnabled(false); txtGrpDesc.setEnabled(false); btnOk.setEnabled(false); btnCancel.requestFocus(); } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
00
Code Sample 1: public static byte[] getHashedPassword(String password, byte[] randomBytes) { byte[] hashedPassword = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(randomBytes); messageDigest.update(password.getBytes("UTF-8")); hashedPassword = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hashedPassword; } Code Sample 2: @Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: private void copyResource(String resource, File targetDir) { InputStream is = FragmentFileSetTest.class.getResourceAsStream(resource); Assume.assumeNotNull(is); int i = resource.lastIndexOf("/"); String filename; if (i == -1) { filename = resource; } else { filename = resource.substring(i + 1); } try { FileOutputStream fos = new FileOutputStream(new File(targetDir, filename)); IOUtils.copy(is, fos); fos.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } Code Sample 2: public void doCompress(File[] files, File out, List<String> excludedKeys) { Map<String, File> map = new HashMap<String, File>(); String parent = FilenameUtils.getBaseName(out.getName()); for (File f : files) { CompressionUtil.list(f, parent, map, excludedKeys); } if (!map.isEmpty()) { FileOutputStream fos = null; ArchiveOutputStream aos = null; InputStream is = null; try { fos = new FileOutputStream(out); aos = getArchiveOutputStream(fos); for (Map.Entry<String, File> entry : map.entrySet()) { File file = entry.getValue(); ArchiveEntry ae = getArchiveEntry(file, entry.getKey()); aos.putArchiveEntry(ae); if (file.isFile()) { IOUtils.copy(is = new FileInputStream(file), aos); IOUtils.closeQuietly(is); is = null; } aos.closeArchiveEntry(); } aos.finish(); } catch (IOException ex) { ex.printStackTrace(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(aos); IOUtils.closeQuietly(fos); } } }
11
Code Sample 1: private void createSoundbank(String testSoundbankFileName) throws Exception { System.out.println("Create soundbank"); File packageDir = new File("testsoundbank"); if (packageDir.exists()) { for (File file : packageDir.listFiles()) assertTrue(file.delete()); assertTrue(packageDir.delete()); } packageDir.mkdir(); String sourceFileName = "testsoundbank/TestSoundBank.java"; File sourceFile = new File(sourceFileName); FileWriter writer = new FileWriter(sourceFile); writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + " @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + " return 0;\n" + " }\n" + " @Override public String getVersion() {\n" + " return \"" + (soundbankRevision++) + "\";\n" + " }\n" + "}\n"); writer.close(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File("."))); compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call(); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName)); ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank"); zos.putNextEntry(ze); zos.write("testsoundbank.TestSoundBank".getBytes()); ze = new ZipEntry("testsoundbank/TestSoundBank.class"); zos.putNextEntry(ze); FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class"); int b = fis.read(); while (b != -1) { zos.write(b); b = fis.read(); } zos.close(); } Code Sample 2: 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(); } } } } }
00
Code Sample 1: public static String hashString(String sPassword) { if (sPassword == null || sPassword.equals("")) { return "empty:"; } else { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sPassword.getBytes("UTF-8")); byte[] res = md.digest(); return "sha1:" + StringUtils.byte2hex(res); } catch (NoSuchAlgorithmException e) { return "plain:" + sPassword; } catch (UnsupportedEncodingException e) { return "plain:" + sPassword; } } } Code Sample 2: public static void main(String[] args) throws Exception { String localSrc = args[0]; String dst = args[1]; InputStream in = new BufferedInputStream(new FileInputStream(localSrc)); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(dst), conf); OutputStream out = fs.create(new Path(dst), new Progressable() { public void progress() { System.out.print("."); } }); IOUtils.copyBytes(in, out, 4096, true); }
00
Code Sample 1: public void put(String path, File fileToPut) throws IOException { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(this.endpointURL, this.endpointPort); log.debug("Ftp put reply: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp put server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); InputStream input = new FileInputStream(fileToPut); if (ftp.storeFile(path, input) != true) { ftp.logout(); input.close(); throw new IOException("FTP put exception"); } input.close(); ftp.logout(); } catch (Exception e) { log.error("Ftp client exception: " + e.getMessage(), e); throw new IOException(e.getMessage()); } } Code Sample 2: private void constructDialogContent(Composite parent) { SashForm splitter = new SashForm(parent, SWT.HORIZONTAL); splitter.setLayoutData(new GridData(GridData.FILL_BOTH)); Group fragmentsGroup = new Group(splitter, SWT.NONE); fragmentsGroup.setLayout(new GridLayout(1, false)); fragmentsGroup.setText("Result Fragments"); fragmentsTable = CheckboxTableViewer.newCheckList(fragmentsGroup, SWT.NONE); fragmentsTable.getTable().setLayoutData(new GridData(GridData.FILL_BOTH)); fragmentsTable.setContentProvider(new ArrayContentProvider()); fragmentsTable.setLabelProvider(new LabelProvider() { public Image getImage(Object element) { return JFaceResources.getImage(WsmoImageRegistry.INSTANCE_ICON); } public String getText(Object element) { if (element == null) { return ""; } if (element instanceof ProcessFragment) { ProcessFragment frag = (ProcessFragment) element; String label = (frag.getName() == null) ? " <no-fragment-name>" : frag.getName(); if (frag.getDescription() != null) { label += " [" + Utils.normalizeSpaces(frag.getDescription()) + ']'; } return label; } return element.toString(); } }); fragmentsTable.setInput(results.toArray()); final MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { if (false == GUIHelper.containsCursor(fragmentsTable.getTable())) { return; } if (false == fragmentsTable.getSelection().isEmpty()) { menuMgr.add(new Action("Edit Name") { public void run() { doEditName(); } }); menuMgr.add(new Action("Edit Description") { public void run() { doEditDescription(); } }); menuMgr.add(new Separator()); } menuMgr.add(new Action("Select All") { public void run() { fragmentsTable.setAllChecked(true); updateSelectionMonitor(); } }); menuMgr.add(new Separator()); menuMgr.add(new Action("Unselect All") { public void run() { fragmentsTable.setAllChecked(false); updateSelectionMonitor(); } }); } }); fragmentsTable.getTable().setMenu(menuMgr.createContextMenu(fragmentsTable.getTable())); fragmentsTable.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updatePreviewPanel((IStructuredSelection) event.getSelection()); } }); new FragmentsToolTipProvider(this.fragmentsTable.getTable()); Group previewGroup = new Group(splitter, SWT.NONE); previewGroup.setLayout(new GridLayout(1, false)); previewGroup.setText("Fragment Preview"); createZoomToolbar(previewGroup); previewArea = new Composite(previewGroup, SWT.BORDER); previewArea.setLayoutData(new GridData(GridData.FILL_BOTH)); previewArea.setLayout(new GridLayout(1, false)); viewer = new ScrollingGraphicalViewer(); viewer.createControl(previewArea); ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart(); viewer.setRootEditPart(rootEditPart); viewer.setEditPartFactory(new GraphicalPartFactory()); viewer.getControl().setBackground(ColorConstants.listBackground); viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); ZoomManager zoomManager = rootEditPart.getZoomManager(); ArrayList<String> zoomContributions = new ArrayList<String>(); zoomContributions.add(ZoomManager.FIT_ALL); zoomContributions.add(ZoomManager.FIT_HEIGHT); zoomContributions.add(ZoomManager.FIT_WIDTH); zoomManager.setZoomLevelContributions(zoomContributions); zoomManager.setZoomLevels(new double[] { 0.25, 0.33, 0.5, 0.75, 1.0 }); zoomManager.setZoom(1.0); Composite businessGoalPanel = new Composite(previewGroup, SWT.NONE); businessGoalPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); businessGoalPanel.setLayout(new GridLayout(4, false)); Label lab = new Label(businessGoalPanel, SWT.NONE); lab.setText("Process goal:"); bpgIRI = new Text(businessGoalPanel, SWT.BORDER | SWT.READ_ONLY); bpgIRI.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectBpgButton = new Button(businessGoalPanel, SWT.NONE); selectBpgButton.setText("Select"); selectBpgButton.setEnabled(false); selectBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { doSelectProcessGoal(); } }); clearBpgButton = new Button(businessGoalPanel, SWT.NONE); clearBpgButton.setText("Clear"); clearBpgButton.setEnabled(false); clearBpgButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent s) { IStructuredSelection sel = (IStructuredSelection) fragmentsTable.getSelection(); if (sel.isEmpty() || false == sel.getFirstElement() instanceof ProcessFragment) { return; } ((ProcessFragment) sel.getFirstElement()).setBusinessProcessGoal(null); updatePreviewPanel(sel); } }); splitter.setWeights(new int[] { 1, 2 }); }
00
Code Sample 1: public void initialize() { if (shieldings == null) { try { URL url = ClassLoader.getSystemResource(RF); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); SharcReader sr1 = new SharcReader(br); shieldings = new Hashtable(); while (sr1.hasNext()) { SharcShielding ss1 = sr1.next(); shieldings.put(ss1.getMethod(), ss1); } String[] shieldingNames = new String[shieldings.size()]; int i = 0; for (Enumeration k = shieldings.keys(); k.hasMoreElements(); ) { shieldingNames[i] = (String) k.nextElement(); i++; } dialog = new SelectSharcReference(null, shieldingNames, true); } catch (Exception ex) { shieldings = null; } } } Code Sample 2: public static void copy(String file1, String file2) throws IOException { File inputFile = new File(file1); File outputFile = new File(file2); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); System.out.println("Copy file from: " + file1 + " to: " + file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
00
Code Sample 1: public static void ftpUpload(FTPConfig config, String directory, File file, String remoteFileName) throws IOException { FTPClient server = new FTPClient(); server.connect(config.host, config.port); assertValidReplyCode(server.getReplyCode(), server); server.login(config.userName, config.password); assertValidReplyCode(server.getReplyCode(), server); assertValidReplyCode(server.cwd(directory), server); server.setFileTransferMode(FTP.IMAGE_FILE_TYPE); server.setFileType(FTP.IMAGE_FILE_TYPE); server.storeFile(remoteFileName, new FileInputStream(file)); assertValidReplyCode(server.getReplyCode(), server); server.sendNoOp(); server.disconnect(); } Code Sample 2: private void addConfigurationResource(final String fileName, NotFoundPolicy notFoundPolicy) { try { final ClassLoader cl = this.getClass().getClassLoader(); final Properties p = new Properties(); final URL url = cl.getResource(fileName); if (url == null) { throw new NakedObjectException("Failed to load configuration resource: " + fileName); } p.load(url.openStream()); LOG.info("configuration resource " + fileName + " loaded"); configuration.add(p); } catch (final Exception e) { if (notFoundPolicy == NotFoundPolicy.FAIL_FAST) { throw new NakedObjectException(e); } LOG.info("configuration resource " + fileName + " not found, but not needed"); } }
00
Code Sample 1: public ProgramProfilingSymbol updateProgramProfilingSymbol(int id, int configID, int programSymbolID) throws AdaptationException { ProgramProfilingSymbol pps = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE ProgramProfilingSymbols SET " + "projectDeploymentConfigurationID = " + configID + ", " + "programSymbolID = " + programSymbolID + ", " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from ProgramProfilingSymbols WHERE " + "id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program profiling " + "symbol failed."; log.error(msg); throw new AdaptationException(msg); } pps = getProfilingSymbol(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramProfilingSymbol"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return pps; } Code Sample 2: private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
00
Code Sample 1: public Book importFromURL(URL url) { InputStream is = null; try { is = url.openStream(); return importFromStream(is, url.toString()); } catch (Exception ex) { throw ModelException.Aide.wrap(ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw ModelException.Aide.wrap(ex); } } } } Code Sample 2: protected Context getResource3ServerInitialContext() throws Exception { if (resource3ServerJndiProps == null) { URL url = ClassLoader.getSystemResource("jndi.properties"); resource3ServerJndiProps = new java.util.Properties(); resource3ServerJndiProps.load(url.openStream()); String jndiHost = System.getProperty("jbosstest.resource3.server.host", "localhost"); String jndiUrl = "jnp://" + jndiHost + ":1099"; resource3ServerJndiProps.setProperty("java.naming.provider.url", jndiUrl); } return new InitialContext(resource3ServerJndiProps); }
00
Code Sample 1: public static void main(String[] args) { String url = "jdbc:mysql://localhost/test"; String user = "root"; String password = "password"; String imageLocation = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\01100002.tif"; String imageLocation2 = "C:\\Documents and Settings\\EddyM\\Desktop\\Nick\\011000022.tif"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } try { File f = new File(imageLocation); InputStream fis = new FileInputStream(f); Connection c = DriverManager.getConnection(url, user, password); ResultSet rs = c.createStatement().executeQuery("SELECT Image FROM ImageTable WHERE ImageID=12345678"); new File(imageLocation2).createNewFile(); rs.first(); System.out.println("GotFirst"); InputStream is = rs.getAsciiStream("Image"); System.out.println("gotStream"); FileOutputStream fos = new FileOutputStream(new File(imageLocation2)); int readInt; int i = 0; while (true) { readInt = is.read(); if (readInt == -1) { System.out.println("ReadInt == -1"); break; } i++; if (i % 1000000 == 0) System.out.println(i + " / " + is.available()); fos.write(readInt); } c.close(); } catch (SQLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: public void testJTLM_publish100() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/JTLM/schemas/TLMComposite.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.DEFAULT_OPTIONS); AlignmentType[] alignments = new AlignmentType[] { AlignmentType.bitPacked, AlignmentType.byteAligned, AlignmentType.preCompress, AlignmentType.compress }; for (AlignmentType alignment : alignments) { Transmogrifier encoder = new Transmogrifier(); EXIDecoder decoder = new EXIDecoder(999); Scanner scanner; InputSource inputSource; encoder.setAlignmentType(alignment); decoder.setAlignmentType(alignment); encoder.setEXISchema(grammarCache); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/JTLM/publish100.xml"); inputSource = new InputSource(url.toString()); inputSource.setByteStream(url.openStream()); byte[] bts; int n_events, n_texts; encoder.encode(inputSource); bts = baos.toByteArray(); decoder.setEXISchema(grammarCache); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); ArrayList<EXIEvent> exiEventList = new ArrayList<EXIEvent>(); EXIEvent exiEvent; n_events = 0; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { ++n_events; if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (n_texts % 100 == 0) { final int n = n_texts / 100; Assert.assertEquals(publish100_centennials[n], exiEvent.getCharacters().makeString()); } ++n_texts; } exiEventList.add(exiEvent); } Assert.assertEquals(10610, n_events); } }
11
Code Sample 1: public void doPreparedStatementQueryAndUpdate(Connection conn, String id) throws SQLException { try { int key = getNextKey(); String bValue = "doPreparedStatementQueryAndUpdate:" + id + ":" + testId; PreparedStatement s1; if (key >= MAX_KEY_VALUE) { key = key % MAX_KEY_VALUE; s1 = conn.prepareStatement("delete from many_threads where a = ?"); s1.setInt(1, key); s1.executeUpdate(); s1.close(); } s1 = conn.prepareStatement("insert into many_threads values (?, ?, 0)"); s1.setInt(1, key); s1.setString(2, bValue); assertEquals(1, s1.executeUpdate()); s1.close(); s1 = conn.prepareStatement("select a from many_threads where a = ?"); s1.setInt(1, key); assertEquals(key, executeQuery(s1)); s1.close(); s1 = conn.prepareStatement("update many_threads set value = a * a, b = b || ? where a = ?"); s1.setString(1, "&" + bValue); s1.setInt(2, key + 1); s1.executeUpdate(); s1.close(); if (!conn.getAutoCommit()) { conn.commit(); } } catch (SQLException e) { if (!conn.getAutoCommit()) { try { conn.rollback(); } catch (SQLException e2) { } } } } Code Sample 2: public Integer execute(Connection con) throws SQLException { int updateCount = 0; boolean oldAutoCommitSetting = con.getAutoCommit(); Statement stmt = null; try { con.setAutoCommit(autoCommit); stmt = con.createStatement(); int statementCount = 0; for (String statement : sql) { try { updateCount += stmt.executeUpdate(statement); statementCount++; if (statementCount % commitRate == 0 && !autoCommit) { con.commit(); } } catch (SQLException ex) { if (!failOnError) { log.log(LogLevel.WARN, "%s. Failed to execute: %s.", ex.getMessage(), sql); } else { throw translate(statement, ex); } } } if (!autoCommit) { con.commit(); } return updateCount; } catch (SQLException ex) { if (!autoCommit) { con.rollback(); } throw ex; } finally { close(stmt); con.setAutoCommit(oldAutoCommitSetting); } }
00
Code Sample 1: private void readCard() { try { final String urlString = createURLStringExistRESTGetXQuery("//scheda[cata = \"" + cata + "\"]"); InputStream inputStream = new URL(urlString).openStream(); uiSchedaXml.read(inputStream); inputStream.close(); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } Code Sample 2: private Properties loadPropertiesFromURL(String propertiesURL, Properties defaultProperties) { Properties properties = new Properties(defaultProperties); URL url; try { url = new URL(propertiesURL); URLConnection urlConnection = url.openConnection(); properties.load(urlConnection.getInputStream()); } catch (MalformedURLException e) { System.out.println("Error while loading url " + propertiesURL + " (" + e.getClass().getName() + ")"); e.printStackTrace(); } catch (IOException e) { System.out.println("Error while loading url " + propertiesURL + " (" + e.getClass().getName() + ")"); e.printStackTrace(); } return properties; }
00
Code Sample 1: public static String hash(String string, String algorithm, String encoding) throws UnsupportedEncodingException { try { MessageDigest digest = MessageDigest.getInstance(algorithm); digest.update(string.getBytes(encoding)); byte[] encodedPassword = digest.digest(); return new BigInteger(1, encodedPassword).toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } Code Sample 2: public void insert() throws Exception { Connection con = DbUtil.connectToDb(); PreparedStatement pStmt = null; try { pStmt = con.prepareStatement("INSERT INTO " + Constants.TABLENAME + " (name,phone,address)" + " values(?,?,?)"); con.setAutoCommit(false); pStmt.setString(1, name); pStmt.setString(2, phone); pStmt.setString(3, address); int j = pStmt.executeUpdate(); con.commit(); } catch (Exception ex) { try { con.rollback(); } catch (SQLException sqlex) { sqlex.printStackTrace(System.out); } throw ex; } finally { try { pStmt.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } }
00
Code Sample 1: public boolean renameTo(Folder f) throws MessagingException, StoreClosedException, NullPointerException { String[] aLabels = new String[] { "en", "es", "fr", "de", "it", "pt", "ca", "ja", "cn", "tw", "fi", "ru", "pl", "nl", "xx" }; PreparedStatement oUpdt = null; if (!((DBStore) getStore()).isConnected()) throw new StoreClosedException(getStore(), "Store is not connected"); if (oCatg.isNull(DB.gu_category)) throw new NullPointerException("Folder is closed"); try { oUpdt = getConnection().prepareStatement("DELETE FROM " + DB.k_cat_labels + " WHERE " + DB.gu_category + "=?"); oUpdt.setString(1, oCatg.getString(DB.gu_category)); oUpdt.executeUpdate(); oUpdt.close(); oUpdt.getConnection().prepareStatement("INSERT INTO " + DB.k_cat_labels + " (" + DB.gu_category + "," + DB.id_language + "," + DB.tr_category + "," + DB.url_category + ") VALUES (?,?,?,NULL)"); oUpdt.setString(1, oCatg.getString(DB.gu_category)); for (int l = 0; l < aLabels.length; l++) { oUpdt.setString(2, aLabels[l]); oUpdt.setString(3, f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1).toLowerCase()); oUpdt.executeUpdate(); } oUpdt.close(); oUpdt = null; getConnection().commit(); } catch (SQLException sqle) { try { if (null != oUpdt) oUpdt.close(); } catch (SQLException ignore) { } try { getConnection().rollback(); } catch (SQLException ignore) { } throw new MessagingException(sqle.getMessage(), sqle); } return true; } Code Sample 2: public void invoke() throws IOException { String[] command = new String[files.length + options.length + 2]; command[0] = chmod; System.arraycopy(options, 0, command, 1, options.length); command[1 + options.length] = perms; for (int i = 0; i < files.length; i++) { File file = files[i]; command[2 + options.length + i] = file.getAbsolutePath(); } Process p = Runtime.getRuntime().exec(command); try { p.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (p.exitValue() != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(p.getErrorStream(), writer); throw new IOException("Unable to chmod files: " + writer.toString()); } }
00
Code Sample 1: public static void connectServer() { if (ftpClient == null) { int reply; try { setArg(configFile); ftpClient = new FTPClient(); ftpClient.setDefaultPort(port); ftpClient.configure(getFtpConfig()); ftpClient.connect(ip); ftpClient.login(username, password); ftpClient.setDefaultPort(port); System.out.print(ftpClient.getReplyString()); reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); } } catch (Exception e) { System.err.println("��¼ftp��������" + ip + "��ʧ��"); e.printStackTrace(); } } } Code Sample 2: public void run() { try { URL url = new URL(myListURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; Pattern folderPattern = Pattern.compile(".*DIR.*<a href=.(.*)/.>(.*)</a>.*"); Pattern folderPatternCloudmake = Pattern.compile(".*<li><a href=./(.*)#breadcrumbs. class=.folder.>(.*)</a></li>.*"); Pattern filePatternCloudmake = Pattern.compile(".*<a href=.(.*).bz2. class=.default.>(.*).osm(.*).bz2</a>&nbsp;<span class=\"file-size\">(.*)</span>.*"); while ((line = reader.readLine()) != null) { Matcher matcher = folderPattern.matcher(line); if (matcher.matches()) { String dirUrl = myListURL + matcher.group(1) + "/"; String name = matcher.group(2); if (name.equalsIgnoreCase("Parent Directory")) { continue; } DownloadMenu.this.add(new DownloadMenu(DownloadMenu.this.myMainFrame, dirUrl, name, myLoadChildren)); continue; } matcher = folderPatternCloudmake.matcher(line); if (matcher.matches()) { String dirUrl = myListURL.substring(0, myListURL.indexOf(".com/") + ".com/".length()) + matcher.group(1); String name = matcher.group(2); DownloadMenu.this.add(new DownloadMenu(DownloadMenu.this.myMainFrame, dirUrl, name, myLoadChildren)); continue; } matcher = filePatternCloudmake.matcher(line); if (matcher.matches()) { String fileUrl = myListURL.substring(0, myListURL.indexOf(".com") + ".com".length()) + matcher.group(1) + ".bz2"; final int typeAt = 3; final int nameAt = 2; String type = matcher.group(typeAt); String name = matcher.group(nameAt); if (type.length() > 0) { if (type.startsWith(".")) { type = type.substring(1); } name += "-" + type; } JMenuItem subMenu = new JMenuItem(name); subMenu.addActionListener(new DownloadActionListener(fileUrl, name)); subMenu.putClientProperty("URL", fileUrl); add(subMenu); continue; } int index = line.indexOf("<a href=\""); if (index < 0) { continue; } index += "<a href=\"".length(); int index2 = line.indexOf("</a"); if (index2 < 0) { continue; } int index1 = line.indexOf(".osm.bz2\">"); if (index1 < 0) { continue; } index1 += ".osm.bz2".length(); String fileUrl = line.substring(index, index1); if (!fileUrl.contains(".osm")) continue; if (!fileUrl.startsWith("http")) fileUrl = myListURL + fileUrl; index1 += "\">".length(); String fileName = line.substring(index1, index2); JMenuItem subMenu = new JMenuItem(fileName); subMenu.addActionListener(new DownloadActionListener(fileUrl, fileName)); subMenu.putClientProperty("URL", fileUrl); add(subMenu); } } catch (Exception e) { LOG.log(Level.SEVERE, "[Exception] Problem in " + getClass().getName(), e); } LOG.info("Done with async download of list of downloadable maps for " + getText() + "..."); remove(isLoadingMenuItem); if (myTreeNode != null) { myTreeNode.doneLoading(); } }
00
Code Sample 1: private static boolean tryExpandGorillaHome(File f) throws GorillaHomeException { if (f.exists()) { if (!f.isDirectory() || !f.canWrite()) { return false; } } else { boolean dirOK = f.mkdirs(); } if (f.exists() && f.isDirectory() && f.canWrite()) { java.net.URL url = GorillaHome.class.getResource("/resource_defaults/GORILLA_HOME"); if (url == null) { throw new GorillaHomeException("cannot find gorilla.home resources relative to class " + GorillaHome.class.getName()); } java.net.URLConnection conn; try { conn = url.openConnection(); } catch (IOException e) { String msg = "Error opening connection to " + url.toString(); logger.error(msg, e); throw new GorillaHomeException("Error copying " + url.toString(), e); } if (conn == null) { throw new GorillaHomeException("cannot find gorilla.home resources relative to class " + GorillaHome.class.getName()); } if (conn instanceof java.net.JarURLConnection) { logger.debug("Expanding gorilla.home from from jar file via url " + url.toString()); try { IOUtil.expandJar((java.net.JarURLConnection) conn, f); return true; } catch (Exception e) { throw new GorillaHomeException("Error expanding gorilla.home" + " from jar file at " + conn.getURL().toString() + ": " + e.getMessage()); } } else { try { IOUtil.copyDir(new File(url.getFile()), f); return true; } catch (Exception e) { throw new GorillaHomeException("Error expanding gorilla.home" + " from file at " + conn.getURL().toString() + ": " + e.getMessage()); } } } return false; } Code Sample 2: @Override public String getData(String blipApiPath, String authHeader) { try { URL url = new URL(BLIP_API_URL + blipApiPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (authHeader != null) { conn.addRequestProperty("Authorization", "Basic " + authHeader); } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuffer content = new StringBuffer(); System.out.println("Resp code " + conn.getResponseCode()); while ((line = reader.readLine()) != null) { System.out.println(">> " + line); content.append(line); } reader.close(); return content.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
00
Code Sample 1: public void initFromXml(final String xmlFileName) throws java.net.MalformedURLException, ConfigurationException, IOException { if (xmlInitialized) { return; } templates = null; MergeTemplateWriter.setTokenList(getTokenProvider().getKnownTokens()); java.net.URL url = new FileFinder().getUrl(getTokenProvider().getClass(), xmlFileName); InputStreamReader xmlFileReader = new InputStreamReader(url.openStream()); KnownTemplates temps = MergeTemplateWriter.importFromXML(xmlFileReader); xmlFileReader.close(); KnownTemplates.setDefaultInstance(temps); setTemplates(temps); setInitialized(true); } Code Sample 2: public String getContentAsString(String url) { StringBuffer sb = new StringBuffer(""); try { URL urlmy = new URL(url); HttpURLConnection con = (HttpURLConnection) urlmy.openConnection(); HttpURLConnection.setFollowRedirects(true); con.setInstanceFollowRedirects(false); con.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String s = ""; while ((s = br.readLine()) != null) { sb.append(s + "\r\n"); } con.disconnect(); } catch (Exception ex) { this.logException(ex); } return sb.toString(); }
00
Code Sample 1: private String save(UploadedFile imageFile) { try { File saveFld = new File(imageFolder + File.separator + userDisplay.getUser().getUsername()); if (!saveFld.exists()) { if (!saveFld.mkdir()) { logger.info("Unable to create folder: " + saveFld.getAbsolutePath()); return null; } } File tmp = File.createTempFile("img", "img"); IOUtils.copy(imageFile.getInputstream(), new FileOutputStream(tmp)); File thumbnailImage = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png"); File fullResolution = new File(saveFld + File.separator + UUID.randomUUID().toString() + ".png"); BufferedImage image = ImageIO.read(tmp); Image thumbnailIm = image.getScaledInstance(310, 210, Image.SCALE_SMOOTH); BufferedImage thumbnailBi = new BufferedImage(thumbnailIm.getWidth(null), thumbnailIm.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics bg = thumbnailBi.getGraphics(); bg.drawImage(thumbnailIm, 0, 0, null); bg.dispose(); ImageIO.write(thumbnailBi, "png", thumbnailImage); ImageIO.write(image, "png", fullResolution); if (!tmp.delete()) { logger.info("Unable to delete: " + tmp.getAbsolutePath()); } String imageId = UUID.randomUUID().toString(); imageBean.addImage(imageId, new ImageRecord(imageFile.getFileName(), fullResolution.getAbsolutePath(), thumbnailImage.getAbsolutePath(), userDisplay.getUser().getUsername())); return imageId; } catch (Throwable t) { logger.log(Level.SEVERE, "Unable to save the image.", t); return null; } } Code Sample 2: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
11
Code Sample 1: public void extractProfile(String parentDir, String fileName, String profileName) { try { byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; if (createProfileDirectory(profileName, parentDir)) { debug("the profile directory created .starting the profile extraction"); String profilePath = parentDir + File.separator + fileName; zipinputstream = new ZipInputStream(new FileInputStream(profilePath)); zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); int n; FileOutputStream fileoutputstream; File newFile = new File(entryName); String directory = newFile.getParent(); if (directory == null) { if (newFile.isDirectory()) break; } fileoutputstream = new FileOutputStream(parentDir + File.separator + profileName + File.separator + newFile.getName()); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n); fileoutputstream.close(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); debug("deleting the profile.zip file"); File newFile = new File(profilePath); if (newFile.delete()) { debug("the " + "[" + profilePath + "]" + " deleted successfully"); } else { debug("profile" + "[" + profilePath + "]" + "deletion fail"); throw new IllegalArgumentException("Error: deletion error!"); } } else { debug("error creating the profile directory"); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: public static String[] viewFilesToImport(HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); String importFTPServer = (String) user.workingPubConfigElementsHash.get("IMPORTFTPSERVER") + ""; String importFTPLogin = (String) user.workingPubConfigElementsHash.get("IMPORTFTPLOGIN") + ""; String importFTPPassword = (String) user.workingPubConfigElementsHash.get("IMPORTFTPPASSWORD") + ""; String importFTPFilePath = (String) user.workingPubConfigElementsHash.get("IMPORTFTPFILEPATH"); String[] dirList = null; if (importFTPServer.equals("") || importFTPLogin.equals("") || importFTPPassword.equals("")) { return dirList; } boolean loggedIn = false; try { int reply; ftp.connect(importFTPServer); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport connecting: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.logout(); ftp.disconnect(); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport ERROR: FTP server refused connection."); } else { loggedIn = ftp.login(importFTPLogin, importFTPPassword); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport Logging in: " + importFTPLogin + " " + importFTPPassword); } if (loggedIn) { try { ftp.changeWorkingDirectory(importFTPFilePath); CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport changing dir: " + importFTPFilePath); if (!FTPReply.isPositiveCompletion(reply)) { CofaxToolsUtil.log("ERROR: cannot change directory"); } FTPFile[] remoteFileList = ftp.listFiles(); ArrayList tmpArray = new ArrayList(); for (int i = 0; i < remoteFileList.length; i++) { FTPFile testFile = remoteFileList[i]; if (testFile.getType() == FTP.ASCII_FILE_TYPE) { tmpArray.add(testFile.getName()); } } dirList = (String[]) tmpArray.toArray(new String[0]); ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport cannot read directory: " + importFTPFilePath); } } } catch (IOException e) { CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport could not connect to server: " + e); } return (dirList); } Code Sample 2: public void constructFundamentalView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { FundView = new BufferedWriter(new FileWriter("InfoFiles/FundamentalView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; FundView.write(className); FundView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; FundView.write("StartOfMethod"); FundView.newLine(); FundView.write(methodName); FundView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (field.compareTo(className) == 0) { FundView.write(readArray[i + j]); FundView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (field.compareTo(className) == 0) { FundView.write(writeArray[i + j]); FundView.newLine(); } } } } } FundView.write("EndOfMethod"); FundView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { FundView.write("EndOfClass"); FundView.newLine(); classWritten = false; } } PC.close(); FundView.close(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } Code Sample 2: public static String encrypt(String algorithm, String str) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(str.getBytes()); StringBuffer sb = new StringBuffer(); byte[] bytes = md.digest(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception e) { return ""; } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void 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: public static void main(String[] args) throws Exception { InputStream in = null; try { in = new URL(args[0]).openStream(); IOUtils.copyBytes(in, System.out, 4096, false); } finally { IOUtils.closeStream(in); } } Code Sample 2: public static void translateTableMetaData(String baseDir, String tableName, NameSpaceDefinition nsDefinition) throws Exception { setVosiNS(baseDir, "table", nsDefinition); String filename = baseDir + "table.xsl"; Scanner s = new Scanner(new File(filename)); PrintWriter fw = new PrintWriter(new File(baseDir + tableName + ".xsl")); while (s.hasNextLine()) { fw.println(s.nextLine().replaceAll("TABLENAME", tableName)); } s.close(); fw.close(); applyStyle(baseDir + "tables.xml", baseDir + tableName + ".json", baseDir + tableName + ".xsl"); }
11
Code Sample 1: public static void request() { try { URL url = new URL("http://www.nseindia.com/marketinfo/companyinfo/companysearch.jsp?cons=ghcl&section=7"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static String callApi(String api, String paramname, String paramvalue) { String loginapp = SSOFilter.getLoginapp(); String u = SSOUtil.addParameter(loginapp + "/api/" + api, paramname, paramvalue); u = SSOUtil.addParameter(u, "servicekey", SSOFilter.getServicekey()); String response = "error"; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { response = line.trim(); } reader.close(); } catch (MalformedURLException e) { } catch (IOException e) { } if ("error".equals(response)) { return "error"; } else { return response; } }
11
Code Sample 1: private String encode(String arg) { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(arg.getBytes()); byte[] md5sum = digest.digest(); final BigInteger bigInt = new BigInteger(1, md5sum); final String output = bigInt.toString(16); return output; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 required: " + e.getMessage(), e); } } Code Sample 2: public void testCryptHash() { Log.v("Test", "[*] testCryptHash()"); String testStr = "Hash me"; byte messageDigest[]; MessageDigest digest = null; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest.digest(testStr.getBytes()); digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(testStr.getBytes()); messageDigest = digest.digest(); digest = null; digest = java.security.MessageDigest.getInstance("SHA1"); digest.update(imei.getBytes()); messageDigest = digest.digest(); hashedImei = this.toHex(messageDigest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
00
Code Sample 1: public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; } Code Sample 2: public static void downloadURLNow(URL url, File to, SHA1Sum sha1, boolean force) throws Exception { { String sep = System.getProperty("file.separator"); String folders = to.getPath(); String path = ""; for (int i = 0; i < folders.length(); i++) { path += folders.charAt(i); if (path.endsWith(sep)) { File f = new File(path); if (!f.exists()) f.mkdir(); if (!f.isDirectory()) { Out.error(URLDownloader.class, path + " is not a directory!"); return; } } } } Out.info(URLDownloader.class, "Downloading " + url.toExternalForm()); URLConnection uc = url.openConnection(); DataInputStream is = new DataInputStream(new BufferedInputStream(uc.getInputStream())); FileOutputStream os = new FileOutputStream(to); byte[] b = new byte[1024]; int fileLength = uc.getHeaderFieldInt("Content-Length", 0) / b.length; Task task = null; if (fileLength > 0) task = TaskManager.createTask(url.toExternalForm(), fileLength, "kB"); do { int c = is.read(b); if (c == -1) break; os.write(b, 0, c); if (task != null) task.advanceProgress(); } while (true); if (task != null) task.complete(); os.close(); is.close(); }
11
Code Sample 1: public boolean copyDirectoryTree(File srcPath, File dstPath) { try { if (srcPath.isDirectory()) { if (!dstPath.exists()) dstPath.mkdir(); String files[] = srcPath.list(); for (int i = 0; i < files.length; i++) copyDirectoryTree(new File(srcPath, files[i]), new File(dstPath, files[i])); } else { if (!srcPath.exists()) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath + "' does not exist.\n"; lastErrMsgLog = errMsgLog; return (false); } else { InputStream in = new FileInputStream(srcPath); OutputStream out = new FileOutputStream(dstPath); byte[] buf = new byte[10240]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } } return (true); } catch (Exception e) { errMsgLog += "copyDirectoryTree I/O error from '" + srcPath.getName() + "' to '" + dstPath.getName() + "\n " + e + "\n"; lastErrMsgLog = errMsgLog; return (false); } } Code Sample 2: private static void extract(ZipFile zipFile) throws Exception { FileUtils.deleteQuietly(WEBKIT_DIR); WEBKIT_DIR.mkdirs(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { new File(WEBKIT_DIR, entry.getName()).mkdirs(); continue; } InputStream inputStream = zipFile.getInputStream(entry); File outputFile = new File(WEBKIT_DIR, entry.getName()); FileOutputStream outputStream = new FileOutputStream(outputFile); IOUtils.copy(inputStream, outputStream); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
00
Code Sample 1: public static final synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the MD5 MessageDigest. " + "We will be unable to function normally."); nsae.printStackTrace(); } } digest.update(data.getBytes()); return encodeHex(digest.digest()); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public OOXMLSignatureService(InputStream documentInputStream, OutputStream documentOutputStream, SignatureFacet signatureFacet, String role, IdentityDTO identity, byte[] photo, RevocationDataService revocationDataService, TimeStampService timeStampService, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".ooxml"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(signatureFacet); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } Code Sample 2: private static FileChannel getFileChannel(File file, boolean isOut, boolean append) throws OpenR66ProtocolSystemException { FileChannel fileChannel = null; try { if (isOut) { FileOutputStream fileOutputStream = new FileOutputStream(file.getPath(), append); fileChannel = fileOutputStream.getChannel(); if (append) { try { fileChannel.position(file.length()); } catch (IOException e) { } } } else { if (!file.exists()) { throw new OpenR66ProtocolSystemException("File does not exist"); } FileInputStream fileInputStream = new FileInputStream(file.getPath()); fileChannel = fileInputStream.getChannel(); } } catch (FileNotFoundException e) { throw new OpenR66ProtocolSystemException("File not found", e); } return fileChannel; }
00
Code Sample 1: public void excluir(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "delete from cliente where cod_cliente = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setLong(1, cliente.getId()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } } Code Sample 2: protected boolean check(String username, String password, String realm, String nonce, String nc, String cnonce, String qop, String uri, String response, HttpServletRequest request) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update((byte) ':'); md.update(realm.getBytes()); md.update((byte) ':'); md.update(password.getBytes()); byte[] ha1 = md.digest(); md.reset(); md.update(request.getMethod().getBytes()); md.update((byte) ':'); md.update(uri.getBytes()); byte[] ha2 = md.digest(); md.update(TypeUtil.toString(ha1, 16).getBytes()); md.update((byte) ':'); md.update(nonce.getBytes()); md.update((byte) ':'); md.update(nc.getBytes()); md.update((byte) ':'); md.update(cnonce.getBytes()); md.update((byte) ':'); md.update(qop.getBytes()); md.update((byte) ':'); md.update(TypeUtil.toString(ha2, 16).getBytes()); byte[] digest = md.digest(); return response.equals(encode(digest)); } catch (Exception e) { e.printStackTrace(); return false; } }
00
Code Sample 1: private static String func(String sf) { int total = 0, temp; String fnctn[] = { "sin", "cos", "tan", "log", "ln", "sqrt", "!" }, temp2 = ""; int pos[] = new int[7]; for (int n = 0; n < fnctn.length; n++) { pos[n] = sf.lastIndexOf(fnctn[n]); } for (int m = 0; m < fnctn.length; m++) { total += pos[m]; } if (total == -7) { return sf; } for (int i = pos.length; i > 1; i--) { for (int j = 0; j < i - 1; j++) { if (pos[j] < pos[j + 1]) { temp = pos[j]; pos[j] = pos[j + 1]; pos[j + 1] = temp; temp2 = fnctn[j]; fnctn[j] = fnctn[j + 1]; fnctn[j + 1] = temp2; } } } if (fnctn[0].equals("sin")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.sine(sf, pos[0], false)); } else { return func(Functions.asin(sf, pos[0], false)); } } else if (fnctn[0].equals("cos")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.cosine(sf, pos[0], false)); } else { return func(Functions.acos(sf, pos[0], false)); } } else if (fnctn[0].equals("tan")) { if ((pos[0] == 0 || sf.charAt(pos[0] - 1) != 'a')) { return func(Functions.tangent(sf, pos[0], false)); } else { return func(Functions.atan(sf, pos[0], false)); } } else if (fnctn[0].equals("log")) { return func(Functions.logarithm(sf, pos[0])); } else if (fnctn[0].equals("ln")) { return func(Functions.lnat(sf, pos[0])); } else if (fnctn[0].equals("sqrt")) { return func(Functions.sqroot(sf, pos[0])); } else { return func(Functions.factorial(sf, pos[0])); } } Code Sample 2: public void copyFile(String source_file_path, String destination_file_path) { FileWriter fw = null; FileReader fr = null; BufferedReader br = null; BufferedWriter bw = null; File source = null; try { fr = new FileReader(source_file_path); fw = new FileWriter(destination_file_path); br = new BufferedReader(fr); bw = new BufferedWriter(fw); source = new File(source_file_path); int fileLength = (int) source.length(); char charBuff[] = new char[fileLength]; while (br.read(charBuff, 0, fileLength) != -1) bw.write(charBuff, 0, fileLength); } catch (FileNotFoundException fnfe) { System.out.println(source_file_path + " does not exist!"); } catch (IOException ioe) { System.out.println("Error reading/writing files!"); } finally { try { if (br != null) br.close(); if (bw != null) bw.close(); } catch (IOException ioe) { } } }
11
Code Sample 1: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } Code Sample 2: private static void zip(File d) throws FileNotFoundException, IOException { String[] entries = d.list(); byte[] buffer = new byte[4096]; int bytesRead; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(d.getParent() + File.separator + "dist.zip"))); for (int i = 0; i < entries.length; i++) { File f = new File(d, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); int skipl = d.getCanonicalPath().length(); ZipEntry entry = new ZipEntry(f.getPath().substring(skipl)); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); FileUtils.moveFile(new File(d.getParent() + File.separator + "dist.zip"), new File(d + File.separator + "dist.zip")); }
11
Code Sample 1: public SM2Client(String umn, String authorizationID, String protocol, String serverName, Map props, CallbackHandler handler) { super(SM2_MECHANISM + "-" + umn, authorizationID, protocol, serverName, props, handler); this.umn = umn; complete = false; state = 0; if (sha == null) try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException x) { cat.error("SM2Client()", x); throw new RuntimeException(String.valueOf(x)); } sha.update(String.valueOf(umn).getBytes()); sha.update(String.valueOf(authorizationID).getBytes()); sha.update(String.valueOf(protocol).getBytes()); sha.update(String.valueOf(serverName).getBytes()); sha.update(String.valueOf(properties).getBytes()); sha.update(String.valueOf(Thread.currentThread().getName()).getBytes()); uid = new BigInteger(1, sha.digest()).toString(26); Ec = null; } Code Sample 2: public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
00
Code Sample 1: private String GetStringFromURL(String URL) { InputStream in = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; String outstring = ""; try { java.net.URL url = new java.net.URL(URL); in = url.openStream(); inputStreamReader = new InputStreamReader(in); bufferedReader = new BufferedReader(inputStreamReader); StringBuffer out = new StringBuffer(""); String nextLine; String newline = System.getProperty("line.separator"); while ((nextLine = bufferedReader.readLine()) != null) { out.append(nextLine); out.append(newline); } outstring = new String(out); } catch (IOException e) { System.out.println("Failed to read from " + URL); outstring = ""; } finally { try { bufferedReader.close(); inputStreamReader.close(); } catch (Exception e) { } } return outstring; } Code Sample 2: public void guardarCantidad() { try { String can = String.valueOf(cantidadArchivos); File archivo = new File("cantidadArchivos.txt"); FileWriter fw = new FileWriter(archivo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter salida = new PrintWriter(bw); salida.print(can); salida.close(); BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("cantidadArchivos.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[buffer]; File f = new File("cantidadArchivos.txt"); FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, buffer); ZipEntry entry = new ZipEntry("cantidadArchivos.txt"); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, buffer)) != -1) out.write(data, 0, count); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } }
00
Code Sample 1: @Override public synchronized void deleteHttpSessionStatistics(String contextName, String project, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getHttpSessionInvocationsSchemaAndTableName() + " FROM " + this.getHttpSessionInvocationsSchemaAndTableName() + " INNER JOIN " + this.getHttpSessionElementsSchemaAndTableName() + " ON " + this.getHttpSessionElementsSchemaAndTableName() + ".element_id = " + this.getHttpSessionInvocationsSchemaAndTableName() + ".element_id WHERE "; if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if (project != null) { queryString = queryString + " project LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if (project != null) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting HTTP session statistics.", e); } finally { this.releaseConnection(connection); } } Code Sample 2: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0) outFile.write(buf, 0, read); inFile.close(); }
11
Code Sample 1: public static void copyFile(File source, File destination) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[4096]; int read = -1; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.flush(); out.close(); in.close(); } Code Sample 2: private String unJar(String jarPath, String jarEntry) { String path; if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/")); String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/")); try { new File(path + "/" + relPath).mkdirs(); JarFile jar = new JarFile(jarPath); ZipEntry ze = jar.getEntry(jarEntry); File bin = new File(path + "/" + jarEntry); IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin)); } catch (Exception e) { e.printStackTrace(); } return path + "/" + jarEntry; }
00
Code Sample 1: public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; } Code Sample 2: public static String getKeyWithRightLength(final String key, int keyLength) { if (keyLength > 0) { if (key.length() == keyLength) { return key; } else { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return ""; } md.update(key.getBytes()); byte[] hash = md.digest(); if (keyLength > 20) { byte nhash[] = new byte[keyLength]; for (int i = 0; i < keyLength; i++) { nhash[i] = hash[i % 20]; } hash = nhash; } return new String(hash).substring(0, keyLength); } } else { return key; } }
11
Code Sample 1: public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("utf-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public void run() { counter = 0; Log.debug("Fetching news"); Session session = botService.getSession(); if (session == null) { Log.warn("No current IRC session"); return; } final List<Channel> channels = session.getChannels(); if (channels.isEmpty()) { Log.warn("No channel for the current IRC session"); return; } if (StringUtils.isEmpty(feedURL)) { Log.warn("No feed provided"); return; } Log.debug("Creating feedListener"); FeedParserListener feedParserListener = new DefaultFeedParserListener() { public void onChannel(FeedParserState state, String title, String link, String description) throws FeedParserException { Log.debug("onChannel:" + title + "," + link + "," + description); } public void onItem(FeedParserState state, String title, String link, String description, String permalink) throws FeedParserException { if (counter >= MAX_FEEDS) { throw new FeedPollerCancelException("Maximum number of items reached"); } boolean canAnnounce = false; try { if (lastDigest == null) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); lastDigest = md.digest(); canAnnounce = true; } else { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); byte[] currentDigest = md.digest(); if (!MessageDigest.isEqual(currentDigest, lastDigest)) { lastDigest = currentDigest; canAnnounce = true; } } if (canAnnounce) { String shortTitle = title; if (shortTitle.length() > TITLE_MAX_LEN) { shortTitle = shortTitle.substring(0, TITLE_MAX_LEN) + " ..."; } String shortLink = IOUtil.getTinyUrl(link); Log.debug("Link:" + shortLink); for (Channel channel : channels) { channel.say(String.format("%s, %s", shortTitle, shortLink)); } } } catch (Exception e) { throw new FeedParserException(e); } counter++; } public void onCreated(FeedParserState state, Date date) throws FeedParserException { } }; if (parser != null) { InputStream is = null; try { Log.debug("Reading feedURL"); is = new URL(feedURL).openStream(); parser.parse(feedParserListener, is, feedURL); Log.debug("Parsing done"); } catch (IOException ioe) { Log.error(ioe.getMessage(), ioe); } catch (FeedPollerCancelException fpce) { } catch (FeedParserException e) { for (Channel channel : channels) { channel.say(e.getMessage()); } } finally { IOUtil.closeQuietly(is); } } else { Log.warn("Wasn't able to create feed parser"); } }
11
Code Sample 1: private void copy(File source, File destination) throws PackageException { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(destination); byte[] buff = new byte[1024]; int len; while ((len = in.read(buff)) > 0) out.write(buff, 0, len); in.close(); out.close(); } catch (IOException e) { throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString()); } } Code Sample 2: private 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 String loadFileContent(final String _resourceURI) { final Lock readLock = this.fileLock.readLock(); final Lock writeLock = this.fileLock.writeLock(); boolean hasReadLock = false; boolean hasWriteLock = false; try { readLock.lock(); hasReadLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { readLock.unlock(); hasReadLock = false; writeLock.lock(); hasWriteLock = true; if (!this.cachedResources.containsKey(_resourceURI)) { final InputStream resourceAsStream = this.getClass().getResourceAsStream(_resourceURI); final StringWriter writer = new StringWriter(); try { IOUtils.copy(resourceAsStream, writer); } catch (final IOException ex) { throw new IllegalStateException("Resource not read-able", ex); } final String loadedResource = writer.toString(); this.cachedResources.put(_resourceURI, loadedResource); } writeLock.unlock(); hasWriteLock = false; readLock.lock(); hasReadLock = true; } return this.cachedResources.get(_resourceURI); } finally { if (hasReadLock) { readLock.unlock(); } if (hasWriteLock) { writeLock.unlock(); } } } Code Sample 2: public int read(String name) { status = STATUS_OK; try { name = name.trim(); if (name.indexOf("://") > 0) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; }
00
Code Sample 1: public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } } Code Sample 2: @Override public void saveStructure(long userId, TreeStructureInfo info, List<TreeStructureNode> structure) throws DatabaseException { if (info == null) throw new NullPointerException("info"); if (structure == null) throw new NullPointerException("structure"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement insertInfoSt = null, insSt = null; try { insertInfoSt = getConnection().prepareStatement(INSERT_INFO); insertInfoSt.setLong(1, userId); insertInfoSt.setString(2, info.getDescription() != null ? info.getDescription() : ""); insertInfoSt.setString(3, info.getBarcode()); insertInfoSt.setString(4, info.getName()); insertInfoSt.setString(5, info.getInputPath()); insertInfoSt.setString(6, info.getModel()); insertInfoSt.executeUpdate(); PreparedStatement seqSt = getConnection().prepareStatement(INFO_VALUE); ResultSet rs = seqSt.executeQuery(); int key = -1; while (rs.next()) { key = rs.getInt(1); } if (key == -1) { getConnection().rollback(); throw new DatabaseException("Unable to obtain new id from DB when executing query: " + insertInfoSt); } int total = 0; for (TreeStructureNode node : structure) { insSt = getConnection().prepareStatement(INSERT_NODE); insSt.setLong(1, key); insSt.setString(2, node.getPropId()); insSt.setString(3, node.getPropParent()); insSt.setString(4, node.getPropName()); insSt.setString(5, node.getPropPicture()); insSt.setString(6, node.getPropType()); insSt.setString(7, node.getPropTypeId()); insSt.setString(8, node.getPropPageType()); insSt.setString(9, node.getPropDateIssued()); insSt.setString(10, node.getPropAltoPath()); insSt.setString(11, node.getPropOcrPath()); insSt.setBoolean(12, node.getPropExist()); total += insSt.executeUpdate(); } if (total != structure.size()) { getConnection().rollback(); throw new DatabaseException("Unable to insert _ALL_ nodes: " + total + " nodes were inserted of " + structure.size()); } getConnection().commit(); } catch (SQLException e) { LOGGER.error("Queries: \"" + insertInfoSt + "\" and \"" + insSt + "\"", e); } finally { closeConnection(); } }
11
Code Sample 1: private String MD5(String s) { Log.d("MD5", "Hashing '" + s + "'"); String hash = ""; try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); hash = new BigInteger(1, m.digest()).toString(16); Log.d("MD5", "Hash: " + hash); } catch (Exception e) { Log.e("MD5", e.getMessage()); } return hash; } Code Sample 2: public static String getEncodedHex(String text) { MessageDigest md = null; String encodedString = null; try { md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } Hex hex = new Hex(); encodedString = new String(hex.encode(md.digest())); md.reset(); return encodedString; }
00
Code Sample 1: @Test public void testGrantLicense() throws Exception { context.turnOffAuthorisationSystem(); Item item = Item.create(context); String defaultLicense = ConfigurationManager.getDefaultSubmissionLicense(); LicenseUtils.grantLicense(context, item, defaultLicense); StringWriter writer = new StringWriter(); IOUtils.copy(item.getBundles("LICENSE")[0].getBitstreams()[0].retrieve(), writer); String license = writer.toString(); assertThat("testGrantLicense 0", license, equalTo(defaultLicense)); context.restoreAuthSystemState(); } Code Sample 2: private void addPlugin(URL url) throws IOException { logger.debug("Adding plugin with URL {}", url); InputStream in = url.openStream(); try { Properties properties = new Properties(); properties.load(in); plugins.add(new WtfPlugin(properties)); } finally { in.close(); } }
00
Code Sample 1: final void saveProject(Project project, final File file) { if (projectsList.contains(project)) { if (project.isDirty() || !file.getParentFile().equals(workspaceDirectory)) { try { if (!file.exists()) { if (!file.createNewFile()) throw new IOException("cannot create file " + file.getAbsolutePath()); } File tmpFile = File.createTempFile("JFPSM", ".tmp"); ZipOutputStream zoStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file))); zoStream.setMethod(ZipOutputStream.DEFLATED); ZipEntry projectXMLEntry = new ZipEntry("project.xml"); projectXMLEntry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(projectXMLEntry); CustomXMLEncoder encoder = new CustomXMLEncoder(new BufferedOutputStream(new FileOutputStream(tmpFile))); encoder.writeObject(project); encoder.close(); int bytesIn; byte[] readBuffer = new byte[1024]; FileInputStream fis = new FileInputStream(tmpFile); while ((bytesIn = fis.read(readBuffer)) != -1) zoStream.write(readBuffer, 0, bytesIn); fis.close(); ZipEntry entry; String floorDirectory; for (FloorSet floorSet : project.getLevelSet().getFloorSetsList()) for (Floor floor : floorSet.getFloorsList()) { floorDirectory = "levelset/" + floorSet.getName() + "/" + floor.getName() + "/"; for (MapType type : MapType.values()) { entry = new ZipEntry(floorDirectory + type.getFilename()); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(floor.getMap(type).getImage(), "png", zoStream); } } final String tileDirectory = "tileset/"; for (Tile tile : project.getTileSet().getTilesList()) for (int textureIndex = 0; textureIndex < tile.getMaxTextureCount(); textureIndex++) if (tile.getTexture(textureIndex) != null) { entry = new ZipEntry(tileDirectory + tile.getName() + textureIndex + ".png"); entry.setMethod(ZipEntry.DEFLATED); zoStream.putNextEntry(entry); ImageIO.write(tile.getTexture(textureIndex), "png", zoStream); } zoStream.close(); tmpFile.delete(); } catch (IOException ioe) { throw new RuntimeException("The project " + project.getName() + " cannot be saved!", ioe); } } } else throw new IllegalArgumentException("The project " + project.getName() + " is not handled by this project set!"); } Code Sample 2: @Override protected List<String[]> get(URL url) throws Exception { CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(url.openStream())); return reader.readAll(); } finally { IOUtils.closeQuietly(reader); } }
00
Code Sample 1: @Override protected void processImport() throws SudokuInvalidFormatException { importFolder(mUri.getLastPathSegment()); try { URL url = new URL(mUri.toString()); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = null; try { br = new BufferedReader(isr); String s; while ((s = br.readLine()) != null) { if (!s.equals("")) { importGame(s); } } } finally { if (br != null) br.close(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } Code Sample 2: public boolean delete(int id) { boolean deletionOk = false; Connection conn = null; try { conn = db.getConnection(); conn.setAutoCommit(false); String sql = "DELETE FROM keyphrases WHERE website_id=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); deletionOk = ps.executeUpdate() == 1; ps.close(); sql = "DELETE FROM websites WHERE id=?"; ps = conn.prepareStatement(sql); ps.setInt(1, id); boolean success = ps.executeUpdate() == 1; deletionOk = deletionOk && success; ps.close(); conn.commit(); conn.setAutoCommit(true); } catch (SQLException sqle) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException sex) { throw new OsseoFailure("SQL error: roll back failed. ", sex); } throw new OsseoFailure("SQL error: cannot remove website with id " + id + ".", sqle); } finally { db.putConnection(conn); } return deletionOk; }
11
Code Sample 1: public void resumereceive(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { setHeader(resp); try { logger.debug("ResRec: Resume a 'receive' session with session id " + command.getSession() + " this client already received " + command.getLen() + " bytes"); File tempFile = new File(this.getSyncWorkDirectory(req), command.getSession() + ".smodif"); if (!tempFile.exists()) { logger.debug("ResRec: the file doesn't exist, so we created it by serializing the entities"); try { OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); fos.close(); } catch (ImogSerializationException mse) { logger.error(mse.getMessage(), mse); } } InputStream fis = new FileInputStream(tempFile); fis.skip(command.getLen()); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); fis.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } } Code Sample 2: private static boolean genMovieRatingFile(String completePath, String masterFile, String CustLocationsFileName, String MovieRatingFileName) { try { File inFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC1 = new FileInputStream(inFile1).getChannel(); int fileSize1 = (int) inC1.size(); int totalNoDataRows = fileSize1 / 7; ByteBuffer mappedBuffer = inC1.map(FileChannel.MapMode.READ_ONLY, 0, fileSize1); System.out.println("Loaded master binary file"); File inFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel inC2 = new FileInputStream(inFile2).getChannel(); int fileSize2 = (int) inC2.size(); System.out.println(fileSize2); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieRatingFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); for (int i = 0; i < 1; i++) { ByteBuffer locBuffer = inC2.map(FileChannel.MapMode.READ_ONLY, i * fileSize2, fileSize2); System.out.println("Loaded cust location file chunk: " + i); while (locBuffer.hasRemaining()) { int locationToRead = locBuffer.getInt(); mappedBuffer.position((locationToRead - 1) * 7); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); ByteBuffer outBuf = ByteBuffer.allocate(3); outBuf.putShort(movieName); outBuf.put(rating); outBuf.flip(); outC.write(outBuf); } } mappedBuffer.clear(); inC1.close(); inC2.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
00
Code Sample 1: ServiceDescription getServiceDescription() throws ConfigurationException { final XPath pathsXPath = this.xPathFactory.newXPath(); try { final Node serviceDescriptionNode = (Node) pathsXPath.evaluate(ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration, XPathConstants.NODE); final String title = getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.TITLE_ELEMENT); ServiceDescription.Builder builder = new ServiceDescription.Builder(title, Migrate.class.getCanonicalName()); Property[] serviceProperties = getServiceProperties(serviceDescriptionNode); builder.author(getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.CREATOR_ELEMENT)); builder.classname(this.canonicalServiceName); builder.description(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.DESCRIPTION_ELEMENT)); final String serviceVersion = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.VERSION_ELEMENT); final Tool toolDescription = getToolDescriptionElement(serviceDescriptionNode); String identifier = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.IDENTIFIER_ELEMENT); if (identifier == null || "".equals(identifier)) { try { final MessageDigest identDigest = MessageDigest.getInstance("MD5"); identDigest.update(this.canonicalServiceName.getBytes()); final String versionInfo = (serviceVersion != null) ? serviceVersion : ""; identDigest.update(versionInfo.getBytes()); final URI toolIDURI = toolDescription.getIdentifier(); final String toolIdentifier = toolIDURI == null ? "" : toolIDURI.toString(); identDigest.update(toolIdentifier.getBytes()); final BigInteger md5hash = new BigInteger(identDigest.digest()); identifier = md5hash.toString(16); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } } builder.identifier(identifier); builder.version(serviceVersion); builder.tool(toolDescription); builder.instructions(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.INSTRUCTIONS_ELEMENT)); builder.furtherInfo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.FURTHER_INFO_ELEMENT)); builder.logo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.LOGO_ELEMENT)); builder.serviceProvider(this.serviceProvider); final DBMigrationPathFactory migrationPathFactory = new DBMigrationPathFactory(this.configuration); final MigrationPaths migrationPaths = migrationPathFactory.getAllMigrationPaths(); builder.paths(MigrationPathConverter.toPlanetsPaths(migrationPaths)); builder.inputFormats(migrationPaths.getInputFormatURIs().toArray(new URI[0])); builder.parameters(getUniqueParameters(migrationPaths)); builder.properties(serviceProperties); return builder.build(); } catch (XPathExpressionException xPathExpressionException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), xPathExpressionException); } catch (NullPointerException nullPointerException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), nullPointerException); } } Code Sample 2: public static void downloadFromUrl(String url1, String fileName) { try { URL url = new URL(url1); File file = new File(fileName); URLConnection ucon = url.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } FileOutputStream fos = new FileOutputStream(file); fos.write(baf.toByteArray()); fos.close(); } catch (IOException e) { } }
11
Code Sample 1: protected void createFile(File sourceActionDirectory, File destinationActionDirectory, LinkedList<String> segments) throws DuplicateActionFileException { File currentSrcDir = sourceActionDirectory; File currentDestDir = destinationActionDirectory; String segment = ""; for (int i = 0; i < segments.size() - 1; i++) { segment = segments.get(i); currentSrcDir = new File(currentSrcDir, segment); currentDestDir = new File(currentDestDir, segment); } if (currentSrcDir != null && currentDestDir != null) { File srcFile = new File(currentSrcDir, segments.getLast()); if (srcFile.exists()) { File destFile = new File(currentDestDir, segments.getLast()); if (destFile.exists()) { throw new DuplicateActionFileException(srcFile.toURI().toASCIIString()); } try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel destChannel = new FileOutputStream(destFile).getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) srcChannel.size()); while (srcChannel.position() < srcChannel.size()) { srcChannel.read(buffer); } srcChannel.close(); buffer.rewind(); destChannel.write(buffer); destChannel.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private String fetchHtml(URL url) throws IOException { URLConnection connection; if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) { Proxy proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(proxyHost, proxyPort)); connection = url.openConnection(proxy); } else { connection = url.openConnection(); } Object content = connection.getContent(); if (content instanceof InputStream) { return IOUtils.toString(InputStream.class.cast(content)); } else { String msg = "Bad content type! " + content.getClass(); log.error(msg); throw new IOException(msg); } } Code Sample 2: private static List<String> getContent(URL url) throws IOException { final HttpURLConnection http = (HttpURLConnection) url.openConnection(); try { http.connect(); final int code = http.getResponseCode(); if (code != 200) throw new IOException("IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]"); return getContent(http); } finally { http.disconnect(); } }
11
Code Sample 1: public static boolean predictDataSet(String completePath, String Type, String predictionOutputFileName, String slopeOneDataFolderName) { try { if (Type.equalsIgnoreCase("Qualifying")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteQualifyingDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap qualMap = new TShortObjectHashMap(17770, 1); ByteBuffer qualmappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (qualmappedfile.hasRemaining()) { short movie = qualmappedfile.getShort(); int customer = qualmappedfile.getInt(); if (qualMap.containsKey(movie)) { TIntArrayList arr = (TIntArrayList) qualMap.get(movie); arr.add(customer); qualMap.put(movie, arr); } else { TIntArrayList arr = new TIntArrayList(); arr.add(customer); qualMap.put(movie, arr); } } System.out.println("Populated qualifying hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; TShortObjectHashMap movieDiffStats; double finalPrediction; short[] movies = qualMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); System.out.println(movieDiffStats.size()); TIntArrayList customersToProcess = (TIntArrayList) qualMap.get(movieToProcess); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(10); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else if (Type.equalsIgnoreCase("Probe")) { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "CompleteProbeDataInByteFormat.txt"); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); TShortObjectHashMap probeMap = new TShortObjectHashMap(17770, 1); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); while (probemappedfile.hasRemaining()) { short movie = probemappedfile.getShort(); int customer = probemappedfile.getInt(); byte rating = probemappedfile.get(); if (probeMap.containsKey(movie)) { TIntByteHashMap actualRatings = (TIntByteHashMap) probeMap.get(movie); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } else { TIntByteHashMap actualRatings = new TIntByteHashMap(); actualRatings.put(customer, rating); probeMap.put(movie, actualRatings); } } System.out.println("Populated probe hashmap"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionOutputFileName); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf; double finalPrediction; TShortObjectHashMap movieDiffStats; short[] movies = probeMap.keys(); Arrays.sort(movies); for (int i = 0; i < movies.length; i++) { short movieToProcess = movies[i]; movieDiffStats = loadMovieDiffStats(completePath, movieToProcess, slopeOneDataFolderName); TIntByteHashMap custRatingsToProcess = (TIntByteHashMap) probeMap.get(movieToProcess); TIntArrayList customersToProcess = new TIntArrayList(custRatingsToProcess.keys()); for (int j = 0; j < customersToProcess.size(); j++) { int customerToProcess = customersToProcess.getQuick(j); byte rating = custRatingsToProcess.get(customerToProcess); finalPrediction = predictSlopeOneRating(customerToProcess, movieDiffStats); if (finalPrediction == finalPrediction) { if (finalPrediction < 1.0) finalPrediction = 1.0; else if (finalPrediction > 5.0) finalPrediction = 5.0; } else finalPrediction = GetAveragePrediction(movieToProcess); buf = ByteBuffer.allocate(11); buf.putShort(movieToProcess); buf.putInt(customerToProcess); buf.put(rating); buf.putFloat(new Double(finalPrediction).floatValue()); buf.flip(); outC.write(buf); } } outC.close(); return true; } else return false; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public void unzip(String zipFileName, String outputDirectory) throws Exception { ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName)); ZipEntry z; while ((z = in.getNextEntry()) != null) { System.out.println("unziping " + z.getName()); if (z.isDirectory()) { String name = z.getName(); name = name.substring(0, name.length() - 1); File f = new File(outputDirectory + File.separator + name); f.mkdir(); System.out.println("mkdir " + outputDirectory + File.separator + name); } else { File f = new File(outputDirectory + File.separator + z.getName()); f.createNewFile(); FileOutputStream out = new FileOutputStream(f); int b; while ((b = in.read()) != -1) out.write(b); out.close(); } } in.close(); }
11
Code Sample 1: private final void saveCopy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; 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"); } to = null; from = null; } Code Sample 2: private void encryptChkFile(ProjectMember member, File chkFile) throws Exception { final java.io.FileReader reader = new java.io.FileReader(chkFile); final File encryptedChkFile = new File(member.createOutputFileName(outputPath, "chk")); FileOutputStream outfile = null; ObjectOutputStream outstream = null; Utilities.discardBooleanResult(encryptedChkFile.getParentFile().mkdirs()); outfile = new FileOutputStream(encryptedChkFile); outstream = new ObjectOutputStream(outfile); outstream.writeObject(new Format().parse(reader)); reader.close(); outfile.close(); outstream.close(); }
00
Code Sample 1: public Gif(URL url) throws BadElementException, IOException { super(url); type = GIF; InputStream is = null; try { is = url.openStream(); if (is.read() != 'G' || is.read() != 'I' || is.read() != 'F') { throw new BadElementException(url.toString() + " is not a valid GIF-file."); } skip(is, 3); scaledWidth = is.read() + (is.read() << 8); setRight((int) scaledWidth); scaledHeight = is.read() + (is.read() << 8); setTop((int) scaledHeight); } finally { if (is != null) { is.close(); } plainWidth = width(); plainHeight = height(); } } Code Sample 2: public Usuario insertUsuario(IUsuario usuario) throws SQLException { Connection conn = null; String insert = "insert into Usuario (idusuario, nome, email, telefone, cpf, login, senha) " + "values " + "(nextval('seq_usuario'), '" + usuario.getNome() + "', '" + usuario.getEmail() + "', " + "'" + usuario.getTelefone() + "', '" + usuario.getCpf() + "', '" + usuario.getLogin() + "', '" + usuario.getSenha() + "')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_usuario"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { usuario.setIdUsuario(rs.getInt("last_value")); } if (usuario instanceof Requerente) { RequerenteDAO requerenteDAO = new RequerenteDAO(); requerenteDAO.insertRequerente((Requerente) usuario, conn); } else if (usuario instanceof RecursoHumano) { RecursoHumanoDAO recursoHumanoDAO = new RecursoHumanoDAO(); recursoHumanoDAO.insertRecursoHumano((RecursoHumano) usuario, conn); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; }
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 void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
11
Code Sample 1: public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream contentIn2 = getClass().getResourceAsStream(CONTENT2_FILE); sourceOut = emptySource.getOutputStream(); try { IOUtils.copy(contentIn2, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn2.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT2_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); } Code Sample 2: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { assertTrue(resourceName.startsWith("/")); final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
00
Code Sample 1: public String parse(String queryText) throws ParseException { try { StringBuilder sb = new StringBuilder(); queryText = Val.chkStr(queryText); if (queryText.length() > 0) { URL url = new URL(getUrl(queryText)); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } } return sb.toString(); } catch (IOException ex) { throw new ParseException("Ontology parser is unable to parse term: \"" + queryText + "\" due to internal error: " + ex.getMessage()); } } Code Sample 2: protected <T extends AbstractResponse> T readResponse(HttpUriRequest httpUriRequest, Class<T> clazz) throws IOException, TranslatorException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Executing request " + httpUriRequest.getURI()); } HttpResponse httpResponse = httpClient.execute(httpUriRequest); String response = EntityUtils.toString(httpResponse.getEntity()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Reading '" + response + "' into " + clazz.getName()); } T abstractResponse = TranslatorObjectMapper.instance().readValue(response, clazz); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Response object " + abstractResponse); } if (abstractResponse.getError() != null) { throw new TranslatorException(abstractResponse.getError()); } return abstractResponse; }
11
Code Sample 1: public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); } Code Sample 2: public ValidationReport validate(OriginalDeployUnitDescription unit) throws UnitValidationException { ValidationReport vr = new DefaultValidationReport(); errorHandler = new SimpleErrorHandler(vr); vr.setFileUri(unit.getAbsolutePath()); SAXParser parser; SAXReader reader = null; try { parser = factory.newSAXParser(); reader = new SAXReader(parser.getXMLReader()); reader.setValidation(false); reader.setErrorHandler(this.errorHandler); } catch (ParserConfigurationException e) { throw new UnitValidationException("The configuration of parser is illegal.", e); } catch (SAXException e) { String m = "Something is wrong when register schema"; logger.error(m, e); throw new UnitValidationException(m, e); } ZipInputStream zipInputStream; InputStream tempInput = null; try { tempInput = new FileInputStream(unit.getAbsolutePath()); } catch (FileNotFoundException e1) { String m = String.format("The file [%s] don't exist.", unit.getAbsolutePath()); logger.error(m, e1); throw new UnitValidationException(m, e1); } zipInputStream = new ZipInputStream(tempInput); ZipEntry zipEntry = null; try { zipEntry = zipInputStream.getNextEntry(); if (zipEntry == null) { String m = String.format("Error when get zipEntry. Maybe the [%s] is not zip file!", unit.getAbsolutePath()); logger.error(m); throw new UnitValidationException(m); } while (zipEntry != null) { if (configFiles.contains(zipEntry.getName())) { byte[] extra = new byte[(int) zipEntry.getSize()]; zipInputStream.read(extra); File file = File.createTempFile("temp", "extra"); file.deleteOnExit(); logger.info("[TempFile:]" + file.getAbsoluteFile()); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(extra); FileOutputStream tempFileOutputStream = new FileOutputStream(file); IOUtils.copy(byteInputStream, tempFileOutputStream); tempFileOutputStream.flush(); IOUtils.closeQuietly(tempFileOutputStream); InputStream inputStream = new FileInputStream(file); reader.read(inputStream, unit.getAbsolutePath() + ":" + zipEntry.getName()); IOUtils.closeQuietly(inputStream); } zipEntry = zipInputStream.getNextEntry(); } } catch (IOException e) { ValidationMessage vm = new XMLValidationMessage("IOError", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } catch (DocumentException e) { ValidationMessage vm = new XMLValidationMessage("Document Error.", 0, 0, unit.getUrl() + ":" + zipEntry.getName(), e); vr.addValidationMessage(vm); } finally { IOUtils.closeQuietly(tempInput); IOUtils.closeQuietly(zipInputStream); } return vr; }
11
Code Sample 1: 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; } } Code Sample 2: public static boolean copyFile(File from, File to) { try { FileChannel fromChannel = new FileInputStream(from).getChannel(); FileChannel toChannel = new FileOutputStream(to).getChannel(); toChannel.transferFrom(fromChannel, 0, fromChannel.size()); fromChannel.close(); toChannel.close(); } catch (IOException e) { log.error("failed to copy " + from.getAbsolutePath() + " to " + to.getAbsolutePath() + ": caught exception", e); return false; } return true; }
11
Code Sample 1: protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final FileManager fmanager = FileManager.getFileManager(request, leechget); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter; try { iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (!item.isFormField()) { final FileObject file = fmanager.getFile(name); if (!file.exists()) { IOUtils.copyLarge(stream, file.getContent().getOutputStream()); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } } Code Sample 2: private void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); }
00
Code Sample 1: public static final boolean copy(File source, File target, boolean overwrite) { if (!overwrite && target.exists()) { LOGGER.error("Target file exist and it not permitted to overwrite it !"); return false; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); if (LOGGER.isDebugEnabled()) e.printStackTrace(); return false; } finally { try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } } return true; } Code Sample 2: public List<String> getFtpFileList(String serverIp, int port, String user, String password, String synchrnPath) throws Exception { List<String> list = new ArrayList<String>(); FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(serverIp)) { throw new RuntimeException("IP is needed. (" + serverIp + ")"); } InetAddress host = InetAddress.getByName(serverIp); ftpClient.connect(host, port); ftpClient.login(user, password); ftpClient.changeWorkingDirectory(synchrnPath); FTPFile[] fTPFile = ftpClient.listFiles(synchrnPath); for (int i = 0; i < fTPFile.length; i++) { list.add(fTPFile[i].getName()); } return list; }
11
Code Sample 1: public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public void SetRoles(Connection conn, User user, String[] roles) throws NpsException { if (!IsSysAdmin() && !IsLocalAdmin()) throw new NpsException(ErrorHelper.ACCESS_NOPRIVILEGE); PreparedStatement pstmt = null; ResultSet rs = null; try { String sql = "delete from userrole where userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); pstmt.executeUpdate(); if (roles != null && roles.length > 0) { try { pstmt.close(); } catch (Exception e1) { } sql = "insert into userrole(userid,roleid) values(?,?)"; pstmt = conn.prepareStatement(sql); for (int i = 0; i < roles.length; i++) { if (roles[i] != null && roles[i].length() > 0) { pstmt.setString(1, user.GetId()); pstmt.setString(2, roles[i]); pstmt.executeUpdate(); } } } try { pstmt.close(); } catch (Exception e1) { } if (user.roles_by_name != null) user.roles_by_name.clear(); if (user.roles_by_id != null) user.roles_by_id.clear(); if (roles != null && roles.length > 0) { sql = "select b.* from UserRole a,Role b where a.roleid = b.id and a.userid=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.id); rs = pstmt.executeQuery(); while (rs.next()) { if (user.roles_by_name == null) user.roles_by_name = new Hashtable(); if (user.roles_by_id == null) user.roles_by_id = new Hashtable(); user.roles_by_name.put(rs.getString("name"), rs.getString("id")); user.roles_by_id.put(rs.getString("id"), rs.getString("name")); } } } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { } nps.util.DefaultLog.error(e); } finally { if (rs != null) try { rs.close(); } catch (Exception e) { } if (pstmt != null) try { pstmt.close(); } catch (Exception e1) { } } } Code Sample 2: private void addLine(AmazonItem coverAdress) { try { URL url = new URL("" + coverAdress.getMediumImageURL()); TableItem ligne1 = new TableItem(table, SWT.DRAW_DELIMITER | SWT.DRAW_TAB | SWT.DRAW_MNEMONIC); url.openConnection(); InputStream is = url.openStream(); Image coverPicture = new Image(display, is); coverAvailable.add(url); ligne1.setImage(new Image[] { coverPicture, null }); ligne1.setText(new String[] { null, coverAdress.getArtist() + "\n" + coverAdress.getCDTitle() + "\nTrack : " + coverAdress.getNbTrack() }); } catch (MalformedURLException e) { } catch (IOException e) { System.err.println(e.toString()); } }
00
Code Sample 1: public static void main(String[] args) { int dizi[] = { 23, 78, 45, 8, 3, 32, 56, 39, 92, 28 }; boolean test = false; int kars = 0; int tas = 0; while (true) { for (int j = 0; j < dizi.length - 1; j++) { kars++; if (dizi[j] > dizi[j + 1]) { int temp = dizi[j]; dizi[j] = dizi[j + 1]; dizi[j + 1] = temp; test = true; tas++; } } if (!test) { break; } else { test = false; } } for (int i = 0; i < dizi.length; i++) { System.out.print(dizi[i] + " "); } for (int i = 0; i < 5; i++) { System.out.println("i" + i); } } 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; }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public static void copy(File srcDir, File dstDir) throws IOException { if (srcDir.isDirectory()) { if (!dstDir.exists()) dstDir.mkdir(); String[] children = srcDir.list(); for (int i = 0; i < children.length; i++) copy(new File(srcDir, children[i]), new File(dstDir, children[i])); } else { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcDir); out = new FileOutputStream(dstDir); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } } }
00
Code Sample 1: public int fileUpload(File pFile, String uploadName, Hashtable pValue) throws Exception { int res = 0; MultipartEntity reqEntity = new MultipartEntity(); if (uploadName != null) { FileBody bin = new FileBody(pFile); reqEntity.addPart(uploadName, bin); } Enumeration<String> enm = pValue.keys(); String key; while (enm.hasMoreElements()) { key = enm.nextElement(); reqEntity.addPart(key, new StringBody("" + pValue.get(key))); } httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity(); res = response.getStatusLine().getStatusCode(); close(); return res; } Code Sample 2: @Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { String resourceDir = System.getProperty("resourceDir"); File resource = new File(resourceDir, filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (resource.exists()) { in = new FileInputStream(resource); } else { in = LOADER.getResourceAsStream(RES_PKG + filename); } IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
00
Code Sample 1: public static 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 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()); }
00
Code Sample 1: public void readPage(String search) { InputStream is = null; try { URL url = new URL("http://www.english-german-dictionary.com/index.php?search=" + search.trim()); is = url.openStream(); InputStreamReader isr = new InputStreamReader(is, "ISO-8859-15"); Scanner scan = new Scanner(isr); String str = new String(); String translate = new String(); String temp; while (scan.hasNextLine()) { temp = (scan.nextLine()); if (temp.contains("<td style='padding-top:4px;' class='ergebnisse_res'>")) { int anfang = temp.indexOf("-->") + 3; temp = temp.substring(anfang); temp = temp.substring(0, temp.indexOf("<!--")); translate = temp.trim(); } else if (temp.contains("<td style='' class='ergebnisse_art'>") || temp.contains("<td style='' class='ergebnisse_art_dif'>") || temp.contains("<td style='padding-top:4px;' class='ergebnisse_art'>")) { if (searchEnglish == false && searchGerman == false) { searchEnglish = temp.contains("<td style='' class='ergebnisse_art'>"); searchGerman = temp.contains("<td style='' class='ergebnisse_art_dif'>"); } int anfang1 = temp.lastIndexOf("'>") + 2; temp = temp.substring(anfang1, temp.lastIndexOf("</td>")); String to = temp.trim() + " "; temp = scan.nextLine(); int anfang2 = temp.lastIndexOf("\">") + 2; temp = (to != null ? to : "") + temp.substring(anfang2, temp.lastIndexOf("</a>")); str += translate + " - " + temp + "\n"; germanList.add(translate); englishList.add(temp.trim()); } } if (searchEnglish) { List<String> temp2 = englishList; englishList = germanList; germanList = temp2; } } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) try { is.close(); } catch (IOException e) { } } } Code Sample 2: public String[] getFile() { List<String> records = new ArrayList<String>(); FTPClient ftp = new FTPClient(); try { int reply; FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftp.configure(conf); ftp.connect(host, port); System.out.println("Connected to " + host + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } ftp.login(user, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused login."); } InputStream is = ftp.retrieveFileStream(remotedir + "/" + remotefile); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { if (!line.equals("")) { records.add(line); } } br.close(); isr.close(); is.close(); ftp.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return records.toArray(new String[0]); }
11
Code Sample 1: private void fetchTree() throws IOException { String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily; URL url = new URL(urlString); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String toParse = in.readLine(); while (in.ready()) { String add = in.readLine(); if (add == null) break; toParse += add; } if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse); } Code Sample 2: private Image retrievePdsImage(double lat, double lon) { imageDone = false; try { StringBuffer urlBuff = new StringBuffer(psdUrl + psdCgi + "?"); urlBuff.append("DATA_SET_NAME=" + dataSet); urlBuff.append("&VERSION=" + version); urlBuff.append("&PIXEL_TYPE=" + pixelType); urlBuff.append("&PROJECTION=" + projection); urlBuff.append("&STRETCH=" + stretch); urlBuff.append("&GRIDLINE_FREQUENCY=" + gridlineFrequency); urlBuff.append("&SCALE=" + URLEncoder.encode(scale)); urlBuff.append("&RESOLUTION=" + resolution); urlBuff.append("&LATBOX=" + latbox); urlBuff.append("&LONBOX=" + lonbox); urlBuff.append("&BANDS_SELECTED=" + bandsSelected); urlBuff.append("&LAT=" + lat); urlBuff.append("&LON=" + lon); URL url = new URL(urlBuff.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String result = null; String line; String imageSrc; int count = 0; while ((line = in.readLine()) != null) { if (count == 6) result = line; count++; } int startIndex = result.indexOf("<TH COLSPAN=2 ROWSPAN=2><IMG SRC = \"") + 36; int endIndex = result.indexOf("\"", startIndex); imageSrc = result.substring(startIndex, endIndex); URL imageUrl = new URL(imageSrc); return (Toolkit.getDefaultToolkit().getImage(imageUrl)); } catch (MalformedURLException e) { } catch (IOException e) { } return null; }
00
Code Sample 1: private String clientLogin(AuthInfo authInfo) throws AuthoricationRequiredException { logger.fine("clientLogin."); try { String url = "https://www.google.com/accounts/ClientLogin"; HttpPost httpPost = new HttpPost(url); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE")); params.add(new BasicNameValuePair("Email", authInfo.getEmail())); params.add(new BasicNameValuePair("Passwd", new String(authInfo.getPassword()))); params.add(new BasicNameValuePair("service", "ah")); params.add(new BasicNameValuePair("source", "client.kotan-server.appspot.com")); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = clientManager.httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { entity.consumeContent(); throw new AuthoricationRequiredException(EntityUtils.toString(entity)); } BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); while (true) { String line = reader.readLine(); if (line == null) break; if (line.startsWith("Auth=")) { return line.substring("Auth=".length()); } } reader.close(); throw new AuthoricationRequiredException("Login failure."); } catch (IOException e) { throw new AuthoricationRequiredException(e); } } Code Sample 2: public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwd = null; SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); pwd = new byte[digest.length + SALT_LENGTH]; System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); return byteToHexString(pwd); }
11
Code Sample 1: public static String httpGet(URL url) throws Exception { URLConnection connection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer content = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { content.append(line); } return content.toString(); } Code Sample 2: private static <T> Collection<T> loadFromServices(Class<T> interf) throws Exception { ClassLoader classLoader = DSServiceLoader.class.getClassLoader(); Enumeration<URL> e = classLoader.getResources("META-INF/services/" + interf.getName()); Collection<T> services = new ArrayList<T>(); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) { break; } int comment = line.indexOf('#'); if (comment >= 0) { line = line.substring(0, comment); } String name = line.trim(); if (name.length() == 0) { continue; } Class<?> clz = Class.forName(name, true, classLoader); Class<? extends T> impl = clz.asSubclass(interf); Constructor<? extends T> ctor = impl.getConstructor(); T svc = ctor.newInstance(); services.add(svc); } } finally { is.close(); } } return services; }
11
Code Sample 1: public String doUpload(@ParamName(name = "file") MultipartFile file, @ParamName(name = "uploadDirectory") String _uploadDirectory) throws IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); String tempUploadDir = MewitProperties.getTemporaryUploadDirectory(); if (!tempUploadDir.endsWith("/") && !tempUploadDir.endsWith("\\")) { tempUploadDir += "\\"; } String fileName = null; int position = file.getOriginalFilename().lastIndexOf("."); if (position <= 0) { fileName = java.util.UUID.randomUUID().toString(); } else { fileName = java.util.UUID.randomUUID().toString() + file.getOriginalFilename().substring(position); } File outputFile = new File(tempUploadDir, fileName); log(INFO, "writing the content of uploaded file to: " + outputFile); FileOutputStream fos = new FileOutputStream(outputFile); IOUtils.copy(file.getInputStream(), fos); file.getInputStream().close(); fos.close(); return doUploadFile(sessionId, outputFile, file.getOriginalFilename()); } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private void createTree(DefaultMutableTreeNode top) throws MalformedURLException, ParserConfigurationException, SAXException, IOException { InputStream stream; URL url = new URL(SHIPS_URL + view.getBaseurl()); try { stream = url.openStream(); } catch (Exception e) { stream = getClass().getResourceAsStream("ships.xml"); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(stream); NodeList races = doc.getElementsByTagName("race"); for (int i = 0; i < races.getLength(); i++) { Element race = (Element) races.item(i); top.add(buildRaceTree(race)); } top.setUserObject("Ships"); view.getShipTree().repaint(); view.getShipTree().expandRow(0); } Code Sample 2: public List<BoardObject> favBoard() throws NetworkException, ContentException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_FAV); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isHttp200(response) && HTTPUtil.isXmlContentType(response)) { Document doc = XmlOperator.readDocument(entity.getContent()); return BBSBodyParseHelper.parseFavBoardList(doc); } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
00
Code Sample 1: @org.junit.Test public void simpleRead() throws Exception { final InputStream istream = StatsInputStreamTest.class.getResourceAsStream("/testFile.txt"); final StatsInputStream ris = new StatsInputStream(istream); assertEquals("read size", 0, ris.getSize()); IOUtils.copy(ris, new NullOutputStream()); assertEquals("in the end", 30, ris.getSize()); } Code Sample 2: public void reademi(Vector<String> descriptions, Vector<String> links, String linkaddress, String idmap) { InputStream is = null; URL url; ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> names = new ArrayList<String>(); try { url = new URL(idmap); is = url.openStream(); Scanner scanner = new Scanner(is); scanner.nextLine(); String line = ""; String id = ""; while (scanner.hasNextLine()) { line = scanner.nextLine(); Scanner linescanner = new Scanner(line); linescanner.useDelimiter("\t"); id = linescanner.next(); id = id.substring(0, id.length() - 2); keys.add(id); linescanner.next(); linescanner.next(); linescanner.next(); linescanner.useDelimiter("\n"); names.add(linescanner.next()); } BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(linkaddress).openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; while ((line = reader.readLine()) != null) { if (line.indexOf("style=raw") != -1) { int linkstart = line.indexOf("http://www.ebi.ac.uk/cgi-bin/dbfetch?db"); int idstart = line.indexOf("id=") + 3; int linkend = line.substring(linkstart).indexOf("\"") + linkstart; link = line.substring(linkstart, linkend); key = line.substring(idstart, linkend); if (keys.indexOf(key) != -1) { name = names.get(keys.indexOf(key)); counter++; descriptions.add(counter + " " + key + " " + name); links.add(link); } } } } catch (MalformedURLException e) { } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public synchronized void run() { logger.info("SEARCH STARTED"); JSONObject json = null; logger.info("Opening urlConnection"); URLConnection connection = null; try { connection = url.openConnection(); connection.addRequestProperty("Referer", HTTP_REFERER); } catch (IOException e) { logger.warn("PROBLEM CONTACTING GOOGLE"); e.printStackTrace(); } String line; StringBuilder builder = new StringBuilder(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { builder.append(line); } } catch (IOException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } logger.info("Google RET: " + builder.toString()); try { json = new JSONObject(builder.toString()); json.append("query", q); } catch (JSONException e) { logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE"); e.printStackTrace(); } sc.onSearchFinished(json); } Code Sample 2: public static void copyFile(File source, String target) throws FileNotFoundException, IOException { File fout = new File(target); fout.mkdirs(); fout.delete(); fout = new File(target); FileChannel in = new FileInputStream(source).getChannel(); FileChannel out = new FileOutputStream(target).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
11
Code Sample 1: public static byte[] expandPasswordToKey(String password, int keyLen, byte[] salt) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] mdBuf = new byte[digLen]; byte[] key = new byte[keyLen]; int cnt = 0; while (cnt < keyLen) { if (cnt > 0) { md5.update(mdBuf); } md5.update(password.getBytes()); md5.update(salt); md5.digest(mdBuf, 0, digLen); int n = ((digLen > (keyLen - cnt)) ? keyLen - cnt : digLen); System.arraycopy(mdBuf, 0, key, cnt, n); cnt += n; } return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKey: " + e); } } Code Sample 2: public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); int hashLength = hash.length; StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { System.out.println("Error getting password hash - " + nsae.getMessage()); return null; } }
11
Code Sample 1: public static void copy(File src, File dst) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { srcChannel.close(); } finally { dstChannel.close(); } } } Code Sample 2: @Override public synchronized File download_dictionary(Dictionary dict, String localfpath) { abort = false; try { URL dictionary_location = new URL(dict.getLocation()); InputStream in = dictionary_location.openStream(); FileOutputStream w = new FileOutputStream(local_cache, false); int b = 0; while ((b = in.read()) != -1) { w.write(b); if (abort) throw new Exception("Download Aborted"); } in.close(); w.close(); File lf = new File(localfpath); FileInputStream r = new FileInputStream(local_cache); FileOutputStream fw = new FileOutputStream(lf); int c; while ((c = r.read()) != -1) fw.write(c); r.close(); fw.close(); clearCache(); return lf; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidTupleOperationException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } clearCache(); return null; }
00
Code Sample 1: public void invoke(String args[]) { System.err.println("invoked with args of size " + args.length); try { for (int i = 0; i < args.length; i++) { System.err.println("processing URL: " + args[i]); URL url = new URL(args[i]); AnnotatedLinearObjectParser parserObj = findParserForURL(url); if (parserObj == null) { continue; } InputStream data = url.openStream(); CompMapViewerWrapper wrapper = ((CompMapViewerProvider) sp).getWrapper(); wrapper.parseIntoDataModel(data, new URLImpl(url.toString()), parserObj, false); JFrame f = wrapper.getViewer().getMainFrame(); f.show(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void launch(String xmlControl, String xmlDoc, long docId) { AgentLauncher l; Environment env; Properties prop; Resource res; String token; String deflt; String answ; String key; String entry; ShipService service; de.fhg.igd.util.URL url; java.net.URL wsurl; NodeList flow; InputSource xmlcontrolstream; TreeMap results; synchronized (lock_) { if (xmlControl == null || xmlControl.length() == 0 || xmlDoc == null || xmlDoc.length() == 0) { System.out.println("---- Need control AND XML document! ----"); return; } Vector v_delegations_host = new Vector(); Vector v_delegations_url = new Vector(); Vector v_delegations_method = new Vector(); xmlcontrolstream = new InputSource(new StringReader(xmlControl)); NodeList destinations = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_DELEGATE); for (int i = 0; i < destinations.getLength(); i++) { if (destinations.item(i).getTextContent() != null && destinations.item(i).getTextContent().length() > 0) { System.out.println(destinations.item(i).getTextContent()); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_HOST); v_delegations_host.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_URL); v_delegations_url.add(entry); entry = SimpleXMLParser.findChildEntry(destinations.item(i), AgentBehaviour.XML_METHOD); v_delegations_method.add(entry); } } token = ""; results = new TreeMap(); for (int i = 0; i < TOKEN_LENGTH; i++) { token = token + (char) (Math.random() * 26 + 65); } results.put(token, null); prop = AgentStructure.defaults(); prop.setProperty(AgentStructure.PROP_AGENT_CLASS, AGENT_); prop.setProperty(AgentBehaviour.CTX_DOCID, String.valueOf(docId)); prop.setProperty(AgentBehaviour.CTX_XML, xmlDoc); prop.setProperty("token", token); deflt = prop.getProperty(AgentStructure.PROP_AGENT_EXCLUDE); prop.setProperty(AgentStructure.PROP_AGENT_EXCLUDE, deflt + ":" + ADDITIONAL_EXCLUDES); service = (ShipService) getEnvironment().lookup(WhatIs.stringValue(ShipService.WHATIS)); for (int i = 0; i < v_delegations_host.size(); i++) { System.out.println("\n-----SCANNING DELEGATES-----"); System.out.println("\n-----DELEGATE " + i + "-----"); System.out.println("-----HOST: " + i + ": " + (String) v_delegations_host.elementAt(i)); System.out.println("-----URL: " + i + ": " + (String) v_delegations_url.elementAt(i)); System.out.println("-----METHOD: " + i + ": " + (String) v_delegations_method.elementAt(i)); try { url = new de.fhg.igd.util.URL((String) v_delegations_host.elementAt(i)); boolean alive = service.isAlive(url); System.out.println("-----ALIVE: " + alive); if (alive) { wsurl = new java.net.URL((String) v_delegations_url.elementAt(i)); try { wsurl.openStream(); System.out.println("-----WEBSERVICE: ON"); if (!prop.containsKey(0 + "." + AgentBehaviour.XML_URL)) { System.out.println("-----MIGRATION: First online host found. I will migrate here:)!"); prop.setProperty(0 + "." + AgentBehaviour.XML_HOST, (String) v_delegations_host.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_URL, (String) v_delegations_url.elementAt(i)); prop.setProperty(0 + "." + AgentBehaviour.XML_METHOD, (String) v_delegations_method.elementAt(i)); } else { System.out.println("-----MIGRATION: I will not migrate here:(!"); } } catch (IOException ex) { System.out.println("-----WEBSERVICE: Could not connect to the webservice!"); System.out.println("-----MIGRATION: WEBSERVICE NOT FOUND! I will not migrate here:(!"); } } } catch (ShipException she) { System.out.println("-----ALIVE: false"); System.out.println("-----MIGRATION: HOST NOT FOUND! I will not migrate here:(!"); } catch (SecurityException see) { System.out.println("-----EXCEPTION: Access connection to remote SHIP service fails! " + "No proper ShipPermission permission to invoke lookups! " + "Ignoring this host...."); } catch (MalformedURLException murle) { System.out.println("-----EXCEPTION: The host URL is not valid! Ignoring this host...."); } } res = new MemoryResource(); env = Environment.getEnvironment(); key = WhatIs.stringValue(AgentLauncher.WHATIS); l = (AgentLauncher) env.lookup(key); if (l == null) { System.out.println("Can't find the agent launcher"); return; } try { l.launchAgent(res, prop); } catch (IllegalAgentException ex) { System.out.println(ex); } catch (GeneralSecurityException ex) { System.out.println(ex); } catch (IOException ex) { System.out.println(ex); } syncmap_.put(token, results); System.out.println("----- TOKEN = " + token + "------"); } try { synchronized (token) { token.wait(TIMEOUT); Map m_results = (Map) syncmap_.get(token); Collection c_results = m_results.values(); String[] sa_results = (String[]) c_results.toArray(new String[0]); answ = ""; for (int j = 0; j < sa_results.length; j++) { answ = answ + sa_results[j]; } syncmap_.remove(token); System.out.println("----- " + answ + " -----"); callbackWS(xmlControl, answ, docId); } } catch (InterruptedException ex) { System.out.println(ex); } }
00
Code Sample 1: public static void compressAll(File dir, File file) throws IOException { if (!dir.isDirectory()) throw new IllegalArgumentException("Given file is no directory"); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file)); out.setLevel(0); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytesRead; for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getName()); out.putNextEntry(entry); while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); } Code Sample 2: private final Vector<Class<?>> findSubclasses(URL location, String packageName, Class<?> superClass) { synchronized (results) { Map<Class<?>, URL> thisResult = new TreeMap<Class<?>, URL>(CLASS_COMPARATOR); Vector<Class<?>> v = new Vector<Class<?>>(); String fqcn = searchClass.getName(); List<URL> knownLocations = new ArrayList<URL>(); knownLocations.add(location); for (int loc = 0; loc < knownLocations.size(); loc++) { URL url = knownLocations.get(loc); File directory = new File(url.getFile()); if (directory.exists()) { String[] files = directory.list(); for (int i = 0; i < files.length; i++) { if (files[i].endsWith(".class")) { String classname = files[i].substring(0, files[i].length() - 6); try { Class<?> c = Class.forName(packageName + "." + classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(packageName + "." + classname)) { thisResult.put(c, url); } } catch (ClassNotFoundException cnfex) { errors.add(cnfex); } catch (Exception ex) { errors.add(ex); } } } } else { try { JarURLConnection conn = (JarURLConnection) url.openConnection(); JarFile jarFile = conn.getJarFile(); Enumeration<JarEntry> e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); String entryname = entry.getName(); if (!entry.isDirectory() && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) classname = classname.substring(1); classname = classname.replace('/', '.'); try { Class c = Class.forName(classname); if (superClass.isAssignableFrom(c) && !fqcn.equals(classname)) { thisResult.put(c, url); } } catch (ClassNotFoundException cnfex) { errors.add(cnfex); } catch (NoClassDefFoundError ncdfe) { errors.add(ncdfe); } catch (UnsatisfiedLinkError ule) { errors.add(ule); } catch (Exception exception) { errors.add(exception); } catch (Error error) { errors.add(error); } } } } catch (IOException ioex) { errors.add(ioex); } } } results.putAll(thisResult); Iterator<Class<?>> it = thisResult.keySet().iterator(); while (it.hasNext()) { v.add(it.next()); } return v; } }
11
Code Sample 1: private synchronized void ensureParsed() throws IOException, BadIMSCPException { if (cp != null) return; if (on_disk == null) { on_disk = createTemporaryFile(); OutputStream to_disk = new FileOutputStream(on_disk); IOUtils.copy(in.getInputStream(), to_disk); to_disk.close(); } try { ZipFilePackageParser parser = utils.getIMSCPParserFactory().createParser(); parser.parse(on_disk); cp = parser.getPackage(); } catch (BadParseException x) { throw new BadIMSCPException("Cannot parse content package", x); } } 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 void includeCss(Group group, Writer out, PageContext pageContext) throws IOException { ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = null; try { fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".css"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); } finally { if (fileStream != null) fileStream.close(); } } } Code Sample 2: public static void main(String args[]) throws IOException, TrimmerException, DataStoreException { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("ace", "path to ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("phd", "path to phd file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("out", "path to new ace file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("min_sanger", "min sanger end coveage default =" + DEFAULT_MIN_SANGER_END_CLONE_CVG).build()); options.addOption(new CommandLineOptionBuilder("min_biDriection", "min bi directional end coveage default =" + DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE).build()); options.addOption(new CommandLineOptionBuilder("ignore_threshold", "min end coveage threshold to stop trying to trim default =" + DEFAULT_IGNORE_END_CVG_THRESHOLD).build()); CommandLine commandLine; PhdDataStore phdDataStore = null; AceContigDataStore datastore = null; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int minSangerEndCloneCoverage = commandLine.hasOption("min_sanger") ? Integer.parseInt(commandLine.getOptionValue("min_sanger")) : DEFAULT_MIN_SANGER_END_CLONE_CVG; int minBiDirectionalEndCoverage = commandLine.hasOption("min_biDriection") ? Integer.parseInt(commandLine.getOptionValue("min_biDriection")) : DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE; int ignoreThresholdEndCoverage = commandLine.hasOption("ignore_threshold") ? Integer.parseInt(commandLine.getOptionValue("ignore_threshold")) : DEFAULT_IGNORE_END_CVG_THRESHOLD; AceContigTrimmer trimmer = new NextGenClosureAceContigTrimmer(minSangerEndCloneCoverage, minBiDirectionalEndCoverage, ignoreThresholdEndCoverage); File aceFile = new File(commandLine.getOptionValue("ace")); File phdFile = new File(commandLine.getOptionValue("phd")); phdDataStore = new DefaultPhdFileDataStore(phdFile); datastore = new IndexedAceFileDataStore(aceFile); File tempFile = File.createTempFile("nextGenClosureAceTrimmer", ".ace"); tempFile.deleteOnExit(); OutputStream tempOut = new FileOutputStream(tempFile); int numberOfContigs = 0; int numberOfTotalReads = 0; for (AceContig contig : datastore) { AceContig trimmedAceContig = trimmer.trimContig(contig); if (trimmedAceContig != null) { numberOfContigs++; numberOfTotalReads += trimmedAceContig.getNumberOfReads(); AceFileWriter.writeAceFile(trimmedAceContig, phdDataStore, tempOut); } } IOUtil.closeAndIgnoreErrors(tempOut); OutputStream masterAceOut = new FileOutputStream(new File(commandLine.getOptionValue("out"))); masterAceOut.write(String.format("AS %d %d%n", numberOfContigs, numberOfTotalReads).getBytes()); InputStream tempInput = new FileInputStream(tempFile); IOUtils.copy(tempInput, masterAceOut); } catch (ParseException e) { System.err.println(e.getMessage()); printHelp(options); } finally { IOUtil.closeAndIgnoreErrors(phdDataStore, datastore); } }
00
Code Sample 1: public static void copyFile(File in, File outDir) throws IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); File out = new File(outDir, in.getName()); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { if (sourceChannel != null) { sourceChannel.close(); } } finally { if (destinationChannel != null) { destinationChannel.close(); } } } } Code Sample 2: public static void contentTrans(String contents, String urlString, String urlString2, String serverIp, int port) { try { URL url = new URL(urlString); url.openStream(); } catch (Exception e) { e.printStackTrace(); } try { Socket server = new Socket(InetAddress.getByName(serverIp), port); OutputStream outputStream = server.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); bufferedWriter.write(contents); bufferedWriter.flush(); bufferedWriter.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } try { URL url2 = new URL(urlString2); url2.openStream(); } catch (Exception e) { e.printStackTrace(); } }