label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public String connectToServlet() { URL urlStory = null; BufferedReader brStory; String result = ""; try { urlStory = new URL(getCodeBase(), "http://localhost:8080/javawebconsole/ToApplet"); } catch (MalformedURLException MUE) { MUE.printStackTrace(); } try { brStory = new BufferedReader(new InputStreamReader(urlStory.openStream())); while (brStory.ready()) { result += brStory.readLine(); } } catch (IOException IOE) { IOE.printStackTrace(); } return result; } Code Sample 2: @SuppressWarnings("unused") private GraphicalViewer createGraphicalViewer(Composite parent) { GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); viewer.getControl().setBackground(parent.getBackground()); viewer.setRootEditPart(new ScalableFreeformRootEditPart()); viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer)); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); viewer.setContents(getContent()); return viewer; }
00
Code Sample 1: public void run() { RandomAccessFile file = null; InputStream stream = null; try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); connection.connect(); if (connection.getResponseCode() / 100 != 2) { error(); } int contentLength = connection.getContentLength(); if (contentLength < 1) { error(); } if (size == -1) { size = contentLength; stateChanged(); } file = new RandomAccessFile(saveas, "rw"); file.seek(downloaded); stream = connection.getInputStream(); while (status == DOWNLOADING) { byte buffer[]; if (size - downloaded > MAX_BUFFER_SIZE) { buffer = new byte[MAX_BUFFER_SIZE]; } else { buffer = new byte[size - downloaded]; } int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); downloaded += read; stateChanged(); } if (status == DOWNLOADING) { status = COMPLETE; stateChanged(); } } catch (Exception e) { e.printStackTrace(); error(); } finally { if (file != null) { try { file.close(); } catch (Exception e) { } } if (stream != null) { try { stream.close(); } catch (Exception e) { } } } } Code Sample 2: public static String gerarDigest(String mensagem) { String mensagemCriptografada = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); System.out.println("Mensagem original: " + mensagem); md.update(mensagem.getBytes()); byte[] digest = md.digest(); mensagemCriptografada = converterBytesEmHexa(digest); } catch (Exception e) { e.printStackTrace(); } return mensagemCriptografada; }
00
Code Sample 1: public static void bubble_sort(Sortable[] objects) { for (int i = objects.length; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (objects[j].greater_than(objects[j + 1])) { Sortable tmp = objects[j]; objects[j] = objects[j + 1]; objects[j + 1] = tmp; flipped = true; } } if (!flipped) return; } } Code Sample 2: private static URL handleRedirectUrl(URL url) { try { URLConnection cn = url.openConnection(); Utils.setHeader(cn); if (!(cn instanceof HttpURLConnection)) { return url; } HttpURLConnection hcn = (HttpURLConnection) cn; hcn.setInstanceFollowRedirects(false); int resCode = hcn.getResponseCode(); if (resCode == 200) { System.out.println("URL: " + url); return url; } String location = hcn.getHeaderField("Location"); hcn.disconnect(); return handleRedirectUrl(new URL(location.replace(" ", "%20"))); } catch (IOException e) { e.printStackTrace(); } return url; }
11
Code Sample 1: private void javaToHtml(File source, File destination) throws IOException { Reader reader = new FileReader(source); Writer writer = new FileWriter(destination); JavaUtils.writeJava(reader, writer); writer.flush(); writer.close(); } Code Sample 2: @Transactional(readOnly = false) public void saveOrUpdateProduct(Product product, File[] doc, String[] docFileName, String[] docContentType) throws IOException { logger.info("addOrUpdateProduct()"); List<Images> imgList = new ArrayList<Images>(); InputStream in = null; OutputStream out = null; String saveDirectory = ServletActionContext.getServletContext().getRealPath("common/userfiles/image/"); if (doc != null && doc.length > 0) { File uploadPath = new File(saveDirectory); if (!uploadPath.exists()) uploadPath.mkdirs(); for (int i = 0; i < doc.length; i++) { Images img = new Images(); in = new FileInputStream(doc[i]); img.setName(docFileName[i].substring(0, docFileName[i].lastIndexOf("."))); img.setRenameAs(docFileName[i]); imgList.add(img); out = new FileOutputStream(saveDirectory + "/" + img.getRenameAs()); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.flush(); } } product.setImagesCollection(imgList); productDao.saveOrUpdateProduct(product); if (null != in) { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } if (null != out) { try { out.close(); } catch (Exception e) { logger.info("addOrUpdateProduct() **********" + e.getStackTrace()); e.printStackTrace(); } } }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public static String getTextFromPart(Part part) { try { if (part != null && part.getBody() != null) { InputStream in = part.getBody().getInputStream(); String mimeType = part.getMimeType(); if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) { ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); in = null; String charset = getHeaderParameter(part.getContentType(), "charset"); if (charset != null) { charset = CharsetUtil.toJavaCharset(charset); } if (charset == null) { charset = "ASCII"; } String result = out.toString(charset); out.close(); return result; } } } catch (OutOfMemoryError oom) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + oom.toString()); } catch (Exception e) { Log.e(Email.LOG_TAG, "Unable to getTextFromPart " + e.toString()); } return null; }
00
Code Sample 1: public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); System.out.println("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { System.out.println("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); return UTType.Item; } if (contentType != null) { System.out.println("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; System.out.println("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; } Code Sample 2: public static void putWithUserSettings(String from, String to, String renameTo, boolean binary, IProgressMonitor monitor) { if (monitor != null && monitor.isCanceled()) { return; } FTPHolder ftpHolder = new FTPHolder(from, to, renameTo, binary); synchedSet.add(ftpHolder); int ftpqueuesize = PrefPageOne.getIntValue(CONSTANTS.PREF_FTPQUEUE); if (synchedSet.size() >= ftpqueuesize) { JobHandler.aquireFTPLock(); try { ftpClient = new FTPClient(); ftpClient.setRemoteAddr(InetAddress.getByName(PrefPageOne.getValue(CONSTANTS.PREF_HOST))); ftpClient.setControlPort(PrefPageOne.getIntValue(CONSTANTS.PREF_FTPPORT)); ftpClient.connect(); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } ftpClient.login((PrefPageOne.getValue(CONSTANTS.PREF_USERNAME)), FTPUtils.decrypt(PrefPageOne.getValue(CONSTANTS.PREF_PASSWORD))); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (monitor != null && monitor.isCanceled()) { JobHandler.releaseFTPLock(); ftpClient.quit(); return; } synchronized (synchedSet) { for (Iterator iter = synchedSet.iterator(); iter.hasNext(); ) { if (monitor != null && monitor.isCanceled()) { JobHandler.releaseFTPLock(); ftpClient.quit(); return; } Thread.yield(); FTPHolder element = (FTPHolder) iter.next(); if (element.binary) { ftpClient.setType(FTPTransferType.BINARY); } else { ftpClient.setType(FTPTransferType.ASCII); } ftpClient.put(element.from, element.to); if (element.renameTo != null) { try { ftpClient.delete(element.renameTo); } catch (Exception e) { } ftpClient.rename(element.to, element.renameTo); log.info("RENAME: " + element.to + "To: " + element.renameTo); } } synchedSet.clear(); } JobHandler.releaseFTPLock(); ftpClient.quit(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (FTPException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
11
Code Sample 1: public static void main(String[] args) throws IOException { System.out.println("Start filtering zgps..."); final Config config = ConfigUtils.loadConfig(args[0]); final String CONFIG_MODULE = "GPSFilterZGPS"; File sourceFileSelectedStages = new File(config.findParam(CONFIG_MODULE, "sourceFileSelectedStages")); File sourceFileZGPS = new File(config.findParam(CONFIG_MODULE, "sourceFileZGPS")); File targetFile = new File(config.findParam(CONFIG_MODULE, "targetFile")); System.out.println("Start reading selected stages..."); FilterZGPSSelectedStages selectedStages = new FilterZGPSSelectedStages(); selectedStages.createSelectedStages(sourceFileSelectedStages); System.out.println("Done. " + selectedStages.getSelectedStages().size() + " stages were stored"); System.out.println("Start reading and writing zgps..."); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFileZGPS))); BufferedWriter out = new BufferedWriter(new FileWriter(targetFile)); out.write(in.readLine()); out.newLine(); String lineFromInputFile; while ((lineFromInputFile = in.readLine()) != null) { String[] entries = lineFromInputFile.split("\t"); if (selectedStages.containsStage(Integer.parseInt(entries[0]), Integer.parseInt(entries[1]), Integer.parseInt(entries[2]))) { out.write(lineFromInputFile); out.newLine(); out.flush(); } } in.close(); out.close(); } catch (FileNotFoundException e) { System.out.println("Could not find source file for selected stages."); e.printStackTrace(); } catch (IOException e) { System.out.println("IO Exception while reading or writing zgps."); e.printStackTrace(); } System.out.println("Done."); } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); resp.setCharacterEncoding("utf-8"); EntityManager em = EMF.get().createEntityManager(); String url = req.getRequestURL().toString(); String key = req.getParameter("key"); String format = req.getParameter("format"); if (key == null || !key.equals(Keys.APPREGKEY)) { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); if (format != null && format.equals("xml")) resp.getWriter().print(Error.notAuthorised("").toXML(em)); else resp.getWriter().print(Error.notAuthorised("").toJSON(em)); em.close(); return; } String appname = req.getParameter("name"); if (appname == null || appname.equals("")) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); if (format != null && format.equals("xml")) resp.getWriter().print(Error.noAppId(null).toXML(em)); else resp.getWriter().print(Error.noAppId(null).toJSON(em)); em.close(); return; } StringBuffer appkey = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); String api = System.nanoTime() + "" + System.identityHashCode(this) + "" + appname; algorithm.update(api.getBytes()); byte[] digest = algorithm.digest(); for (int i = 0; i < digest.length; i++) { appkey.append(Integer.toHexString(0xFF & digest[i])); } } catch (NoSuchAlgorithmException e) { resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); log.severe(e.toString()); em.close(); return; } ClientApp app = new ClientApp(); app.setName(appname); app.setKey(appkey.toString()); app.setNumreceipts(0L); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(app); tx.commit(); } catch (Throwable t) { log.severe("Error persisting application " + app.getName() + ": " + t.getMessage()); tx.rollback(); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); if (format != null && format.equals("xml")) resp.getWriter().print(Error.unknownError().toXML(em)); else resp.getWriter().print(Error.unknownError().toJSON(em)); em.close(); return; } resp.setStatus(HttpServletResponse.SC_CREATED); if (format != null && format.equals("xml")) resp.getWriter().print(app.toXML(em)); else resp.getWriter().print(app.toJSON(em)); em.close(); } Code Sample 2: public void deploy(String baseDir, boolean clean) throws IOException { try { ftp.connect(hostname, port); log.debug("Connected to: " + hostname + ":" + port); ftp.login(username, password); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { throw new IOException("Error logging onto ftp server. FTPClient returned code: " + reply); } log.debug("Logged in"); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); if (clean) { deleteDir(remoteDir); } storeFolder(baseDir, remoteDir); } finally { ftp.disconnect(); } }
11
Code Sample 1: private static void _checkConfigFile() throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; boolean copy = false; File from = new java.io.File(filePath); if (!from.exists()) { Properties properties = new Properties(); properties.put(Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CELL_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CELL_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_VISIBILITY")); Company comp = PublicCompanyFactory.getDefaultCompany(); int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW"); for (int i = 1; i <= numberGenericVariables; i++) { properties.put(LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + i).replace(" ", "_"), Config.getStringProperty("ADDITIONAL_INFO_DEFAULT_VISIBILITY")); } try { properties.store(new java.io.FileOutputStream(filePath), null); } catch (Exception e) { Logger.error(UserManagerPropertiesFactory.class, e.getMessage(), e); } from = new java.io.File(filePath); copy = true; } String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File to = new java.io.File(tmpFilePath); if (!to.exists()) { to.createNewFile(); copy = true; } if (copy) { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "_checkLanguagesFiles:Property File Copy Failed " + e, e); } } Code Sample 2: private void copyXsl(File aTargetLogDir) { Trace.println(Trace.LEVEL.UTIL, "copyXsl( " + aTargetLogDir.getName() + " )", true); if (myXslSourceDir == null) { return; } File[] files = myXslSourceDir.listFiles(); for (int i = 0; i < files.length; i++) { File srcFile = files[i]; if (!srcFile.isDirectory()) { File tgtFile = new File(aTargetLogDir + File.separator + srcFile.getName()); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(srcFile).getChannel(); outChannel = new FileOutputStream(tgtFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw new IOError(e); } finally { if (inChannel != null) try { inChannel.close(); } catch (IOException exc) { throw new IOError(exc); } if (outChannel != null) try { outChannel.close(); } catch (IOException exc) { throw new IOError(exc); } } } } }
11
Code Sample 1: @HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } } Code Sample 2: public String storeUploadedZip(byte[] zip, String name) { List filesToStore = new ArrayList(); int i = 0; ZipInputStream zipIs = new ZipInputStream(new ByteArrayInputStream(zip)); ZipEntry zipEntry = zipIs.getNextEntry(); while (zipEntry != null) { if (zipEntry.isDirectory() == false) { i++; ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zipIs, baos); baos.close(); } zipIs.closeEntry(); zipEntry = zipIs.getNextEntry(); } }
11
Code Sample 1: public void testPreparedStatementRollback1() throws Exception { Connection localCon = getConnection(); Statement stmt = localCon.createStatement(); stmt.execute("CREATE TABLE #psr1 (data BIT)"); localCon.setAutoCommit(false); PreparedStatement pstmt = localCon.prepareStatement("INSERT INTO #psr1 (data) VALUES (?)"); pstmt.setBoolean(1, true); assertEquals(1, pstmt.executeUpdate()); pstmt.close(); localCon.rollback(); ResultSet rs = stmt.executeQuery("SELECT data FROM #psr1"); assertFalse(rs.next()); rs.close(); stmt.close(); localCon.close(); try { localCon.commit(); fail("Expecting commit to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } try { localCon.rollback(); fail("Expecting rollback to fail, connection was closed"); } catch (SQLException ex) { assertEquals("HY010", ex.getSQLState()); } } Code Sample 2: public void insertComponent() throws SQLException { Connection connection = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(this.jdbcURL); connection.setAutoCommit(false); String query = "INSERT INTO components(name,rate,quantity, description) VALUES(?,?,?,?)"; ps = (PreparedStatement) connection.prepareStatement(query); ps.setString(1, this.name); ps.setDouble(2, this.rate); ps.setInt(3, this.quantity); ps.setString(4, this.description); ps.executeUpdate(); connection.commit(); } catch (Exception ex) { connection.rollback(); } finally { try { connection.close(); } catch (Exception ex) { } try { ps.close(); } catch (Exception ex) { } } }
00
Code Sample 1: public HttpEntity execute(final HttpRequestBase request) throws IOException, ClientProtocolException { final HttpResponse response = mClient.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK | statusCode == HttpStatus.SC_CREATED) { return response.getEntity(); } return null; } Code Sample 2: private void Download(String uri) throws MalformedURLException { URL url = new URL(uri); try { bm = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException ex) { bm = getError(); } }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".zip"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(role); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
11
Code Sample 1: public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public static void upload(FTPDetails ftpDetails) { FTPClient ftp = new FTPClient(); try { String host = ftpDetails.getHost(); logger.info("Connecting to ftp host: " + host); ftp.connect(host); logger.info("Received reply from ftp :" + ftp.getReplyString()); ftp.login(ftpDetails.getUserName(), ftpDetails.getPassword()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.makeDirectory(ftpDetails.getRemoterDirectory()); logger.info("Created directory :" + ftpDetails.getRemoterDirectory()); ftp.changeWorkingDirectory(ftpDetails.getRemoterDirectory()); BufferedInputStream ftpInput = new BufferedInputStream(new FileInputStream(new File(ftpDetails.getLocalFilePath()))); OutputStream storeFileStream = ftp.storeFileStream(ftpDetails.getRemoteFileName()); IOUtils.copy(ftpInput, storeFileStream); logger.info("Copied file : " + ftpDetails.getLocalFilePath() + " >>> " + host + ":/" + ftpDetails.getRemoterDirectory() + "/" + ftpDetails.getRemoteFileName()); ftpInput.close(); storeFileStream.close(); ftp.logout(); ftp.disconnect(); logger.info("Logged out. "); } catch (Exception e) { throw new RuntimeException(e); } }
00
Code Sample 1: public synchronized DASMetaData fillInDASMetaData(URL url) throws DASException { try { con = (HttpURLConnection) url.openConnection(); dasRespVersion = con.getHeaderField("X-DAS-Version"); dasSchema = con.getHeaderField("X-DAS-SchemaName"); dasSchemaVersion = con.getHeaderField("X-DAS-SchemaVersion"); String dasStatusString = con.getHeaderField("X-DAS-Status"); if (dasStatusString == null) { throw new DASException("Temporary DAS Error"); } if (dasStatusString.indexOf(" ") != -1) { dasStatusString = dasStatusString.substring(0, dasStatusString.indexOf(" ")); } dasStatus = Integer.parseInt(dasStatusString); if (dasStatus != 200) { throw new DASException("Command cannot be executed: Error was " + Integer.toString(dasStatus)); } } catch (IOException e) { throw new DASException("Cannot connect to data source"); } if (dasSchema != null && dasSchemaVersion != null) { headers.put("X-DAS-Version", dasRespVersion); headers.put("X-DAS-SchemaName", dasSchema); headers.put("X-DAS-SchemaVersion", dasSchemaVersion); dasVersion = Float.parseFloat(dasRespVersion.substring(dasRespVersion.indexOf("/") + 1, dasRespVersion.length())); theMetaData = new DASMetaDataImpl(dasVersion, Float.parseFloat(dasSchemaVersion), dasSchema); } else { dasVersion = Float.parseFloat(dasRespVersion.substring(dasRespVersion.indexOf("/") + 1, dasRespVersion.length())); headers.put("X-DAS-Version", dasRespVersion); theMetaData = new DASMetaDataImpl(dasVersion); } String lengthStr = con.getHeaderField("content-length"); if (lengthStr != null) headers.put("content-length", lengthStr); theMetaData.setDASHeaders(headers); return theMetaData; } Code Sample 2: private void removeCollection(long oid, Connection conn) throws XMLDBException { try { String sql = "DELETE FROM X_DOCUMENT WHERE X_DOCUMENT.XDB_COLLECTION_OID = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); sql = "DELETE FROM XDB_COLLECTION WHERE XDB_COLLECTION.XDB_COLLECTION_OID = ?"; pstmt = conn.prepareStatement(sql); pstmt.setLong(1, oid); pstmt.executeUpdate(); pstmt.close(); removeChildCollection(oid, conn); } catch (java.sql.SQLException se) { try { conn.rollback(); } catch (java.sql.SQLException se2) { se2.printStackTrace(); } se.printStackTrace(); } }
11
Code Sample 1: private void fileCopier(String filenameFrom, String filenameTo) { FileInputStream fromStream = null; FileOutputStream toStream = null; try { fromStream = new FileInputStream(new File(filenameFrom)); if (new File(filenameTo).exists()) { new File(filenameTo).delete(); } File dirr = new File(getContactPicPath()); if (!dirr.exists()) { dirr.mkdir(); } toStream = new FileOutputStream(new File(filenameTo)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fromStream.read(buffer)) != -1) toStream.write(buffer, 0, bytesRead); } catch (FileNotFoundException e) { Errmsg.errmsg(e); } catch (IOException e) { Errmsg.errmsg(e); } finally { try { if (fromStream != null) { fromStream.close(); } if (toStream != null) { toStream.close(); } } catch (IOException e) { Errmsg.errmsg(e); } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private static String md5(String pwd) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(pwd.getBytes(), 0, pwd.length()); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new Error(); } } Code Sample 2: public String setEncryptedPassword(String rawPassword) { String out = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(rawPassword.getBytes()); byte raw[] = md.digest(); out = new String(); for (int x = 0; x < raw.length; x++) { String hex2 = Integer.toHexString((int) raw[x] & 0xFF); if (1 == hex2.length()) { hex2 = "0" + hex2; } out += hex2; int a = 1; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return out; }
11
Code Sample 1: public static String getMD5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); String salt = "UseTheForce4"; password = salt + password; md5.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, md5.digest()).toString(16); } catch (Exception e) { } return password; } Code Sample 2: public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); }
11
Code Sample 1: private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } } Code Sample 2: @SuppressWarnings("unchecked") public static void unzip(String input, String output) { try { if (!output.endsWith("/")) output = output + "/"; ZipFile zip = new ZipFile(input); Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { FileUtils.forceMkdir(new File(output + entry.getName())); } else { FileOutputStream out = new FileOutputStream(output + entry.getName()); IOUtils.copy(zip.getInputStream(entry), out); IOUtils.closeQuietly(out); } } } catch (Exception e) { log.error("�����ҵ��ļ�:" + output, e); throw new RuntimeException("�����ҵ��ļ�:" + output, e); } }
11
Code Sample 1: private void sendBinaryFile(File file) throws IOException, CVSException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); if (m_bCompressFiles) { GZIPOutputStream gzipOut = null; InputStream gzipIn = null; File gzipFile = null; try { gzipFile = File.createTempFile("javacvs", "tmp"); gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile))); int b; while ((b = in.read()) != -1) gzipOut.write((byte) b); gzipOut.close(); long gzipLength = gzipFile.length(); sendLine("z" + Long.toString(gzipLength)); gzipIn = new BufferedInputStream(new FileInputStream(gzipFile)); for (long i = 0; i < gzipLength; i++) { b = gzipIn.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } finally { if (gzipOut != null) gzipOut.close(); if (gzipIn != null) gzipIn.close(); if (gzipFile != null) gzipFile.delete(); } } else { long nLength = file.length(); sendLine(Long.toString(nLength)); for (long i = 0; i < nLength; i++) { int b = in.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } } Code Sample 2: private static void copyFile(File src, File dst) throws IOException { FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); }
11
Code Sample 1: public void covertFile(File file) throws IOException { if (!file.isFile()) { return; } Reader reader = null; OutputStream os = null; File newfile = null; String filename = file.getName(); boolean succeed = false; try { newfile = new File(file.getParentFile(), filename + ".bak"); reader = new InputStreamReader(new FileInputStream(file), fromEncoding); os = new FileOutputStream(newfile); IOUtils.copy(reader, os, toEncoding); } catch (Exception e) { e.printStackTrace(); throw new IOException("Encoding error for file [" + file.getAbsolutePath() + "]"); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (Exception e) { e.printStackTrace(); } } } try { file.delete(); succeed = newfile.renameTo(file); } catch (Exception e) { throw new IOException("Clear bak error for file [" + file.getAbsolutePath() + "]"); } if (succeed) { System.out.println("Changed encoding for file [" + file.getAbsolutePath() + "]"); } } Code Sample 2: private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; }
11
Code Sample 1: public static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception { org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password); HttpMethod method = new GetMethod(url); client.executeMethod(method); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copyLarge(method.getResponseBodyAsStream(), output); } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public String getScenarioData(String urlForSalesData) throws IOException, Exception { InputStream inputStream = null; BufferedReader bufferedReader = null; DataInputStream input = null; StringBuffer sBuf = new StringBuffer(); Proxy proxy; if (httpWebProxyServer != null && Integer.toString(httpWebProxyPort) != null) { SocketAddress address = new InetSocketAddress(httpWebProxyServer, httpWebProxyPort); proxy = new Proxy(Proxy.Type.HTTP, address); } else { proxy = null; } proxy = null; URL url; try { url = new URL(urlForSalesData); HttpURLConnection httpUrlConnection; if (proxy != null) httpUrlConnection = (HttpURLConnection) url.openConnection(proxy); else httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setDoInput(true); httpUrlConnection.setRequestMethod("GET"); String name = rb.getString("WRAP_NAME"); String password = rb.getString("WRAP_PASSWORD"); Credentials simpleAuthCrentials = new Credentials(TOKEN_TYPE.SimpleApiAuthToken, name, password); ACSTokenProvider tokenProvider = new ACSTokenProvider(httpWebProxyServer, httpWebProxyPort, simpleAuthCrentials); String requestUriStr1 = "https://" + solutionName + "." + acmHostName + "/" + serviceName; String appliesTo1 = rb.getString("SIMPLEAPI_APPLIES_TO"); String token = tokenProvider.getACSToken(requestUriStr1, appliesTo1); httpUrlConnection.addRequestProperty("token", "WRAPv0.9 " + token); httpUrlConnection.addRequestProperty("solutionName", solutionName); httpUrlConnection.connect(); if (httpUrlConnection.getResponseCode() == HttpServletResponse.SC_UNAUTHORIZED) { List<TestSalesOrderService> salesOrderServiceBean = new ArrayList<TestSalesOrderService>(); TestSalesOrderService response = new TestSalesOrderService(); response.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED); response.setResponseMessage(httpUrlConnection.getResponseMessage()); salesOrderServiceBean.add(response); } inputStream = httpUrlConnection.getInputStream(); input = new DataInputStream(inputStream); bufferedReader = new BufferedReader(new InputStreamReader(input)); String str; while (null != ((str = bufferedReader.readLine()))) { sBuf.append(str); } String responseString = sBuf.toString(); return responseString; } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } } Code Sample 2: public static String getUploadDeleteComboBox(String fromMode, String fromFolder, String action, String object, HttpSession session) { FTPClient ftp = new FTPClient(); CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user"); StringBuffer links = new StringBuffer(); StringBuffer folders = new StringBuffer(); String folder = ""; String server = ""; String login = ""; String password = ""; int i = 0; String liveFTPServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER") + ""; liveFTPServer = liveFTPServer.trim(); if ((liveFTPServer == null) || (liveFTPServer.equals("null")) || (liveFTPServer.equals(""))) { return ("This tool is not " + "configured and will not operate. " + "If you wish it to do so, please edit " + "this publication's properties and add correct values to " + " the Remote Server Upstreaming section."); } if (action.equals("Upload")) { server = (String) user.workingPubConfigElementsHash.get("TESTFTPSERVER"); login = (String) user.workingPubConfigElementsHash.get("TESTFTPLOGIN"); password = (String) user.workingPubConfigElementsHash.get("TESTFTPPASSWORD"); CofaxToolsUtil.log("server= " + server + " , login= " + login + " , password=" + password); if (object.equals("Media")) { folder = (String) user.workingPubConfigElementsHash.get("TESTIMAGESFOLDER"); } if (object.equals("Templates")) { folder = (String) user.workingPubConfigElementsHash.get("TESTTEMPLATEFOLDER"); CofaxToolsUtil.log("testTemplateFolder= " + folder); } } if (action.equals("Delete")) { login = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN"); password = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD"); if (object.equals("Media")) { server = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESSERVER"); folder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER"); } if (object.equals("Templates")) { server = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER"); folder = (String) user.workingPubConfigElementsHash.get("LIVETEMPLATEFOLDER"); } } ArrayList servers = splitServers(server); try { int reply; ftp.connect((String) servers.get(0)); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox connecting to server: " + (String) servers.get(0)); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox results: " + ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return ("CofaxToolsFTP getUploadDeleteComboBox ERROR: FTP server refused connection: " + server); } else { ftp.login(login, password); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox login / pass " + login + " " + password); } try { String tempParentFolderName = folder; CofaxToolsUtil.log("fromfolder is " + fromFolder); if ((fromFolder != null) && (fromFolder.length() > folder.length())) { folder = fromFolder; tempParentFolderName = folder; int subSt = folder.lastIndexOf("/"); tempParentFolderName = tempParentFolderName.substring(0, subSt); String publicName = ""; int subStri = folder.lastIndexOf((String) user.workingPubName); if (subStri > -1) { publicName = folder.substring(subStri); } folders.append("<B><A HREF=\'/tools/?mode=" + fromMode + "&hl=templates_view_templates_images&fromFolder=" + tempParentFolderName + "\'>" + tempParentFolderName + "</A></B><BR>\n"); } else if ((fromFolder != null) && (fromFolder.length() == folder.length())) { folder = fromFolder; tempParentFolderName = folder; int subSt = folder.lastIndexOf("/"); tempParentFolderName = tempParentFolderName.substring(0, subSt); } boolean changed = ftp.changeWorkingDirectory(folder); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox changing working directory to " + folder); CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox results " + changed); FTPFile[] files = null; if ((action.equals("Delete")) && (object.equals("Templates"))) { files = ftp.listFiles(new CofaxToolsNTFileListParser()); } else { files = ftp.listFiles(new CofaxToolsNTFileListParser()); } if (files == null) { CofaxToolsUtil.log("null"); } for (int ii = 0; ii < files.length; ii++) { FTPFile thisFile = (FTPFile) files[ii]; String name = thisFile.getName(); if (!thisFile.isDirectory()) { links.append("<INPUT TYPE=CHECKBOX NAME=" + i + " VALUE=" + folder + "/" + name + ">" + name + "<BR>\n"); i++; } if ((thisFile.isDirectory()) && (!name.startsWith(".")) && (!name.endsWith("."))) { int subStr = folder.lastIndexOf((String) user.workingPubName); String tempFolderName = ""; if (subStr > -1) { tempFolderName = folder.substring(subStr); } else { tempFolderName = folder; } folders.append("<LI><A HREF=\'/tools/?mode=" + fromMode + "&hl=templates_view_templates_images&fromFolder=" + folder + "/" + name + "\'>" + tempFolderName + "/" + name + "</A><BR>"); } } ftp.logout(); ftp.disconnect(); } catch (java.io.IOException e) { return ("CofaxToolsFTP getUploadDeleteComboBox cannot read directory: " + folder); } } catch (IOException e) { return ("Could not connect to server: " + e); } links.append("<INPUT TYPE=HIDDEN NAME=numElements VALUE=" + i + " >\n"); links.append("<INPUT TYPE=SUBMIT VALUE=\"" + action + " " + object + "\">\n"); return (folders.toString() + links.toString()); }
00
Code Sample 1: public static String validateAuthTicketAndGetSessionId(ServletRequest request, String servicekey) { String loginapp = SSOFilter.getLoginapp(); String authticket = request.getParameter("authticket"); String u = SSOUtil.addParameter(loginapp + "/api/validateauthticket", "authticket", authticket); u = SSOUtil.addParameter(u, "servicekey", servicekey); String sessionid = null; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { sessionid = line.trim(); } reader.close(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } if ("error".equals(sessionid)) { return null; } return sessionid; } Code Sample 2: public List<T_new> executeGet(HttpTransport transport, String targetUrl) throws HttpResponseException, IOException { HttpRequest req = transport.buildGetRequest(); req.setUrl(targetUrl); NotifyFeed feed = req.execute().parseAs(NotifyFeed.class); if (feed.entry == null) { return Collections.emptyList(); } List<T_new> results = new ArrayList<T_new>(); for (NotifyEntry e : feed.entry) { StringBuilder buffer = new StringBuilder(); if (e.id != null) { buffer.append(e.id); } buffer.append("@"); if (e.updated != null) { buffer.append(e.updated.toStringRfc3339().substring(0, 19) + "Z"); } Key key = Datastore.createKey(T_new.class, buffer.toString()); T_new news = new T_new(); news.setTitle(e.title); if (e.content != null) { news.setNewText(e.content.substring(0, Math.min(e.content.length(), 500))); } if (e.status != null && e.content == null) { news.setNewText(e.status); } if (e.updated != null) { news.setCreatedAt(new Date(e.updated.value)); } news.setContentUrl(e.getAlternate()); if (e.author != null) { news.setAuthor(e.author.name); } news.setKey(key); results.add(news); } return results; }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public static void appendFile(String namePrefix, File baseDir, File file, ZipOutputStream zipOut) throws IOException { Assert.Arg.notNull(baseDir, "baseDir"); Assert.Arg.notNull(file, "file"); Assert.Arg.notNull(zipOut, "zipOut"); if (namePrefix == null) namePrefix = ""; String path = FileSystemUtils.getRelativePath(baseDir, file); ZipEntry zipEntry = new ZipEntry(namePrefix + path); zipOut.putNextEntry(zipEntry); InputStream fileInput = FileUtils.openInputStream(file); try { org.apache.commons.io.IOUtils.copyLarge(fileInput, zipOut); } finally { fileInput.close(); } }
11
Code Sample 1: public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } Code Sample 2: public EncodedScript(PackageScript source, DpkgData data) throws IOException { _source = source; final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream output = null; try { output = MimeUtility.encode(bytes, BASE64); } catch (final MessagingException e) { throw new IOException("Failed to uuencode script. name=[" + _source.getFriendlyName() + "], reason=[" + e.getMessage() + "]."); } IOUtils.write(HEADER, bytes, Dpkg.CHAR_ENCODING); bytes.flush(); IOUtils.copy(_source.getSource(data), output); output.flush(); IOUtils.write(FOOTER, bytes, Dpkg.CHAR_ENCODING); bytes.flush(); output.close(); bytes.close(); _encoded = bytes.toString(Dpkg.CHAR_ENCODING); }
00
Code Sample 1: private void checkSites() { Log.d(LOG_TAG, "Updating sites: " + sitesToCheck.keySet().toString()); for (Map.Entry<Site, Item> entry : sitesToCheck.entrySet()) { final Site site = entry.getKey(); final Item oldItem = entry.getValue(); try { final HttpGet req = new HttpGet(site.getUrl().toURI()); req.addHeader("Cache-Control", "no-cache"); req.addHeader("Pragma", "no-cache"); if (oldItem != null) { final Date lastModified = oldItem.getTimestamp(); if (lastModified != null) { req.addHeader("If-Modified-Since", Utils.formatRFC822Date(lastModified)); } } final HttpResponse response = httpClient.execute(req); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final FeedHandler handler = site.getHandler().newInstance(); final InputStream in = response.getEntity().getContent(); Xml.parse(in, site.getEncoding(), handler); in.close(); notify(site, handler.getCurrentItem()); } else if (response.getStatusLine().getStatusCode() != 304) { Log.e(LOG_TAG, "HTTP request for " + site.name() + " failed: " + response.getStatusLine().toString()); } } catch (Throwable e) { Log.e(LOG_TAG, e.getMessage(), e); } } } Code Sample 2: public static byte[] readUrl(URL url) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); InputStream is = url.openStream(); try { IOUtils.copy(is, os); return os.toByteArray(); } finally { is.close(); } }
11
Code Sample 1: public static String md5Encode(String pass) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); return bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La librería java.security no implemente MD5"); } } Code Sample 2: 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; }
11
Code Sample 1: private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) { final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir())); final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey())); InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(fileIn); fileOutputStream = new FileOutputStream(fileOut); IOUtils.copy(fileInputStream, fileOutputStream); fileInputStream.close(); fileOutputStream.close(); } catch (final IOException e) { log.error("file io exception", e); return; } } Code Sample 2: private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { } } catch (FileNotFoundException e) { } }
00
Code Sample 1: protected void onSubmit() { try { Connection conn = ((JdbcRequestCycle) getRequestCycle()).getConnection(); String sql = "insert into entry (author, accessibility) values(?,?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); pstmt.setInt(2, accessibility.getId()); pstmt.executeUpdate(); ResultSet insertedEntryIdRs = pstmt.getGeneratedKeys(); insertedEntryIdRs.next(); int insertedEntryId = insertedEntryIdRs.getInt(1); sql = "insert into revisions (title, entry, content, tags," + " revision_remark) values(?,?,?,?,?)"; PreparedStatement pstmt2 = conn.prepareStatement(sql); pstmt2.setString(1, getTitle()); pstmt2.setInt(2, insertedEntryId); pstmt2.setString(3, getContent()); pstmt2.setString(4, getTags()); pstmt2.setString(5, "newly added"); int insertCount = pstmt2.executeUpdate(); if (insertCount > 0) { info("Successfully added one new record."); } else { conn.rollback(); info("Addition of one new record failed."); } } catch (SQLException ex) { ex.printStackTrace(); } } Code Sample 2: public void updateChecksum() { try { MessageDigest md = MessageDigest.getInstance("SHA"); List<Parameter> sortedKeys = new ArrayList<Parameter>(parameter_instances.keySet()); for (Parameter p : sortedKeys) { if (parameter_instances.get(p) != null && !(parameter_instances.get(p) instanceof OptionalDomain.OPTIONS) && !(parameter_instances.get(p).equals(FlagDomain.FLAGS.OFF))) { md.update(parameter_instances.get(p).toString().getBytes()); } } this.checksum = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
11
Code Sample 1: private void copyResources(File oggDecDir, String[] resources, String resPrefix) throws FileNotFoundException, IOException { for (int i = 0; i < resources.length; i++) { String res = resPrefix + resources[i]; InputStream is = this.getClass().getResourceAsStream(res); if (is == null) throw new IllegalArgumentException("cannot find resource '" + res + "'"); File file = new File(oggDecDir, resources[i]); if (!file.exists() || file.length() == 0) { FileOutputStream fos = new FileOutputStream(file); try { IOUtils.copyStreams(is, fos); } finally { fos.close(); } } } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: protected String readFileUsingFileUrl(String fileUrlName) { String response = ""; try { URL url = new URL(fileUrlName); URLConnection connection = url.openConnection(); InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine = ""; while ((inputLine = in.readLine()) != null) { response += inputLine + "\n"; } if (response.endsWith("\n")) { response = response.substring(0, response.length() - 1); } in.close(); } catch (Exception x) { x.printStackTrace(); } return response; } Code Sample 2: public void fillTableValues() { java.util.ArrayList cpool = newgen.presentation.NewGenMain.getAppletInstance().getCataloguingPool(); String xmlreq = AdministrationXMLGenerator.getInstance().getPoolChronologicalSubDivision("4", cpool); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); java.util.List onelist = rootelement.getChildren(); for (int i = 0; i < onelist.size(); i++) { Element rec = (Element) onelist.get(i); Object[] r = new Object[7]; String[] chronolib = new String[2]; chronolib[0] = rec.getChild("ChronologicalSubDivisionId").getText(); chronolib[1] = rec.getChild("LibraryId").getText(); this.chronoid_libid.add(chronolib); r[0] = rec.getChild("ChronologicalSubDivision").getText(); this.dtmSearch.addRow(r); } } catch (Exception e) { System.out.println(e); } }
11
Code Sample 1: protected static void copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) targetLocation.mkdir(); children = sourceLocation.list(); for (i = 0; i < children.length; i++) { copyOrMove(new File(sourceLocation, children[i]), new File(targetLocation, children[i]), move); } if (move) sourceLocation.delete(); } else { in = new FileInputStream(sourceLocation); if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation); buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) sourceLocation.delete(); } } 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: protected boolean checkLogin(String username, String password) { log.debug("Called checkLogin with " + username); String urlIn = GeoNetworkContext.url + "/" + GeoNetworkContext.loginService + "?username=" + username + "&password=" + password; Element results = null; String cookieValue = null; try { URL url = new URL(urlIn); URLConnection conn = url.openConnection(); conn.setConnectTimeout(1000); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); try { results = Xml.loadStream(in); log.debug("CheckLogin to GeoNetwork returned " + Xml.getString(results)); } finally { in.close(); } Map<String, List<String>> headers = conn.getHeaderFields(); List<String> values = headers.get("Set-Cookie"); for (Iterator iter = values.iterator(); iter.hasNext(); ) { String v = (String) iter.next(); if (cookieValue == null) { cookieValue = v; } else { cookieValue = cookieValue + ";" + v; } } } catch (Exception e) { throw new RuntimeException("User login to GeoNetwork failed: ", e); } if (!results.getName().equals("ok")) return false; Session session = getConnection().getSession(); session.removeAttribute("usercookie.object"); session.setAttribute("usercookie.object", cookieValue); log.debug("Cookie set is " + cookieValue); return true; } Code Sample 2: public static String post(String actionUrl, Map<String, String> params) { HttpPost httpPost = new HttpPost(actionUrl); List<NameValuePair> list = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } try { httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { return EntityUtils.toString(httpResponse.getEntity()); } } catch (Exception e) { throw new RuntimeException(e); } return null; }
00
Code Sample 1: public void process() throws Exception { String searchXML = FileUtils.readFileToString(new File(getSearchRequestRelativeFilePath())); Map<String, String> parametersMap = new HashMap<String, String>(); parametersMap.put("searchXML", searchXML); String proxyHost = null; int proxyPort = -1; String serverUserName = null; String serverUserPassword = null; FileOutputStream fos = null; if (getUseProxy()) { serverUserName = getServerUserName(); serverUserPassword = getServerUserPassword(); } if (getUseProxy()) { proxyHost = getProxyHost(); proxyPort = getProxyPort(); } try { InputStream responseInputStream = URLUtils.getHttpResponse(getSearchBaseURL(), serverUserName, serverUserPassword, URLUtils.HTTP_POST_METHOD, proxyHost, proxyPort, parametersMap, -1); fos = new FileOutputStream(getSearchResponseRelativeFilePath()); IOUtils.copyLarge(responseInputStream, fos); } finally { if (null != fos) { fos.flush(); fos.close(); } } } Code Sample 2: @Override public String decryptString(String passphrase, String crypted) throws Exception { MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(passphrase.getBytes("UTF-8")); byte digest[] = md.digest(); String digestString = base64encode(digest); System.out.println(digestString); SecureRandom sr = new SecureRandom(digestString.getBytes()); KeyGenerator kGen = KeyGenerator.getInstance("AES"); kGen.init(128, sr); Key key = kGen.generateKey(); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] cryptString = base64decode(crypted); byte[] bOut = cipher.doFinal(cryptString); String outString = new String(bOut, "UTF-8"); return outString; }
11
Code Sample 1: public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } } Code Sample 2: @Test public void config() throws IOException { Reader reader = new FileReader(new File("src/test/resources/test.yml")); Writer writer = new FileWriter(new File("src/site/apt/config.apt")); writer.write("------\n"); writer.write(FileUtils.readFully(reader)); writer.flush(); writer.close(); }
00
Code Sample 1: 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(); } } } Code Sample 2: private ResponseStatus performHandshake(String url) throws IOException { HttpURLConnection connection = Caller.getInstance().openConnection(url); InputStream is = connection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); int statusCode = ResponseStatus.codeForStatus(status); ResponseStatus responseStatus; if (statusCode == ResponseStatus.OK) { this.sessionId = r.readLine(); this.nowPlayingUrl = r.readLine(); this.submissionUrl = r.readLine(); responseStatus = new ResponseStatus(statusCode); } else if (statusCode == ResponseStatus.FAILED) { responseStatus = new ResponseStatus(statusCode, status.substring(status.indexOf(' ') + 1)); } else { return new ResponseStatus(statusCode); } r.close(); return responseStatus; }
11
Code Sample 1: public void fileCopy2(File inFile, File outFile) throws Exception { try { FileChannel srcChannel = new FileInputStream(inFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { throw new Exception("Could not copy file: " + inFile.getName()); } } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: private void duplicateIndices(Connection scon, Connection dcon, String table) { try { String idx_name, idx_att, query; ResultSet idxs = scon.getMetaData().getIndexInfo(null, null, table, false, false); Statement stmt = dcon.createStatement(); while (idxs.next()) { idx_name = idxs.getString(6); idx_att = idxs.getString(9); idx_name += "_" + idx_att + "_idx"; logger.debug("Creating index " + idx_name); query = "CREATE INDEX " + idx_name + " ON " + table + "(" + idx_att + ")"; stmt.executeUpdate(query); dcon.commit(); } } catch (Exception e) { logger.error("Unable to copy indices " + e); try { dcon.rollback(); } catch (SQLException e1) { logger.fatal(e1); } } } Code Sample 2: public void removeRoom(int thisRoom) { DBConnection con = null; try { con = DBServiceManager.allocateConnection(); con.setAutoCommit(false); String query = "DELETE FROM cafe_Chat_Category WHERE cafe_Chat_Category_id=? "; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); query = "DELETE FROM cafe_Chatroom WHERE cafe_chatroom_category=? "; ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); con.commit(); con.setAutoCommit(true); } catch (SQLException e) { try { con.rollback(); } catch (SQLException sqle) { } } finally { if (con != null) con.release(); } }
11
Code Sample 1: private void addAllSpecialPages(Environment env, ZipOutputStream zipout, int progressStart, int progressLength) throws Exception, IOException { ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", locale); String tpl; int count = 0; int numberOfSpecialPages = 7; progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; String cssContent = wb.readRaw(virtualWiki, "StyleSheet"); addZipEntry(zipout, "css/vqwiki.css", cssContent); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; tpl = getTemplateFilledWithContent("search"); addTopicEntry(zipout, tpl, "WikiSearch", "WikiSearch.html"); progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; zipout.putNextEntry(new ZipEntry("applets/export2html-applet.jar")); IOUtils.copy(new FileInputStream(ctx.getRealPath("/WEB-INF/classes/export2html/export2html-applet.jar")), zipout); zipout.closeEntry(); zipout.flush(); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JarOutputStream indexjar = new JarOutputStream(bos); JarEntry jarEntry; File searchDir = new File(wb.getSearchEngine().getSearchIndexPath(virtualWiki)); String files[] = searchDir.list(); StringBuffer listOfAllFiles = new StringBuffer(); for (int i = 0; i < files.length; i++) { if (listOfAllFiles.length() > 0) { listOfAllFiles.append(","); } listOfAllFiles.append(files[i]); jarEntry = new JarEntry("lucene/index/" + files[i]); indexjar.putNextEntry(jarEntry); IOUtils.copy(new FileInputStream(new File(searchDir, files[i])), indexjar); indexjar.closeEntry(); } indexjar.flush(); indexjar.putNextEntry(new JarEntry("lucene/index.dir")); IOUtils.copy(new StringReader(listOfAllFiles.toString()), indexjar); indexjar.closeEntry(); indexjar.flush(); indexjar.close(); zipout.putNextEntry(new ZipEntry("applets/index.jar")); zipout.write(bos.toByteArray()); zipout.closeEntry(); zipout.flush(); bos.reset(); } catch (Exception e) { logger.log(Level.FINE, "Exception while adding lucene index: ", e); } progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99); count++; StringBuffer content = new StringBuffer(); content.append("<table><tr><th>" + messages.getString("common.date") + "</th><th>" + messages.getString("common.topic") + "</th><th>" + messages.getString("common.user") + "</th></tr>" + IOUtils.LINE_SEPARATOR); Collection all = null; try { Calendar cal = Calendar.getInstance(); ChangeLog cl = wb.getChangeLog(); int n = env.getIntSetting(Environment.PROPERTY_RECENT_CHANGES_DAYS); if (n == 0) { n = 5; } all = new ArrayList(); for (int i = 0; i < n; i++) { Collection col = cl.getChanges(virtualWiki, cal.getTime()); if (col != null) { all.addAll(col); } cal.add(Calendar.DATE, -1); } } catch (Exception e) { } DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale); for (Iterator iter = all.iterator(); iter.hasNext(); ) { Change change = (Change) iter.next(); content.append("<tr><td class=\"recent\">" + df.format(change.getTime()) + "</td><td class=\"recent\"><a href=\"" + safename(change.getTopic()) + ".html\">" + change.getTopic() + "</a></td><td class=\"recent\">" + change.getUser() + "</td></tr>"); } content.append("</table>" + IOUtils.LINE_SEPARATOR); tpl = getTemplateFilledWithContent(null); tpl = tpl.replaceAll("@@CONTENTS@@", content.toString()); addTopicEntry(zipout, tpl, "RecentChanges", "RecentChanges.html"); logger.fine("Done adding all special topics."); } Code Sample 2: static void copy(String scr, String dest) throws IOException { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(scr); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { closeIgnoringException(in); closeIgnoringException(out); } }
00
Code Sample 1: public static InputStream sendReq(String url, String content, ConnectData data) { try { URLConnection con = new URL(url).openConnection(); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); con.setUseCaches(false); setUA(con); con.setRequestProperty("Accept-Charset", "utf-8"); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (data.cookie != null) con.setRequestProperty("Cookie", data.cookie); HttpURLConnection httpurl = (HttpURLConnection) con; httpurl.setRequestMethod("POST"); Writer wr = new OutputStreamWriter(con.getOutputStream()); wr.write(content); wr.flush(); con.connect(); InputStream is = con.getInputStream(); is = new BufferedInputStream(is); wr.close(); parseCookie(con, data); return is; } catch (IOException ioe) { Log.except("failed to send request " + url, ioe); } return null; } Code Sample 2: public XMLResourceBundle() throws MissingResourceException { String systemId = getShortName() + ".xml"; URL url; if ((url = getClass().getResource(systemId)) != null) { InputStream is = null; try { is = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); xmlReader.setContentHandler(new MessageContentHandler()); xmlReader.parse(new InputSource(is)); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } catch (SAXException se) { System.err.println(se.getMessage()); se.printStackTrace(); } catch (ParserConfigurationException pce) { System.err.println(pce.getMessage()); pce.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } } } else { throw new MissingResourceException("Resource file '" + systemId + "' could not be found.", systemId, null); } }
00
Code Sample 1: public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); } Code Sample 2: public static final String crypt(String password, String salt) throws NoSuchAlgorithmException { String magic = "$1$"; byte finalState[]; MessageDigest ctx, ctx1; long l; if (salt.startsWith(magic)) { salt = salt.substring(magic.length()); } if (salt.indexOf('$') != -1) { salt = salt.substring(0, salt.indexOf('$')); } if (salt.length() > 8) { salt = salt.substring(0, 8); } ctx = MessageDigest.getInstance("MD5"); ctx.update(password.getBytes()); ctx.update(magic.getBytes()); ctx.update(salt.getBytes()); ctx1 = MessageDigest.getInstance("MD5"); ctx1.update(password.getBytes()); ctx1.update(salt.getBytes()); ctx1.update(password.getBytes()); finalState = ctx1.digest(); for (int pl = password.length(); pl > 0; pl -= 16) { for (int i = 0; i < (pl > 16 ? 16 : pl); i++) ctx.update(finalState[i]); } clearbits(finalState); for (int i = password.length(); i != 0; i >>>= 1) { if ((i & 1) != 0) { ctx.update(finalState[0]); } else { ctx.update(password.getBytes()[0]); } } finalState = ctx.digest(); for (int i = 0; i < 1000; i++) { ctx1 = MessageDigest.getInstance("MD5"); if ((i & 1) != 0) { ctx1.update(password.getBytes()); } else { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } if ((i % 3) != 0) { ctx1.update(salt.getBytes()); } if ((i % 7) != 0) { ctx1.update(password.getBytes()); } if ((i & 1) != 0) { for (int c = 0; c < 16; c++) ctx1.update(finalState[c]); } else { ctx1.update(password.getBytes()); } finalState = ctx1.digest(); } StringBuffer result = new StringBuffer(); result.append(magic); result.append(salt); result.append("$"); l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]); result.append(to64(l, 4)); l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]); result.append(to64(l, 4)); l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]); result.append(to64(l, 4)); l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]); result.append(to64(l, 4)); l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]); result.append(to64(l, 4)); l = bytes2u(finalState[11]); result.append(to64(l, 2)); clearbits(finalState); return result.toString(); }
11
Code Sample 1: private String[] verifyConnection(Socket clientConnection) throws Exception { List<String> requestLines = new ArrayList<String>(); InputStream is = clientConnection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringTokenizer st = new StringTokenizer(in.readLine()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no method token in this connection"); } String method = st.nextToken(); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no URI token in this connection"); } String uri = decodePercent(st.nextToken()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no version token in this connection"); } String version = st.nextToken(); Properties parms = new Properties(); int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } String params = ""; if (parms.size() > 0) { params = "?"; for (Object key : parms.keySet()) { params = params + key + "=" + parms.getProperty(((String) key)) + "&"; } params = params.substring(0, params.length() - 1).replace(" ", "%20"); } logger.debug("HTTP Request: " + method + " " + uri + params + " " + version); requestLines.add(method + " " + uri + params + " " + version); Properties headerVars = new Properties(); String line; String currentBoundary = null; Stack<String> boundaryStack = new Stack<String>(); boolean readingBoundary = false; String additionalData = ""; while (in.ready() && (line = in.readLine()) != null) { if (line.equals("") && (headerVars.get("Content-Type") == null || headerVars.get("Content-Length") == null)) { break; } logger.debug("HTTP Request Header: " + line); if (line.contains(": ")) { String vals[] = line.split(": "); headerVars.put(vals[0].trim(), vals[1].trim()); } if (!readingBoundary && line.contains(": ")) { if (line.contains("boundary=")) { currentBoundary = line.split("boundary=")[1].trim(); boundaryStack.push("--" + currentBoundary); } continue; } else if (line.equals("") && boundaryStack.isEmpty()) { int val = Integer.parseInt((String) headerVars.get("Content-Length")); if (headerVars.getProperty("Content-Type").contains("x-www-form-urlencoded")) { char buf[] = new char[val]; int read = in.read(buf); line = String.valueOf(buf, 0, read); additionalData = line; logger.debug("HTTP Request Header Form Parameters: " + line); } } else if (line.equals(boundaryStack.peek()) && !readingBoundary) { readingBoundary = true; } else if (line.equals(boundaryStack.peek()) && readingBoundary) { readingBoundary = false; } else if (line.contains(": ") && readingBoundary) { if (method.equalsIgnoreCase("PUT")) { if (line.contains("form-data; ")) { String formValues = line.split("form-data; ")[1]; for (String varValue : formValues.replace("\"", "").split("; ")) { String[] vV = varValue.split("="); vV[0] = decodePercent(vV[0]); vV[1] = decodePercent(vV[1]); headerVars.put(vV[0], vV[1]); } } } } else if (line.contains("") && readingBoundary && !boundaryStack.isEmpty() && headerVars.get("filename") != null) { int length = Integer.parseInt(headerVars.getProperty("Content-Length")); if (headerVars.getProperty("Content-Transfer-Encoding").contains("binary")) { File uploadFilePath = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory")); if (!uploadFilePath.exists()) { logger.error("Temporaty dir does not exist: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.isDirectory()) { logger.error("Temporary dir is not a directory: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.canWrite()) { logger.error("VOctopus Webserver doesn't have permissions to write on temporary dir: " + uploadFilePath.getCanonicalPath()); } FileOutputStream out = null; try { String putUploadPath = uploadFilePath.getAbsolutePath() + "/" + headerVars.getProperty("filename"); out = new FileOutputStream(putUploadPath); OutputStream outf = new BufferedOutputStream(out); int c; while (in.ready() && (c = in.read()) != -1 && length-- > 0) { outf.write(c); } } finally { if (out != null) { out.close(); } } File copied = new File(VOctopusConfigurationManager.getInstance().getDocumentRootPath() + uri + headerVars.get("filename")); File tempFile = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory") + "/" + headerVars.get("filename")); FileChannel ic = new FileInputStream(tempFile.getAbsolutePath()).getChannel(); FileChannel oc = new FileOutputStream(copied.getAbsolutePath()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } } } for (Object var : headerVars.keySet()) { requestLines.add(var + ": " + headerVars.get(var)); } if (!additionalData.equals("")) { requestLines.add("ADDITIONAL" + additionalData); } return requestLines.toArray(new String[requestLines.size()]); } Code Sample 2: @Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { File result = new File(parent, doc.getName()); if (doc instanceof XMLDOMDocument) { new PlainXMLDocumentWriter(result).writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { IOUtils.copy(bin.getContent().getInputStream(), new FileOutputStream(result)); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
11
Code Sample 1: public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException { BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); String result = ""; String str; while ((str = in.readLine()) != null) { result += str + EOL; } in.close(); return result; } Code Sample 2: private List<Intrebare> citesteIntrebari() throws IOException { ArrayList<Intrebare> intrebari = new ArrayList<Intrebare>(); try { URL url = new URL(getCodeBase(), "../intrebari.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream()))); String intrebare; while ((intrebare = reader.readLine()) != null) { Collection<String> raspunsuri = new ArrayList<String>(); Collection<String> predicate = new ArrayList<String>(); String raspuns = ""; while (!"".equals(raspuns = reader.readLine())) { raspunsuri.add(raspuns); predicate.add(reader.readLine()); } Intrebare i = new Intrebare(intrebare, raspunsuri.toArray(new String[raspunsuri.size()]), predicate.toArray(new String[predicate.size()])); intrebari.add(i); } } catch (ArgumentExcetpion e) { e.printStackTrace(); } return intrebari; }
00
Code Sample 1: public String getRssFeedUrl(boolean searchWeb) { String rssFeedUrl = null; if (entity.getNewsFeedUrl() != null & !entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (entity.getUrl() == null || entity.getUrl().equals("")) { return entity.getNewsFeedUrl(); } else if (searchWeb) { HttpURLConnection con = null; InputStream is = null; try { URL url = new URL(entity.getUrl()); con = (HttpURLConnection) url.openConnection(); con.connect(); is = con.getInputStream(); InputStreamReader sr = new InputStreamReader(is); BufferedReader br = new BufferedReader(sr); String ln; StringBuffer sb = new StringBuffer(); while ((ln = br.readLine()) != null) { sb.append(ln + "\n"); } rssFeedUrl = extractRssFeedUrl(sb.toString()); } catch (Exception e) { log.error(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error(e); } } if (con != null) { con.disconnect(); } } } return rssFeedUrl; } Code Sample 2: public boolean saveTemplate(Template t) { try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); String query; ResultSet rset; if (Integer.parseInt(executeMySQLGet("SELECT COUNT(*) FROM templates WHERE name='" + escapeCharacters(t.getName()) + "'")) != 0) return false; query = "select * from templates where templateid = " + t.getID(); rset = stmt.executeQuery(query); if (rset.next()) { System.err.println("Updating already saved template is not supported!!!!!!"); return false; } else { query = "INSERT INTO templates (name, parentid) VALUES ('" + escapeCharacters(t.getName()) + "', " + t.getParentID() + ")"; try { stmt.executeUpdate(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } int templateid = Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()")); t.setID(templateid); LinkedList<Field> fields = t.getFields(); ListIterator<Field> iter = fields.listIterator(); Field f = null; PreparedStatement pstmt = conn.prepareStatement("INSERT INTO templatefields(fieldtype, name, templateid, defaultvalue)" + "VALUES (?,?,?,?)"); try { while (iter.hasNext()) { f = iter.next(); if (f.getType() == Field.IMAGE) { System.out.println("field is an image."); byte data[] = ((FieldDataImage) f.getDefault()).getDataBytes(); pstmt.setBytes(4, data); } else { System.out.println("field is not an image"); String deflt = (f.getDefault()).getData(); pstmt.setString(4, deflt); } pstmt.setInt(1, f.getType()); pstmt.setString(2, f.getName()); pstmt.setInt(3, t.getID()); pstmt.execute(); f.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { System.err.println("Error saving the Template"); return false; } return true; }
11
Code Sample 1: public static boolean writeFileByChars(Reader pReader, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pReader, fw); fw.flush(); fw.close(); pReader.close(); flag = true; } catch (Exception e) { LOG.error("将字符流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; } Code Sample 2: private void copyFile(String sourceFilename, String destDirname) throws BuildException { log("Copying file " + sourceFilename + " to " + destDirname); File destFile = getDestFile(sourceFilename, destDirname); InputStream inStream = null; OutputStream outStream = null; try { inStream = new BufferedInputStream(new FileInputStream(sourceFilename)); outStream = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] buffer = new byte[1024]; int n = 0; while ((n = inStream.read(buffer)) != -1) outStream.write(buffer, 0, n); } catch (Exception e) { throw new BuildException("Failed to copy file \"" + sourceFilename + "\" to directory \"" + destDirname + "\""); } finally { try { if (inStream != null) inStream.close(); } catch (IOException e) { } try { if (outStream != null) outStream.close(); } catch (IOException e) { } } }
00
Code Sample 1: public ScoreModel(URL url) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; list = new ArrayList<ScoreModelItem>(); map = new HashMap<String, ScoreModelItem>(); line = in.readLine(); int n = 1; String[] rowAttrib; ScoreModelItem item; while ((line = in.readLine()) != null) { rowAttrib = line.split(";"); item = new ScoreModelItem(n, Double.valueOf(rowAttrib[3]), Double.valueOf(rowAttrib[4]), Double.valueOf(rowAttrib[2]), Double.valueOf(rowAttrib[5]), rowAttrib[1]); list.add(item); map.put(item.getHash(), item); n++; } in.close(); } Code Sample 2: public static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception { org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password); HttpMethod method = new GetMethod(url); client.executeMethod(method); BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copyLarge(method.getResponseBodyAsStream(), output); }
11
Code Sample 1: public static final void copyFile(File argSource, File argDestination) throws IOException { FileChannel srcChannel = new FileInputStream(argSource).getChannel(); FileChannel dstChannel = new FileOutputStream(argDestination).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } } Code Sample 2: public static void copyResourceFileTo(String destFileName, String resourceFileName) { if (destFileName == null || resourceFileName == null) throw new IllegalArgumentException("Argument cannot be null."); try { FileInputStream in = null; FileOutputStream out = null; URL url = HelperMethods.class.getResource(resourceFileName); if (url == null) { System.out.println("URL " + resourceFileName + " cannot be created."); return; } String fileName = url.getFile(); fileName = fileName.replaceAll("%20", " "); File resourceFile = new File(fileName); if (!resourceFile.isFile()) { System.out.println(fileName + " cannot be opened."); return; } in = new FileInputStream(resourceFile); out = new FileOutputStream(new File(destFileName)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } }
00
Code Sample 1: private void sendToURL(String URL, String file) throws Exception { URL url = new URL(URL); InputStream is = new BufferedInputStream(new FileInputStream(file)); OutputStream os = url.openConnection().getOutputStream(); copyDocument(is, os); is.close(); os.close(); } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
11
Code Sample 1: private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } } Code Sample 2: public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception { String tmpFile = file + ".tmp"; BufferedInputStream in = null; BufferedOutputStream out = null; long byteCount = 0; try { in = new BufferedInputStream(new FileInputStream(new File(file))); out = new BufferedOutputStream(new FileOutputStream(tmpFile)); long size = fromByte; byte[] buf = null; if (size == 0) { } else { buf = new byte[(int) size]; int length = -1; if ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } else { String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error."; logger.warning(msg); throw new Exception(msg); } } buf = textToInsert.getBytes(); int length = buf.length; out.write(buf, 0, length); byteCount = byteCount + length; long skipLength = toByte - fromByte; long skippedBytes = in.skip(skipLength); if (skippedBytes == -1) { } else { buf = new byte[4096]; length = -1; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); byteCount = byteCount + length; } } in.close(); in = null; out.close(); out = null; File fileToDelete = new File(file); boolean wasDeleted = fileToDelete.delete(); if (!wasDeleted) { String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion."; logger.warning(msg); throw new Exception(msg); } File fileToRename = new File(tmpFile); boolean wasRenamed = fileToRename.renameTo(fileToDelete); if (!wasRenamed) { String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'"; logger.warning(msg); throw new Exception(msg); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e); } } } }
00
Code Sample 1: public InputStream getDaoConfig(String connectionType) throws IOException { URL url = null; InputStream inStream = null; if (connectionType.equals(SQL.ORACLE)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("oracle.xml"); } else if (connectionType.equals(SQL.SQL2K)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("sql2k.xml"); } else if (connectionType.equals(SQL.CACHE)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("cache.xml"); } else if (connectionType.equals(SQL.DB2)) { url = com.apelon.selext.db.config.MatchLoadConfig.class.getResource("db2.xml"); } else { Categories.dataXml().error("* Problem: Unknown connection type: " + connectionType); } try { inStream = url.openStream(); } catch (NullPointerException npe) { Categories.dataXml().error("* Problem: Undefined resource URL: " + npe.getMessage()); throw npe; } return inStream; } Code Sample 2: private void sendToURL(String URL, String file) throws Exception { URL url = new URL(URL); InputStream is = new BufferedInputStream(new FileInputStream(file)); OutputStream os = url.openConnection().getOutputStream(); copyDocument(is, os); is.close(); os.close(); }
00
Code Sample 1: @Deprecated public static void getAndProcessContents(String videoPageURL, int bufsize, String charset, Closure<String> process) throws IOException { URL url = null; HttpURLConnection connection = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { url = new URL(videoPageURL); connection = (HttpURLConnection) url.openConnection(); is = connection.getInputStream(); isr = new InputStreamReader(is, charset); br = new BufferedReader(isr); for (String line = br.readLine(); line != null; line = br.readLine()) { process.exec(line); } } finally { Closeables.closeQuietly(br); Closeables.closeQuietly(isr); Closeables.closeQuietly(is); HttpUtils.disconnect(connection); } } Code Sample 2: private boolean handlePart(Part p) throws MessagingException, GetterException { String filename = p.getFileName(); if (!p.isMimeType("multipart/*")) { String disp = p.getDisposition(); if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { if (checkCriteria(p)) { if (filename == null) filename = "Attachment" + attnum++; if (result == null) { try { File f = File.createTempFile("amorph_pop3-", ".tmp"); f.deleteOnExit(); OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); InputStream is = p.getInputStream(); int c; while ((c = is.read()) != -1) os.write(c); os.close(); result = new FileInputStream(f); System.out.println("saved attachment to file: " + f.getAbsolutePath()); return true; } catch (IOException ex) { throw new GetterException(ex, "Failed to save attachment: " + ex); } } } } } return false; }
00
Code Sample 1: public void delete(String name) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); AttributeTable attribute = new AttributeTable(); attribute.deleteAllForType(stmt, name); String sql = "delete from AttributeCategories " + "where CategoryName = '" + name + "'"; stmt.executeUpdate(sql); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: protected static boolean isLatestVersion(double myVersion, String referenceAddress) { Scanner scanner = null; try { URL url = new URL(referenceAddress); InputStream iS = url.openStream(); scanner = new Scanner(iS); String firstLine = scanner.nextLine(); double latestVersion = Double.valueOf(firstLine.trim()); double thisVersion = OpenSONAR.VERSION; return thisVersion >= latestVersion; } catch (UnknownHostException e) { System.out.println("Unknown Host!!!"); return false; } catch (Exception e) { System.out.println("Can't decide latest version"); e.printStackTrace(); return false; } }
11
Code Sample 1: public ScoreModel(URL url) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; list = new ArrayList<ScoreModelItem>(); map = new HashMap<String, ScoreModelItem>(); line = in.readLine(); int n = 1; String[] rowAttrib; ScoreModelItem item; while ((line = in.readLine()) != null) { rowAttrib = line.split(";"); item = new ScoreModelItem(n, Double.valueOf(rowAttrib[3]), Double.valueOf(rowAttrib[4]), Double.valueOf(rowAttrib[2]), Double.valueOf(rowAttrib[5]), rowAttrib[1]); list.add(item); map.put(item.getHash(), item); n++; } in.close(); } Code Sample 2: public static String[] listFilesInJar(String resourcesLstName, String dirPath, String ext) { try { dirPath = Tools.subString(dirPath, "\\", "/"); if (!dirPath.endsWith("/")) { dirPath = dirPath + "/"; } if (dirPath.startsWith("/")) { dirPath = dirPath.substring(1, dirPath.length()); } URL url = ResourceLookup.getClassResourceUrl(Tools.class, resourcesLstName); if (url == null) { String msg = "File not found " + resourcesLstName; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } InputStream is = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String name = in.readLine(); HashSet<String> list = new HashSet<String>(10); while (name != null) { name = in.readLine(); if (name == null) { continue; } if (ext != null && !name.endsWith(ext)) { continue; } if (name.indexOf('.') == -1 && !name.endsWith("/")) { name = name + "/"; } int index = name.indexOf(dirPath); if (index < 0) { continue; } index += dirPath.length(); if (index >= name.length() - 1) { continue; } index = name.indexOf("/", index); if (ext != null && (name.endsWith("/") || index >= 0)) { continue; } else if (ext == null && (index < 0 || index < name.length() - 1)) { continue; } list.add("/" + name); } is.close(); String[] toReturn = {}; return list.toArray(toReturn); } catch (IOException ioe) { String msg = "Error reading file " + resourcesLstName + " caused by " + ioe; Debug.signal(Debug.ERROR, null, msg); return new String[0]; } }
00
Code Sample 1: public InputLattice(String file, int type, boolean convertJoinMeet) throws FileNotFoundException, IOException { InputStream latStream = null; labels = new Vector(); upperCoversVector = new Vector(); Vector upperCovers = new Vector(); edgeColors = new Hashtable(); Vector upperCovering = new Vector(); int level = 0; String str; String currentElt = null; String cover = null; boolean first = true; StreamTokenizer in; switch(type) { case FILE: latStream = new FileInputStream(file); break; case STRING: latStream = new StringBufferInputStream(file); break; case URL: URL url = new URL("http", Config.HOST, Config.PORT, "/" + Config.HASSE + "/" + Config.URL_STREAMER + file); System.out.println("url is " + url); URLConnection connection = url.openConnection(); latStream = new DataInputStream(connection.getInputStream()); break; } in = new StreamTokenizer(latStream); in.wordChars('^', '_'); in.wordChars('*', '.'); while (in.nextToken() != StreamTokenizer.TT_EOF) { if (in.ttype == StreamTokenizer.TT_WORD || in.ttype == StreamTokenizer.TT_NUMBER || in.ttype == '"') { if (in.ttype == StreamTokenizer.TT_NUMBER) { str = "" + Math.round(in.nval); } else { str = in.sval; } if (convertJoinMeet && level > 1) { str = stringSubstitute(str, joinStr, joinSign); str = stringSubstitute(str, meetStr, meetSign); } if (level == 1) { name = new String(str); } if (level == 2) { labels.addElement(str); currentElt = str; } if (level == 3) { upperCovers.addElement(str); } if (level == 4) { if (first) { upperCovers.addElement(str); cover = str; first = false; } else { edgeColors.put(new Edge(currentElt, cover), str); } } } if (in.ttype == '(') { level++; if (level == 3) upperCovers = new Vector(); } if (in.ttype == ')') { level--; if (level == 3) first = true; if (level == 2) upperCoversVector.addElement(upperCovers); if (level == 0) { if (latStream != null) latStream.close(); return; } } } } Code Sample 2: private String calculateHash(String s) { if (s == null) { return null; } MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { logger.error("Could not find a message digest algorithm."); return null; } messageDigest.update(s.getBytes()); byte[] hash = messageDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : hash) { sb.append(String.format("%02x", b)); } return sb.toString(); }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: protected void copyFile(File sourceFile, File destFile) { FileChannel in = null; FileChannel out = null; try { if (!verifyOrCreateParentPath(destFile.getParentFile())) { throw new IOException("Parent directory path " + destFile.getAbsolutePath() + " did not exist and could not be created"); } if (destFile.exists() || destFile.createNewFile()) { in = new FileInputStream(sourceFile).getChannel(); out = new FileOutputStream(destFile).getChannel(); in.transferTo(0, in.size(), out); } else { throw new IOException("Couldn't create file for " + destFile.getAbsolutePath()); } } catch (IOException ioe) { if (destFile.exists() && destFile.length() < sourceFile.length()) { destFile.delete(); } ioe.printStackTrace(); } finally { try { in.close(); } catch (Throwable t) { } try { out.close(); } catch (Throwable t) { } destFile.setLastModified(sourceFile.lastModified()); } }
11
Code Sample 1: private void saveFile(File destination) { InputStream in = null; OutputStream out = null; try { if (fileScheme) in = new BufferedInputStream(new FileInputStream(source.getPath())); else in = new BufferedInputStream(getContentResolver().openInputStream(source)); out = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[1024]; while (in.read(buffer) != -1) out.write(buffer); Toast.makeText(this, R.string.saveas_file_saved, Toast.LENGTH_SHORT).show(); } catch (FileNotFoundException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static void copyFile(String source, String destination) throws IOException { File srcDir = new File(source); File[] files = srcDir.listFiles(); FileChannel in = null; FileChannel out = null; for (File file : files) { try { in = new FileInputStream(file).getChannel(); File outFile = new File(destination, file.getName()); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } } } Code Sample 2: @Override public void objectToEntry(String object, TupleOutput output) { byte array[] = object.getBytes(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream out = new GZIPOutputStream(baos); ByteArrayInputStream in = new ByteArrayInputStream(array); IOUtils.copyTo(in, out); in.close(); out.close(); byte array2[] = baos.toByteArray(); if (array2.length + 4 < array.length) { output.writeBoolean(true); output.writeInt(array2.length); output.write(array2); } else { output.writeBoolean(false); output.writeString(object); } } catch (IOException err) { throw new RuntimeException(err); } }
11
Code Sample 1: public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: static byte[] genDigest(String pad, byte[] passwd) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM); digest.update(pad.getBytes()); digest.update(passwd); return digest.digest(); } Code Sample 2: public static String generateNonce(boolean is32) { Random random = new Random(); String result = String.valueOf(random.nextInt(9876599) + 123400); if (is32) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(result.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return result; }
11
Code Sample 1: public static synchronized String encrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(text.getBytes("UTF-8")); byte raw[] = md.digest(); return new Base64(-1).encodeToString(raw); } Code Sample 2: public static String getMD5(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); }
00
Code Sample 1: public static String encrypt(String plaintext) throws NoSuchAlgorithmException { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { logger.error("unable to encrypt password" + e.getMessage()); throw new NoSuchAlgorithmException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("unable to encrypt password" + e.getMessage()); throw new NoSuchAlgorithmException(e.getMessage()); } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } Code Sample 2: public int doCheck(URL url) throws IOException { long start = (System.currentTimeMillis()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { } in.close(); long end = (System.currentTimeMillis()); return (int) (end - start); }
11
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("FileCopy: no such source file: " + from_name); if (!from_file.isFile()) abort("FileCopy: can't copy directory: " + from_name); if (!from_file.canRead()) abort("FileCopy: source file is unreadable: " + from_name); if (to_file.isDirectory()) to_file = new File(to_file, from_file.getName()); String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("FileCopy: destination directory doesn't exist: " + parent); if (dir.isFile()) abort("FileCopy: destination is not a directory: " + parent); if (!dir.canWrite()) abort("FileCopy: destination directory is unwriteable: " + parent); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: public static EXISchema getEXISchema(String fileName, Class<?> cls, EXISchemaFactoryErrorHandler compilerErrorHandler) throws IOException, ClassNotFoundException, EXISchemaFactoryException { EXISchemaFactory schemaCompiler = new EXISchemaFactory(); schemaCompiler.setCompilerErrorHandler(compilerErrorHandler); InputSource inputSource = null; if (fileName != null) { URL url; if ((url = cls.getResource(fileName)) != null) { inputSource = new InputSource(url.openStream()); inputSource.setSystemId(url.toString()); } else throw new RuntimeException("File '" + fileName + "' not found."); } EXISchema compiled = schemaCompiler.compile(inputSource); InputStream serialized = serializeSchema(compiled); return loadSchema(serialized); }
11
Code Sample 1: @Test public void testCopy_readerToOutputStream_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null); fail(); } catch (NullPointerException ex) { } } Code Sample 2: protected void doDownload(S3Bucket bucket, S3Object s3object) throws Exception { String key = s3object.getKey(); key = trimPrefix(key); String[] path = key.split("/"); String fileName = path[path.length - 1]; String dirPath = ""; for (int i = 0; i < path.length - 1; i++) { dirPath += path[i] + "/"; } File outputDir = new File(downloadFileOutputDir + "/" + dirPath); if (outputDir.exists() == false) { outputDir.mkdirs(); } File outputFile = new File(outputDir, fileName); long size = s3object.getContentLength(); if (outputFile.exists() && outputFile.length() == size) { return; } long startTime = System.currentTimeMillis(); log.info("Download start.S3 file=" + s3object.getKey() + " local file=" + outputFile.getAbsolutePath()); FileOutputStream fout = null; S3Object dataObject = null; try { fout = new FileOutputStream(outputFile); dataObject = s3.getObject(bucket, s3object.getKey()); InputStream is = dataObject.getDataInputStream(); IOUtils.copyStream(is, fout); downloadedFileList.add(key); long downloadTime = System.currentTimeMillis() - startTime; log.info("Download complete.Estimete time=" + downloadTime + "ms " + IOUtils.toBPSText(downloadTime, size)); } catch (Exception e) { log.error("Download fail. s3 file=" + key, e); outputFile.delete(); throw e; } finally { IOUtils.closeNoException(fout); if (dataObject != null) { dataObject.closeDataInputStream(); } } }
11
Code Sample 1: public static void writeEntry(File file, File input) throws PersistenceException { try { File temporaryFile = File.createTempFile("pmMDA_zargo", ARGOUML_EXT); temporaryFile.deleteOnExit(); ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile)); FileInputStream inputStream = new FileInputStream(input); ZipEntry entry = new ZipEntry(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + XMI_EXT); output.putNextEntry(new ZipEntry(entry)); IOUtils.copy(inputStream, output); output.closeEntry(); inputStream.close(); entry = new ZipEntry(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + ".argo"); output.putNextEntry(new ZipEntry(entry)); output.write(ArgoWriter.getArgoContent(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + XMI_EXT).getBytes()); output.closeEntry(); output.close(); temporaryFile.renameTo(file); } catch (IOException ioe) { throw new PersistenceException(ioe); } } Code Sample 2: private void sendBinaryFile(File file) throws IOException, CVSException { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); if (m_bCompressFiles) { GZIPOutputStream gzipOut = null; InputStream gzipIn = null; File gzipFile = null; try { gzipFile = File.createTempFile("javacvs", "tmp"); gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile))); int b; while ((b = in.read()) != -1) gzipOut.write((byte) b); gzipOut.close(); long gzipLength = gzipFile.length(); sendLine("z" + Long.toString(gzipLength)); gzipIn = new BufferedInputStream(new FileInputStream(gzipFile)); for (long i = 0; i < gzipLength; i++) { b = gzipIn.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } finally { if (gzipOut != null) gzipOut.close(); if (gzipIn != null) gzipIn.close(); if (gzipFile != null) gzipFile.delete(); } } else { long nLength = file.length(); sendLine(Long.toString(nLength)); for (long i = 0; i < nLength; i++) { int b = in.read(); if (b == -1) throw new EOFException(); m_Out.write((byte) b); } } } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
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 testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
00
Code Sample 1: @Override public URLConnection openConnection(URL url, Proxy proxy) throws IOException { if (null == url) { throw new IllegalArgumentException(Messages.getString("luni.1B")); } String host = url.getHost(); if (host == null || host.length() == 0 || host.equalsIgnoreCase("localhost")) { return new FileURLConnection(url); } URL ftpURL = new URL("ftp", host, url.getFile()); return (proxy == null) ? ftpURL.openConnection() : ftpURL.openConnection(proxy); } Code Sample 2: @Override public String addUser(UserInfoItem user) throws DatabaseException { if (user == null) throw new NullPointerException("user"); if (user.getSurname() == null || "".equals(user.getSurname())) throw new NullPointerException("user.getSurname()"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } String retID = "exist"; PreparedStatement insSt = null, updSt = null, seqSt = null; try { int modified = 0; if (user.getId() != null) { long id = Long.parseLong(user.getId()); updSt = getConnection().prepareStatement(UPDATE_USER_STATEMENT); updSt.setString(1, user.getName()); updSt.setString(2, user.getSurname()); updSt.setLong(3, id); modified = updSt.executeUpdate(); } else { insSt = getConnection().prepareStatement(INSERT_USER_STATEMENT); insSt.setString(1, user.getName()); insSt.setString(2, user.getSurname()); insSt.setBoolean(3, "m".equalsIgnoreCase(user.getSex())); modified = insSt.executeUpdate(); seqSt = getConnection().prepareStatement(USER_CURR_VALUE); ResultSet rs = seqSt.executeQuery(); while (rs.next()) { retID = rs.getString(1); } } if (modified == 1) { getConnection().commit(); LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\""); } else { getConnection().rollback(); LOGGER.debug("DB has not been updated. -> rollback! Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\""); retID = "error"; } } catch (SQLException e) { LOGGER.error(e); retID = "error"; } finally { closeConnection(); } return retID; }
11
Code Sample 1: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.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 void invoke() throws IOException { String[] command = new String[files.length + options.length + 2]; command[0] = chmod; System.arraycopy(options, 0, command, 1, options.length); command[1 + options.length] = perms; for (int i = 0; i < files.length; i++) { File file = files[i]; command[2 + options.length + i] = file.getAbsolutePath(); } Process p = Runtime.getRuntime().exec(command); try { p.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (p.exitValue() != 0) { StringWriter writer = new StringWriter(); IOUtils.copy(p.getErrorStream(), writer); throw new IOException("Unable to chmod files: " + writer.toString()); } }
00
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: public File getAppHome() { if (appHome == null) { if (System.getProperty("app.home") != null) { appHome = new File(System.getProperty("app.home")); } if (appHome == null) { URL url = Main.class.getClassLoader().getResource("com/hs/mail/container/Main.class"); if (url != null) { try { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); url = jarConnection.getJarFileURL(); URI baseURI = new URI(url.toString()).resolve(".."); appHome = new File(baseURI).getCanonicalFile(); System.setProperty("app.home", appHome.getAbsolutePath()); } catch (Exception ignored) { } } } if (appHome == null) { appHome = new File("../."); System.setProperty("app.home", appHome.getAbsolutePath()); } } return appHome; }
00
Code Sample 1: private static String encode(String str, String method) { MessageDigest md = null; String dstr = null; try { md = MessageDigest.getInstance(method); md.update(str.getBytes()); dstr = new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return dstr; } Code Sample 2: public String htmlContentSimple(String urlStr, String charset) { StringBuffer html = new StringBuffer(); URL url = null; BufferedReader reader = null; try { url = new URL(urlStr); reader = new BufferedReader(new InputStreamReader(url.openStream(), charset)); String line; while ((line = reader.readLine()) != null) { html.append(line).append("\r\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return html.toString(); }
11
Code Sample 1: private void gzip(FileHolder fileHolder) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File destFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(destFile); outStream = new GZIPOutputStream(outStream); File selectedFile = fileHolder.selectedFileList.get(0); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.close(); this.inStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error gzip'ing: " + destFile); logger.logError(errEntry); } } Code Sample 2: public static void fileCopy(File src, File dst) throws FileNotFoundException, IOException { if (src.isDirectory() && (!dst.exists() || dst.isDirectory())) { if (!dst.exists()) { if (!dst.mkdirs()) throw new IOException("unable to mkdir " + dst); } File dst1 = new File(dst, src.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); dst = dst1; File[] files = src.listFiles(); for (File f : files) { if (f.isDirectory()) { dst1 = new File(dst, f.getName()); if (!dst1.exists() && !dst1.mkdir()) throw new IOException("unable to mkdir " + dst1); } else { dst1 = dst; } fileCopy(f, dst1); } return; } else if (dst.isDirectory()) { dst = new File(dst, src.getName()); } FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(dst).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
11
Code Sample 1: @Override public String execute() throws Exception { SystemContext sc = getSystemContext(); if (sc.getExpireTime() == -1) { return LOGIN; } else if (upload != null) { try { Enterprise e = LicenceUtils.get(upload); sc.setEnterpriseName(e.getEnterpriseName()); sc.setExpireTime(e.getExpireTime()); String webPath = ServletActionContext.getServletContext().getRealPath("/"); File desFile = new File(webPath, LicenceUtils.LICENCE_FILE_NAME); FileChannel sourceChannel = new FileInputStream(upload).getChannel(); FileChannel destinationChannel = new FileOutputStream(desFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); return LOGIN; } catch (Exception e) { } } return "license"; } Code Sample 2: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: private static void copy(File source, File target, byte[] buffer) throws FileNotFoundException, IOException { InputStream in = new FileInputStream(source); File parent = target.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } if (target.isDirectory()) { target = new File(target, source.getName()); } OutputStream out = new FileOutputStream(target); int read; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch (IOException e) { throw e; } finally { in.close(); out.close(); } } Code Sample 2: private static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } Code Sample 2: public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getParameter("i") != null) { String img = req.getParameter("i"); if (img == null) { resp.sendError(404, "Image was null"); return; } File f = null; if (img.startsWith("file")) { try { f = new File(new URI(img)); } catch (URISyntaxException e) { resp.sendError(500, e.getMessage()); return; } } else { f = new File(img); } if (f.exists()) { f = f.getCanonicalFile(); if (f.getName().endsWith(".jpg") || f.getName().endsWith(".png")) { resp.setContentType("image/png"); FileInputStream fis = null; OutputStream os = resp.getOutputStream(); try { fis = new FileInputStream(f); IOUtils.copy(fis, os); } finally { os.flush(); if (fis != null) fis.close(); } } } return; } String mediaUrl = "/media" + req.getPathInfo(); String parts[] = mediaUrl.split("/"); mediaHandler.handleRequest(parts, req, resp); } Code Sample 2: private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
00
Code Sample 1: @org.junit.Test public void testReadWrite() throws Exception { final String reference = "testString"; final Reader reader = new StringReader(reference); final StringWriter osString = new StringWriter(); final Reader teeStream = new TeeReaderWriter(reader, osString); IOUtils.copy(teeStream, new NullWriter()); teeStream.close(); osString.toString(); } Code Sample 2: @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); TextView tv = new TextView(this); try { URL url = new URL(""); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); ExampleHandler myExampleHandler = new ExampleHandler(); xr.setContentHandler(myExampleHandler); xr.parse(new InputSource(url.openStream())); ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData(); tv.setText(parsedExampleDataSet.toString()); } catch (Exception e) { tv.setText("Error: " + e.getMessage()); Log.e(MY_DEBUG_TAG, "WeatherQueryError", e); } this.setContentView(tv); }
11
Code Sample 1: public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; } Code Sample 2: public DataSet newparse() throws SnifflibDatatypeException { NumberFormat numformat = NumberFormat.getInstance(); if (this.headers.size() != this.types.size()) { throw new SnifflibDatatypeException("Different number of headers (" + this.headers.size() + ") and types(" + this.types.size() + ")."); } DataSet out = null; if (!this.dryrun) { out = new DataSet(); } BufferedReader r = null; StreamTokenizer tokenizer = null; try { if (this.isURL) { if (this.url2goto == null) { return (null); } DataInputStream in = null; try { in = new DataInputStream(this.url2goto.openStream()); System.out.println("READY TO READ FROM URL:" + url2goto); r = new BufferedReader(new InputStreamReader(in)); } catch (Exception err) { throw new RuntimeException("Problem reading from URL " + this.url2goto + ".", err); } } else { if (this.file == null) { throw new RuntimeException("Data file to be parsed can not be null."); } if (!this.file.exists()) { throw new RuntimeException("The file " + this.file + " does not exist."); } r = new BufferedReader(new FileReader(this.file)); } if (this.ignorePreHeaderLines > 0) { String strLine; int k = 0; while ((k < this.ignorePreHeaderLines) && ((strLine = r.readLine()) != null)) { k++; } } tokenizer = new StreamTokenizer(r); tokenizer.resetSyntax(); tokenizer.eolIsSignificant(true); boolean parseNumbers = false; for (int k = 0; k < this.types.size(); k++) { Class type = (Class) this.types.get(k); if (Number.class.isAssignableFrom(type)) { parseNumbers = true; break; } } if (parseNumbers) { tokenizer.parseNumbers(); } tokenizer.eolIsSignificant(true); if (this.delimiter.equals("\\t")) { tokenizer.whitespaceChars('\t', '\t'); tokenizer.quoteChar('"'); tokenizer.whitespaceChars(' ', ' '); } else if (this.delimiter.equals(",")) { tokenizer.quoteChar('"'); tokenizer.whitespaceChars(',', ','); tokenizer.whitespaceChars(' ', ' '); } else { if (this.delimiter.length() > 1) { throw new RuntimeException("Delimiter must be a single character. Multiple character delimiters are not allowed."); } if (this.delimiter.length() > 0) { tokenizer.whitespaceChars(this.delimiter.charAt(0), this.delimiter.charAt(0)); } else { tokenizer.wordChars(Character.MIN_VALUE, Character.MAX_VALUE); tokenizer.eolIsSignificant(true); tokenizer.ordinaryChar('\n'); } } boolean readingHeaders = true; boolean readingInitialValues = false; boolean readingData = false; boolean readingScientificNotation = false; if (this.headers.size() > 0) { readingHeaders = false; readingInitialValues = true; } if (this.types.size() > 0) { readingInitialValues = false; Class targetclass; for (int j = 0; j < this.types.size(); j++) { targetclass = (Class) this.types.get(j); try { this.constructors.add(targetclass.getConstructor(String.class)); } catch (java.lang.NoSuchMethodException err) { throw new SnifflibDatatypeException("Could not find appropriate constructor for " + targetclass + ". " + err.getMessage()); } } readingData = true; } int currentColumn = 0; int currentRow = 0; this.rowcount = 0; boolean advanceField = true; while (true) { tokenizer.nextToken(); switch(tokenizer.ttype) { case StreamTokenizer.TT_WORD: { advanceField = true; if (readingScientificNotation) { throw new RuntimeException("Problem reading scientific notation at row " + currentRow + " column " + currentColumn + "."); } if (readingHeaders) { this.headers.add(tokenizer.sval); } else { if (readingInitialValues) { this.types.add(String.class); } if (!this.dryrun) { if (out.getColumnCount() <= currentColumn) { out.addColumn((String) this.headers.get(currentColumn), (Class) this.types.get(currentColumn)); } } try { Constructor construct; if (currentColumn < this.constructors.size()) { construct = (Constructor) this.constructors.get(currentColumn); } else { Class targetclass = (Class) this.types.get(currentColumn); construct = targetclass.getConstructor(String.class); this.constructors.add(construct); } try { try { try { if (!this.dryrun) { out.setValueAt(construct.newInstance((String) tokenizer.sval), currentRow, currentColumn); } else if (this.findingTargetValue) { Object vvv = construct.newInstance((String) tokenizer.sval); this.valueQueue.push(vvv); if ((this.targetRow == currentRow) && (this.targetColumn == currentColumn)) { this.targetValue = vvv; r.close(); return (null); } } } catch (java.lang.reflect.InvocationTargetException err) { throw new SnifflibDatatypeException("Problem constructing 1" + err.getMessage()); } } catch (java.lang.IllegalAccessException err) { throw new SnifflibDatatypeException("Problem constructing 2" + err.getMessage()); } } catch (java.lang.InstantiationException err) { throw new SnifflibDatatypeException("Problem constructing 3" + err.getMessage()); } } catch (java.lang.NoSuchMethodException err) { throw new SnifflibDatatypeException("Problem constructing 4" + err.getMessage()); } } break; } case StreamTokenizer.TT_NUMBER: { advanceField = true; if (readingHeaders) { throw new SnifflibDatatypeException("Expecting string header at row=" + currentRow + ", column=" + currentColumn + "."); } else { if (readingInitialValues) { this.types.add(Double.class); } if (!this.dryrun) { if (out.getColumnCount() <= currentColumn) { out.addColumn((String) this.headers.get(currentColumn), (Class) this.types.get(currentColumn)); } } try { Constructor construct; if (currentColumn < this.constructors.size()) { construct = (Constructor) this.constructors.get(currentColumn); } else { Class targetclass = (Class) this.types.get(currentColumn); construct = targetclass.getConstructor(double.class); this.constructors.add(construct); } if (readingScientificNotation) { Double val = this.scientificNumber; if (!this.dryrun) { try { out.setValueAt(new Double(val.doubleValue() * tokenizer.nval), currentRow, currentColumn); } catch (Exception err) { throw new SnifflibDatatypeException("Problem constructing " + construct.getDeclaringClass() + "at row " + currentRow + " column " + currentColumn + ".", err); } } else if (this.findingTargetValue) { Double NVAL = new Double(tokenizer.nval); Object vvv = null; try { vvv = Double.parseDouble(val + "E" + NVAL.intValue()); } catch (Exception err) { throw new RuntimeException("Problem parsing scientific notation at row=" + currentRow + " col=" + currentColumn + ".", err); } tokenizer.nextToken(); if (tokenizer.ttype != 'e') { this.valueQueue.push(vvv); if ((this.targetRow == currentRow) && (this.targetColumn == currentColumn)) { this.targetValue = vvv; r.close(); return (null); } currentColumn++; } else { tokenizer.pushBack(); } } readingScientificNotation = false; } else { try { this.scientificNumber = new Double(tokenizer.nval); if (!this.dryrun) { out.setValueAt(this.scientificNumber, currentRow, currentColumn); } else if (this.findingTargetValue) { this.valueQueue.push(this.scientificNumber); if ((this.targetRow == currentRow) && (this.targetColumn == currentColumn)) { this.targetValue = this.scientificNumber; r.close(); return (null); } } } catch (Exception err) { throw new SnifflibDatatypeException("Problem constructing " + construct.getDeclaringClass() + "at row " + currentRow + " column " + currentColumn + ".", err); } } } catch (java.lang.NoSuchMethodException err) { throw new SnifflibDatatypeException("Problem constructing" + err.getMessage()); } } break; } case StreamTokenizer.TT_EOL: { if (readingHeaders) { readingHeaders = false; readingInitialValues = true; } else { if (readingInitialValues) { readingInitialValues = false; readingData = true; } } if (readingData) { if (valueQueue.getUpperIndex() < currentRow) { valueQueue.push(""); } currentRow++; } break; } case StreamTokenizer.TT_EOF: { if (readingHeaders) { throw new SnifflibDatatypeException("End of file reached while reading headers."); } if (readingInitialValues) { throw new SnifflibDatatypeException("End of file reached while reading initial values."); } if (readingData) { readingData = false; } break; } default: { if (tokenizer.ttype == '"') { advanceField = true; if (readingHeaders) { this.headers.add(tokenizer.sval); } else { if (readingInitialValues) { this.types.add(String.class); } if (!this.dryrun) { if (out.getColumnCount() <= currentColumn) { out.addColumn((String) this.headers.get(currentColumn), (Class) this.types.get(currentColumn)); } } try { Constructor construct; if (currentColumn < this.constructors.size()) { construct = (Constructor) this.constructors.get(currentColumn); } else { Class targetclass = (Class) this.types.get(currentColumn); construct = targetclass.getConstructor(String.class); this.constructors.add(construct); } try { try { try { if (!this.dryrun) { out.setValueAt(construct.newInstance((String) tokenizer.sval), currentRow, currentColumn); } else if (this.findingTargetValue) { Object vvv = construct.newInstance((String) tokenizer.sval); this.valueQueue.push(vvv); if ((this.targetRow == currentRow) && (this.targetColumn == currentColumn)) { this.targetValue = vvv; r.close(); return (null); } } } catch (java.lang.reflect.InvocationTargetException err) { throw new SnifflibDatatypeException("Problem constructing a " + construct, err); } } catch (java.lang.IllegalAccessException err) { throw new SnifflibDatatypeException("Problem constructing 2 ", err); } } catch (java.lang.InstantiationException err) { throw new SnifflibDatatypeException("Problem constructing 3 ", err); } } catch (java.lang.NoSuchMethodException err) { throw new SnifflibDatatypeException("Problem constructing 4", err); } } } else if (tokenizer.ttype == 'e') { Class targetclass = (Class) this.types.get(currentColumn); if (Number.class.isAssignableFrom(targetclass)) { currentColumn--; readingScientificNotation = true; advanceField = false; } } else { advanceField = false; } break; } } if (tokenizer.ttype == StreamTokenizer.TT_EOF) { advanceField = false; break; } if (advanceField) { currentColumn++; if (!readingHeaders) { if (currentColumn >= this.headers.size()) { currentColumn = 0; } } } } if (!readingHeaders) { this.rowcount = currentRow; } else { this.rowcount = 0; readingHeaders = false; if (this.ignorePostHeaderLines > 0) { String strLine; int k = 0; while ((k < this.ignorePostHeaderLines) && ((strLine = r.readLine()) != null)) { k++; } } } r.close(); } catch (java.io.IOException err) { throw new SnifflibDatatypeException(err.getMessage()); } if (!this.dryrun) { for (int j = 0; j < this.headers.size(); j++) { out.setColumnName(j, (String) this.headers.get(j)); } } return (out); }
00
Code Sample 1: public void run() { videoId = videoId.trim(); System.out.println("fetching video"); String requestUrl = "http://www.youtube.com/get_video_info?&video_id=" + videoId; try { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = rd.readLine(); int from = line.indexOf("&token=") + 7; int to = line.indexOf("&thumbnail_url="); String id = line.substring(from, to); String tmp = "http://www.youtube.com/get_video?video_id=" + videoId + "&t=" + id; url = new URL(tmp); conn = (HttpURLConnection) url.openConnection(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); rd.readLine(); tmp = conn.getURL().toString(); url = new URL(tmp); conn = (HttpURLConnection) url.openConnection(); InputStream is; OutputStream outStream; URLConnection uCon; byte[] buf; int ByteRead, ByteWritten = 0; url = new URL(tmp); outStream = new BufferedOutputStream(new FileOutputStream(videoId + ".flv")); uCon = url.openConnection(); is = uCon.getInputStream(); buf = new byte[1024]; while ((ByteRead = is.read(buf)) != -1) { outStream.write(buf, 0, ByteRead); ByteWritten += ByteRead; } is.close(); outStream.close(); System.out.println(videoUrl + " is ready"); } catch (Exception e) { System.out.println("Could not find flv-url " + videoId + "! " + e.getMessage()); } finally { ready = true; } } Code Sample 2: private void load() throws SQLException { Connection conn = null; Statement stmt = null; try { conn = FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); ClearData.clearTables(stmt); stmt.executeUpdate("insert into AttributeCategories (CategoryName) values ('color')"); stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('blue', 'color')"); stmt.executeUpdate("insert into Attributes (AttributeName, Category) values ('red', 'color')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (100, 'ball')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (101, 'blue ball')"); stmt.executeUpdate("insert into Objects (ObjectId, Description) values (102, 'red ball')"); stmt.executeQuery("select setval('objects_objectid_seq', 1000)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (100, 'isa', 1)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (101, 'instance', 100)"); stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (102, 'instance', 100)"); stmt.executeUpdate("insert into ObjectAttributes (ObjectId, AttributeName) values (101, 'blue')"); stmt.executeUpdate("insert into ObjectAttributes (ObjectId, AttributeName) values (102, 'red')"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('LEFT-WALL', '1', 'AV+ | ADJ+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('the', '1', 'D+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('red', '1', 'ADJ- | ADJ+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('blue', '1', 'ADJ- | ADJ+', 1)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('ball', '1', '[@ADJ-] & [D-] & DO-', 100)"); stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('throw', '1', 'AV- & DO+', 1)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('DO', 3)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('AV', 7)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('D', 10)"); stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('ADJ', 11)"); stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('the', 1)"); stmt.executeUpdate("insert into FrameSlots (SlotName) values ('object')"); stmt.executeUpdate("insert into QuestionWords (QuestionWord, Type) values ('which', 7)"); stmt.executeUpdate("insert into Verbs (VerbName, Type, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('throw', 1, '', '', 'object')"); stmt.executeQuery("select setval('instructions_instructionid_seq', 1)"); stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, '', null, 0, null, null, null)"); stmt.executeQuery("select setval('transactions_transactionid_seq', 1)"); stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (2, 'throw')"); stmt.executeQuery("select setval('verbtransactions_verbid_seq', 1)"); stmt.executeUpdate("insert into VerbTransactions (VerbString, MoodType, TransactionId) values ('throw', 1, 2)"); stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'object', 1)"); stmt.executeUpdate("update SystemProperties set value = 'Tutorial 3 Data' where name = 'DB Data Version'"); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } }
00
Code Sample 1: private static void addFileToZip(String path, String srcFile, ZipOutputStream zip, String prefix, String suffix) throws Exception { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip, prefix, suffix); } else { if (isFileNameMatch(folder.getName(), prefix, suffix)) { FileInputStream fis = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); IOUtils.copy(fis, zip); fis.close(); } } } Code Sample 2: public LOCKSSDaemonStatusTableTO getDataFromDaemonStatusTable() throws HttpResponseException { LOCKSSDaemonStatusTableXmlStreamParser ldstxp = null; LOCKSSDaemonStatusTableTO ldstTO = null; HttpEntity entity = null; HttpGet httpget = null; xstream.setMode(XStream.NO_REFERENCES); xstream.alias("HttpClientDAO", HttpClientDAO.class); try { httpget = new HttpGet(dataUrl); logger.log(Level.INFO, "executing request {0}", httpget.getURI()); HttpResponse resp = httpClient.execute(httpget); int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.log(Level.WARNING, "response to the request is not OK: skip this IP: status code={0}", statusCode); httpget.abort(); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); return ldstTO; } entity = resp.getEntity(); InputStream is = entity.getContent(); ldstxp = new LOCKSSDaemonStatusTableXmlStreamParser(); ldstxp.read(new BufferedInputStream(is)); ldstTO = ldstxp.getLOCKSSDaemonStatusTableTO(); ldstTO.setIpAddress(this.ip); logger.log(Level.INFO, "After parsing [{0}] table", this.tableId); logger.log(Level.FINEST, "After parsing {0}: contents of ldstTO:\n{1}", new Object[] { this.tableId, ldstTO }); if (ldstTO.hasIncompleteRows) { logger.log(Level.WARNING, "!!!!!!!!! incomplete rows are found for {0}", tableId); if (ldstTO.getTableData() != null && ldstTO.getTableData().size() > 0) { logger.log(Level.FINE, "incomplete rows: table(map) data dump =[\n{0}\n]", xstream.toXML(ldstTO.getTableData())); } } else { logger.log(Level.INFO, "All rows are complete for {0}", tableId); } } catch (ConnectTimeoutException ce) { logger.log(Level.WARNING, "ConnectTimeoutException occurred", ce); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (SocketTimeoutException se) { logger.log(Level.WARNING, "SocketTimeoutException occurred", se); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (ClientProtocolException pe) { logger.log(Level.SEVERE, "The protocol was not http; https is suspected", pe); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); ldstTO.setHttpProtocol(false); if (httpget != null) { httpget.abort(); } return ldstTO; } catch (IOException ex) { logger.log(Level.SEVERE, "IO exception occurs", ex); ldstTO = new LOCKSSDaemonStatusTableTO(); ldstTO.setBoxHttpStatusOK(false); if (httpget != null) { httpget.abort(); } return ldstTO; } finally { if (entity != null) { try { EntityUtils.consume(entity); } catch (IOException ex) { logger.log(Level.SEVERE, "io exception when entity was to be" + "consumed", ex); } } } return ldstTO; }
00
Code Sample 1: public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { size = outputFile.length(); if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(outputFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } } } Code Sample 2: private void connect(URL url) throws IOException { String protocol = url.getProtocol(); if (!protocol.equals("http")) throw new IllegalArgumentException("URL must use 'http:' protocol"); int port = url.getPort(); if (port == -1) port = 80; fileName = url.getFile(); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); toServer = new OutputStreamWriter(conn.getOutputStream()); fromServer = conn.getInputStream(); }
00
Code Sample 1: public void getDataFiles(String server, String username, String password, String folder, String destinationFolder) { try { FTPClient ftp = new FTPClient(); ftp.connect(server); ftp.login(username, password); System.out.println("Connected to " + server + "."); System.out.print(ftp.getReplyString()); ftp.enterLocalActiveMode(); ftp.changeWorkingDirectory(folder); System.out.println("Changed to " + folder); FTPFile[] files = ftp.listFiles(); System.out.println("Number of files in dir: " + files.length); for (int i = 0; i < files.length; i++) { getFiles(ftp, files[i], destinationFolder); } ftp.logout(); ftp.disconnect(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public InputStream getExportFile() { URL url = ExportAction.class.getClassLoader().getResource("sysConfig.xml"); if (url != null) try { return url.openStream(); } catch (IOException e) { e.printStackTrace(); } return null; }
00
Code Sample 1: public boolean authorize(String username, String password, String filename) { open(filename); boolean isAuthorized = false; StringBuffer encPasswd = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(password.getBytes()); byte[] digest = mdAlgorithm.digest(); encPasswd = new StringBuffer(); for (int i = 0; i < digest.length; i++) { password = Integer.toHexString(255 & digest[i]); if (password.length() < 2) { password = "0" + password; } encPasswd.append(password); } } catch (NoSuchAlgorithmException ex) { } String encPassword = encPasswd.toString(); String tempPassword = getPassword(username); System.out.println("epass" + encPassword); System.out.println("pass" + tempPassword); if (tempPassword.equals(encPassword)) { isAuthorized = true; } else { isAuthorized = false; } close(); return isAuthorized; } Code Sample 2: @Override public void setDocumentSpace(DocumentSpace space) { for (Document doc : space) { if (doc instanceof XMLDOMDocument) { writer.writeDocument(doc); } else if (doc instanceof BinaryDocument) { BinaryDocument bin = (BinaryDocument) doc; try { ManagedFile result = resolveFileFor(folder, (BinaryDocument) doc); IOUtils.copy(bin.getContent().getInputStream(), result.getContent().getOutputStream()); } catch (IOException e) { throw ManagedIOException.manage(e); } } else { System.err.println("Unkown Document type"); } } }
11
Code Sample 1: private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } Code Sample 2: public static 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; }
11
Code Sample 1: public int delete(BusinessObject o) throws DAOException { int delete = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_BILL")); pst.setInt(1, bill.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; } Code Sample 2: private void handleInterfaceReparented(String ipAddr, Parms eventParms) { Category log = ThreadCategory.getInstance(OutageWriter.class); if (log.isDebugEnabled()) log.debug("interfaceReparented event received..."); if (ipAddr == null || eventParms == null) { log.warn(EventConstants.INTERFACE_REPARENTED_EVENT_UEI + " ignored - info incomplete - ip/parms: " + ipAddr + "/" + eventParms); return; } long oldNodeId = -1; long newNodeId = -1; String parmName = null; Value parmValue = null; String parmContent = null; Enumeration parmEnum = eventParms.enumerateParm(); while (parmEnum.hasMoreElements()) { Parm parm = (Parm) parmEnum.nextElement(); parmName = parm.getParmName(); parmValue = parm.getValue(); if (parmValue == null) continue; else parmContent = parmValue.getContent(); if (parmName.equals(EventConstants.PARM_OLD_NODEID)) { try { oldNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_OLD_NODEID + " cannot be non-numeric"); oldNodeId = -1; } } else if (parmName.equals(EventConstants.PARM_NEW_NODEID)) { try { newNodeId = Integer.valueOf(parmContent).intValue(); } catch (NumberFormatException nfe) { log.warn("Parameter " + EventConstants.PARM_NEW_NODEID + " cannot be non-numeric"); newNodeId = -1; } } } if (newNodeId == -1 || oldNodeId == -1) { log.warn("Unable to process 'interfaceReparented' event, invalid event parm."); return; } Connection dbConn = null; try { dbConn = DatabaseConnectionFactory.getInstance().getConnection(); try { dbConn.setAutoCommit(false); } catch (SQLException sqle) { log.error("Unable to change database AutoCommit to FALSE", sqle); return; } PreparedStatement reparentOutagesStmt = dbConn.prepareStatement(OutageConstants.DB_REPARENT_OUTAGES); reparentOutagesStmt.setLong(1, newNodeId); reparentOutagesStmt.setLong(2, oldNodeId); reparentOutagesStmt.setString(3, ipAddr); int count = reparentOutagesStmt.executeUpdate(); try { dbConn.commit(); if (log.isDebugEnabled()) log.debug("Reparented " + count + " outages - ip: " + ipAddr + " reparented from " + oldNodeId + " to " + newNodeId); } catch (SQLException se) { log.warn("Rolling back transaction, reparent outages failed for newNodeId/ipAddr: " + newNodeId + "/" + ipAddr); try { dbConn.rollback(); } catch (SQLException sqle) { log.warn("SQL exception during rollback, reason", sqle); } } reparentOutagesStmt.close(); } catch (SQLException se) { log.warn("SQL exception while handling \'interfaceReparented\'", se); } finally { try { if (dbConn != null) dbConn.close(); } catch (SQLException e) { log.warn("Exception closing JDBC connection", e); } } }
00
Code Sample 1: public void login(String a_username, String a_password) throws GB_SecurityException { Exception l_exception = null; try { if (clientFtp == null) { clientFtp = new FTPClient(); clientFtp.connect("ftp://" + ftp); } boolean b = clientFtp.login(a_username, a_password); if (b) { username = a_username; password = a_password; return; } } catch (Exception ex) { l_exception = ex; } String l_msg = "Cannot login to ftp server with user [{1}], {2}"; String[] l_replaces = new String[] { a_username, ftp }; l_msg = STools.replace(l_msg, l_replaces); throw new GB_SecurityException(l_msg, l_exception); } Code Sample 2: public void run() { XmlFilesFilter filter = new XmlFilesFilter(); String pathTemp = Settings.get("vo_store.databaseMetaCollection"); String sectionName = pathTemp.substring(1, pathTemp.indexOf("/", 2)); String templateName = VOAccess.getElementByName(settingsDB, "TEMPLATE", sectionName); String schemaName = VOAccess.getElementByName(settingsDB, "SCHEMA", sectionName); byte[] buf = new byte[1024]; Hashtable templateElements = null; try { URL xmlTemplateUrl = new URL(httpURI + settingsDB + "/" + templateName); URL getDocPathsAndValuesXslUrl = new URL(httpURI + settingsDB + "/" + "getDocPathsValuesAndDisplays.xsl"); org.w3c.dom.Document curTemplateXml = VOAccess.readDocument(xmlTemplateUrl); DOMResult templateResult = new DOMResult(); InputStream tempInput = getDocPathsAndValuesXslUrl.openStream(); javax.xml.transform.sax.SAXSource tempXslSource = new javax.xml.transform.sax.SAXSource(new org.xml.sax.InputSource(tempInput)); Transformer trans = TransformerFactory.newInstance().newTransformer(tempXslSource); trans.setParameter("schemaUrl", httpURI + settingsDB + "/" + schemaName); trans.transform(new javax.xml.transform.dom.DOMSource(curTemplateXml), templateResult); tempInput.close(); templateElements = VOAccess.displaysToHashtable(templateResult); ((CollectionManagementService) CollectionsManager.getService(xmldbURI + rootDB, false, "CollectionManager")).createCollection(rootDB + pathTemp); } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); } while (true) { File[] fileList = sourceMetaFilesDir.listFiles(filter); for (int i = 0; i < Math.min(fileList.length, 500); i++) { File newFile = fileList[i]; try { Document metaDoc = build.build(newFile); Element metaElm = metaDoc.getRootElement(); String dataFileName = metaElm.getChildText("Content"), previewFileName = metaElm.getChildText("Preview"); String objId = VOAccess.getUniqueId(); metaElm.getChild("Content").setText("videostore?type=doc&objId=" + objId); metaElm.getChild("Preview").setText("videostore?type=preview&objId=" + objId); boolean found = false; for (Iterator it = sourceDataFilesDirs.iterator(); it.hasNext() && !found; ) { String sourceDataFilesDir = (String) it.next(); File dataInput = new File(sourceDataFilesDir + "/" + dataFileName); if (dataInput.exists()) { found = true; BufferedInputStream inp = new BufferedInputStream(new FileInputStream(dataInput)); FileOutputStream outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".dat")); int read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); dataInput = new File(sourceDataFilesDir + "/" + previewFileName); inp = new BufferedInputStream(new FileInputStream(dataInput)); outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".jpg")); read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); curDirWriteTo++; if (curDirWriteTo >= targetDataFilesDirs.size()) { curDirWriteTo = 0; } } } if (!found) { newFile.renameTo(new File(newFile.getAbsolutePath() + ".not_found")); } else { String title = getValueByPath((String) templateElements.get("title"), metaDoc.getRootElement()); String description = getValueByPath((String) templateElements.get("description"), metaDoc.getRootElement()); String onlink = ""; if (null != templateElements.get("onlink")) { onlink = getValueByPath((String) templateElements.get("onlink"), metaDoc.getRootElement()); } String ncover = ""; if (null != templateElements.get("ncover")) { ncover = getValueByPath((String) templateElements.get("ncover"), metaDoc.getRootElement()); } String wcover = ""; if (null != templateElements.get("wcover")) { wcover = getValueByPath((String) templateElements.get("wcover"), metaDoc.getRootElement()); } String ecover = ""; if (null != templateElements.get("ecover")) { ecover = getValueByPath((String) templateElements.get("ecover"), metaDoc.getRootElement()); } String scover = ""; if (null != templateElements.get("scover")) { scover = getValueByPath((String) templateElements.get("scover"), metaDoc.getRootElement()); } String datefrom = ""; if (null != templateElements.get("datefrom")) { datefrom = getValueByPath((String) templateElements.get("datefrom"), metaDoc.getRootElement()); } String dateto = ""; if (null != templateElements.get("dateto")) { dateto = getValueByPath((String) templateElements.get("dateto"), metaDoc.getRootElement()); } String previewimg = ""; if (null != templateElements.get("previewimg")) { previewimg = getValueByPath((String) templateElements.get("previewimg"), metaDoc.getRootElement()); } String discRestr = "false"; String votingRestr = "false"; datefrom = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); dateto = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); Hashtable discussionFields = new Hashtable(); discussionFields.put("OBJECT_ID", objId); discussionFields.put("AUTHOR_ID", "auto"); discussionFields.put("AUTHOR_NAME", "auto"); discussionFields.put("OBJECT_SECTION", sectionName); discussionFields.put("OBJECT_PATH", pathTemp); discussionFields.put("FILE_PATH", ""); discussionFields.put("TITLE", title); discussionFields.put("DESCRIPTION", description); discussionFields.put("ONLINK", onlink); discussionFields.put("NCOVER", ncover); discussionFields.put("ECOVER", ecover); discussionFields.put("SCOVER", scover); discussionFields.put("WCOVER", wcover); discussionFields.put("PERIOD_START", datefrom); discussionFields.put("PERIOD_END", dateto); discussionFields.put("PREVIEW_IMG", previewimg); discussionFields.put("DISCUSSRESTRICTION", discRestr); discussionFields.put("VOTINGRESTRICTION", votingRestr); VOAccess.createDiscussionFile(discussionFields); VOAccess.updateLastItem(objId, sectionName); Collection col = CollectionsManager.getCollection(rootDB + pathTemp, true); XMLResource document = (XMLResource) col.createResource(objId + ".xml", XMLResource.RESOURCE_TYPE); document.setContent(outXml.outputString(metaElm)); col.storeResource(document); Indexer.index(objId); newFile.delete(); } } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); newFile.renameTo(new File(newFile.getAbsolutePath() + ".bad")); } } try { this.sleep(600000); } catch (InterruptedException ex1) { ex1.printStackTrace(); } } }
00
Code Sample 1: public void get(final String remoteFilePath, final String remoteFileName, final String localName) { final FTPClient ftp = new FTPClient(); final FTPMessageCollector listener = new FTPMessageCollector(); try { final String localDirName = localName.substring(0, localName.lastIndexOf(File.separator)); System.out.println("ftp:"); System.out.println(" remoteDir " + remoteFilePath); System.out.println(" localDir " + localDirName); final File localDir = new File(localDirName); if (!localDir.exists()) { System.out.println(" create Dir " + localDirName); localDir.mkdir(); } ftp.setTimeout(10000); ftp.setRemoteHost(host); ftp.setMessageListener(listener); } catch (final UnknownHostException e) { showConnectError(); return; } catch (final Exception e) { e.printStackTrace(); } final TileInfoManager tileInfoMgr = TileInfoManager.getInstance(); final Job downloadJob = new Job(Messages.job_name_ftpDownload) { @Override protected IStatus run(final IProgressMonitor monitor) { try { showTileInfo(remoteFileName, -1); System.out.println(" connect " + host); ftp.connect(); showTileInfo(remoteFileName, -2); System.out.println(" login " + user + " " + password); ftp.login(user, password); System.out.println(" set passive mode"); ftp.setConnectMode(FTPConnectMode.PASV); System.out.println(" set type binary"); ftp.setType(FTPTransferType.BINARY); showTileInfo(remoteFileName, -3); System.out.println(" chdir " + remoteFilePath); ftp.chdir(remoteFilePath); ftp.setProgressMonitor(new FTPProgressMonitor() { public void bytesTransferred(final long count) { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_LOADING_MONITOR, remoteFileName, count); } }); showTileInfo(remoteFileName, -4); System.out.println(" get " + remoteFileName + " -> " + localName + " ..."); ftp.get(localName, remoteFileName); System.out.println(" quit"); ftp.quit(); } catch (final UnknownHostException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_cannotConnectToServer, host), e); } catch (final SocketTimeoutException e) { return new Status(IStatus.ERROR, TourbookPlugin.PLUGIN_ID, IStatus.ERROR, NLS.bind(Messages.error_message_timeoutWhenConnectingToServer, host), e); } catch (final Exception e) { e.printStackTrace(); tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_ERROR_LOADING, remoteFileName, 0); } finally { tileInfoMgr.updateSRTMTileInfo(TileEventId.SRTM_DATA_END_LOADING, remoteFileName, 0); } return Status.OK_STATUS; } }; downloadJob.schedule(); try { downloadJob.join(); } catch (final InterruptedException e) { e.printStackTrace(); } } Code Sample 2: @Test public final void testImportODS() throws Exception { URL url = ODSTableImporterTest.class.getResource("/Messages.ods"); InputStream in = url.openStream(); ODSTableImporter b = new ODSTableImporter(); b.importODS(in, null); assertMessagesOds(b); }
11
Code Sample 1: public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = String.valueOf(Base64Coder.encode(raw)); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; } Code Sample 2: public static final String getUniqueId() { String digest = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); String timeVal = "" + (System.currentTimeMillis() + 1); String localHost = ""; ; try { localHost = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { log.error("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) { log.error("Error trying to generate unique Id" + e.getMessage()); } return digest; }
00
Code Sample 1: public long add(T t) throws BaseException { Connection conn = null; PreparedStatement pstmt = null; long result = -1L; boolean flag = false; try { conn = getConnection(); if (conn != null) { flag = true; } else { conn = ConnectionManager.getConn(getStrConnection()); conn.setAutoCommit(false); } pstmt = getAdd(conn, t, this.getTableName()); pstmt.executeUpdate(); result = t.getId(); } catch (SQLException e) { try { if (!flag) { conn.rollback(); } } catch (Exception ex) { log.error("add(T " + t.toString() + ")回滚出错,错误信息:" + ex.getMessage()); } log.error("add(T " + t.toString() + ")方法出错:" + e.getMessage()); } catch (BaseException e) { throw e; } finally { try { if (!flag) { conn.setAutoCommit(true); } } catch (Exception e) { log.error("add(T " + t.toString() + ")方法设置自动提交出错,信息为:" + e.getMessage()); } ConnectionManager.closePreparedStatement(pstmt); if (!flag) { ConnectionManager.closeConn(conn); } } return result; } Code Sample 2: public String copyImages(Document doc, String sXML, String newPath, String tagName, String itemName) { NodeList nl = null; Node n = null; NamedNodeMap nnp = null; Node nsrc = null; URL url = null; String sFilename = ""; String sNewPath = ""; int index; String sOldPath = ""; try { nl = doc.getElementsByTagName(tagName); for (int i = 0; i < nl.getLength(); i++) { n = nl.item(i); nnp = n.getAttributes(); nsrc = nnp.getNamedItem(itemName); String sTemp = nsrc.getTextContent(); url = new URL("file", "localhost", sTemp); sOldPath = url.getPath(); sOldPath = sOldPath.replace('/', File.separatorChar); int indexFirstSlash = sOldPath.indexOf(File.separatorChar); String sSourcePath; if (itemName.equals("data")) sSourcePath = sOldPath; else sSourcePath = sOldPath.substring(indexFirstSlash + 1); index = sOldPath.lastIndexOf(File.separatorChar); sFilename = sOldPath.substring(index + 1); sNewPath = newPath + sFilename; FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(sSourcePath).getChannel(); out = new FileOutputStream(sNewPath).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } sXML = sXML.replace(nsrc.getTextContent(), sFilename); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sXML; }
11
Code Sample 1: protected void assignListeners() { groupsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent event) { refreshInfo(); } }); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showSaveDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName))); ReaderWriterGroup.write(out, writer); System.err.println("Wrote groups informations to output '" + fileName + "'."); out.close(); } catch (IOException e) { System.err.println("error while writing (GroupManager.saveClt):"); e.printStackTrace(); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { JFileChooser fileDialog = new JFileChooser("."); fileDialog.setFileFilter(ReaderData.mkExtensionFileFilter(".grp", "Group Files")); int outcome = fileDialog.showOpenDialog((Frame) null); if (outcome == JFileChooser.APPROVE_OPTION) { assert (fileDialog.getCurrentDirectory() != null); assert (fileDialog.getSelectedFile() != null); String fileName = fileDialog.getCurrentDirectory().toString() + File.separator + fileDialog.getSelectedFile().getName(); BufferedReader fileReader = null; try { fileReader = new BufferedReader(new FileReader(fileName)); ReaderWriterGroup.read(fileReader, writer); fileReader.close(); } catch (Exception e) { System.err.println("Exception while reading from file '" + fileName + "'."); System.err.println(e); } } else if (outcome == JFileChooser.CANCEL_OPTION) { } } }); ItemListener propItemListener = new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { int[] indices = groupsList.getSelectedIndices(); for (int index : indices) { Group group = getGroupFromListIndex(index); if (group != null) { if (event.getSource() instanceof JComboBox) { JComboBox eventSource = (JComboBox) event.getSource(); if (eventSource == colorComboBox) { Color color = colorComboBox.getSelectedColor(); assert (color != null); group.setColor(color); shapeComboBox.setColor(color); } else if (eventSource == shapeComboBox) { Shape shape = shapeComboBox.getSelectedShape(); assert (shape != null); group.setShape(shape); } } else if (event.getSource() instanceof JCheckBox) { JCheckBox eventSource = (JCheckBox) event.getSource(); if (eventSource == showGroupCheckBox) { group.visible = showGroupCheckBox.isSelected(); } else if (eventSource == showGraphicInfoCheckBox) { group.info = showGraphicInfoCheckBox.isSelected(); } } } } graph.notifyAboutGroupsChange(null); } }; colorComboBox.addItemListener(propItemListener); shapeComboBox.addItemListener(propItemListener); showGroupCheckBox.addItemListener(propItemListener); showGraphicInfoCheckBox.addItemListener(propItemListener); showGroupfreeNodesCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent event) { graph.getGroup(0).visible = showGroupfreeNodesCheckBox.isSelected(); graph.notifyAboutGroupsChange(null); } }); ActionListener propActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JButton botton = (JButton) event.getSource(); Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { for (GraphVertex graphVertex : group) { if (botton == showLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, true); } else if (botton == hideLabelsButton) { graphVertex.setShowName(NameVisibility.Priority.GROUPS, false); } } graph.notifyAboutGroupsChange(null); } } }; showLabelsButton.addActionListener(propActionListener); hideLabelsButton.addActionListener(propActionListener); newButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String newGroupName = JOptionPane.showInputDialog(null, "Enter a name", "Name of the new group", JOptionPane.QUESTION_MESSAGE); if (newGroupName != null) { if (graph.getGroup(newGroupName) == null) { graph.addGroup(new Group(newGroupName, graph)); } } } }); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { Group group = getGroupFromListIndex(groupsList.getSelectedIndex()); if (group != null) { DialogEditGroup dialog = new DialogEditGroup(graph, group); dialog.setModal(true); dialog.setVisible(true); } } }); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index > 0 && index < graph.getNumberOfGroups() - 1) { graph.removeGroup(index); } } }); upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupUp(index); groupsList.setSelectedIndex(index - 1); } } }); downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { int index = groupsList.getSelectedIndex(); if (index < graph.getNumberOfGroups() - 1) { graph.moveGroupDown(index); groupsList.setSelectedIndex(index + 1); } } }); } 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); }
00
Code Sample 1: public static void parseString(String str, String name) { BufferedReader reader; String zeile = null; boolean firstL = true; int lambda; float intens; int l_b = 0; int l_e = 0; HashMap<Integer, Float> curve = new HashMap<Integer, Float>(); String[] temp; try { File f = File.createTempFile("tempFile", null); URL url = new URL(str); InputStream is = url.openStream(); FileOutputStream os = new FileOutputStream(f); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); is.close(); os.close(); reader = new BufferedReader(new FileReader(f)); zeile = reader.readLine(); lambda = 0; while (zeile != null) { if (!(zeile.length() > 0 && zeile.charAt(0) == '#')) { zeile = reader.readLine(); break; } zeile = reader.readLine(); } while (zeile != null) { if (zeile.length() > 0) { temp = zeile.split(" "); lambda = Integer.parseInt(temp[0]); intens = Float.parseFloat(temp[1]); if (firstL) { firstL = false; l_b = lambda; } curve.put(lambda, intens); } zeile = reader.readLine(); } l_e = lambda; } catch (IOException e) { System.err.println("Error2 :" + e); } try { String tempV; File file = new File("C:/spectralColors/" + name + ".sd"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write("# COLOR: " + name + " Auto generated File: 02/09/2009; From " + l_b + " to " + l_e); bw.newLine(); bw.write(l_b + ""); bw.newLine(); for (int i = l_b; i <= l_e; i++) { if (curve.containsKey(i)) { tempV = i + " " + curve.get(i); bw.write(tempV); bw.newLine(); } } bw.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public LineIterator iterator() { LineIterator ret; final String charsetname; final Charset charset; final CharsetDecoder charsetDecoder; synchronized (this) { charsetname = this.charsetname; charset = this.charset; charsetDecoder = this.charsetDecoder; } try { if (charsetDecoder != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charsetDecoder); else if (charset != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charset); else if (charsetname != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, Charset.forName(charsetname)); else ret = new LineIterator(this, url.openStream(), returnNullUponEof, (Charset) null); synchronized (openedIterators) { openedIterators.add(ret); } return ret; } catch (IOException e) { throw new IllegalStateException(e); } }
00
Code Sample 1: private static byte[] loadBytecodePrivileged() { URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz"); try { InputStream in = url.openStream(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (; ; ) { int r = in.read(); if (r == -1) { return bout.toByteArray(); } bout.write(r); } } finally { in.close(); } } catch (IOException e) { throw new UndeclaredThrowableException(e); } } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public OOXMLSignatureService(InputStream documentInputStream, OutputStream documentOutputStream, SignatureFacet signatureFacet, String role, IdentityDTO identity, byte[] photo, RevocationDataService revocationDataService, TimeStampService timeStampService, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".ooxml"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(signatureFacet); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } Code Sample 2: private static 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 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 void externalizeFiles(Document doc, File out) throws IOException { File[] files = doc.getImages(); if (files.length > 0) { File dir = new File(out.getParentFile(), out.getName() + ".images"); if (!dir.mkdirs()) throw new IOException("cannot create directory " + dir); if (dir.exists()) { for (int i = 0; i < files.length; i++) { File file = files[i]; File copy = new File(dir, file.getName()); FileChannel from = null, to = null; long count = -1; try { from = new FileInputStream(file).getChannel(); count = from.size(); to = new FileOutputStream(copy).getChannel(); from.transferTo(0, count, to); doc.setImage(file, dir.getName() + "/" + copy.getName()); } catch (Throwable t) { LOG.log(Level.WARNING, "Copying '" + file + "' to '" + copy + "' failed (size=" + count + ")", t); } finally { try { to.close(); } catch (Throwable t) { } try { from.close(); } catch (Throwable t) { } } } } } }
00
Code Sample 1: @Test public void shouldDownloadFileUsingPublicLink() throws Exception { String bucketName = "test-" + UUID.randomUUID(); Service service = new WebClientService(credentials); service.createBucket(bucketName); File file = folder.newFile("foo.txt"); FileUtils.writeStringToFile(file, UUID.randomUUID().toString()); service.createObject(bucketName, file.getName(), file, new NullProgressListener()); String publicUrl = service.getPublicUrl(bucketName, file.getName(), new DateTime().plusDays(5)); File saved = folder.newFile("saved.txt"); InputStream input = new URL(publicUrl).openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(saved); IOUtils.copy(input, output); output.close(); assertThat("Corrupted download", Files.computeMD5(saved), equalTo(Files.computeMD5(file))); service.deleteObject(bucketName, file.getName()); service.deleteBucket(bucketName); } Code Sample 2: public static InputStream openRemoteFile(URL urlParam) throws KExceptionClass { InputStream result = null; try { result = urlParam.openStream(); } catch (IOException error) { String message = new String(); message = "No se puede abrir el recurso ["; message += urlParam.toString(); message += "]["; message += error.toString(); message += "]"; throw new KExceptionClass(message, error); } ; return (result); }
11
Code Sample 1: public void copyFilesIntoProject(HashMap<String, String> files) { Set<String> filenames = files.keySet(); for (String key : filenames) { String realPath = files.get(key); if (key.equals("fw4ex.xml")) { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + bundle.getString("Stem") + STEM_FILE_EXETENSION)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } else { try { FileReader in = new FileReader(new File(realPath)); FileWriter out = new FileWriter(new File(project.getLocation() + "/" + key)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { Activator.getDefault().showMessage("File " + key + " not found... Error while moving files to the new project."); } catch (IOException ie) { Activator.getDefault().showMessage("Error while moving " + key + " to the new project."); } } } } Code Sample 2: protected static void copyDeleting(File source, File dest) throws ErrorCodeException { byte[] buf = new byte[8 * 1024]; FileInputStream in = null; try { in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { int count; while ((count = in.read(buf)) >= 0) out.write(buf, 0, count); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new ErrorCodeException(e); } }
00
Code Sample 1: public static void postData(Reader data, URL endpoint, Writer output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endpoint.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlc != null) urlc.disconnect(); } } Code Sample 2: protected Properties load(URL url) { try { InputStream i = url.openStream(); Properties p = new Properties(); p.load(i); i.close(); return p; } catch (IOException e) { throw new RuntimeException(e); } }
00
Code Sample 1: public static int doPost(String urlString, String username, String password, Map<String, String> parameters) throws IOException { PrintWriter out = null; try { URL url = new URL(urlString); URLConnection connection = url.openConnection(); if (username != null && password != null) { String encoding = base64Encode(username + ':' + password); connection.setRequestProperty("Authorization", "Basic " + encoding); } connection.setDoOutput(true); out = new PrintWriter(connection.getOutputStream()); boolean first = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (first) { first = false; } else { out.print('&'); } out.print(entry.getKey()); out.print('='); out.print(URLEncoder.encode(entry.getValue(), "UTF-8")); } out.close(); connection.connect(); if (!(connection instanceof HttpURLConnection)) { throw new IOException(); } return ((HttpURLConnection) connection).getResponseCode(); } catch (IOException ex) { throw ex; } finally { if (out != null) { out.close(); } } } Code Sample 2: public static String toMD5Sum(String arg0) { String ret; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(arg0.getBytes()); ret = toHexString(md.digest()); } catch (Exception e) { ret = arg0; } return ret; }
00
Code Sample 1: public static EXISchema getEXISchema(String fileName, Class<?> cls, EXISchemaFactoryErrorHandler compilerErrorHandler) throws IOException, ClassNotFoundException, EXISchemaFactoryException { EXISchemaFactory schemaCompiler = new EXISchemaFactory(); schemaCompiler.setCompilerErrorHandler(compilerErrorHandler); InputSource inputSource = null; if (fileName != null) { URL url; if ((url = cls.getResource(fileName)) != null) { inputSource = new InputSource(url.openStream()); inputSource.setSystemId(url.toString()); } else throw new RuntimeException("File '" + fileName + "' not found."); } EXISchema compiled = schemaCompiler.compile(inputSource); InputStream serialized = serializeSchema(compiled); return loadSchema(serialized); } Code Sample 2: public static String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); byte[] hash = md.digest(); int hashLength = hash.length; StringBuffer hashStringBuf = new StringBuffer(); String byteString; int byteLength; for (int index = 0; index < hash.length; index++) { byteString = String.valueOf(hash[index] + 128); byteLength = byteString.length(); switch(byteLength) { case 1: byteString = "00" + byteString; break; case 2: byteString = "0" + byteString; break; } hashStringBuf.append(byteString); } return hashStringBuf.toString(); } catch (NoSuchAlgorithmException nsae) { System.out.println("Error getting password hash - " + nsae.getMessage()); return null; } }