label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public void processAction(DatabaseAdapter db_, DataDefinitionActionDataListType parameters) throws Exception { PreparedStatement ps = null; try { if (log.isDebugEnabled()) log.debug("db connect - " + db_.getClass().getName()); String seqName = DefinitionService.getString(parameters, "sequence_name", null); if (seqName == null) { String errorString = "Name of sequnce not found"; log.error(errorString); throw new Exception(errorString); } String tableName = DefinitionService.getString(parameters, "name_table", null); if (tableName == null) { String errorString = "Name of table not found"; log.error(errorString); throw new Exception(errorString); } String columnName = DefinitionService.getString(parameters, "name_pk_field", null); if (columnName == null) { String errorString = "Name of column not found"; log.error(errorString); throw new Exception(errorString); } CustomSequenceType seqSite = new CustomSequenceType(); seqSite.setSequenceName(seqName); seqSite.setTableName(tableName); seqSite.setColumnName(columnName); long seqValue = db_.getSequenceNextValue(seqSite); String valueColumnName = DefinitionService.getString(parameters, "name_value_field", null); if (columnName == null) { String errorString = "Name of valueColumnName not found"; log.error(errorString); throw new Exception(errorString); } String insertValue = DefinitionService.getString(parameters, "insert_value", null); if (columnName == null) { String errorString = "Name of insertValue not found"; log.error(errorString); throw new Exception(errorString); } String sql = "insert into " + tableName + " " + "(" + columnName + "," + valueColumnName + ")" + "values" + "(?,?)"; if (log.isDebugEnabled()) { log.debug(sql); log.debug("pk " + seqValue); log.debug("value " + insertValue); } ps = db_.prepareStatement(sql); ps.setLong(1, seqValue); ps.setString(2, insertValue); ps.executeUpdate(); db_.commit(); } catch (Exception e) { try { db_.rollback(); } catch (Exception e1) { } log.error("Error insert value", e); throw e; } finally { org.riverock.generic.db.DatabaseManager.close(ps); ps = null; } } Code Sample 2: private static Collection<String> createTopLevelFiles(Configuration configuration, Collections collections, Sets sets) throws FlickrException, SAXException, IOException, JDOMException, TransformerException { Collection<String> createdFiles = new HashSet<String>(); File toplevelXmlFilename = getToplevelXmlFilename(configuration.photosBaseDirectory); Logger.getLogger(FlickrDownload.class).info("Creating XML file " + toplevelXmlFilename.getAbsolutePath()); MediaIndexer indexer = new XmlMediaIndexer(configuration); Element toplevel = new Element("flickr").addContent(XmlUtils.createApplicationXml()).addContent(XmlUtils.createUserXml(configuration)).addContent(collections.createTopLevelXml()).addContent(sets.createTopLevelXml()).addContent(new Stats(sets).createStatsXml(indexer)); createdFiles.addAll(indexer.writeIndex()); XmlUtils.outputXmlFile(toplevelXmlFilename, toplevel); createdFiles.add(toplevelXmlFilename.getName()); Logger.getLogger(FlickrDownload.class).info("Copying support files and performing XSLT transformations"); IOUtils.copyToFileAndCloseStreams(XmlUtils.class.getResourceAsStream("xslt/" + PHOTOS_CSS_FILENAME), new File(configuration.photosBaseDirectory, PHOTOS_CSS_FILENAME)); createdFiles.add(PHOTOS_CSS_FILENAME); IOUtils.copyToFileAndCloseStreams(XmlUtils.class.getResourceAsStream("xslt/" + PLAY_ICON_FILENAME), new File(configuration.photosBaseDirectory, PLAY_ICON_FILENAME)); createdFiles.add(PLAY_ICON_FILENAME); XmlUtils.performXsltTransformation(configuration, "all_sets.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, ALL_SETS_HTML_FILENAME)); createdFiles.add(ALL_SETS_HTML_FILENAME); XmlUtils.performXsltTransformation(configuration, "all_collections.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, ALL_COLLECTIONS_HTML_FILENAME)); createdFiles.add(ALL_COLLECTIONS_HTML_FILENAME); createdFiles.add(Collections.COLLECTIONS_ICON_DIRECTORY); XmlUtils.performXsltTransformation(configuration, "stats.xsl", toplevelXmlFilename, new File(configuration.photosBaseDirectory, STATS_HTML_FILENAME)); createdFiles.add(STATS_HTML_FILENAME); sets.performXsltTransformation(); for (AbstractSet set : sets.getSets()) { createdFiles.add(set.getSetId()); } return createdFiles; }
11
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 boolean restore() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "/Android/bluebox.bak"; String backupDBPath = "/data/android.bluebox/databases/bluebox.db"; File currentDB = new File(sd, currentDBPath); File backupDB = new File(data, backupDBPath); if (currentDB.exists()) { FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); return true; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
00
Code Sample 1: public static void copyFile(File in, File out) throws EnhancedException { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (Exception e) { throw new EnhancedException("Could not copy file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + ".", e); } } Code Sample 2: @Test public void testImageshackUpload() throws Exception { request.setUrl("http://www.imageshack.us/index.php"); request.addParameter("xml", "yes"); request.setFile("fileupload", file); HttpResponse response = httpClient.execute(request); assertTrue(response.is2xxSuccess()); assertTrue(response.getResponseHeaders().size() > 0); String body = IOUtils.toString(response.getResponseBody()); assertTrue(body.contains("<image_link>")); assertTrue(body.contains("<thumb_link>")); assertTrue(body.contains("<image_location>")); assertTrue(body.contains("<image_name>")); response.close(); }
11
Code Sample 1: public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } }
00
Code Sample 1: protected void refreshMods(String modsUrl) { while (true) { JMenuItem mi = mnMods.getItem(mnMods.getItemCount() - 1); if (mi == null) break; mnMods.remove(mnMods.getItemCount() - 1); } try { log.info("Loading mods from " + modsUrl); URL url = new URL(modsUrl); URLConnection conn = url.openConnection(); conn.setUseCaches(false); SAXReader reader = new SAXReader(); Document document = reader.read(conn.getInputStream()); Element root = document.getRootElement(); for (Iterator i = root.elementIterator("mod"); i.hasNext(); ) { final Element mod = (Element) i.next(); JMenuItem mi = new JMenuItem(mod.element("name").getTextTrim()); mi.setIcon(Application.icon("applications-other")); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Application.getInstance().openUrl(mod.element("siteUrl").getTextTrim()); } }); mnMods.add(mi); } } catch (Throwable t) { t.printStackTrace(); log.warn("Failed to dynamically add mod links"); } } Code Sample 2: public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,nextval('pilot_id_seq'))"); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); if (pilotData.id != 0) { psta.setInt(19, pilotData.id); } psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } }
11
Code Sample 1: public static void copy(File source, File sink) throws IOException { if (source == null) throw new NullPointerException("Source file must not be null"); if (sink == null) throw new NullPointerException("Target file must not be null"); if (!source.exists()) throw new IOException("Source file " + source.getPath() + " does not exist"); if (!source.isFile()) throw new IOException("Source file " + source.getPath() + " is not a regular file"); if (!source.canRead()) throw new IOException("Source file " + source.getPath() + " can not be read (missing acces right)"); if (!sink.exists()) throw new IOException("Target file " + sink.getPath() + " does not exist"); if (!sink.isFile()) throw new IOException("Target file " + sink.getPath() + " is not a regular file"); if (!sink.canWrite()) throw new IOException("Target file " + sink.getPath() + " is write protected"); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(sink); byte[] buffer = new byte[1024]; while (input.available() > 0) { int bread = input.read(buffer); if (bread > 0) output.write(buffer, 0, bread); } } finally { if (input != null) try { input.close(); } catch (IOException x) { } if (output != null) try { output.close(); } catch (IOException x) { } } } Code Sample 2: public static void getResponseAsStream(String _url, Object _stringOrStream, OutputStream _stream, Map _headers, Map _params, String _contentType, int _timeout) throws IOException { if (_url == null || _url.length() <= 0) throw new IllegalArgumentException("Url can not be null."); String temp = _url.toLowerCase(); if (!temp.startsWith("http://") && !temp.startsWith("https://")) _url = "http://" + _url; HttpMethod method = null; if (_stringOrStream == null && (_params == null || _params.size() <= 0)) method = new GetMethod(_url); else method = new PostMethod(_url); HttpMethodParams params = ((HttpMethodBase) method).getParams(); if (params == null) { params = new HttpMethodParams(); ((HttpMethodBase) method).setParams(params); } if (_timeout < 0) params.setSoTimeout(0); else params.setSoTimeout(_timeout); if (_contentType != null && _contentType.length() > 0) { if (_headers == null) _headers = new HashMap(); _headers.put("Content-Type", _contentType); } if (_headers != null) { Iterator iter = _headers.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); method.setRequestHeader((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof PostMethod && (_params != null && _params.size() > 0)) { Iterator iter = _params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); ((PostMethod) method).addParameter((String) entry.getKey(), (String) entry.getValue()); } } if (method instanceof EntityEnclosingMethod && _stringOrStream != null) { if (_stringOrStream instanceof InputStream) { RequestEntity entity = new InputStreamRequestEntity((InputStream) _stringOrStream); ((EntityEnclosingMethod) method).setRequestEntity(entity); } else { RequestEntity entity = new StringRequestEntity(_stringOrStream.toString(), _contentType, null); ((EntityEnclosingMethod) method).setRequestEntity(entity); } } HttpClient httpClient = new HttpClient(new org.apache.commons.httpclient.SimpleHttpConnectionManager()); try { int status = httpClient.executeMethod(method); if (status != HttpStatus.SC_OK) { if (status >= 500 && status < 600) throw new IOException("Remote service<" + _url + "> respose a error, status:" + status); } InputStream instream = method.getResponseBodyAsStream(); IOUtils.copy(instream, _stream); instream.close(); } catch (IOException err) { throw err; } finally { if (method != null) method.releaseConnection(); } }
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: @Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
11
Code Sample 1: private void createJarArchive(File archiveFile, List<File> filesToBeJared, File base) throws Exception { FileOutputStream stream = new FileOutputStream(archiveFile); JarOutputStream out = new JarOutputStream(stream); for (File tobeJared : filesToBeJared) { if (tobeJared == null || !tobeJared.exists() || tobeJared.isDirectory()) continue; String entryName = tobeJared.getAbsolutePath().substring(base.getAbsolutePath().length() + 1).replace("\\", "/"); JarEntry jarEntry = new JarEntry(entryName); jarEntry.setTime(tobeJared.lastModified()); out.putNextEntry(jarEntry); FileInputStream in = new FileInputStream(tobeJared); IOUtils.copy(in, out); IOUtils.closeQuietly(in); out.closeEntry(); } out.close(); stream.close(); System.out.println("Generated file: " + archiveFile); } Code Sample 2: public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
11
Code Sample 1: private String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); } Code Sample 2: private String generaHashMD5(String plainText) throws Exception { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes(FirmaUtil.CHARSET)); byte[] digest = mdAlgorithm.digest(); return toHex(digest); }
00
Code Sample 1: public ReqJsonContent(String useragent, String urlstr, String domain, String pathinfo, String alarmMessage) throws IOException { URL url = new URL(urlstr); URLConnection conn = url.openConnection(); conn.setRequestProperty("user-agent", useragent); conn.setRequestProperty("pathinfo", pathinfo); conn.setRequestProperty("domain", domain); try { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF8")); response = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); jsonContectResult = response.toString(); } catch (SocketTimeoutException e) { log.severe(alarmMessage + "-> " + e.getMessage()); jsonContectResult = null; } catch (Exception e) { log.severe(alarmMessage + "-> " + e.getMessage()); jsonContectResult = null; } } Code Sample 2: public Service findServiceFor(final int serviceID) throws JAXBException, IOException, BadResponseException { final String USER_AGENT = "SBSIVisual (CSBE, University of Edinburgh)"; String urlToConnectTo = "http://www.biocatalogue.org/services/" + serviceID; URL url = new URL(urlToConnectTo); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Accept", "application/xml"); int iResponseCode = conn.getResponseCode(); InputStream serverResponse = null; switch(iResponseCode) { case HttpURLConnection.HTTP_OK: serverResponse = conn.getInputStream(); break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new BadResponseException("Received BadResponse from server:" + HttpURLConnection.HTTP_BAD_REQUEST); } Service service = new ResponseParser<Service>().getObjectFor(serverResponse, Service.class); return service; }
11
Code Sample 1: public void anular() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ms = null; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentencia_delete = "DELETE FROM BZOFRENT " + " WHERE REN_OFANY=? AND REN_OFOFI=? AND REN_OFNUM=?"; ms = conn.prepareStatement(sentencia_delete); ms.setInt(1, anoOficio != null ? Integer.parseInt(anoOficio) : 0); ms.setInt(2, oficinaOficio != null ? Integer.parseInt(oficinaOficio) : 0); ms.setInt(3, numeroOficio != null ? Integer.parseInt(numeroOficio) : 0); int afectados = ms.executeUpdate(); if (afectados > 0) { registroActualizado = true; } else { registroActualizado = false; } conn.commit(); } catch (Exception ex) { System.out.println("Error inesperat, no s'ha desat el registre: " + ex.getMessage()); ex.printStackTrace(); registroActualizado = false; errores.put("", "Error inesperat, no s'ha desat el registre" + ": " + ex.getClass() + "->" + ex.getMessage()); try { if (conn != null) conn.rollback(); } catch (SQLException sqle) { throw new RemoteException("S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats", sqle); } throw new RemoteException("Error inesperat, no s'ha modifcat el registre", ex); } finally { ToolsBD.closeConn(conn, ms, null); } } Code Sample 2: public static void process(PricesType prices, Long id_site, DatabaseAdapter dbDyn) throws PriceException { PreparedStatement ps = null; String sql_ = null; PriceListItemType debugItem = null; try { if (log.isDebugEnabled()) { log.debug("dbDyn - " + dbDyn); if (dbDyn != null) log.debug("dbDyn.conn - " + dbDyn.getConnection()); } dbDyn.getConnection().setAutoCommit(false); if (dbDyn.getFamaly() != DatabaseManager.MYSQL_FAMALY) { sql_ = "delete from WM_PRICE_IMPORT_TABLE where shop_code in " + "( select shop_code from WM_PRICE_SHOP_LIST where ID_SITE=? )"; ps = dbDyn.prepareStatement(sql_); RsetTools.setLong(ps, 1, id_site); ps.executeUpdate(); ps.close(); ps = null; } else { String sqlCheck = ""; boolean isFound = false; WmPriceShopListListType shops = GetWmPriceShopListWithIdSiteList.getInstance(dbDyn, id_site).item; boolean isFirst = true; for (int i = 0; i < shops.getWmPriceShopListCount(); i++) { WmPriceShopListItemType shop = shops.getWmPriceShopList(i); isFound = true; if (isFirst) isFirst = false; else sqlCheck += ","; sqlCheck += ("'" + shop.getCodeShop() + "'"); } if (isFound) { sql_ = "delete from WM_PRICE_IMPORT_TABLE where shop_code in ( " + sqlCheck + " )"; if (log.isDebugEnabled()) log.debug("sql " + sql_); ps = dbDyn.prepareStatement(sql_); ps.executeUpdate(); ps.close(); ps = null; } } if (log.isDebugEnabled()) log.debug("Start unmarshalling data"); if (prices == null) throw new PriceException("������ ������� ����� �������. ��� ������ #10.03"); int batchLoop = 0; int count = 0; sql_ = "insert into WM_PRICE_IMPORT_TABLE " + "(is_group, id, id_main, name, price, currency, is_to_load, shop_code, ID_UPLOAD_PRICE) " + "values (?,?,?,?,?,?,?,?,?)"; Long id_upload_session = null; for (int j = 0; j < prices.getPriceListCount(); j++) { PriceListType price = prices.getPriceList(j); if (log.isDebugEnabled()) { log.debug("shopCode " + price.getShopCode()); log.debug("Size vector: " + price.getItemCount()); } for (int i = 0; (i < price.getItemCount()) && (count < 5000); i++, count++) { if (ps == null) ps = dbDyn.prepareStatement(sql_); PriceListItemType item = price.getItem(i); debugItem = item; ps.setInt(1, Boolean.TRUE.equals(item.getIsGroup()) ? 1 : 0); RsetTools.setLong(ps, 2, item.getItemID()); RsetTools.setLong(ps, 3, item.getParentID()); ps.setString(4, item.getNameItem()); RsetTools.setDouble(ps, 5, item.getPrice()); ps.setString(6, item.getCurr()); ps.setString(7, item.getIsLoad().toString()); ps.setString(8, price.getShopCode().toUpperCase()); RsetTools.setLong(ps, 9, id_upload_session); if (dbDyn.getIsBatchUpdate()) { ps.addBatch(); if (++batchLoop >= 200) { int[] updateCounts = ps.executeBatch(); ps.close(); ps = null; batchLoop = 0; } } else ps.executeUpdate(); } } if (dbDyn.getIsBatchUpdate()) { if (ps != null) { int[] updateCounts = ps.executeBatch(); ps.close(); ps = null; } } ImportPriceProcess.process(dbDyn, id_site); dbDyn.commit(); } catch (Exception e) { if (debugItem != null) { log.error("debugItem.getIsGroup() " + (Boolean.TRUE.equals(debugItem.getIsGroup()) ? 1 : 0)); log.error("debugItem.getItemID() " + debugItem.getItemID()); log.error("debugItem.getParentID() " + debugItem.getParentID()); log.error("debugItem.getNameItem() " + debugItem.getNameItem()); log.error("debugItem.getPrice() " + debugItem.getPrice()); log.error("debugItem.getCurr() " + debugItem.getCurr()); log.error("debugItem.getIsLoad().toString() " + debugItem.getIsLoad().toString()); } else log.error("debugItem is null"); log.error("sql:\n" + sql_); final String es = "error process import price-list"; log.error(es, e); try { dbDyn.rollback(); } catch (Exception e11) { } throw new PriceException(es, e); } finally { DatabaseManager.close(ps); ps = null; } }
00
Code Sample 1: public void addGames(List<Game> games) throws StadiumException, SQLException { Connection conn = ConnectionManager.getManager().getConnection(); conn.setAutoCommit(false); PreparedStatement stm = null; ResultSet rs = null; try { for (Game game : games) { stm = conn.prepareStatement(Statements.SELECT_STADIUM); stm.setString(1, game.getStadiumName()); stm.setString(2, game.getStadiumCity()); rs = stm.executeQuery(); int stadiumId = -1; while (rs.next()) { stadiumId = rs.getInt("stadiumID"); } if (stadiumId == -1) throw new StadiumException("No such stadium"); stm = conn.prepareStatement(Statements.INSERT_GAME); stm.setInt(1, stadiumId); stm.setDate(2, game.getGameDate()); stm.setTime(3, game.getGameTime()); stm.setString(4, game.getTeamA()); stm.setString(5, game.getTeamB()); stm.executeUpdate(); int gameId = getMaxId(); List<SectorPrice> sectorPrices = game.getSectorPrices(); for (SectorPrice price : sectorPrices) { stm = conn.prepareStatement(Statements.INSERT_TICKET_PRICE); stm.setInt(1, gameId); stm.setInt(2, price.getSectorId()); stm.setInt(3, price.getPrice()); stm.executeUpdate(); } } } catch (SQLException e) { conn.rollback(); throw e; } finally { rs.close(); stm.close(); } conn.commit(); conn.setAutoCommit(true); } Code Sample 2: public static String getMD5(final String text) { if (null == text) return null; final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } algorithm.reset(); algorithm.update(text.getBytes()); final byte[] digest = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (byte b : digest) { String str = Integer.toHexString(0xFF & b); str = str.length() == 1 ? '0' + str : str; hexString.append(str); } return hexString.toString(); }
00
Code Sample 1: public void importarHistoricoDeProventos(File pArquivoXLS, boolean pFiltrarPelaDataDeCorteDoCabecalho, Andamento pAndamento) throws IOException, SQLException, InvalidFormatException { int iLinha = -1; String nomeDaColuna = ""; Statement stmtLimpezaInicialDestino = null; OraclePreparedStatement stmtDestino = null; try { Workbook arquivo = WorkbookFactory.create(new FileInputStream(pArquivoXLS)); Sheet plan1 = arquivo.getSheetAt(0); int QUANTIDADE_DE_REGISTROS_DE_METADADOS = 2; int quantidadeDeRegistrosEstimada = plan1.getPhysicalNumberOfRows() - QUANTIDADE_DE_REGISTROS_DE_METADADOS; String vNomeDePregao, vTipoDaAcao, vDataDaAprovacao, vTipoDoProvento, vDataDoUltimoPrecoCom; BigDecimal vValorDoProvento, vUltimoPrecoCom, vProventoPorPreco; int vProventoPor1Ou1000Acoes, vPrecoPor1Ou1000Acoes; java.sql.Date vUltimoDiaCom; DateFormat formatadorData = new SimpleDateFormat("yyyyMMdd"); DateFormat formatadorPadraoData = DateFormat.getDateInstance(); Row registro; Cell celula; java.util.Date dataLimite = plan1.getRow(0).getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getDateCellValue(); Cell celulaUltimoDiaCom; java.util.Date tmpUltimoDiaCom; stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_PROVENTO_EM_DINHEIRO"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "INSERT INTO TMP_TB_PROVENTO_EM_DINHEIRO(NOME_DE_PREGAO, TIPO_DA_ACAO, DATA_DA_APROVACAO, VALOR_DO_PROVENTO, PROVENTO_POR_1_OU_1000_ACOES, TIPO_DO_PROVENTO, ULTIMO_DIA_COM, DATA_DO_ULTIMO_PRECO_COM, ULTIMO_PRECO_COM, PRECO_POR_1_OU_1000_ACOES, PERC_PROVENTO_POR_PRECO) VALUES(:NOME_DE_PREGAO, :TIPO_DA_ACAO, :DATA_DA_APROVACAO, :VALOR_DO_PROVENTO, :PROVENTO_POR_1_OU_1000_ACOES, :TIPO_DO_PROVENTO, :ULTIMO_DIA_COM, :DATA_DO_ULTIMO_PRECO_COM, :ULTIMO_PRECO_COM, :PRECO_POR_1_OU_1000_ACOES, :PERC_PROVENTO_POR_PRECO)"; stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportados = 0; final int NUMERO_DA_LINHA_INICIAL = 1; for (iLinha = NUMERO_DA_LINHA_INICIAL; true; iLinha++) { registro = plan1.getRow(iLinha); if (registro != null) { nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.toString(); celulaUltimoDiaCom = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_DIA_COM.ordinal()); if (celulaUltimoDiaCom != null) { if (celulaUltimoDiaCom.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpUltimoDiaCom = celulaUltimoDiaCom.getDateCellValue(); if (tmpUltimoDiaCom.compareTo(dataLimite) <= 0 || !pFiltrarPelaDataDeCorteDoCabecalho) { vUltimoDiaCom = new java.sql.Date(celulaUltimoDiaCom.getDateCellValue().getTime()); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.toString(); vNomeDePregao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.NOME_DE_PREGAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.toString(); vTipoDaAcao = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DA_ACAO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DA_APROVACAO.ordinal()); try { java.util.Date tmpDataDaAprovacao; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDaAprovacao = celula.getDateCellValue(); } else { tmpDataDaAprovacao = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDaAprovacao = formatadorData.format(tmpDataDaAprovacao); } catch (ParseException ex) { vDataDaAprovacao = celula.getStringCellValue(); } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.toString(); vValorDoProvento = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.VALOR_DO_PROVENTO.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.toString(); vProventoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.toString(); vTipoDoProvento = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.TIPO_DO_PROVENTO.ordinal()).getStringCellValue().trim(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.DATA_DO_ULTIMO_PRECO_COM.ordinal()); if (celula != null) { try { java.util.Date tmpDataDoUltimoPrecoCom; if (celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { tmpDataDoUltimoPrecoCom = celula.getDateCellValue(); } else { tmpDataDoUltimoPrecoCom = formatadorPadraoData.parse(celula.getStringCellValue()); } vDataDoUltimoPrecoCom = formatadorData.format(tmpDataDoUltimoPrecoCom); } catch (ParseException ex) { vDataDoUltimoPrecoCom = celula.getStringCellValue().trim(); } } else { vDataDoUltimoPrecoCom = ""; } nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.toString(); vUltimoPrecoCom = new BigDecimal(String.valueOf(registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.ULTIMO_PRECO_COM.ordinal()).getNumericCellValue())); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.toString(); vPrecoPor1Ou1000Acoes = (int) registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PRECO_POR_1_OU_1000_ACOES.ordinal()).getNumericCellValue(); nomeDaColuna = CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.toString(); celula = registro.getCell(CampoDaPlanilhaDosProventosEmDinheiro.PROVENTO_POR_PRECO.ordinal()); if (celula != null && celula.getCellType() == Cell.CELL_TYPE_NUMERIC) { vProventoPorPreco = new BigDecimal(String.valueOf(celula.getNumericCellValue())); } else { vProventoPorPreco = null; } stmtDestino.clearParameters(); stmtDestino.setStringAtName("NOME_DE_PREGAO", vNomeDePregao); stmtDestino.setStringAtName("TIPO_DA_ACAO", vTipoDaAcao); stmtDestino.setStringAtName("DATA_DA_APROVACAO", vDataDaAprovacao); stmtDestino.setBigDecimalAtName("VALOR_DO_PROVENTO", vValorDoProvento); stmtDestino.setIntAtName("PROVENTO_POR_1_OU_1000_ACOES", vProventoPor1Ou1000Acoes); stmtDestino.setStringAtName("TIPO_DO_PROVENTO", vTipoDoProvento); stmtDestino.setDateAtName("ULTIMO_DIA_COM", vUltimoDiaCom); stmtDestino.setStringAtName("DATA_DO_ULTIMO_PRECO_COM", vDataDoUltimoPrecoCom); stmtDestino.setBigDecimalAtName("ULTIMO_PRECO_COM", vUltimoPrecoCom); stmtDestino.setIntAtName("PRECO_POR_1_OU_1000_ACOES", vPrecoPor1Ou1000Acoes); stmtDestino.setBigDecimalAtName("PERC_PROVENTO_POR_PRECO", vProventoPorPreco); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; } } } else { break; } double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } else { break; } } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = pArquivoXLS.getName(); problemaDetalhado.linhaProblematicaDoArquivo = iLinha + 1; problemaDetalhado.colunaProblematicaDoArquivo = nomeDaColuna; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { pAndamento.setPercentualCompleto(100); if (stmtLimpezaInicialDestino != null && (!stmtLimpezaInicialDestino.isClosed())) { stmtLimpezaInicialDestino.close(); } if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } } Code Sample 2: public String quebraLink(String link) throws StringIndexOutOfBoundsException { link = link.replace(".url", ""); int cod = 0; final String linkInit = link.replace("#", ""); boolean estado = false; char letra; String linkOrig; String newlink = ""; linkOrig = link.replace("#", ""); linkOrig = linkOrig.replace(".url", ""); linkOrig = linkOrig.replace(".html", ""); linkOrig = linkOrig.replace("http://", ""); if (linkOrig.contains("clubedodownload")) { for (int i = 7; i < linkInit.length(); i++) { if (linkOrig.charAt(i) == '/') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains("//:ptth")) { newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } else if (newlink.contains("http://")) { if (isValid(newlink)) { return newlink; } } } } } if (linkOrig.contains("protetordelink.tv")) { for (int i = linkOrig.length() - 1; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '/') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } newlink = HexToChar(newlink); if (newlink.contains("ptth")) { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } else { newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if (linkOrig.contains("baixeaquifilmes")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains(":ptth")) { newlink = inverteFrase(newlink); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if (linkOrig.contains("downloadsgratis")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '!') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (precisaRepassar(QuebraLink.decode64(newlink))) { newlink = quebraLink(QuebraLink.decode64(newlink)); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } newlink = ""; if (linkOrig.contains("vinxp")) { System.out.println("é"); for (int i = 1; i < linkOrig.length(); i++) { if (linkOrig.charAt(i) == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } break; } } if (newlink.contains(".vinxp")) { newlink = newlink.replace(".vinxp", ""); } newlink = decodeCifraDeCesar(newlink); System.out.println(newlink); return newlink; } if (linkOrig.contains("?")) { String linkTemporary = ""; newlink = ""; if (linkOrig.contains("go!")) { linkOrig = linkOrig.replace("?go!", "?"); } if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } linkTemporary = QuebraLink.decode64(newlink); break; } } if (linkTemporary.contains("http")) { newlink = ""; for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (linkTemporary.contains("ptth")) { newlink = ""; linkTemporary = inverteFrase(linkTemporary); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } linkTemporary = ""; for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { linkTemporary += linkOrig.charAt(j); } link = QuebraLink.decode64(linkTemporary); break; } } if (link.contains("http")) { newlink = ""; for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == 'h') { for (int j = i; j < link.length(); j++) { newlink += link.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (link.contains("ptth")) { newlink = ""; linkTemporary = inverteFrase(link); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } linkOrig = linkInit; link = linkOrig; newlink = ""; } if (linkOrig.contains("?")) { String linkTemporary = ""; newlink = ""; if (linkOrig.contains("go!")) { linkOrig = linkOrig.replace("?go!", "?"); } if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } linkTemporary = linkTemporary.replace(".", ""); try { linkTemporary = HexToChar(newlink); } catch (Exception e) { System.err.println("erro hex 1º"); estado = true; } break; } } if (linkTemporary.contains("http") && !estado) { newlink = ""; for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (linkTemporary.contains("ptth") && !estado) { newlink = ""; linkTemporary = inverteFrase(linkTemporary); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } estado = false; linkTemporary = ""; for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { linkTemporary += linkOrig.charAt(j); } linkTemporary = linkTemporary.replace(".", ""); try { link = HexToChar(linkTemporary); } catch (Exception e) { System.err.println("erro hex 2º"); estado = true; } break; } } if (link.contains("http") && !estado) { newlink = ""; for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == 'h') { for (int j = i; j < link.length(); j++) { newlink += link.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (link.contains("ptth") && !estado) { newlink = ""; linkTemporary = inverteFrase(link); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } linkOrig = linkInit; link = linkOrig; newlink = ""; } if (linkOrig.contains("?") && !linkOrig.contains("id=") && !linkOrig.contains("url=") && !linkOrig.contains("link=") && !linkOrig.contains("r=http") && !linkOrig.contains("r=ftp")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { newlink = ""; for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains("ptth")) { newlink = inverteFrase(newlink); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if ((link.contains("url=")) || (link.contains("link=")) || (link.contains("?r=http")) || (link.contains("?r=ftp"))) { if (!link.contains("//:ptth")) { for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == '=') { for (int j = i + 1; j < link.length(); j++) { letra = link.charAt(j); newlink += letra; } break; } } if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } if (linkOrig.contains("//:ptth") || linkOrig.contains("//:sptth")) { if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = linkOrig.length() - 1; j > i; j--) { letra = linkOrig.charAt(j); newlink += letra; } break; } } if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } newlink = inverteFrase(linkOrig); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } if (linkOrig.contains("?go!")) { linkOrig = linkOrig.replace("?go!", "?down!"); newlink = linkOrig; if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } if (linkOrig.contains("down!")) { linkOrig = linkOrig.replace("down!", ""); return quebraLink(linkOrig); } newlink = ""; for (int i = linkOrig.length() - 4; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } break; } } String ltmp = ""; try { ltmp = HexToChar(newlink); } catch (Exception e) { System.err.println("erro hex 3º"); } if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = newlink; } ltmp = decode64(newlink); if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { newlink = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = newlink; } try { ltmp = decodeAscii(newlink); } catch (NumberFormatException e) { System.err.println("erro ascii"); } if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = null; } newlink = ""; int cont = 0; letra = '\0'; ltmp = ""; newlink = ""; for (int i = linkOrig.length() - 4; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '=' || letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { if (linkOrig.charAt(j) == '.') { break; } newlink += linkOrig.charAt(j); } break; } } ltmp = newlink; String tmp = ""; String tmp2 = ""; do { try { tmp = HexToChar(ltmp); tmp2 = HexToChar(inverteFrase(ltmp)); if (!tmp.isEmpty() && tmp.length() > 5 && !tmp.contains("") && !tmp.contains("§") && !tmp.contains("�") && !tmp.contains("")) { ltmp = HexToChar(ltmp); } else if (!inverteFrase(tmp2).isEmpty() && inverteFrase(tmp2).length() > 5 && !inverteFrase(tmp2).contains("”") && !inverteFrase(tmp2).contains("§") && !inverteFrase(tmp2).contains("�")) { ltmp = HexToChar(inverteFrase(ltmp)); } } catch (NumberFormatException e) { } tmp = decode64(ltmp); tmp2 = decode64(inverteFrase(ltmp)); if (!tmp.contains("�") && !tmp.contains("ޚ")) { ltmp = decode64(ltmp); } else if (!tmp2.contains("�") && !tmp2.contains("ޚ")) { ltmp = decode64(inverteFrase(ltmp)); } try { tmp = decodeAscii(ltmp); tmp2 = decodeAscii(inverteFrase(ltmp)); if (!tmp.contains("Œ") && !tmp.contains("�") && !tmp.contains("§") && !tmp.contains("½") && !tmp.contains("*") && !tmp.contains("\"") && !tmp.contains("^")) { ltmp = decodeAscii(ltmp); } else if (!tmp2.contains("Œ") && !tmp2.contains("�") && !tmp2.contains("§") && !tmp2.contains("½") && !tmp2.contains("*") && !tmp2.contains("\"") && !tmp2.contains("^")) { ltmp = decodeAscii(inverteFrase(ltmp)); } } catch (NumberFormatException e) { } cont++; if (ltmp.contains("http")) { newlink = ltmp; if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else if (ltmp.contains("ptth")) { newlink = inverteFrase(ltmp); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } while (!isValid(newlink) && cont <= 20); tmp = null; tmp2 = null; ltmp = null; String leitura = ""; try { leitura = readHTML(linkInit); } catch (IOException e) { } leitura = leitura.toLowerCase(); if (leitura.contains("trocabotao")) { newlink = ""; for (int i = leitura.indexOf("trocabotao"); i < leitura.length(); i++) { if (Character.isDigit(leitura.charAt(i))) { int tmpInt = i; while (Character.isDigit(leitura.charAt(tmpInt))) { newlink += leitura.charAt(tmpInt); tmpInt++; } cod = Integer.parseInt(newlink); break; } } if (cod != 0) { for (int i = 7; i < linkInit.length(); i++) { letra = linkInit.charAt(i); if (letra == '/') { newlink = linkInit.substring(0, i + 1) + "linkdiscover.php?cod=" + cod; break; } } DataInputStream dat = null; try { URL url = new URL(newlink); InputStream in = url.openStream(); dat = new DataInputStream(new BufferedInputStream(in)); leitura = ""; int dado; while ((dado = dat.read()) != -1) { letra = (char) dado; leitura += letra; } newlink = leitura.replaceAll(" ", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } catch (MalformedURLException ex) { System.out.println("URL mal formada."); } catch (IOException e) { } finally { try { if (dat != null) { dat.close(); } } catch (IOException e) { System.err.println("Falha ao fechar fluxo."); } } } } if (precisaRepassar(linkInit)) { if (linkInit.substring(8).contains("http")) { newlink = linkInit.substring(linkInit.indexOf("http", 8), linkInit.length()); if (isValid(newlink)) { return newlink; } } } newlink = ""; StringBuffer strBuf = null; try { strBuf = new StringBuffer(readHTML(linkInit)); for (String tmp3 : getLibrary()) { if (strBuf.toString().toLowerCase().contains(tmp3)) { for (int i = strBuf.toString().indexOf(tmp3); i >= 0; i--) { if (strBuf.toString().charAt(i) == '"') { for (int j = i + 1; j < strBuf.length(); j++) { if (strBuf.toString().charAt(j) == '"') { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { newlink += strBuf.toString().charAt(j); } } } } } } } catch (IOException ex) { } GUIQuebraLink.isBroken = false; return "Desculpe o link não pode ser quebrado."; }
11
Code Sample 1: public List<SysSequences> getSeqs() throws Exception { List<SysSequences> list = new ArrayList<SysSequences>(); Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("update ss_sys_sequences set next_value=next_value+step_value"); ps.executeUpdate(); ps.close(); ps = conn.prepareStatement("select * from ss_sys_sequences"); ResultSet rs = ps.executeQuery(); while (rs.next()) { SysSequences seq = new SysSequences(); seq.setTableName(rs.getString(1)); long nextValue = rs.getLong(2); long stepValue = rs.getLong(3); seq.setNextValue(nextValue - stepValue); seq.setStepValue(stepValue); list.add(seq); } rs.close(); ps.close(); conn.commit(); } catch (Exception e) { conn.rollback(); e.printStackTrace(); } finally { try { conn.setAutoCommit(true); } catch (Exception e) { } ConnectUtil.closeConn(conn); } return list; } Code Sample 2: @Override public void run() { Shell currentShell = Display.getCurrent().getActiveShell(); if (DMManager.getInstance().getOntology() == null) return; DataRecordSet data = DMManager.getInstance().getOntology().getDataView().dataset(); InputDialog input = new InputDialog(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.tablename"), data.getRelationName(), null); input.open(); String tablename = input.getValue(); if (tablename == null) return; super.getProfile().connect(); IManagedConnection mc = super.getProfile().getManagedConnection("java.sql.Connection"); java.sql.Connection sql = (java.sql.Connection) mc.getConnection().getRawConnection(); try { sql.setAutoCommit(false); DatabaseMetaData dbmd = sql.getMetaData(); ResultSet tables = dbmd.getTables(null, null, tablename, new String[] { "TABLE" }); if (tables.next()) { if (!MessageDialog.openConfirm(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.overwriteTable"))) return; Statement statement = sql.createStatement(); statement.executeUpdate("DROP TABLE " + tablename); statement.close(); } String createTableQuery = null; for (int i = 0; i < data.getNumAttributes(); i++) { if (DMManager.getInstance().getOntology().isIDAttribute(data.getAttribute(i))) continue; if (createTableQuery == null) createTableQuery = ""; else createTableQuery += ","; createTableQuery += getColumnDefinition(data.getAttribute(i)); } Statement statement = sql.createStatement(); statement.executeUpdate("CREATE TABLE " + tablename + "(" + createTableQuery + ")"); statement.close(); exportRecordSet(data, sql, tablename); sql.commit(); sql.setAutoCommit(true); MessageDialog.openInformation(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.successful")); } catch (SQLException e) { try { sql.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } MessageDialog.openError(currentShell, Resources.I18N.getString("vikamine.dtp.title"), Resources.I18N.getString("vikamine.dtp.export.failed")); e.printStackTrace(); } }
00
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("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static long removePropertyInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, String propriete) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (propriete.equals(Metadata.TITLE)) { coreProperties.setTitle(""); } else if (propriete.equals(Metadata.AUTHOR)) { coreProperties.setCreator(""); } else if (propriete.equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(""); } else if (propriete.equals(Metadata.COMMENTS)) { coreProperties.setDescription(""); } else if (propriete.equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(""); } else if (propriete.equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(""); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(propriete)) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(propriete)) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } } Code Sample 2: public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException { CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key); ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(in, bout); return bout.toByteArray(); }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); try { IOUtils.copy((Reader) null, out); fail(); } catch (NullPointerException ex) { } } Code Sample 2: public byte[] getFile(final String file) throws IOException { if (this.files.contains(file)) { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if ((entry.getName().equals(file)) && (!entry.isDirectory())) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(input, output); output.close(); input.close(); return output.toByteArray(); } } input.close(); } return null; }
11
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: public void merge(VMImage image, VMSnapShot another) throws VMException { if (path == null || another.getPath() == null) throw new VMException("EmuVMSnapShot is NULL!"); logging.debug(LOG_NAME, "merge images " + path + " and " + another.getPath()); File target = new File(path); File src = new File(another.getPath()); if (target.isDirectory() || src.isDirectory()) return; try { FileInputStream in = new FileInputStream(another.getPath()); FileChannel inChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(path, true); FileChannel outChannel = out.getChannel(); outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { throw new VMException(e); } }
11
Code Sample 1: public void applyTo(File source, File target) throws IOException { boolean failed = true; FileInputStream fin = new FileInputStream(source); try { FileChannel in = fin.getChannel(); FileOutputStream fos = new FileOutputStream(target); try { FileChannel out = fos.getChannel(); long pos = 0L; for (Replacement replacement : replacements) { in.transferTo(pos, replacement.pos - pos, out); if (replacement.val != null) out.write(ByteBuffer.wrap(replacement.val)); pos = replacement.pos + replacement.len; } in.transferTo(pos, source.length() - pos, out); failed = false; } finally { fos.close(); if (failed == true) target.delete(); } } finally { fin.close(); } } Code Sample 2: public void postProcess() throws StopWriterVisitorException { shpWriter.postProcess(); try { FileChannel fcinShp = new FileInputStream(fTemp).getChannel(); FileChannel fcoutShp = new FileOutputStream(fileShp).getChannel(); DriverUtilities.copy(fcinShp, fcoutShp); File shxFile = SHP.getShxFile(fTemp); FileChannel fcinShx = new FileInputStream(shxFile).getChannel(); FileChannel fcoutShx = new FileOutputStream(SHP.getShxFile(fileShp)).getChannel(); DriverUtilities.copy(fcinShx, fcoutShx); File dbfFile = getDataFile(fTemp); short originalEncoding = DbfEncodings.getInstance().getDbfIdForCharset(shpWriter.getCharset()); RandomAccessFile fo = new RandomAccessFile(dbfFile, "rw"); fo.seek(29); fo.writeByte(originalEncoding); fo.close(); FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel(); FileChannel fcoutDbf = new FileOutputStream(getDataFile(fileShp)).getChannel(); DriverUtilities.copy(fcinDbf, fcoutDbf); fTemp.delete(); shxFile.delete(); dbfFile.delete(); reload(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } catch (ReloadDriverException e) { throw new StopWriterVisitorException(getName(), e); } }
11
Code Sample 1: public static final String getUniqueKey() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage()); } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { println("Warn: getUniqueKey() " + e); } return digest; } Code Sample 2: public static String crypt(String senha) { String md5 = null; MessageDigest md; try { md = MessageDigest.getInstance(CRYPT_ALGORITHM); md.update(senha.getBytes()); Hex hex = new Hex(); md5 = new String(hex.encode(md.digest())); } catch (NoSuchAlgorithmException e) { logger.error(ResourceUtil.getLOGMessage("_nls.mensagem.geral.log.crypt.no.such.algorithm", CRYPT_ALGORITHM)); } return md5; }
11
Code Sample 1: protected String calcAuthResponse(String challenge) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(securityPolicy); md.update(challenge.getBytes()); for (int i = 0, n = password.length; i < n; i++) { md.update((byte) password[i]); } byte[] digest = md.digest(); StringBuffer digestText = new StringBuffer(); for (int i = 0; i < digest.length; i++) { int v = (digest[i] < 0) ? digest[i] + 256 : digest[i]; String hex = Integer.toHexString(v); if (hex.length() == 1) { digestText.append("0"); } digestText.append(hex); } return digestText.toString(); } Code Sample 2: public String hmacSHA256(String message, byte[] key) { MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new java.lang.AssertionError(this.getClass().getName() + ".hmacSHA256(): SHA-256 algorithm not found!"); } if (key.length > 64) { sha256.update(key); key = sha256.digest(); sha256.reset(); } byte block[] = new byte[64]; for (int i = 0; i < key.length; ++i) block[i] = key[i]; for (int i = key.length; i < block.length; ++i) block[i] = 0; for (int i = 0; i < 64; ++i) block[i] ^= 0x36; sha256.update(block); try { sha256.update(message.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new java.lang.AssertionError("ITunesU.hmacSH256(): UTF-8 encoding not supported!"); } byte[] hash = sha256.digest(); sha256.reset(); for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c); sha256.update(block); sha256.update(hash); hash = sha256.digest(); char[] hexadecimals = new char[hash.length * 2]; for (int i = 0; i < hash.length; ++i) { for (int j = 0; j < 2; ++j) { int value = (hash[i] >> (4 - 4 * j)) & 0xf; char base = (value < 10) ? ('0') : ('a' - 10); hexadecimals[i * 2 + j] = (char) (base + value); } } return new String(hexadecimals); }
00
Code Sample 1: private String send(String method, String contentType, String urlStr, String body) throws MalformedURLException, IOException { HttpURLConnection postCon = (HttpURLConnection) new URL(getUrl(urlStr)).openConnection(); postCon.setRequestMethod(method); postCon.setDoOutput(true); postCon.setDoInput(true); if (cookie != null) { postCon.setRequestProperty("Cookie", cookie); if (contentType != null) { postCon.setRequestProperty("Content-type", contentType); } postCon.setRequestProperty("Content-Length", body == null ? "0" : Integer.toString(body.length())); } if (body != null) { OutputStream os = postCon.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os); out.write(body); out.close(); } InputStream is = null; try { is = postCon.getInputStream(); } catch (IOException ioe) { is = postCon.getErrorStream(); } int resCode = postCon.getResponseCode(); if (resCode == 201 || resCode == 202) { String loc = postCon.getHeaderField("Location"); System.out.println("loc:" + loc); return loc; } StringBuffer sb = StreamUtil.readStream(is); return sb.toString(); } Code Sample 2: public void xtestGetThread() throws Exception { GMSearchOptions options = new GMSearchOptions(); options.setFrom(loginInfo.getUsername() + "*"); options.setSubject("message*"); GMSearchResponse mail = client.getMail(options); for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) { GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next(); GMThread thread = client.getThread(threadSnapshot.getThreadID()); log.info("Most Recent Thread: " + thread); for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) { GMMessage message = (GMMessage) iter.next(); log.info("Message: " + message); Iterable<GMAttachment> attachments = message.getAttachments(); for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) { GMAttachment attachment = (GMAttachment) iterator.next(); String ext = FilenameUtils.getExtension(attachment.getFilename()); if (ext.trim().length() > 0) ext = "." + ext; String base = FilenameUtils.getBaseName(attachment.getFilename()); File file = File.createTempFile(base, ext, new File(System.getProperty("user.home"))); log.info("Saving attachment: " + file.getPath()); InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID()); IOUtils.copy(attStream, new FileOutputStream(file)); attStream.close(); assertEquals(file.length(), attachment.getSize()); log.info("Done. Successfully saved: " + file.getPath()); file.delete(); } } } }
11
Code Sample 1: public static byte[] 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 sha1hash; } Code Sample 2: public void test_digest() throws UnsupportedEncodingException { MessageDigest sha = null; try { sha = MessageDigest.getInstance("SHA"); assertNotNull(sha); } catch (NoSuchAlgorithmException e) { fail("getInstance did not find algorithm"); } sha.update(MESSAGE.getBytes("UTF-8")); byte[] digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST)); sha.reset(); for (int i = 0; i < 63; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_63_As)); sha.reset(); for (int i = 0; i < 64; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_64_As)); sha.reset(); for (int i = 0; i < 65; i++) { sha.update((byte) 'a'); } digest = sha.digest(); assertTrue("bug in SHA", MessageDigest.isEqual(digest, MESSAGE_DIGEST_65_As)); testSerializationSHA_DATA_1(sha); testSerializationSHA_DATA_2(sha); }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); list = (ListView) findViewById(R.id.list); db = new DBAdapter(this); news = new ArrayList<Data>(); adapter = new NewsAdapter(news); list.setAdapter(adapter); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = null; DefaultHandler handler = null; try { parser = factory.newSAXParser(); handler = new DefaultHandler() { Data newsItem; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { Log.d(TAG, qName); if (qName.equals("item")) newsItem = new Data(); if (qName.equals("title")) title = true; if (qName.equals("link")) link = true; if (qName.equals("description")) description = true; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (qName.equals("item")) news.add(newsItem); if (qName.equals("title")) title = false; if (qName.equals("link")) link = false; if (qName.equals("description")) description = false; } @Override public void characters(char ch[], int start, int length) throws SAXException { if (newsItem == null) { return; } if (title) { newsItem.setTitle(new String(ch, start, length)); } if (link) { newsItem.setLink(new String(ch, start, length)); } if (description) { newsItem.setDesc(new String(ch, start, length)); } } }; } catch (ParserConfigurationException e1) { e1.printStackTrace(); } catch (SAXException e1) { e1.printStackTrace(); } Intent siteIntent = getIntent(); String siteurl = siteIntent.getStringExtra("siteurl"); URLConnection connection = null; URL url; try { url = new URL(siteurl); Log.i(TAG, "1"); connection = url.openConnection(); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.i(TAG, "2"); try { parser.parse(connection.getInputStream(), handler); Log.i(TAG, "3"); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } adapter.notifyDataSetChanged(); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapt, View view, int position, long id) { String link; link = news.get(position).getLink(); Intent intent = new Intent(NewsReaderActivity.this, WebViewActivity.class); intent.putExtra("link", link); startActivity(intent); } }); } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
00
Code Sample 1: @SuppressWarnings({ "ProhibitedExceptionDeclared" }) public int run(@NotNull final List<String> args) throws Exception { int returnCode = 0; if (args.size() == 0) { log(Level.SEVERE, "noarguments"); returnCode++; } final byte[] buf = new byte[BUF_SIZE]; for (final String arg : args) { try { final URL url = new URL(arg); final URLConnection con = url.openConnection(); final InputStream in = con.getInputStream(); try { final String location = con.getHeaderField("Content-Location"); final String outputFilename = new File((location != null ? new URL(url, location) : url).getFile()).getName(); log(Level.INFO, "writing", arg, outputFilename); final OutputStream out = new FileOutputStream(outputFilename); try { for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) { out.write(buf, 0, bytesRead); } } finally { out.close(); } } finally { in.close(); } } catch (final IOException e) { log(Level.WARNING, "cannotopen", arg, e); returnCode++; } } return returnCode; } Code Sample 2: private static void ftpTest() { FTPClient f = new FTPClient(); try { f.connect("oscomak.net"); System.out.print(f.getReplyString()); f.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String password = JOptionPane.showInputDialog("Enter password"); if (password == null || password.equals("")) { System.out.println("No password"); return; } try { f.login("oscomak_pointrel", password); System.out.print(f.getReplyString()); } catch (IOException e) { e.printStackTrace(); } try { String workingDirectory = f.printWorkingDirectory(); System.out.println("Working directory: " + workingDirectory); System.out.print(f.getReplyString()); } catch (IOException e1) { e1.printStackTrace(); } try { f.enterLocalPassiveMode(); System.out.print(f.getReplyString()); System.out.println("Trying to list files"); String[] fileNames = f.listNames(); System.out.print(f.getReplyString()); System.out.println("Got file list fileNames: " + fileNames.length); for (String fileName : fileNames) { System.out.println("File: " + fileName); } System.out.println(); System.out.println("done reading stream"); System.out.println("trying alterative way to read stream"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); f.retrieveFile(fileNames[0], outputStream); System.out.println("size: " + outputStream.size()); System.out.println(outputStream.toString()); System.out.println("done with alternative"); System.out.println("Trying to store file back"); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); boolean storeResult = f.storeFile("test.txt", inputStream); System.out.println("Done storing " + storeResult); f.disconnect(); System.out.print(f.getReplyString()); System.out.println("disconnected"); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String version = req.getParameter("version"); String cdn = req.getParameter("cdn"); String dependencies = req.getParameter("dependencies"); String optimize = req.getParameter("optimize"); String cacheFile = null; String result = null; boolean isCached = false; Boolean isError = true; if (!version.equals("1.3.2")) { result = "invalid version: " + version; } if (!cdn.equals("google") && !cdn.equals("aol")) { result = "invalide CDN type: " + cdn; } if (!optimize.equals("comments") && !optimize.equals("shrinksafe") && !optimize.equals("none") && !optimize.equals("shrinksafe.keepLines")) { result = "invalid optimize type: " + optimize; } if (!dependencies.matches("^[\\w\\-\\,\\s\\.]+$")) { result = "invalid dependency list: " + dependencies; } try { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { result = e.getMessage(); } if (result == null) { md.update(dependencies.getBytes()); String digest = (new BASE64Encoder()).encode(md.digest()).replace('+', '~').replace('/', '_').replace('=', '_'); cacheFile = cachePath + "/" + version + "/" + cdn + "/" + digest + "/" + optimize + ".js"; File file = new File(cacheFile); if (file.exists()) { isCached = true; isError = false; } } if (result == null && !isCached) { BuilderContextAction contextAction = new BuilderContextAction(builderPath, version, cdn, dependencies, optimize); ContextFactory.getGlobal().call(contextAction); Exception exception = contextAction.getException(); if (exception != null) { result = exception.getMessage(); } else { result = contextAction.getResult(); FileUtil.writeToFile(cacheFile, result, null, true); isError = false; } } } catch (Exception e) { result = e.getMessage(); } res.setCharacterEncoding("utf-8"); if (isError) { result = result.replaceAll("\\\"", "\\\""); result = "<html><head><script type=\"text/javascript\">alert(\"" + result + "\");</script></head><body></body></html>"; PrintWriter writer = res.getWriter(); writer.append(result); } else { res.setHeader("Content-Type", "application/x-javascript"); res.setHeader("Content-disposition", "attachment; filename=dojo.js"); res.setHeader("Content-Encoding", "gzip"); File file = new File(cacheFile); BufferedInputStream in = new java.io.BufferedInputStream(new DataInputStream(new FileInputStream(file))); OutputStream out = res.getOutputStream(); byte[] bytes = new byte[64000]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = in.read(bytes); if (bytesRead != -1) { out.write(bytes, 0, bytesRead); } } } } Code Sample 2: public static String getMD5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.toLowerCase().getBytes()); return HexString.bufferToHex(md5.digest()); } catch (NoSuchAlgorithmException e) { System.err.println("Error grave al inicializar MD5"); e.printStackTrace(); return "!!"; } }
00
Code Sample 1: List HttpPost(URL url, List requestList) throws IOException { List responseList = new ArrayList(); URLConnection con; BufferedReader in; OutputStreamWriter out; StringBuffer req; String line; logInfo("HTTP POST: " + url); con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); out = new OutputStreamWriter(con.getOutputStream()); req = new StringBuffer(); for (int i = 0, n = requestList.size(); i < n; i++) { if (i != 0) req.append("&"); req.append(((HttpHeader) requestList.get(i)).key); req.append("="); if (((HttpHeader) requestList.get(i)).unicode) { StringBuffer tmp = new StringBuffer(200); byte[] uniBytes = ((HttpHeader) requestList.get(i)).value.getBytes("UnicodeBigUnmarked"); for (int j = 0; j < uniBytes.length; j++) tmp.append(Integer.toHexString(uniBytes[j]).length() == 1 ? "0" + Integer.toHexString(uniBytes[j]) : Integer.toHexString(uniBytes[j])); req.append(tmp.toString().replaceAll("ff", "")); } else req.append(((HttpHeader) requestList.get(i)).value); } out.write(req.toString()); out.flush(); out.close(); in = new BufferedReader(new InputStreamReader((con.getInputStream()))); while ((line = in.readLine()) != null) responseList.add(line); in.close(); return responseList; } Code Sample 2: public static String hashClientPassword(String algorithm, String password, String salt) throws IllegalArgumentException, DruidSafeRuntimeException { if (algorithm == null) { throw new IllegalArgumentException("THE ALGORITHM MUST NOT BE NULL"); } if (password == null) { throw new IllegalArgumentException("THE PASSWORD MUST NOT BE NULL"); } if (salt == null) { salt = ""; } String result = null; try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(password.getBytes()); md.update(salt.getBytes()); result = SecurityHelper.byteArrayToHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new DruidSafeRuntimeException(e); } return result; }
00
Code Sample 1: public static void executeUpdate(Database db, String... statements) throws SQLException { Connection con = null; Statement stmt = null; try { con = getConnection(db); con.setAutoCommit(false); stmt = con.createStatement(); for (String statement : statements) { stmt.executeUpdate(statement); } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { } throw e; } finally { closeStatement(stmt); closeConnection(con); } } Code Sample 2: private static void setEnvEntry(File fromEAR, File toEAR, String ejbJarName, String envEntryName, String envEntryValue) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEAR)); FileOutputStream fos = new FileOutputStream(toEAR); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals(ejbJarName)) { content = editEJBJAR(next, content, envEntryName, envEntryValue); next = new ZipEntry(ejbJarName); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); }
11
Code Sample 1: public void testReaderWriterF2() throws Exception { String inFile = "test_data/mri.png"; String outFile = "test_output/mri__smooth_testReaderWriter.mhd"; itkImageFileReaderF2_Pointer reader = itkImageFileReaderF2.itkImageFileReaderF2_New(); itkImageFileWriterF2_Pointer writer = itkImageFileWriterF2.itkImageFileWriterF2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); } Code Sample 2: public static void copieFichier(File fichier1, File fichier2) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fichier1).getChannel(); out = new FileOutputStream(fichier2).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
11
Code Sample 1: public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) { try { if (password == null) { password = ""; } MessageDigest md5 = MessageDigest.getInstance("MD5"); int digLen = md5.getDigestLength(); byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen]; int cnt = 0; while (cnt < keyLen) { md5.update(password.getBytes()); if (cnt > 0) { md5.update(buf, 0, cnt); } md5.digest(buf, cnt, digLen); cnt += digLen; } byte[] key = new byte[keyLen]; System.arraycopy(buf, 0, key, 0, keyLen); return key; } catch (Exception e) { throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e); } } Code Sample 2: private String hashPassword(String password) { if (password != null && password.trim().length() > 0) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.trim().getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } } return null; }
00
Code Sample 1: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); } Code Sample 2: protected final Properties getResourceProperties(Long id, String baseURL) { try { URL url = getClass().getResource(baseURL + id + ".properties"); if (url == null) { url = new URL(baseURL + id + ".properties"); } Properties props = new Properties(); InputStream is = url.openStream(); props.load(is); is.close(); return props; } catch (IOException e) { e.printStackTrace(); return null; } }
00
Code Sample 1: public static byte[] computeMD5(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(s.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } } Code Sample 2: private String getSearchResults(String id) { try { final URL url = new URL("http://www.jaap.nl/api/jaapAPI.do?clientId=iPhone&limit=5&request=details&id=" + id + "&format=JSON&field=street_nr&field=zip&field=city&field=price&field=thumb&field=since&field=houseType&field=area&field=rooms&field=id"); final StringBuilder builder = new StringBuilder(); final BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream())); String s = ""; while ((s = rd.readLine()) != null) { builder.append(s); } rd.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
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: 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(); } }
00
Code Sample 1: private void callbackWS(String xmlControl, String ws_results, long docId) { SimpleProvider config; Service service; Object ret; Call call; Object[] parameter; String method; String wsurl; URL url; NodeList delegateNodes; Node actualNode; InputSource xmlcontrolstream; try { xmlcontrolstream = new InputSource(new StringReader(xmlControl)); delegateNodes = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_CALLBACK); actualNode = delegateNodes.item(0); wsurl = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_URL); method = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_METHOD); if (wsurl == null || method == null) { System.out.println("----- Did not get method or wsurl from the properties! -----"); return; } url = new java.net.URL(wsurl); try { url.openConnection().connect(); } catch (IOException ex) { System.out.println("----- Could not connect to the webservice! -----"); } Vector v_param = new Vector(); v_param.add(ws_results); v_param.add(new Long(docId)); parameter = v_param.toArray(); config = new SimpleProvider(); config.deployTransport("http", new HTTPSender()); service = new Service(config); call = (Call) service.createCall(); call.setTargetEndpointAddress(url); call.setOperationName(new QName("http://schemas.xmlsoap.org/soap/encoding/", method)); try { ret = call.invoke(parameter); if (ret == null) { ret = new String("No response from callback function!"); } System.out.println("Callback function returned: " + ret); } catch (RemoteException ex) { System.out.println("----- Could not invoke the method! -----"); } } catch (Exception ex) { ex.printStackTrace(System.err); } } Code Sample 2: private void getRandomGUID(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } }
00
Code Sample 1: public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); } Code Sample 2: public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
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: private static boolean unzipWithWarning(File source, File targetDirectory, OverwriteValue policy) { try { if (!source.exists()) return false; ZipInputStream input = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry = null; byte[] buffer = new byte[1024]; while ((zipEntry = input.getNextEntry()) != null) { if (zipEntry.isDirectory()) continue; File newFile = new File(targetDirectory, zipEntry.getName()); if (newFile.exists()) { switch(policy.value) { case NO_TO_ALL: continue; case YES_TO_ALL: break; default: switch(policy.value = confirmOverwrite(zipEntry.getName())) { case NO_TO_ALL: case NO: continue; default: } } } newFile.getParentFile().mkdirs(); int bytesRead; FileOutputStream output = new FileOutputStream(newFile); while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead); output.close(); input.closeEntry(); } input.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
00
Code Sample 1: public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public Document getWsdlDomResource(String aResourceName) throws SdlException { logger.debug("getWsdlDomResource() " + aResourceName); InputStream in = null; try { URL url = getDeploymentContext().getResourceURL(aResourceName); if (url == null) { logger.error("url is null"); return null; } else { logger.debug("loading wsdl document " + aResourceName); in = url.openStream(); return getSdlParser().loadWsdlDocument(in, null); } } catch (Throwable t) { logger.error("Error: " + t + " for " + aResourceName); throw new SdlDeploymentException(MessageFormat.format("unable to load: {0} from {1}", new Object[] { aResourceName, getDeploymentContext().getDeploymentLocation() }), t); } finally { SdlCloser.close(in); } }
11
Code Sample 1: private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); } Code Sample 2: public static File copyFile(File file) { File src = file; File dest = new File(src.getName()); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
11
Code Sample 1: public static File[] splitFile(FileValidator validator, File source, long target_length, File todir, String prefix) { if (target_length == 0) return null; if (todir == null) { todir = new File(System.getProperty("java.io.tmpdir")); } if (prefix == null || prefix.equals("")) { prefix = source.getName(); } Vector result = new Vector(); FileOutputStream fos = null; FileInputStream fis = null; try { fis = new FileInputStream(source); byte[] bytes = new byte[CACHE_SIZE]; long current_target_size = 0; int current_target_nb = 1; int nbread = -1; try { File f = new File(todir, prefix + i18n.getString("targetname_suffix") + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); while ((nbread = fis.read(bytes)) > -1) { if ((current_target_size + nbread) > target_length) { int limit = (int) (target_length - current_target_size); fos.write(bytes, 0, limit); fos.close(); current_target_nb++; current_target_size = 0; f = new File(todir, prefix + "_" + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); fos.write(bytes, limit, nbread - limit); current_target_size += nbread - limit; } else { fos.write(bytes, 0, nbread); current_target_size += nbread; } } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } try { if (fis != null) fis.close(); } catch (IOException e) { } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } File[] fresult = null; if (result.size() > 0) { fresult = new File[result.size()]; fresult = (File[]) result.toArray(fresult); } return fresult; } 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(); } }
00
Code Sample 1: public static boolean update(String user, String pass, String channelString, String globalIP) { FTPClient ftp = new FTPClient(); int reply; try { ftp.connect("witna.co.uk", 21); ftp.login(user, pass); reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { updateChannelList(ftp, channelString); if (!ipUpdated) { ipUpdated = updateMasterChannelIP(ftp, globalIP); } ftp.disconnect(); return true; } else { ftp.disconnect(); } } catch (Exception ex) { ex.printStackTrace(); } return false; } Code Sample 2: @Override public InputStream getInputStream() { String url = resourceURL_; try { return new URL(url).openStream(); } catch (Exception e) { } try { return new FileInputStream("/" + url); } catch (Exception e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public void connect(String ftpHost, int ftpPort, String ftpUser, String ftpPwd) throws IOException { ftpClient = new FTPClient(); ftpClient.setReaderThread(false); if (ftpPort == -1) ftpClient.connect(ftpHost); else ftpClient.connect(ftpHost, ftpPort); logger.info("FTP Connection Successful: " + ftpHost); ftpClient.login(ftpUser, ftpPwd); } Code Sample 2: private String getXml(String url) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); String results = null; if (entity != null) { long len = entity.getContentLength(); if (len != -1 && len < 2048) { results = EntityUtils.toString(entity); } else { } } return (results); }
00
Code Sample 1: private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); try { data = Data.valueOf(md.digest()); response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); ID = response.getWord(); registerSettings(); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } } Code Sample 2: public int instantiate(int objectId, String description) throws FidoDatabaseException, ObjectNotFoundException, ClassLinkTypeNotFoundException { try { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { String sql = "insert into Objects (Description) " + "values ('" + description + "')"; conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, objectId) == false) throw new ObjectNotFoundException(objectId); stmt.executeUpdate(sql); int id; sql = "select currval('objects_objectid_seq')"; rs = stmt.executeQuery(sql); if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1); ObjectLinkTable objectLinkList = new ObjectLinkTable(); objectLinkList.linkObjects(stmt, id, "instance", objectId); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } }
11
Code Sample 1: static final String md5(String text) throws RtmApiException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("UTF-8"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RtmApiException("Md5 error: NoSuchAlgorithmException - " + e.getMessage()); } catch (UnsupportedEncodingException e) { throw new RtmApiException("Md5 error: UnsupportedEncodingException - " + e.getMessage()); } } Code Sample 2: private void getRandomGuid(boolean secure) { MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = secureRandom.nextLong(); } else { rand = random.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); String valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } guid = sb.toString(); }
00
Code Sample 1: private Store openConnection(String url) throws MessagingException { URLName urlName = new URLName(url); log.debug("opening " + urlName.getProtocol() + " conection to " + urlName.getHost()); Properties props = new Properties(); Session session = Session.getDefaultInstance(props); Store store = session.getStore(urlName); store.connect(); return store; } Code Sample 2: public static void main(String[] args) { if (args.length != 3) { System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>"); System.exit(1); } try { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream in = new FileInputStream(args[1]); int len = 0; byte buf[] = new byte[1024]; while ((len = in.read(buf)) > 0) os.write(buf, 0, len); in.close(); os.close(); byte[] data = null; if (args[0].equals("dec")) data = decode(os.toString()); else { String strData = encode(os.toByteArray()); data = strData.getBytes(); } FileOutputStream fos = new FileOutputStream(args[2]); fos.write(data); fos.close(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public String decrypt(String text, String passphrase, int keylen) { RC2ParameterSpec parm = new RC2ParameterSpec(keylen); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes(getCharset())); SecretKeySpec skeySpec = new SecretKeySpec(md.digest(), "RC2"); Cipher cipher = Cipher.getInstance("RC2/ECB/NOPADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, parm); byte[] dString = Base64.decode(text); byte[] d = cipher.doFinal(dString); String clearTextNew = decodeBytesNew(d); return clearTextNew; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: public static void main(String[] args) throws IOException { System.out.println("start"); URL url = new URL("https://spreadsheets.google.com/feeds/list/" + "0AnoMCh3_x82sdERLR3FvVDBIWXpjT1JlcENmOFdERVE/" + "od7/public/basic"); InputStream is = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { String[] mass = line.split("<entry>"); for (String m : mass) { System.out.println(m); } } }
00
Code Sample 1: private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } } Code Sample 2: public static void assertEquals(String xmlpath, Object actualObject) throws Exception { InputStreamReader isr; try { isr = new FileReader(xmlpath); } catch (FileNotFoundException e) { URL url = AssertHelper.class.getClassLoader().getResource(xmlpath); if (null != url) { try { isr = new InputStreamReader(url.openStream()); } catch (Exception e1) { throw new AssertionFailedError("Unable to find output xml : " + xmlpath); } } else { throw new AssertionFailedError("Could not read output xml : " + xmlpath); } } DOMParser parser = new DOMParser(); parser.parse(new InputSource(isr)); Document document = parser.getDocument(); try { assertEqual(document.getDocumentElement(), actualObject); } catch (AssertionFailedError e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } AssertionFailedError a = new AssertionFailedError(sbf.toString()); a.setStackTrace(e.getStackTrace()); throw a; } catch (Exception e) { String message = null; if (null != e.getCause()) { message = e.getCause().getMessage(); } else { message = e.getMessage(); } StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath); Iterator iter = nodestack.iterator(); while (iter.hasNext()) { sbf.append(" -> " + ((Object[]) iter.next())[0]); iter.remove(); } Exception ex = new Exception(sbf.toString()); ex.setStackTrace(e.getStackTrace()); throw ex; } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private static String readUrl(String filePath, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; InputStream is = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); is = uc.getInputStream(); chunkLength = uc.getContentLength(); if (chunkLength <= 0) chunkLength = 1024; if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { if (registeredStreams.containsKey(filePath)) { is = registeredStreams.get(filePath); chunkLength = 4096; } else { File f = new File(filePath); long length = f.length(); chunkLength = (int) length; if (chunkLength != length) throw new IOException("Too big file size: " + length); if (chunkLength == 0) { return ""; } is = new FileInputStream(f); } } Reader r; if (charCoding == null) { r = new InputStreamReader(is); } else { r = new InputStreamReader(is, charCoding); } return readReader(r, chunkLength); } finally { if (is != null) is.close(); } }
11
Code Sample 1: private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: 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); } }
11
Code Sample 1: @Override protected void service(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { res.setHeader("X-Generator", "VisualMon"); String path = req.getPathInfo(); if (null == path || "".equals(path)) res.sendRedirect(req.getServletPath() + "/"); else if ("/chart".equals(path)) { try { res.setHeader("Cache-Control", "private,no-cache,no-store,must-revalidate"); res.addHeader("Cache-Control", "post-check=0,pre-check=0"); res.setHeader("Expires", "Sat, 26 Jul 1997 05:00:00 GMT"); res.setHeader("Pragma", "no-cache"); res.setDateHeader("Expires", 0); renderChart(req, res); } catch (InterruptedException e) { log.info("Chart generation was interrupted", e); Thread.currentThread().interrupt(); } } else if (path.startsWith("/log_")) { String name = path.substring(5); LogProvider provider = null; for (LogProvider prov : cfg.getLogProviders()) { if (name.equals(prov.getName())) { provider = prov; break; } } if (null == provider) { log.error("Log provider with name \"{}\" not found", name); res.sendError(HttpServletResponse.SC_NOT_FOUND); } else { render(res, provider.getLog(filter.getLocale())); } } else if ("/".equals(path)) { List<LogEntry> logs = new ArrayList<LogEntry>(); for (LogProvider provider : cfg.getLogProviders()) logs.add(new LogEntry(provider.getName(), provider.getTitle(filter.getLocale()))); render(res, new ProbeDataList(filter.getSnapshot(), filter.getAlerts(), logs, ResourceBundle.getBundle("de.frostcode.visualmon.stats", filter.getLocale()).getString("category.empty"), cfg.getDashboardTitle().get(filter.getLocale()))); } else { URL url = Thread.currentThread().getContextClassLoader().getResource(getClass().getPackage().getName().replace('.', '/') + req.getPathInfo()); if (null == url) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } res.setDateHeader("Last-Modified", new File(url.getFile()).lastModified()); res.setDateHeader("Expires", new Date().getTime() + YEAR_IN_SECONDS * 1000L); res.setHeader("Cache-Control", "max-age=" + YEAR_IN_SECONDS); URLConnection conn = url.openConnection(); String resourcePath = url.getPath(); String contentType = conn.getContentType(); if (resourcePath.endsWith(".xsl")) { contentType = "text/xml"; res.setCharacterEncoding(ENCODING); } if (contentType == null || "content/unknown".equals(contentType)) { if (resourcePath.endsWith(".css")) contentType = "text/css"; else contentType = getServletContext().getMimeType(resourcePath); } res.setContentType(contentType); res.setContentLength(conn.getContentLength()); OutputStream out = res.getOutputStream(); IOUtils.copy(conn.getInputStream(), out); IOUtils.closeQuietly(conn.getInputStream()); IOUtils.closeQuietly(out); } } Code Sample 2: private static boolean prepareProbeFile(String completePath, String outputFile) { try { File inFile = new File(completePath + fSep + "probe.txt"); FileChannel inC = new FileInputStream(inFile).getChannel(); BufferedReader br = new BufferedReader(new FileReader(inFile)); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + outputFile); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); boolean endOfFile = true; short movieName = 0; int customer = 0; while (endOfFile) { String line = br.readLine(); if (line != null) { if (line.indexOf(":") >= 0) { movieName = new Short(line.substring(0, line.length() - 1)).shortValue(); } else { customer = new Integer(line).intValue(); ByteBuffer outBuf = ByteBuffer.allocate(6); outBuf.putShort(movieName); outBuf.putInt(customer); outBuf.flip(); outC.write(outBuf); } } else endOfFile = false; } br.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
00
Code Sample 1: public Object execute(Connection connection) throws JAXRException { RegistryObject registryObject = connection.getRegistryService().getBusinessQueryManager().getRegistryObject(id); if (registryObject instanceof ExtrinsicObject) { ExtrinsicObject extrinsicObject = (ExtrinsicObject) registryObject; DataHandler dataHandler = extrinsicObject.getRepositoryItem(); if (dataHandler != null) { response.setContentType("text/html"); try { PrintWriter out = response.getWriter(); InputStream is = dataHandler.getInputStream(); try { final XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("div"); xmlStreamWriter.writeStartElement("textarea"); xmlStreamWriter.writeAttribute("name", "repositoryItem"); xmlStreamWriter.writeAttribute("class", "xml"); xmlStreamWriter.writeAttribute("style", "display:none"); IOUtils.copy(new XmlInputStreamReader(is), new XmlStreamTextWriter(xmlStreamWriter)); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("script"); xmlStreamWriter.writeAttribute("class", "javascript"); xmlStreamWriter.writeCharacters("dp.SyntaxHighlighter.HighlightAll('repositoryItem');"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } finally { is.close(); } } catch (Throwable ex) { log.error("Error while trying to format repository item " + id, ex); } } else { } } else { } return null; } Code Sample 2: protected Connection openRelativeFile(String file) throws IOException { if (cachedBits == null) { cachedBits = new ByteArray(url.openConnection().getInputStream()).getBytes(); } ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(cachedBits)); ZipEntry zentry; while (true) { zentry = zin.getNextEntry(); if (zentry == null) { throw new IOException("Couldn't find resource " + file + " in ZIP-file"); } if (zentry.getName().equals(file)) { return new Connection(zin, zentry.getSize()); } } }
11
Code Sample 1: public void copy(File source, File dest) throws IOException { System.out.println("copy " + source + " -> " + dest); FileInputStream in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { out.close(); } } finally { in.close(); } } Code Sample 2: public AssessmentItemType getAssessmentItemType(String filename) { if (filename.contains(" ") && (System.getProperty("os.name").contains("Windows"))) { File source = new File(filename); String tempDir = System.getenv("TEMP"); File dest = new File(tempDir + "/temp.xml"); MQMain.logger.info("Importing from " + dest.getAbsolutePath()); 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); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } filename = tempDir + "/temp.xml"; } } AssessmentItemType assessmentItemType = null; JAXBElement<?> jaxbe = null; try { XMLReader reader = XMLReaderFactory.createXMLReader(); ChangeNamespace convertfromv2p0tov2p1 = new ChangeNamespace(reader, "http://www.imsglobal.org/xsd/imsqti_v2p0", "http://www.imsglobal.org/xsd/imsqti_v2p1"); SAXSource source = null; try { FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = null; try { isr = new InputStreamReader(fis, "UTF-8"); } catch (UnsupportedEncodingException e) { } InputSource is = new InputSource(isr); source = new SAXSource(convertfromv2p0tov2p1, is); } catch (FileNotFoundException e) { MQMain.logger.error("SAX/getAssessmentItemType/file not found"); } jaxbe = (JAXBElement<?>) MQModel.qtiCf.unmarshal(MQModel.imsqtiUnmarshaller, source); assessmentItemType = (AssessmentItemType) jaxbe.getValue(); } catch (JAXBException e) { MQMain.logger.error("JAX/getAssessmentItemType", e); } catch (SAXException e) { MQMain.logger.error("SAX/getAssessmentItemType", e); } return assessmentItemType; }
00
Code Sample 1: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (doAuth(request, response)) { Connection conn = null; try { int UID = icsm.getIntChatSession(request).getUID(); conn = getJDBCConnection(icsm.getHeavyDatabaseConnectionPool(), request, response, HttpServletResponse.SC_SERVICE_UNAVAILABLE); if (conn == null) return; ResultSet rs = IntChatDatabaseOperations.executeQuery(conn, "SELECT id FROM ic_messagetypes WHERE templatename='" + IntChatConstants.MessageTemplates.IC_FILES + "' LIMIT 1"); if (rs.next()) { int fileTypeID = rs.getInt("id"); String recipients = request.getHeader(IntChatConstants.HEADER_FILERECIPIENTS); rs.getStatement().close(); rs = null; if (recipients != null) { HashMap<String, String> hm = Tools.parseMultiparamLine(request.getHeader("Content-Disposition")); String fileName = URLDecoder.decode(hm.get("filename"), IntChatServerDefaults.ENCODING); long fileLength = (request.getHeader("Content-Length") != null ? Long.parseLong(request.getHeader("Content-Length")) : -1); fileLength = (request.getHeader(IntChatConstants.HEADER_FILELENGTH) != null ? Long.parseLong(request.getHeader(IntChatConstants.HEADER_FILELENGTH)) : fileLength); long maxFileSize = RuntimeParameters.getIntValue(ParameterNames.MAX_FILE_SIZE) * 1048576; if (maxFileSize > 0 && fileLength > maxFileSize) { request.getInputStream().close(); response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE); return; } long now = System.currentTimeMillis(); long nextid = ic_messages_id_seq.nextval(); IntChatServletInputStream in = new IntChatServletInputStream(request); IntChatMessage icm = null; conn.setAutoCommit(false); try { PreparedStatement ps = conn.prepareStatement("INSERT INTO ic_messages (id, tid, mhead, mbody, mdate, sid) VALUES (?, ?, ?, ?, ?, ?)"); ps.setLong(1, nextid); ps.setInt(2, fileTypeID); ps.setString(3, fileName); ps.setString(4, Long.toString(fileLength)); ps.setLong(5, now); ps.setInt(6, UID); ps.executeUpdate(); ps.close(); if (!insertBLOB(conn, in, fileLength, nextid, maxFileSize)) { conn.rollback(); return; } icm = new IntChatMessage(false, fileTypeID, null, null); String[] id = recipients.split(","); int id1; for (int i = 0; i < id.length; i++) { id1 = Integer.parseInt(id[i].trim()); IntChatDatabaseOperations.executeUpdate(conn, "INSERT INTO ic_recipients (mid, rid) VALUES ('" + nextid + "', '" + id1 + "')"); icm.addTo(id1); } conn.commit(); } catch (Exception e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } if (icm != null) { icm.setID(nextid); icm.setDate(new Timestamp(now - TimeZone.getDefault().getOffset(now))); icm.setFrom(UID); icm.setHeadText(fileName); icm.setBodyText(Long.toString(fileLength)); icsm.onClientSentMessage(icm); } response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } if (rs != null) { rs.getStatement().close(); rs = null; } } catch (RetryRequest rr) { throw rr; } catch (Exception e) { Tools.makeErrorResponse(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { try { if (conn != null) icsm.getHeavyDatabaseConnectionPool().releaseConnection(conn); } catch (Exception e) { } } } } Code Sample 2: public String sruRead(String initialURL) { out('\n'); out(" trying: "); out(initialURL); out('\n'); numTests++; URL url = null; try { url = new URL(initialURL); } catch (java.net.MalformedURLException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { out("</pre><pre class='red'>"); out("test failed: using URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } String contentType = huc.getContentType(); if (contentType == null || (contentType.indexOf("text/xml") < 0 && contentType.indexOf("application/xml") < 0)) { out(" ** Warning: Content-Type not set to text/xml or application/xml"); out('\n'); out(" Content-type: "); out(contentType); out('\n'); numWarns++; } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: opening URL: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading first line of response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine == null) { out("</pre><pre class='red'>"); out("test failed: No input read from URL"); out('\n'); out("</pre><pre>"); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); while (inputLine.length() == 0) inputLine = in.readLine(); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } if (inputLine.startsWith("<?xml-stylesheet ")) { offset = inputLine.indexOf("href="); href = (inputLine.substring(inputLine.indexOf("href=") + 6)); href = href.substring(0, href.indexOf('"')); transformer = (Transformer) transformers.get(href); if (stylesheets.get(href) == null) try { out(" reading stylesheet: "); out(href); out('\n'); out(" from source: "); out(url.toString()); out('\n'); StreamSource source = new StreamSource(url.toString()); TransformerFactory tFactory = TransformerFactory.newInstance(); Source stylesht = tFactory.getAssociatedStylesheet(source, null, null, null); transformer = tFactory.newTransformer(stylesht); transformers.put(href, transformer); } catch (Exception e) { e.printStackTrace(); out("</pre><pre class='red'>"); out("unable to load stylesheet: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); } stylesheets.put(href, href); } else content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { out("</pre><pre class='red'>"); out("test failed: reading response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); out(" successfully applied stylesheet '"); out(href); out("'"); out('\n'); } catch (javax.xml.transform.TransformerException e) { out("</pre><pre class='red'>"); out("unable to apply stylesheet '"); out(href); out("'to response: "); out(e.getMessage()); out('\n'); out("</pre><pre>"); e.printStackTrace(); } } return contentStr; }
00
Code Sample 1: @Override public void excluir(QuestaoMultiplaEscolha q) throws Exception { PreparedStatement stmt = null; String sql = "DELETE FROM questao WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); } catch (SQLException e) { conexao.rollback(); throw e; } } Code Sample 2: public Document parse(Document document) { CSSCompilerBuilder compilerBuilder = new CSSCompilerBuilder(); StyleSheetCompilerFactory compilerFactory = getStyleSheetCompilerFactory(); compilerBuilder.setStyleSheetCompilerFactory(compilerFactory); CSSCompiler cssCompiler = compilerBuilder.getCSSCompiler(); CompiledStyleSheet defaultCompiledStyleSheet; try { URL url = getClass().getResource("/com/volantis/mcs/runtime/default.css"); InputStream stream = url.openStream(); defaultCompiledStyleSheet = cssCompiler.compile(new InputStreamReader(stream), null); } catch (IOException e) { throw new ExtendedRuntimeException(e); } StylingFactory stylingFactory = StylingFactory.getDefaultInstance(); StylingEngine stylingEngine = stylingFactory.createStylingEngine(new InlineStyleSheetCompilerFactory(StylingFunctions.getResolver())); stylingEngine.pushStyleSheet(defaultCompiledStyleSheet); DocumentStyler styler = new DocumentStyler(stylingEngine, XDIMESchemata.CDM_NAMESPACE); styler.style(document); DOMWalker walker = new DOMWalker(new WalkingDOMVisitorStub() { public void visit(Element element) { if (element.getStyles() == null) { throw new IllegalArgumentException("element " + element.getName() + " has no styles"); } } }); walker.walk(document); DOMTransformer transformer = new DeferredInheritTransformer(); document = transformer.transform(null, document); return document; }
00
Code Sample 1: private Store openConnection(String url) throws MessagingException { URLName urlName = new URLName(url); log.debug("opening " + urlName.getProtocol() + " conection to " + urlName.getHost()); Properties props = new Properties(); Session session = Session.getDefaultInstance(props); Store store = session.getStore(urlName); store.connect(); return store; } Code Sample 2: private void parseXmlFile() throws IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); if (file != null) { dom = db.parse(file); } else { dom = db.parse(url.openStream()); } } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } }
00
Code Sample 1: private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; } Code Sample 2: public void concatFiles() throws IOException { Writer writer = null; try { final File targetFile = new File(getTargetDirectory(), getTargetFile()); targetFile.getParentFile().mkdirs(); if (null != getEncoding()) { getLog().info("Writing aggregated file with encoding '" + getEncoding() + "'"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), getEncoding())); } else { getLog().info("WARNING: writing aggregated file with system encoding"); writer = new FileWriter(targetFile); } for (File file : getFiles()) { Reader reader = null; try { if (null != getEncoding()) { getLog().info("Reading file " + file.getCanonicalPath() + " with encoding '" + getEncoding() + "'"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding())); } else { getLog().info("WARNING: Reading file " + file.getCanonicalPath() + " with system encoding"); reader = new FileReader(file); } IOUtils.copy(reader, writer); final String delimiter = getDelimiter(); if (delimiter != null) { writer.write(delimiter.toCharArray()); } } finally { IOUtils.closeQuietly(reader); } } } finally { IOUtils.closeQuietly(writer); } }
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 void copyImage(String from, String to) { File inputFile = new File(from); File outputFile = new File(to); try { if (inputFile.canRead()) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); byte[] buf = new byte[65536]; int c; while ((c = in.read(buf)) > 0) out.write(buf, 0, c); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
00
Code Sample 1: public void doActionOn(TomcatProject prj) throws Exception { String path = TomcatLauncherPlugin.getDefault().getManagerAppUrl(); try { path += "/reload?path=" + prj.getWebPath(); URL url = new URL(path); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { String user = TomcatLauncherPlugin.getDefault().getManagerAppUser(); String password = TomcatLauncherPlugin.getDefault().getManagerAppPassword(); return new PasswordAuthentication(user, password.toCharArray()); } }); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getContent(); connection.disconnect(); Authenticator.setDefault(null); } catch (Exception e) { throw new Exception("The following url was used : \n" + path + "\n\nCheck manager app settings (username and password)\n\n"); } } Code Sample 2: @Override public DownloadingItem download(Playlist playlist, String title, File folder, StopDownloadCondition condition, String uuid) throws IOException, StoreStateException { boolean firstIteration = true; Iterator<PlaylistEntry> entries = playlist.getEntries().iterator(); DownloadingItem prevItem = null; File[] previousDownloadedFiles = new File[0]; while (entries.hasNext()) { PlaylistEntry entry = entries.next(); DownloadingItem item = null; LOGGER.info("Downloading from '" + entry.getTitle() + "'"); InputStream is = RESTHelper.inputStream(entry.getUrl()); boolean stopped = false; File nfile = null; try { nfile = createFileStream(folder, entry); item = new DownloadingItem(nfile, uuid.toString(), title, entry, new Date(), getPID(), condition); if (previousDownloadedFiles.length > 0) { item.setPreviousFiles(previousDownloadedFiles); } addItem(item); if (prevItem != null) deletePrevItem(prevItem); prevItem = item; stopped = IOUtils.copyStreams(is, new FileOutputStream(nfile), condition); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); radioScheduler.fireException(e); if (!condition.isStopped()) { File[] nfiles = new File[previousDownloadedFiles.length + 1]; System.arraycopy(previousDownloadedFiles, 0, nfiles, 0, previousDownloadedFiles.length); nfiles[nfiles.length - 1] = item.getFile(); previousDownloadedFiles = nfiles; if ((!entries.hasNext()) && (firstIteration)) { firstIteration = false; entries = playlist.getEntries().iterator(); } continue; } } if (stopped) { item.setState(ProcessStates.STOPPED); this.radioScheduler.fireStopDownloading(item); return item; } } return null; }
00
Code Sample 1: private boolean getCached(Get g) throws IOException { boolean ret = false; File f = getCachedFile(g); if (f.exists()) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(f); os = new FileOutputStream(getDestFile(g)); int read; byte[] buffer = new byte[4096]; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } ret = true; } finally { if (is != null) is.close(); if (os != null) os.close(); is = null; os = null; } } return ret; } Code Sample 2: public boolean check(String credentials) throws IOException { if (credentials == null) return true; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(method.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(uri.getBytes("ISO-8859-1")); byte[] ha2 = md.digest(); md.update(credentials.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(MessageDigester.byteArrayToHex(ha2).getBytes("ISO-8859-1")); byte[] digest = md.digest(); return (MessageDigester.byteArrayToHex(digest).equalsIgnoreCase(response)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 not supported"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Encoding not supported"); } }
00
Code Sample 1: private FTPClient getFTPConnection(String strUser, String strPassword, String strServer, boolean binaryTransfer, String connectionNote, boolean passiveMode) { FTPClient ftp = new FTPClient(); try { int reply; ftp.connect(strServer); ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + strServer + ", " + connectionNote); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection."); return null; } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { return null; } } ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server."); ResourcePool.LogException(e, this); return null; } try { if (!ftp.login(strUser, strPassword)) { ftp.logout(); ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed."); return null; } ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName() + ", " + connectionNote); if (binaryTransfer) { ftp.setFileType(FTP.BINARY_FILE_TYPE); } else { ftp.setFileType(FTP.ASCII_FILE_TYPE); } if (passiveMode) { ftp.enterLocalPassiveMode(); } else { ftp.enterLocalActiveMode(); } } catch (FTPConnectionClosedException e) { ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection."); ResourcePool.LogException(e, this); return null; } catch (IOException e) { ResourcePool.LogException(e, this); return null; } return ftp; } Code Sample 2: private void loadMap(URI uri) throws IOException { BufferedReader reader = null; InputStream stream = null; try { URL url = uri.toURL(); stream = url.openStream(); if (url.getFile().endsWith(".gz")) { stream = new GZIPInputStream(stream); } reader = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { String[] parts = line.split(" "); if (parts.length == 2) { pinyinZhuyinMap.put(parts[0], parts[1]); zhuyinPinyinMap.put(parts[1], parts[0]); } } } } finally { if (reader != null) { reader.close(); } } }
11
Code Sample 1: public static void copyFile(File src, File dst) throws ResourceNotFoundException, ParseErrorException, Exception { if (src.getAbsolutePath().endsWith(".vm")) { copyVMFile(src, dst.getAbsolutePath().substring(0, dst.getAbsolutePath().lastIndexOf(".vm"))); } else { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dst); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); } } Code Sample 2: public void run() { StringBuffer xml; String tabName; Element guiElement; setBold(monitor.getReading()); setBold(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Working"); HttpMethod method = null; xml = new StringBuffer(); File tempfile = new File(url); if (tempfile.exists()) { try { InputStream in = new FileInputStream(tempfile); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading XML file from local file"); e.printStackTrace(System.err); return; } } else { try { HttpClient client = new HttpClient(); method = new GetMethod(url); int response = client.executeMethod(method); if (response == 200) { InputStream in = method.getResponseBodyAsStream(); int temp; while ((temp = in.read()) != -1) { xml.append((char) temp); } in.close(); } else { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response); return; } } catch (IOException e) { if (method != null) { method.releaseConnection(); } System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server"); e.printStackTrace(System.err); return; } } setPlain(monitor.getReading()); setPlain(monitor.getReadingStatus()); monitor.getReadingStatus().setText(" Done"); setBold(monitor.getValidating()); setBold(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Working"); DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl(); try { DocumentBuilder parser = factory.newDocumentBuilder(); Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes())); if (method != null) { method.releaseConnection(); } Element root = document.getDocumentElement(); NodeList temp = root.getElementsByTagName("resource"); for (int j = 0; j < temp.getLength(); j++) { Element resource = (Element) temp.item(j); resources.add(new URL(resource.getAttribute("url"))); } NodeList connections = root.getElementsByTagName("jmxserver"); for (int j = 0; j < connections.getLength(); j++) { Element connection = (Element) connections.item(j); String name = connection.getAttribute("name"); String tempUrl = connection.getAttribute("url"); String auth = connection.getAttribute("auth"); if (tempUrl.indexOf("${host}") != -1) { HostDialog dialog = new HostDialog(Config.getHosts()); String host = dialog.showDialog(); if (host == null) { System.out.println("Host can not be null, unable to create panel."); return; } tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host); Config.addHost(host); } JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl); JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false)); if (auth != null && auth.equalsIgnoreCase("true")) { LoginTrueService loginService = new LoginTrueService(); JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService); if (status != JXLoginPanel.Status.SUCCEEDED) { return; } server.setUsername(loginService.getName()); server.setPassword(loginService.getPassword()); } servers.put(name, server); NodeList listeners = connection.getElementsByTagName("listener"); for (int i = 0; i < listeners.getLength(); i++) { Element attribute = (Element) listeners.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String filtertype = attribute.getAttribute("filterType"); TaskNotificationListener listener = new TaskNotificationListener(); NotificationFilterSupport filter = new NotificationFilterSupport(); if (filtertype == null || "".equals(filtertype)) { filter = null; } else { filter.enableType(filtertype); } Task task = new Task(-1, Task.LISTEN, server); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); } NodeList attributes = connection.getElementsByTagName("attribute"); for (int i = 0; i < attributes.getLength(); i++) { Element attribute = (Element) attributes.item(i); String taskname = attribute.getAttribute("taskname"); MBean mbean = new MBean(attribute.getAttribute("mbean"), null); String attributename = attribute.getAttribute("attributename"); String frequency = attribute.getAttribute("frequency"); String onEvent = attribute.getAttribute("onEvent"); if (frequency.equalsIgnoreCase("onchange")) { TaskNotificationListener listener = new TaskNotificationListener(); AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter(); filter.enableAttribute(attributename); Task task = new Task(-1, Task.LISTEN, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); task.setListener(listener); task.setFilter(filter); server.getWorker().addTask(task); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server); task2.setAttribute(att); task2.setMbean(mbean); server.getWorker().addTask(task2); List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); hashTempList.add(task2); tasks.put(taskname, hashTempList); } else { int frequency2 = Integer.parseInt(frequency); Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server); MBeanAttribute att = new MBeanAttribute(mbean, attributename); task.setAttribute(att); task.setMbean(mbean); if (tasks.get(taskname) != null) { System.out.println("Task " + taskname + " already exists."); return; } List<Task> hashTempList = new ArrayList<Task>(); hashTempList.add(task); tasks.put(taskname, hashTempList); TaskNotificationListener listener = null; if (onEvent != null && !"".equals(onEvent)) { Task tempTask = tasks.get(onEvent).get(0); if (tempTask == null) { System.out.println(onEvent + " was not found."); return; } else { listener = (TaskNotificationListener) tempTask.getListener(); } } if (listener == null) { server.getWorker().addTask(task); } else { listener.addTask(task); } } } } NodeList guiTemp = root.getElementsByTagName("gui"); guiElement = (Element) guiTemp.item(0); tabName = guiElement.getAttribute("name"); if (MonitorServer.contains(tabName)) { JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setTitleAt(i, tabName); break; } } NodeList tempBindings = root.getElementsByTagName("binding"); for (int i = 0; i < tempBindings.getLength(); i++) { Element binding = (Element) tempBindings.item(i); String guiname = binding.getAttribute("guiname"); String tmethod = binding.getAttribute("method"); String taskname = binding.getAttribute("taskname"); String formater = binding.getAttribute("formater"); BindingContainer tempBinding; if (formater == null || (formater != null && formater.equals(""))) { tempBinding = new BindingContainer(guiname, tmethod, taskname); } else { tempBinding = new BindingContainer(guiname, tmethod, taskname, formater); } bindings.add(tempBinding); } } catch (Exception e) { System.err.println("Exception message: " + e.getMessage()); System.out.println("Loading Monitor Failed, couldnt parse XML file."); e.printStackTrace(System.err); return; } setPlain(monitor.getValidating()); setPlain(monitor.getValidatingStatus()); monitor.getValidatingStatus().setText(" Done"); setBold(monitor.getDownload()); setBold(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Working"); List<File> jarFiles = new ArrayList<File>(); File cacheDir = new File(Config.getCacheDir()); if (!cacheDir.exists()) { cacheDir.mkdir(); } for (URL resUrl : resources) { try { HttpClient client = new HttpClient(); HttpMethod methodRes = new GetMethod(resUrl.toString()); int response = client.executeMethod(methodRes); if (response == 200) { int index = resUrl.toString().lastIndexOf("/") + 1; File file = new File(Config.getCacheDir() + resUrl.toString().substring(index)); FileOutputStream out = new FileOutputStream(file); InputStream in = methodRes.getResponseBodyAsStream(); int readTemp = 0; while ((readTemp = in.read()) != -1) { out.write(readTemp); } System.out.println(file.getName() + " downloaded."); methodRes.releaseConnection(); if (file.getName().endsWith(".jar")) { jarFiles.add(file); } } else { methodRes.releaseConnection(); System.out.println("Loading Monitor Failed. Unable to get resource " + url); return; } } catch (IOException e) { System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server"); e.printStackTrace(System.err); return; } } URL[] urls = new URL[jarFiles.size()]; try { for (int i = 0; i < jarFiles.size(); i++) { File file = jarFiles.get(i); File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName()); FileInputStream in = new FileInputStream(file); FileOutputStream out = new FileOutputStream(newFile); int n = 0; byte[] buf = new byte[1024]; while ((n = in.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); out.close(); in.close(); urls[i] = new URL("file:" + newFile.getAbsolutePath()); } } catch (Exception e1) { System.out.println("Unable to load jar files."); e1.printStackTrace(); } URLClassLoader loader = new URLClassLoader(urls); engine.setClassLoader(loader); setPlain(monitor.getDownload()); setPlain(monitor.getDownloadStatus()); monitor.getDownloadStatus().setText(" Done"); setBold(monitor.getGui()); setBold(monitor.getGuiStatus()); monitor.getGuiStatus().setText(" Working"); Container container; try { String tempXml = xml.toString(); int start = tempXml.indexOf("<gui"); start = tempXml.indexOf('>', start) + 1; int end = tempXml.indexOf("</gui>"); container = engine.render(new StringReader(tempXml.substring(start, end))); } catch (Exception e) { e.printStackTrace(System.err); System.err.println("Exception msg: " + e.getMessage()); System.out.println("Loading Monitor Failed, error creating gui."); return; } for (BindingContainer bcon : bindings) { List<Task> temp = tasks.get(bcon.getTask()); if (temp == null) { System.out.println("Task with name " + bcon.getTask() + " doesnt exist."); } else { for (Task task : temp) { if (task != null) { Object comp = engine.find(bcon.getComponent()); if (comp != null) { if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) { TaskNotificationListener listener = (TaskNotificationListener) task.getListener(); if (bcon.getFormater() == null) { listener.addResultListener(new Binding(comp, bcon.getMethod())); } else { listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } else { if (bcon.getFormater() == null) { task.addResultListener(new Binding(comp, bcon.getMethod())); } else { task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader)); } } } else { System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor."); return; } } else { System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor."); return; } } } } for (int i = 0; i < monitor.getTab().getTabCount(); i++) { if (monitor.getTab().getComponent(i).equals(monitor)) { monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this)); break; } } System.out.println("Connecting to server(s)."); Enumeration e = servers.keys(); List<JmxWorker> list = new ArrayList<JmxWorker>(); while (e.hasMoreElements()) { JmxWorker worker = servers.get(e.nextElement()).getWorker(); worker.setRunning(true); worker.start(); list.add(worker); } MonitorServer.add(tabName, list); Config.addUrl(url); }
00
Code Sample 1: private byte[] cacheInputStream(URL url) throws IOException { InputStream ins = url.openStream(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[256]; while (true) { int n = ins.read(buf); if (n == -1) break; bout.write(buf, 0, n); } return bout.toByteArray(); } Code Sample 2: public static void copyFileStreams(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) { return; } FileInputStream fis = new FileInputStream(fromFile); FileOutputStream fos = new FileOutputStream(toFile); int read = 0; byte[] buf = new byte[1024]; while (-1 != read) { read = fis.read(buf); if (read >= 0) { fos.write(buf, 0, read); } } fos.close(); fis.close(); }
00
Code Sample 1: public RobotList<Resource> sort_incr_Resource(RobotList<Resource> list, String field) { int length = list.size(); Index_value[] resource_dist = new Index_value[length]; if (field.equals("") || field.equals("location")) { Location cur_loc = this.getLocation(); for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, distance(cur_loc, list.get(i).location)); } } else if (field.equals("energy")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).energy); } } else if (field.equals("ammostash")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).ammostash); } } else if (field.equals("speed")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).speed); } } else if (field.equals("health")) { for (int i = 0; i < length; i++) { resource_dist[i] = new Index_value(i, list.get(i).health); } } else { say("impossible to sort list - nothing modified"); return list; } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (resource_dist[i].value > resource_dist[i + 1].value) { Index_value a = resource_dist[i]; resource_dist[i] = resource_dist[i + 1]; resource_dist[i + 1] = a; permut = true; } } } while (permut); RobotList<Resource> new_resource_list = new RobotList<Resource>(Resource.class); for (int i = 0; i < length; i++) { new_resource_list.addLast(list.get(resource_dist[i].index)); } return new_resource_list; } Code Sample 2: public final void propertyChange(final PropertyChangeEvent event) { if (fChecker != null && event.getProperty().equals(ISpellCheckPreferenceKeys.SPELLING_USER_DICTIONARY)) { if (fUserDictionary != null) { fChecker.removeDictionary(fUserDictionary); fUserDictionary = null; } final String file = (String) event.getNewValue(); if (file.length() > 0) { try { final URL url = new URL("file", null, file); InputStream stream = url.openStream(); if (stream != null) { try { fUserDictionary = new PersistentSpellDictionary(url); fChecker.addDictionary(fUserDictionary); } finally { stream.close(); } } } catch (MalformedURLException exception) { } catch (IOException exception) { } } } }
11
Code Sample 1: public static void copy(final File src, final File dst) throws IOException, IllegalArgumentException { long fileSize = src.length(); final FileInputStream fis = new FileInputStream(src); final FileOutputStream fos = new FileOutputStream(dst); final FileChannel in = fis.getChannel(), out = fos.getChannel(); try { long offs = 0, doneCnt = 0; final long copyCnt = Math.min(65536, fileSize); do { doneCnt = in.transferTo(offs, copyCnt, out); offs += doneCnt; fileSize -= doneCnt; } while (fileSize > 0); } finally { try { in.close(); } catch (final IOException e) { } try { out.close(); } catch (final IOException e) { } try { fis.close(); } catch (final IOException e) { } try { fos.close(); } catch (final IOException e) { } src.delete(); } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public static String calculateHA1(String username, byte[] password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes(username, ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(DAAP_REALM, ISO_8859_1)); md.update((byte) ':'); md.update(password); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
00
Code Sample 1: public void deleteUser(final List<Integer> userIds) { try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty("user.delete")); Iterator<Integer> iter = userIds.iterator(); int userId; while (iter.hasNext()) { userId = iter.next(); psImpl.setInt(1, userId); psImpl.executeUpdate(); } } }); connection.commit(); cmDB.removeUsers(userIds); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } } Code Sample 2: private Image getIcon(Element e) { if (!addIconsToButtons) { return null; } else { NodeList nl = e.getElementsByTagName("rc:iconURL"); if (nl.getLength() > 0) { String urlString = nl.item(0).getTextContent(); try { Image img = new Image(Display.getCurrent(), new URL(urlString).openStream()); return img; } catch (Exception exception) { logger.warn("Can't read " + urlString + " using default icon instead."); } } return new Image(Display.getCurrent(), this.getClass().getResourceAsStream("/res/default.png")); } }
11
Code Sample 1: protected void channelConnected() throws IOException { MessageDigest md = null; String digest = ""; try { String userid = nateon.getUserId(); if (userid.endsWith("@nate.com")) userid = userid.substring(0, userid.lastIndexOf('@')); md = MessageDigest.getInstance("MD5"); md.update(nateon.getPassword().getBytes()); md.update(userid.getBytes()); byte[] bData = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bData) { int v = (int) b; v = v < 0 ? v + 0x100 : v; String s = Integer.toHexString(v); if (s.length() == 1) sb.append('0'); sb.append(s); } digest = sb.toString(); } catch (Exception e) { e.printStackTrace(); } NateOnMessage out = new NateOnMessage("LSIN"); out.add(nateon.getUserId()).add(digest).add("MD5").add("3.615"); out.setCallback("processAuth"); writeMessage(out); } Code Sample 2: private String hashMD5(String strToHash) throws Exception { try { byte[] bHash = new byte[strToHash.length() * 2]; MessageDigest md = MessageDigest.getInstance("MD5"); md.update(strToHash.getBytes("UTF-16LE")); bHash = md.digest(); StringBuffer hexString = new StringBuffer(); for (byte element : bHash) { String strTemp = Integer.toHexString(element); hexString.append(strTemp.replaceAll("f", "")); } return hexString.toString(); } catch (NoSuchAlgorithmException duu) { throw new Exception("NoSuchAlgorithmException: " + duu.getMessage()); } }
11
Code Sample 1: private String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } Code Sample 2: public static Properties addAttributes(Node node, String[] names, Properties props, LogEvent evt) throws ConfigurationException { if (props == null) props = new Properties(); try { MessageDigest md = MessageDigest.getInstance("MD5"); for (int i = 0; i < names.length; i++) { String value = addProperty(names[i], props, node, evt); if (value != null) { md.update(names[i].getBytes()); md.update(value.getBytes()); } } byte[] digest = md.digest(); evt.addMessage("digest " + ISOUtil.hexString(digest)); props.put(DIGEST_PROPERTY, digest); } catch (NoSuchAlgorithmException e) { throw new ConfigurationException(e); } return props; }
00
Code Sample 1: private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; } Code Sample 2: public List<String[]> getCSV(String name) { return new ResourceLoader<List<String[]>>(name) { @Override protected List<String[]> get(URL url) throws Exception { CSVReader reader = null; try { reader = new CSVReader(new InputStreamReader(url.openStream())); return reader.readAll(); } finally { IOUtils.closeQuietly(reader); } } }.get(); }
00
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } } Code Sample 2: public static void main(String[] argv) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (Exception e) { e.printStackTrace(); } md.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes(), 0, 56); String exp = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1"; String result = toString(md.digest()); System.out.println(exp); System.out.println(result); if (!exp.equals(result)) System.out.println("NOT EQUAL!"); }
11
Code Sample 1: public static boolean unzip_and_merge(String infile, String outfile) { try { BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(infile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); FileOutputStream fos = new FileOutputStream(outfile); dest = new BufferedOutputStream(fos, BUFFER); while (zis.getNextEntry() != null) { int count; byte data[] = new byte[BUFFER]; while ((count = zis.read(data, 0, BUFFER)) != -1) dest.write(data, 0, count); dest.flush(); } dest.close(); zis.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } Code Sample 2: public static void toValueSAX(Property property, Value value, int valueType, ContentHandler contentHandler, AttributesImpl na, Context context) throws SAXException, RepositoryException { na.clear(); String _value = null; switch(valueType) { case PropertyType.DATE: DateFormat df = new SimpleDateFormat(BackupFormatConstants.DATE_FORMAT_STRING); df.setTimeZone(value.getDate().getTimeZone()); _value = df.format(value.getDate().getTime()); break; case PropertyType.BINARY: String outResourceName = property.getParent().getPath() + "/" + property.getName(); OutputStream os = null; InputStream is = null; try { os = context.getPersistenceManager().getOutResource(outResourceName, true); is = value.getStream(); IOUtils.copy(is, os); os.flush(); } catch (Exception e) { throw new SAXException("Could not backup binary value of property [" + property.getName() + "]", e); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } na.addAttribute("", ATTACHMENT, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + ATTACHMENT, "string", outResourceName); break; case PropertyType.REFERENCE: _value = value.getString(); break; default: _value = value.getString(); } contentHandler.startElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE, na); if (null != _value) contentHandler.characters(_value.toCharArray(), 0, _value.length()); contentHandler.endElement("", VALUE, (NAMESPACE.length() > 0 ? NAMESPACE + ":" : "") + VALUE); }
00
Code Sample 1: protected void loadResourceLocations() { try { for (String path : resourceLocations) { if (path.startsWith("${") && path.endsWith("}")) { int start = path.indexOf('{') + 1; int end = path.indexOf('}'); String key = path.substring(start, end).trim(); if (key.equals(ApplicationConstants.RESOURCE_SQL_LOCATION_PROP_NAME)) path = AdminHelper.getRepository().getURI("sql"); else path = AdminHelper.getRepository().getSetupApplicationProperties().get(key); log.debug(key + "=" + path); } FileObject fo = VFSUtils.resolveFile(path); if (fo.exists()) { URL url = fo.getURL(); url.openConnection(); if (fastDeploy) { if (log.isDebugEnabled()) { log.debug("Fast deploy : " + url); AdminSqlQueryFactory builder = null; for (DirectoryListener listener : scanner.getDirectoryListeners()) { if (listener instanceof AdminSqlQueryFactory) { builder = (AdminSqlQueryFactory) listener; } } File file = new File(url.getFile()); fastDeploy(file, builder); } } scanner.addScanURL(url); } } } catch (Exception e) { } } Code Sample 2: public static void processString(String text) throws Exception { MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST); md5.reset(); md5.update(text.getBytes()); displayResult(null, md5.digest()); }
00
Code Sample 1: public static boolean download(String url, File file) { HttpURLConnection conn = null; BufferedInputStream in = null; BufferedOutputStream out = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.connect(); if (conn.getResponseCode() == 200) { System.out.println("length:" + conn.getContentLength()); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(file)); byte[] b = new byte[1024 << 10]; int i = 0; while ((i = in.read(b)) > -1) { if (i > 0) out.write(b, 0, i); } return true; } else { System.out.println(conn.getResponseCode() + ":" + url); } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } if (conn != null) conn.disconnect(); } return false; } Code Sample 2: public static final boolean zipExtract(String zipfile, String name, String dest) { boolean f = false; try { InputStream in = new BufferedInputStream(new FileInputStream(zipfile)); ZipInputStream zin = new ZipInputStream(in); ZipEntry e; while ((e = zin.getNextEntry()) != null) { if (e.getName().equals(name)) { FileOutputStream out = new FileOutputStream(dest); byte b[] = new byte[TEMP_FILE_BUFFER_SIZE]; int len = 0; while ((len = zin.read(b)) != -1) out.write(b, 0, len); out.close(); f = true; break; } } zin.close(); } catch (FileNotFoundException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } catch (IOException e) { MLUtil.runtimeError(e, "extractZip " + zipfile + " " + name); } return (f); }
11
Code Sample 1: public SOCTradeOffer makeOffer(SOCPossiblePiece targetPiece) { D.ebugPrintln("***** MAKE OFFER *****"); if (targetPiece == null) { return null; } SOCTradeOffer offer = null; SOCResourceSet targetResources = null; switch(targetPiece.getType()) { case SOCPossiblePiece.CARD: targetResources = SOCGame.CARD_SET; break; case SOCPossiblePiece.ROAD: targetResources = SOCGame.ROAD_SET; break; case SOCPossiblePiece.SETTLEMENT: targetResources = SOCGame.SETTLEMENT_SET; break; case SOCPossiblePiece.CITY: targetResources = SOCGame.CITY_SET; break; } SOCResourceSet ourResources = ourPlayerData.getResources(); D.ebugPrintln("*** targetResources = " + targetResources); D.ebugPrintln("*** ourResources = " + ourResources); if (ourResources.contains(targetResources)) { return offer; } if (ourResources.getAmount(SOCResourceConstants.UNKNOWN) > 0) { D.ebugPrintln("AGG WE HAVE UNKNOWN RESOURCES !!!! %%%%%%%%%%%%%%%%%%%%%%%%%%%%"); return offer; } SOCTradeOffer batna = getOfferToBank(targetResources); D.ebugPrintln("*** BATNA = " + batna); SOCBuildingSpeedEstimate estimate = new SOCBuildingSpeedEstimate(ourPlayerData.getNumbers()); SOCResourceSet giveResourceSet = new SOCResourceSet(); SOCResourceSet getResourceSet = new SOCResourceSet(); int batnaBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); D.ebugPrintln("*** batnaBuildingTime = " + batnaBuildingTime); if (batna != null) { batnaBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, batna.getGiveSet(), batna.getGetSet(), estimate); } D.ebugPrintln("*** batnaBuildingTime = " + batnaBuildingTime); int[] rollsPerResource = estimate.getRollsPerResource(); int[] neededRsrc = new int[5]; int[] notNeededRsrc = new int[5]; int neededRsrcCount = 0; int notNeededRsrcCount = 0; for (int rsrcType = SOCResourceConstants.CLAY; rsrcType <= SOCResourceConstants.WOOD; rsrcType++) { if (targetResources.getAmount(rsrcType) > 0) { neededRsrc[neededRsrcCount] = rsrcType; neededRsrcCount++; } else { notNeededRsrc[notNeededRsrcCount] = rsrcType; notNeededRsrcCount++; } } for (int j = neededRsrcCount - 1; j >= 0; j--) { for (int i = 0; i < j; i++) { if (rollsPerResource[neededRsrc[i]] > rollsPerResource[neededRsrc[i + 1]]) { int tmp = neededRsrc[i]; neededRsrc[i] = neededRsrc[i + 1]; neededRsrc[i + 1] = tmp; } } } if (D.ebugOn) { for (int i = 0; i < neededRsrcCount; i++) { D.ebugPrintln("NEEDED RSRC: " + neededRsrc[i] + " : " + rollsPerResource[neededRsrc[i]]); } } for (int j = notNeededRsrcCount - 1; j >= 0; j--) { for (int i = 0; i < j; i++) { if (rollsPerResource[notNeededRsrc[i]] > rollsPerResource[notNeededRsrc[i + 1]]) { int tmp = notNeededRsrc[i]; notNeededRsrc[i] = notNeededRsrc[i + 1]; notNeededRsrc[i + 1] = tmp; } } } if (D.ebugOn) { for (int i = 0; i < notNeededRsrcCount; i++) { D.ebugPrintln("NOT-NEEDED RSRC: " + notNeededRsrc[i] + " : " + rollsPerResource[notNeededRsrc[i]]); } } boolean[] someoneIsSellingResource = new boolean[SOCResourceConstants.MAXPLUSONE]; for (int rsrcType = SOCResourceConstants.CLAY; rsrcType <= SOCResourceConstants.WOOD; rsrcType++) { someoneIsSellingResource[rsrcType] = false; for (int pn = 0; pn < SOCGame.MAXPLAYERS; pn++) { if ((pn != ourPlayerData.getPlayerNumber()) && (isSellingResource[pn][rsrcType])) { someoneIsSellingResource[rsrcType] = true; D.ebugPrintln("*** player " + pn + " is selling " + rsrcType); break; } } } int getRsrcIdx = neededRsrcCount - 1; while ((getRsrcIdx >= 0) && ((ourResources.getAmount(neededRsrc[getRsrcIdx]) >= targetResources.getAmount(neededRsrc[getRsrcIdx])) || (!someoneIsSellingResource[neededRsrc[getRsrcIdx]]))) { getRsrcIdx--; } if (getRsrcIdx >= 0) { D.ebugPrintln("*** getRsrc = " + neededRsrc[getRsrcIdx]); getResourceSet.add(1, neededRsrc[getRsrcIdx]); D.ebugPrintln("*** offer should be null : offer = " + offer); int giveRsrcIdx = 0; while ((giveRsrcIdx < notNeededRsrcCount) && (offer == null)) { D.ebugPrintln("*** ourResources.getAmount(" + notNeededRsrc[giveRsrcIdx] + ") = " + ourResources.getAmount(notNeededRsrc[giveRsrcIdx])); if (ourResources.getAmount(notNeededRsrc[giveRsrcIdx]) > 0) { giveResourceSet.clear(); giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx]); offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]); D.ebugPrintln("*** offer = " + offer); int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime); } giveRsrcIdx++; } D.ebugPrintln("*** ourResources = " + ourResources); if (offer == null) { int giveRsrcIdx1 = 0; while ((giveRsrcIdx1 < neededRsrcCount) && (offer == null)) { D.ebugPrintln("*** ourResources.getAmount(" + neededRsrc[giveRsrcIdx1] + ") = " + ourResources.getAmount(neededRsrc[giveRsrcIdx1])); D.ebugPrintln("*** targetResources.getAmount(" + neededRsrc[giveRsrcIdx1] + ") = " + targetResources.getAmount(neededRsrc[giveRsrcIdx1])); if ((ourResources.getAmount(neededRsrc[giveRsrcIdx1]) > targetResources.getAmount(neededRsrc[giveRsrcIdx1])) && (neededRsrc[giveRsrcIdx1] != neededRsrc[getRsrcIdx])) { giveResourceSet.clear(); giveResourceSet.add(1, neededRsrc[giveRsrcIdx1]); int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) { offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]); D.ebugPrintln("*** offer = " + offer); D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime); } } giveRsrcIdx1++; } } D.ebugPrintln("*** ourResources = " + ourResources); SOCResourceSet leftovers = ourResources.copy(); leftovers.subtract(targetResources); D.ebugPrintln("*** leftovers = " + leftovers); if (offer == null) { int giveRsrcIdx1 = 0; int giveRsrcIdx2 = 0; while ((giveRsrcIdx1 < notNeededRsrcCount) && (offer == null)) { if (ourResources.getAmount(notNeededRsrc[giveRsrcIdx1]) > 0) { while ((giveRsrcIdx2 < notNeededRsrcCount) && (offer == null)) { giveResourceSet.clear(); giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx1]); giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx2]); if (ourResources.contains(giveResourceSet)) { int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) { offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]); D.ebugPrintln("*** offer = " + offer); D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime); } } giveRsrcIdx2++; } giveRsrcIdx2 = 0; while ((giveRsrcIdx2 < neededRsrcCount) && (offer == null)) { if (neededRsrc[giveRsrcIdx2] != neededRsrc[getRsrcIdx]) { giveResourceSet.clear(); giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx1]); giveResourceSet.add(1, neededRsrc[giveRsrcIdx2]); if (leftovers.contains(giveResourceSet)) { int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) { offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]); D.ebugPrintln("*** offer = " + offer); D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime); } } } giveRsrcIdx2++; } } giveRsrcIdx1++; } giveRsrcIdx1 = 0; giveRsrcIdx2 = 0; while ((giveRsrcIdx1 < neededRsrcCount) && (offer == null)) { if ((leftovers.getAmount(neededRsrc[giveRsrcIdx1]) > 0) && (neededRsrc[giveRsrcIdx1] != neededRsrc[getRsrcIdx])) { while ((giveRsrcIdx2 < notNeededRsrcCount) && (offer == null)) { giveResourceSet.clear(); giveResourceSet.add(1, neededRsrc[giveRsrcIdx1]); giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx2]); if (leftovers.contains(giveResourceSet)) { int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) { offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]); D.ebugPrintln("*** offer = " + offer); D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime); } } giveRsrcIdx2++; } giveRsrcIdx2 = 0; while ((giveRsrcIdx2 < neededRsrcCount) && (offer == null)) { if (neededRsrc[giveRsrcIdx2] != neededRsrc[getRsrcIdx]) { giveResourceSet.clear(); giveResourceSet.add(1, neededRsrc[giveRsrcIdx1]); giveResourceSet.add(1, neededRsrc[giveRsrcIdx2]); if (leftovers.contains(giveResourceSet)) { int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) { offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]); D.ebugPrintln("*** offer = " + offer); D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime); } } } giveRsrcIdx2++; } } giveRsrcIdx1++; } } } if (offer == null) { SOCResourceSet leftovers = ourResources.copy(); leftovers.subtract(targetResources); D.ebugPrintln("*** leftovers = " + leftovers); int getRsrcIdx2 = notNeededRsrcCount - 1; while ((getRsrcIdx2 >= 0) && (!someoneIsSellingResource[neededRsrc[getRsrcIdx2]])) { getRsrcIdx2--; } while ((getRsrcIdx2 >= 0) && (offer == null)) { getResourceSet.clear(); getResourceSet.add(1, notNeededRsrc[getRsrcIdx2]); leftovers.add(1, notNeededRsrc[getRsrcIdx2]); if (offer == null) { int giveRsrcIdx1 = 0; while ((giveRsrcIdx1 < notNeededRsrcCount) && (offer == null)) { if ((leftovers.getAmount(notNeededRsrc[giveRsrcIdx1]) > 0) && (notNeededRsrc[giveRsrcIdx1] != notNeededRsrc[getRsrcIdx2])) { leftovers.subtract(1, notNeededRsrc[giveRsrcIdx1]); if (getOfferToBank(targetResources, leftovers) != null) { giveResourceSet.clear(); giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx1]); int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); if (offerBuildingTime < batnaBuildingTime) { offer = makeOfferAux(giveResourceSet, getResourceSet, notNeededRsrc[getRsrcIdx2]); D.ebugPrintln("*** offer = " + offer); D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime); } } leftovers.add(1, notNeededRsrc[giveRsrcIdx1]); } giveRsrcIdx1++; } } if (offer == null) { int giveRsrcIdx1 = 0; while ((giveRsrcIdx1 < neededRsrcCount) && (offer == null)) { if (leftovers.getAmount(neededRsrc[giveRsrcIdx1]) > 0) { leftovers.subtract(1, neededRsrc[giveRsrcIdx1]); if (getOfferToBank(targetResources, leftovers) != null) { giveResourceSet.clear(); giveResourceSet.add(1, neededRsrc[giveRsrcIdx1]); int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate); if (offerBuildingTime < batnaBuildingTime) { offer = makeOfferAux(giveResourceSet, getResourceSet, notNeededRsrc[getRsrcIdx2]); D.ebugPrintln("*** offer = " + offer); D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime); } } leftovers.add(1, neededRsrc[giveRsrcIdx1]); } giveRsrcIdx1++; } } leftovers.subtract(1, notNeededRsrc[getRsrcIdx2]); getRsrcIdx2--; } } return offer; } Code Sample 2: public static void sort(float norm_abst[]) { float temp; for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) { if (norm_abst[j] > norm_abst[j + 1]) { temp = norm_abst[j]; norm_abst[j] = norm_abst[j + 1]; norm_abst[j + 1] = temp; } } } printFixed(norm_abst[0]); print(" "); printFixed(norm_abst[1]); print(" "); printFixed(norm_abst[2]); print(" "); printFixed(norm_abst[3]); print(" "); printFixed(norm_abst[4]); print(" "); printFixed(norm_abst[5]); print(" "); printFixed(norm_abst[6]); print(" "); printFixed(norm_abst[7]); print("\n"); }
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: public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
11
Code Sample 1: protected boolean downloadFile(TestThread thread, ActionResult result) { result.setRequestString("download file " + remoteFile); InputStream input = null; OutputStream output = null; OutputStream target = null; boolean status = false; ftpClient.enterLocalPassiveMode(); try { if (localFile != null) { File lcFile = new File(localFile); if (lcFile.exists() && lcFile.isDirectory()) output = new FileOutputStream(new File(lcFile, remoteFile)); else output = new FileOutputStream(lcFile); target = output; } else { target = new FileOutputStream(remoteFile); } input = ftpClient.retrieveFileStream(remoteFile); long bytes = IOUtils.copy(input, target); status = bytes > 0; if (status) { result.setResponseLength(bytes); } } catch (Exception e) { result.setException(new TestActionException(config, e)); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } return status; } Code Sample 2: private void copy(File source, File destination) { if (!destination.exists()) { destination.mkdir(); } File files[] = source.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { copy(files[i], new File(destination, files[i].getName())); } else { try { FileChannel srcChannel = new FileInputStream(files[i]).getChannel(); FileChannel dstChannel = new FileOutputStream(new File(destination, files[i].getName())).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { log.error("Could not write to " + destination.getAbsolutePath(), ioe); } } } } }
00
Code Sample 1: public synchronized long nextValue(final Session session) { if (sequence < seqLimit) { return ++sequence; } else { final MetaDatabase db = MetaTable.DATABASE.of(table); Connection connection = null; ResultSet res = null; String sql = null; PreparedStatement statement = null; StringBuilder out = new StringBuilder(64); try { connection = session.getSeqConnection(db); String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString(); out.setLength(0); out.setLength(0); sql = db.getDialect().printSequenceNextValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); int i = statement.executeUpdate(); if (i == 0) { out.setLength(0); sql = db.getDialect().printSequenceInit(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.executeUpdate(); } out.setLength(0); sql = db.getDialect().printSequenceCurrentValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); res = statement.executeQuery(); res.next(); seqLimit = res.getLong(1); int step = res.getInt(2); maxValue = res.getLong(3); sequence = (seqLimit - step) + 1; if (maxValue != 0L) { if (seqLimit > maxValue) { seqLimit = maxValue; if (sequence > maxValue) { String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue; throw new IllegalStateException(msg); } statement.close(); sql = db.getDialect().printSetMaxSequence(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.execute(); } if (maxValue > Long.MAX_VALUE - step) { String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)"; LOGGER.log(Level.WARNING, msg); } } connection.commit(); } catch (Throwable e) { if (connection != null) try { connection.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Rollback fails"); } IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e); throw exception; } finally { MetaDatabase.close(null, statement, res, true); } return sequence; } } Code Sample 2: public void configureLogging() { try { PreferenceStore preferences = new PreferenceStore(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IExtensionPoint extensionPoint = registry.getExtensionPoint(CorePlugin.LOGGER_PREFERENCES_EXTENSION_POINT); IConfigurationElement[] members = extensionPoint.getConfigurationElements(); for (int i = 0; i < members.length; i++) { IConfigurationElement element = members[i]; if (element.getName().equals("logger")) { if (element.getAttribute("defaultValue") != null) { String[] item = element.getAttribute("name").split(";"); for (int x = 0; x < item.length; x++) preferences.setDefault("log4j.logger." + item[x], element.getAttribute("defaultValue")); } } } try { URL url = CorePlugin.getDefault().getBundle().getResource("log4j.properties"); Properties properties = new Properties(); properties.load(url.openStream()); for (Iterator iter = properties.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); preferences.setDefault(key, (String) properties.get(key)); } File file = CorePlugin.getDefault().getStateLocation().append("log4j.properties").toFile(); if (file.exists()) preferences.load(new FileInputStream(file)); } catch (Exception e) { CorePlugin.logException(e); } Properties properties = new Properties(); String[] names = preferences.preferenceNames(); for (int i = 0; i < names.length; i++) properties.put(names[i], preferences.getString(names[i])); PropertyConfigurator.configure(properties); } catch (Exception e) { BasicConfigurator.configure(); logException(e); } }
00
Code Sample 1: public static void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { File[] fl = f.listFiles(); base = base.length() == 0 ? "" : base + File.separator; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); IOUtils.copyStream(in, out); in.close(); } Thread.sleep(10); } Code Sample 2: public static String get(String u, String usr, String pwd) { String response = ""; logger.debug("Attempting to call: " + u); logger.debug("Creating Authenticator: usr=" + usr + ", pwd=" + pwd); Authenticator.setDefault(new CustomAuthenticator(usr, pwd)); try { URL url = new URL(u); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer sb = new StringBuffer(0); String str; while ((str = in.readLine()) != null) { sb.append(str); } in.close(); logger.debug("Response: " + sb.toString()); response = sb.toString(); } catch (MalformedURLException e) { logger.error(e); logger.trace(e, e); } catch (IOException e) { logger.error(e); logger.trace(e, e); } return response; }
11
Code Sample 1: private void CopyTo(File dest) throws IOException { FileReader in = null; FileWriter out = null; int c; try { in = new FileReader(image); out = new FileWriter(dest); while ((c = in.read()) != -1) out.write(c); } finally { if (in != null) try { in.close(); } catch (Exception e) { } if (out != null) try { out.close(); } catch (Exception e) { } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "ispyb@esrf.fr", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); } Code Sample 2: private void getLocationAddressByGoogleMapAsync(Location location) { if (location == null) { return; } AsyncTask<Location, Void, String> task = new AsyncTask<Location, Void, String>() { @Override protected String doInBackground(Location... params) { if (params == null || params.length == 0 || params[0] == null) { return null; } Location location = params[0]; String address = ""; String cachedAddress = DataService.GetInstance(mContext).getAddressFormLocationCache(location.getLatitude(), location.getLongitude()); if (!TextUtils.isEmpty(cachedAddress)) { address = cachedAddress; } else { StringBuilder jsonText = new StringBuilder(); HttpClient client = new DefaultHttpClient(); String url = String.format(GoogleMapAPITemplate, location.getLatitude(), location.getLongitude()); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { jsonText.append(line); } JSONObject result = new JSONObject(jsonText.toString()); String status = result.getString(GoogleMapStatusSchema.status); if (GoogleMapStatusCodes.OK.equals(status)) { JSONArray addresses = result.getJSONArray(GoogleMapStatusSchema.results); if (addresses.length() > 0) { address = addresses.getJSONObject(0).getString(GoogleMapStatusSchema.formatted_address); if (!TextUtils.isEmpty(currentBestLocationAddress)) { DataService.GetInstance(mContext).updateAddressToLocationCache(location.getLatitude(), location.getLongitude(), currentBestLocationAddress); } } } } else { Log.e("Error", "Failed to get address via google map API."); } } catch (ClientProtocolException e) { e.printStackTrace(); Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } catch (JSONException e) { Toast.makeText(mContext, "Failed to get location.", Toast.LENGTH_SHORT).show(); } } return address; } @Override protected void onPostExecute(String result) { setCurrentBestLocationAddress(currentBestLocation, result); } }; task.execute(currentBestLocation); }
00
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: private static void copyFile(File source, File dest, boolean visibleFilesOnly) throws IOException { if (visibleFilesOnly && isHiddenOrDotFile(source)) { return; } if (dest.exists()) { System.err.println("Destination File Already Exists: " + dest); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
11
Code Sample 1: public String fileUpload(final ResourceType type, final String currentFolder, final String fileName, final InputStream inputStream) throws InvalidCurrentFolderException, WriteException { String absolutePath = getRealUserFilesAbsolutePath(RequestCycleHandler.getUserFilesAbsolutePath(ThreadLocalData.getRequest())); File typeDir = getOrCreateResourceTypeDir(absolutePath, type); File currentDir = new File(typeDir, currentFolder); if (!currentDir.exists() || !currentDir.isDirectory()) throw new InvalidCurrentFolderException(); File newFile = new File(currentDir, fileName); File fileToSave = UtilsFile.getUniqueFile(newFile.getAbsoluteFile()); try { IOUtils.copyLarge(inputStream, new FileOutputStream(fileToSave)); } catch (IOException e) { throw new WriteException(); } return fileToSave.getName(); } Code Sample 2: public static String getStringFromInputStream(InputStream in) throws Exception { CachedOutputStream bos = new CachedOutputStream(); IOUtils.copy(in, bos); in.close(); bos.close(); return bos.getOut().toString(); }
11
Code Sample 1: public void _testConvertIntoOneFile() { File csvFile = new File("C:/DE311/solution_workspace/WorkbookTaglib/WorkbookTagDemoWebapp/src/main/resources/csv/google.csv"); try { Charset guessedCharset = com.glaforge.i18n.io.CharsetToolkit.guessEncoding(csvFile, 4096); CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), guessedCharset))); Writer writer = new FileWriter("/temp/test.html"); int nbLines = CsvConverterUtils.countLines(new BufferedReader(new FileReader(csvFile))); HtmlConverter conv = new HtmlConverter(); conv.convert(reader, writer, nbLines); } catch (Exception e) { fail(e.getMessage()); } } Code Sample 2: private void download(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } }
11
Code Sample 1: public static void copyFile(File source, File target) throws Exception { if (source.isDirectory()) { if (!target.isDirectory()) { target.mkdirs(); } String[] children = source.list(); for (int i = 0; i < children.length; i++) { copyFile(new File(source, children[i]), new File(target, children[i])); } } else { FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(target).getChannel(); try { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { errorLog("{Malgn.copyFile} " + e.getMessage()); throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } } Code Sample 2: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
00
Code Sample 1: @Override protected IStatus run(IProgressMonitor monitor) { final int BUFFER_SIZE = 1024; final int DISPLAY_BUFFER_SIZE = 8196; File sourceFile = new File(_sourceFile); File destFile = new File(_destFile); if (sourceFile.exists()) { try { Log.getInstance(FileCopierJob.class).debug(String.format("Start copy of %s to %s", _sourceFile, _destFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); monitor.beginTask(Messages.getString("FileCopierJob.MainTask") + " " + _sourceFile, (int) ((sourceFile.length() / DISPLAY_BUFFER_SIZE) + 4)); monitor.worked(1); byte[] buffer = new byte[BUFFER_SIZE]; int stepRead = 0; int read; boolean copying = true; while (copying) { read = bis.read(buffer); if (read > 0) { bos.write(buffer, 0, read); stepRead += read; } else { copying = false; } if (monitor.isCanceled()) { bos.close(); bis.close(); deleteFile(_destFile); return Status.CANCEL_STATUS; } if (stepRead >= DISPLAY_BUFFER_SIZE) { monitor.worked(1); stepRead = 0; } } bos.flush(); bos.close(); bis.close(); monitor.worked(1); } catch (Exception e) { processError("Error while copying: " + e.getMessage()); } Log.getInstance(FileCopierJob.class).debug("End of copy."); return Status.OK_STATUS; } else { processError(Messages.getString("FileCopierJob.ErrorSourceDontExists") + sourceFile.getAbsolutePath()); return Status.CANCEL_STATUS; } } Code Sample 2: public final void conectar() throws IOException, FTPException { ftp = null; ftp = new FTPClient(); ftp.setRemoteHost(cfg.getFTPHost()); ftp.connect(); ftp.login(cfg.getFTPUser(), cfg.getFTPPass()); ftp.setProgressMonitor(pMonitor); ftp.setConnectMode(FTPConnectMode.PASV); ftp.setType(FTPTransferType.BINARY); }
00
Code Sample 1: public static String EncryptString(String method, String input) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); if (method.equals("SHA1") || method.equals("MD5")) { try { md = MessageDigest.getInstance(method); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); return null; } } else { return null; } md.reset(); md.update(input.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { String tmp = Integer.toHexString(0xff & byteHash[i]); if (tmp.length() < 2) tmp = "0" + tmp; resultString.append(tmp); } return (resultString.toString()); } Code Sample 2: private void addIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst = null; try { conn = getConnection(); pst = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst.setInt(1, id); pst.setString(2, ingBean.getName()); pst.setDouble(3, ingBean.getAmount()); pst.setInt(4, ingBean.getType()); pst.setInt(5, ingBean.getShopFlag()); pst.executeUpdate(); } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst != null) pst.close(); pst = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } }
00
Code Sample 1: protected void givenGroupRepository(String repoId, String providerId, Repository... memberRepos) throws AuthenticationException, UnsupportedEncodingException, IOException, ClientProtocolException { HttpResponse response = executeDeleteWithResponse(format("/repo_groups/%s", repoId)); consume(response.getEntity()); final StringEntity content = new StringEntity(format("{data:{id: '%s', name: '%s', provider: '%s', exposed: true, repositories: [%s]}}", repoId, repoId, providerId, render(memberRepos))); response = executePost("/repo_groups", content, new BasicHeader("Content-Type", "application/json")); consume(response.getEntity()); assertThat(response.getStatusLine().getStatusCode(), is(201)); } Code Sample 2: private static String connect(String apiURL, boolean secure) throws IOException { String baseUrl; if (secure) baseUrl = "https://todoist.com/API/"; else baseUrl = "http://todoist.com/API/"; URL url = new URL(baseUrl + apiURL); URLConnection c = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder toReturn = new StringBuilder(""); String toAppend; while ((toAppend = in.readLine()) != null) toReturn.append(toAppend); return toReturn.toString(); }
00
Code Sample 1: public int addDecisionInstruction(int condition, String frameSlot, String linkName, int objectId, String attribute, int positive, int negative) throws FidoDatabaseException, ObjectNotFoundException, InstructionNotFoundException { try { Connection conn = null; Statement stmt = null; try { if ((condition == ConditionalOperatorTable.CONTAINS_LINK) || (condition == ConditionalOperatorTable.NOT_CONTAINS_LINK)) { ObjectTable ot = new ObjectTable(); if (ot.contains(objectId) == false) throw new ObjectNotFoundException(objectId); } conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); if (contains(stmt, positive) == false) throw new InstructionNotFoundException(positive); if (contains(stmt, negative) == false) throw new InstructionNotFoundException(negative); String sql = "insert into Instructions (Type, Operator, FrameSlot, LinkName, ObjectId, AttributeName) " + "values (2, " + condition + ", '" + frameSlot + "', '" + linkName + "', " + objectId + ", '" + attribute + "')"; stmt.executeUpdate(sql); int id = getCurrentId(stmt); InstructionGroupTable groupTable = new InstructionGroupTable(); groupTable.deleteInstruction(stmt, id); if (positive != -1) groupTable.addInstructionAt(stmt, id, 1, positive); if (negative != -1) groupTable.addInstructionAt(stmt, id, 2, negative); conn.commit(); return id; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: public static String getMD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); String result = new BigInteger(1, m.digest()).toString(16); while (result.length() < 32) { result = '0' + result; } return result; } catch (NoSuchAlgorithmException ex) { return null; } }
11
Code Sample 1: 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(); } } } } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public 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); }
00
Code Sample 1: public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } } Code Sample 2: public void contextInitialized(ServletContextEvent event) { try { String osName = System.getProperty("os.name"); if (osName != null && osName.toLowerCase().contains("windows")) { URL url = new URL("http://localhost/"); URLConnection urlConn = url.openConnection(); urlConn.setDefaultUseCaches(false); } } catch (Throwable t) { } }
11
Code Sample 1: protected byte[] createFileID() { try { COSDocument cosDoc = cosGetDoc(); if (cosDoc == null) { return null; } ILocator locator = cosDoc.getLocator(); if (locator == null) { return null; } IRandomAccess ra = cosDoc.stGetDoc().getRandomAccess(); if (ra == null) { ra = new RandomAccessByteArray(StringTools.toByteArray("DummyValue")); } MessageDigest digest = MessageDigest.getInstance("MD5"); long time = System.currentTimeMillis(); digest.update(String.valueOf(time).getBytes()); digest.update(locator.getFullName().getBytes()); digest.update(String.valueOf(ra.getLength()).getBytes()); COSInfoDict infoDict = getInfoDict(); if (infoDict != null) { for (Iterator it = infoDict.cosGetDict().iterator(); it.hasNext(); ) { COSObject object = (COSObject) it.next(); digest.update(object.stringValue().getBytes()); } } return digest.digest(); } catch (Exception e) { throw new IllegalStateException(e); } } Code Sample 2: public String calculateDigest(String str) { StringBuffer s = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); for (byte d : digest) { s.append(Integer.toHexString((int) (d & 0xff))); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return s.toString(); }
11
Code Sample 1: protected static void copyFile(File in, File out) throws IOException { java.io.FileWriter filewriter = null; java.io.FileReader filereader = null; try { filewriter = new java.io.FileWriter(out); filereader = new java.io.FileReader(in); char[] buf = new char[4096]; int nread = filereader.read(buf, 0, 4096); while (nread >= 0) { filewriter.write(buf, 0, nread); nread = filereader.read(buf, 0, 4096); } buf = null; } finally { try { filereader.close(); } catch (Throwable t) { } try { filewriter.close(); } catch (Throwable t) { } } } Code Sample 2: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
11
Code Sample 1: private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); } Code Sample 2: public 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; }
11
Code Sample 1: public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } } 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 < hashLength; 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) { log.error("Error getting password hash: " + nsae.getMessage()); return null; } }
00
Code Sample 1: @Override public void run() { try { IOUtils.copy(getSource(), processStdIn); System.err.println("Copy done."); close(); } catch (IOException e) { e.printStackTrace(); IOUtils.closeQuietly(ExternalDecoder.this); } } Code Sample 2: public static void bubbleSort(int[] a) { if (a == null) { throw new IllegalArgumentException("Null-pointed array"); } int right = a.length - 1; int k = 0; while (right > 0) { k = 0; for (int i = 0; i <= right - 1; i++) { if (a[i] > a[i + 1]) { k = i; int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } right = k; } }
11
Code Sample 1: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } Code Sample 2: public void process(String src, String dest) { try { KanjiDAO kanjiDAO = KanjiDAOFactory.getDAO(); MorphologicalAnalyzer mecab = MorphologicalAnalyzer.getInstance(); if (mecab.isActive()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), "UTF8")); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), "UTF8")); String line; bw.write("// // // \r\n$title=\r\n$singer=\r\n$id=\r\n\r\n + _______ // 0 0 0 0 0 0 0\r\n\r\n"); while ((line = br.readLine()) != null) { System.out.println(line); String segment[] = line.split("//"); String japanese = null; String english = null; if (segment.length > 1) english = segment[1].trim(); if (segment.length > 0) japanese = segment[0].trim().replaceAll(" ", "_"); boolean first = true; if (japanese != null) { ArrayList<ExtractedWord> wordList = mecab.extractWord(japanese); Iterator<ExtractedWord> iter = wordList.iterator(); while (iter.hasNext()) { ExtractedWord word = iter.next(); if (first) { first = false; bw.write("*"); } else bw.write(" "); if (word.isParticle) bw.write("- "); else bw.write("+ "); if (!word.original.equals(word.reading)) { System.out.println("--> " + JapaneseString.toRomaji(word.original) + " / " + JapaneseString.toRomaji(word.reading)); KReading[] kr = ReadingAnalyzer.analyzeReadingStub(word.original, word.reading, kanjiDAO); if (kr != null) { for (int i = 0; i < kr.length; i++) { if (i > 0) bw.write(" "); bw.write(kr[i].kanji); if (kr[i].type != KReading.KANA) { bw.write("|"); bw.write(kr[i].reading); } } } else { bw.write(word.original); bw.write("|"); bw.write(word.reading); } } else { bw.write(word.original); } bw.write(" // \r\n"); } if (english != null) { bw.write(english); bw.write("\r\n"); } bw.write("\r\n"); } } br.close(); bw.close(); } else { System.out.println("Mecab couldn't be initialized"); } } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public 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); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) dir.mkdir(); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } }
00
Code Sample 1: private void headinfoThread() { try { URLConnection urlc = resource.url.openConnection(); resource.setFileSize(urlc.getContentLength()); resource.setDate(urlc.getLastModified()); } catch (IOException e) { System.out.println("Error ResourceConnection, downloading headinfo"); System.out.println(e); } } Code Sample 2: public void testClickToCallOutDirection() throws Exception { init(); SipCall[] receiverCalls = new SipCall[receiversCount]; receiverCalls[0] = sipPhoneReceivers[0].createSipCall(); receiverCalls[1] = sipPhoneReceivers[1].createSipCall(); receiverCalls[0].listenForIncomingCall(); receiverCalls[1].listenForIncomingCall(); logger.info("Trying to reach url : " + CLICK2DIAL_URL + CLICK2DIAL_PARAMS); URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS); InputStream in = url.openConnection().getInputStream(); byte[] buffer = new byte[10000]; int len = in.read(buffer); String httpResponse = ""; for (int q = 0; q < len; q++) httpResponse += (char) buffer[q]; logger.info("Received the follwing HTTP response: " + httpResponse); receiverCalls[0].waitForIncomingCall(timeout); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.OK, "OK", 0)); receiverCalls[1].waitForIncomingCall(timeout); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.RINGING, "Ringing", 0)); assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.OK, "OK", 0)); assertTrue(receiverCalls[1].waitForAck(timeout)); assertTrue(receiverCalls[0].waitForAck(timeout)); assertTrue(receiverCalls[0].disconnect()); assertTrue(receiverCalls[1].waitForDisconnect(timeout)); assertTrue(receiverCalls[1].respondToDisconnect()); }
11
Code Sample 1: public Object send(URL url, Object params) throws Exception { params = processRequest(params); String response = ""; BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); response += in.readLine(); while (response != null) response += in.readLine(); in.close(); return processResponse(response); } Code Sample 2: private ArrayList<Stock> fetchStockData(Stock[] stocks) throws IOException { Log.d(TAG, "Fetching stock data from Yahoo"); ArrayList<Stock> newStocks = new ArrayList<Stock>(stocks.length); if (stocks.length > 0) { StringBuilder sb = new StringBuilder(); for (Stock stock : stocks) { sb.append(stock.getSymbol()); sb.append('+'); } sb.deleteCharAt(sb.length() - 1); String urlStr = "http://finance.yahoo.com/d/quotes.csv?f=sb2n&s=" + sb.toString(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlStr.toString()); HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); int i = 0; Log.d(TAG, "Parsing stock data from Yahoo"); while (line != null) { Log.d(TAG, "Parsing: " + line); String[] values = line.split(","); Stock stock = new Stock(stocks[i], stocks[i].getId()); stock.setCurrentPrice(Double.parseDouble(values[1])); stock.setName(values[2]); Log.d(TAG, "Parsed Stock: " + stock); newStocks.add(stock); line = reader.readLine(); i++; } } return newStocks; }
00
Code Sample 1: public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void createMd5Hash() { try { String vcardObject = new ContactToVcard(TimeZone.getTimeZone("UTC"), "UTF-8").convert(this); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(vcardObject.getBytes()); this.md5Hash = new BigInteger(m.digest()).toString(); if (log.isTraceEnabled()) { log.trace("Hash is:" + this.md5Hash); } } catch (ConverterException ex) { log.error("Error creating hash:" + ex.getMessage()); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { log.error("Error creating hash:" + noSuchAlgorithmException.getMessage()); } }