label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public void deleteUser(String userID) throws XregistryException { try { userID = Utils.canonicalizeDN(userID); Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_USER_SQL_MAIN); statement1.setString(1, userID); statement1.executeUpdate(); PreparedStatement statement2 = connection.prepareStatement(DELETE_USER_SQL_DEPEND); statement2.setString(1, userID); statement2.executeUpdate(); connection.commit(); Collection<Group> groupList = groups.values(); for (Group group : groupList) { group.removeUser(userID); } log.info("Delete User " + userID); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } } Code Sample 2: public boolean setCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) { boolean inserto = false; try { stm = conexion.prepareStatement("insert into clientes values( '" + IDcliente + "' , '" + nombre.toUpperCase() + "' , '" + paterno.toUpperCase() + "' , '" + materno.toUpperCase() + "' , '" + ocupacion.toUpperCase() + "' , '" + rfc + "' )"); stm.executeUpdate(); conexion.commit(); inserto = true; } catch (SQLException e) { System.out.println("error al insertar registro en la tabla clientes general " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return inserto = false; } return inserto; }
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 copyToCurrentDir(File _copyFile, String _fileName) throws IOException { File outputFile = new File(getCurrentPath() + File.separator + _fileName); FileReader in; FileWriter out; if (!outputFile.exists()) { outputFile.createNewFile(); } in = new FileReader(_copyFile); out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); reList(); }
11
Code Sample 1: private void zip(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); } } Code Sample 2: public static void main(String[] args) throws IOException { ReadableByteChannel in = Channels.newChannel((new FileInputStream("/home/sannies/suckerpunch-distantplanet_h1080p/suckerpunch-distantplanet_h1080p.mov"))); Movie movie = MovieCreator.build(in); in.close(); List<Track> tracks = movie.getTracks(); movie.setTracks(new LinkedList<Track>()); double startTime = 35.000; double endTime = 145.000; boolean timeCorrected = false; for (Track track : tracks) { if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) { if (timeCorrected) { throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported."); } startTime = correctTimeToNextSyncSample(track, startTime); endTime = correctTimeToNextSyncSample(track, endTime); timeCorrected = true; } } for (Track track : tracks) { long currentSample = 0; double currentTime = 0; long startSample = -1; long endSample = -1; for (int i = 0; i < track.getDecodingTimeEntries().size(); i++) { TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i); for (int j = 0; j < entry.getCount(); j++) { if (currentTime <= startTime) { startSample = currentSample; } if (currentTime <= endTime) { endSample = currentSample; } else { break; } currentTime += (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale(); currentSample++; } } movie.addTrack(new CroppedTrack(track, startSample, endSample)); } long start1 = System.currentTimeMillis(); IsoFile out = new DefaultMp4Builder().build(movie); long start2 = System.currentTimeMillis(); FileOutputStream fos = new FileOutputStream(String.format("output-%f-%f.mp4", startTime, endTime)); FileChannel fc = fos.getChannel(); out.getBox(fc); fc.close(); fos.close(); long start3 = System.currentTimeMillis(); System.err.println("Building IsoFile took : " + (start2 - start1) + "ms"); System.err.println("Writing IsoFile took : " + (start3 - start2) + "ms"); System.err.println("Writing IsoFile speed : " + (new File(String.format("output-%f-%f.mp4", startTime, endTime)).length() / (start3 - start2) / 1000) + "MB/s"); }
11
Code Sample 1: @Override public void setContentAsStream(InputStream input) throws IOException { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(htmlFile)); try { IOUtils.copy(input, output); } finally { output.close(); } if (this.getLastModified() != -1) { htmlFile.setLastModified(this.getLastModified()); } } Code Sample 2: private String createCSVFile(String fileName) throws FileNotFoundException, IOException { String csvFile = fileName + ".csv"; BufferedReader buf = new BufferedReader(new FileReader(fileName)); BufferedWriter out = new BufferedWriter(new FileWriter(csvFile)); String line; while ((line = buf.readLine()) != null) out.write(line + "\n"); buf.close(); out.close(); return csvFile; }
11
Code Sample 1: public static void encrypt(File plain, File symKey, File ciphered, String algorithm) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { Key key = null; try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(symKey)); key = (Key) in.readObject(); } catch (IOException ioe) { KeyGenerator generator = KeyGenerator.getInstance(algorithm); key = generator.generateKey(); ObjectOutputStream out = new ObjectOutputStream(new java.io.FileOutputStream(symKey)); out.writeObject(key); out.close(); } Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), algorithm)); FileInputStream in = new FileInputStream(plain); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(ciphered), cipher); byte[] buffer = new byte[4096]; for (int read = in.read(buffer); read > -1; read = in.read(buffer)) { out.write(buffer, 0, read); } out.close(); } Code Sample 2: private File newFile(File oldFile) throws IOException { int counter = 0; File nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName()); while (nFile.exists()) { nFile = new File(this.stateDirProvider.get() + File.separator + oldFile.getName() + "_" + counter); } IOUtils.copyFile(oldFile, nFile); return nFile; }
11
Code Sample 1: public static void copyFile(File in, File out, boolean append) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out, append).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public static void copy(FileInputStream in, File destination) throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = in.getChannel(); dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { if (srcChannel != null) { srcChannel.close(); } if (dstChannel != null) { dstChannel.close(); } } }
00
Code Sample 1: private GenomicSequence fetch(Chromosome k, int start, int end) throws IOException { try { String chr = k.toString(); if (chr.toLowerCase().startsWith("chr")) chr = chr.substring(3); SAXParserFactory f = SAXParserFactory.newInstance(); f.setNamespaceAware(false); f.setValidating(false); SAXParser parser = f.newSAXParser(); URL url = new URL("http://genome.ucsc.edu/cgi-bin/das/" + genomeVersion + "/dna?segment=" + URLEncoder.encode(chr, "UTF-8") + ":" + (start + 1) + "," + (end)); DASHandler handler = new DASHandler(); InputStream in = url.openStream(); parser.parse(in, handler); in.close(); GenomicSequence seq = new GenomicSequence(); seq.sequence = handler.bytes.toByteArray(); seq.start = start; seq.end = end; if (seq.sequence.length != seq.length()) throw new IOException("bad bound " + seq + " " + seq.sequence.length + " " + seq.length()); return seq; } catch (IOException err) { throw err; } catch (Exception e) { throw new IOException(e); } } Code Sample 2: @Override public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException { try { return super.select(keyInfo, purpose, method, context); } catch (KeySelectorException e) { LOG.debug("no key found via ds:KeyInfo key selector"); } LOG.debug("signature resource name: " + this.signatureResourceName); String signatureSegment = this.signatureResourceName.substring(0, this.signatureResourceName.lastIndexOf("/")); LOG.debug("signature segment: " + signatureSegment); String signatureBase = this.signatureResourceName.substring(this.signatureResourceName.lastIndexOf("/") + 1); LOG.debug("signature base: " + signatureBase); String signatureRelationshipResourceName = signatureSegment + "/_rels/" + signatureBase + ".rels"; LOG.debug("signature relationship resource name: " + signatureRelationshipResourceName); ZipArchiveInputStream zipInputStream; try { zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true); } catch (IOException e) { throw new KeySelectorException(e); } ZipArchiveEntry zipEntry; try { while (null != (zipEntry = zipInputStream.getNextZipEntry())) { if (signatureRelationshipResourceName.equals(zipEntry.getName())) { break; } } } catch (IOException e) { throw new KeySelectorException(e); } if (null == zipEntry) { LOG.warn("relationship part not present: " + signatureRelationshipResourceName); throw new KeySelectorException("no key found"); } LOG.debug("signature relationship part found"); JAXBElement<CTRelationships> signatureRelationshipsElement; try { signatureRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller.unmarshal(zipInputStream); } catch (JAXBException e) { throw new KeySelectorException(e); } CTRelationships signatureRelationships = signatureRelationshipsElement.getValue(); List<CTRelationship> signatureRelationshipList = signatureRelationships.getRelationship(); List<String> certificateResourceNames = new LinkedList<String>(); for (CTRelationship signatureRelationship : signatureRelationshipList) { if (DIGITAL_SIGNATURE_CERTIFICATE_REL_TYPE.equals(signatureRelationship.getType())) { String certificateResourceName = signatureRelationship.getTarget().substring(1); certificateResourceNames.add(certificateResourceName); } } X509Certificate endEntityCertificate = null; for (String certificateResourceName : certificateResourceNames) { try { zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true); } catch (IOException e) { throw new KeySelectorException(e); } try { while (null != (zipEntry = zipInputStream.getNextZipEntry())) { if (certificateResourceName.equals(zipEntry.getName())) { break; } } } catch (IOException e) { throw new KeySelectorException(e); } if (null == zipEntry) { LOG.warn("certificate part not present: " + certificateResourceName); continue; } X509Certificate certificate; try { certificate = (X509Certificate) this.certificateFactory.generateCertificate(zipInputStream); } catch (CertificateException e) { throw new KeySelectorException(e); } LOG.debug("certificate subject: " + certificate.getSubjectX500Principal()); if (-1 != certificate.getBasicConstraints()) { LOG.debug("skipping CA certificate"); continue; } if (null != endEntityCertificate) { throw new KeySelectorException("two possible end entity certificates"); } endEntityCertificate = certificate; } if (null == endEntityCertificate) { throw new KeySelectorException("no key found"); } this.certificate = endEntityCertificate; return this; }
00
Code Sample 1: public void run() { date = DateUtil.addMonth(-1); List list = bo.getDao().getHibernateTemplate().find("from MailAffixPojo where upload_time <'" + date + "' and to_number(sized) >" + size); if (null != list && list.size() > 0) { try { FTPClient ftp = new FTPClient(); ftp.connect(config.getHostUrl(), config.getFtpPort()); ftp.login(config.getUname(), config.getUpass()); int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { ftp.disconnect(); return; } for (int i = 0; i < list.size(); i++) { MailAffixPojo pojo = (MailAffixPojo) list.get(i); ftp.changeWorkingDirectory(pojo.getUploadTime().substring(0, 7)); ftp.deleteFile(pojo.getAffixSaveName()); ftp.changeToParentDirectory(); bo.delete(MailAffixPojo.class, new Long(pojo.getId())); } } catch (Exception e) { e.printStackTrace(); } } } Code Sample 2: public void testRedirectWithCookie() throws Exception { String host = "localhost"; int port = this.localServer.getServicePort(); this.localServer.register("*", new BasicRedirectService(host, port)); DefaultHttpClient client = new DefaultHttpClient(); CookieStore cookieStore = new BasicCookieStore(); client.setCookieStore(cookieStore); BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookie.setDomain("localhost"); cookie.setPath("/"); cookieStore.addCookie(cookie); HttpContext context = new BasicHttpContext(); HttpGet httpget = new HttpGet("/oldlocation/"); HttpResponse response = client.execute(getServerHttp(), httpget, context); HttpEntity e = response.getEntity(); if (e != null) { e.consumeContent(); } HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri()); Header[] headers = reqWrapper.getHeaders(SM.COOKIE); assertEquals("There can only be one (cookie)", 1, headers.length); }
00
Code Sample 1: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } Code Sample 2: public static int writeFile(URL url, File outFilename) { InputStream input; try { input = url.openStream(); } catch (IOException e) { e.printStackTrace(); return 0; } FileOutputStream outputStream; try { outputStream = new FileOutputStream(outFilename); } catch (FileNotFoundException e) { e.printStackTrace(); return 0; } return writeFile(input, outputStream); }
00
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: private static HttpURLConnection getConnection(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestProperty("Accept", "application/zip;text/html"); return conn; }
00
Code Sample 1: private void outputSignedOpenDocument(byte[] signatureData) throws IOException { LOG.debug("output signed open document"); OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream(); if (null == signedOdfOutputStream) { throw new NullPointerException("signedOpenDocumentOutputStream is null"); } ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream); ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream()); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
11
Code Sample 1: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("�����ļ�ʧ�ܣ�Դ�ļ�" + srcFileName + "������!"); return false; } else if (!srcFile.isFile()) { System.out.println("�����ļ�ʧ�ܣ�" + srcFileName + "����һ���ļ�!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("Ŀ���ļ��Ѵ��ڣ�׼��ɾ��!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("ɾ��Ŀ���ļ�" + descFileName + "ʧ��!"); return false; } } else { System.out.println("�����ļ�ʧ�ܣ�Ŀ���ļ�" + descFileName + "�Ѵ���!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("Ŀ���ļ����ڵ�Ŀ¼�����ڣ�����Ŀ¼!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("����Ŀ���ļ����ڵ�Ŀ¼ʧ��!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("���Ƶ����ļ�" + srcFileName + "��" + descFileName + "�ɹ�!"); return true; } catch (Exception e) { System.out.println("�����ļ�ʧ�ܣ�" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } } Code Sample 2: public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); }
00
Code Sample 1: public static synchronized Map<String, Object> getURLContentMap(String wwwurl) throws IOException, URISyntaxException { Map<String, Object> resultMap = new HashMap<String, Object>(); URI uri = new URI(wwwurl); URL url = new URL(uri.toASCIIString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10 * 1000); HttpURLConnection.setFollowRedirects(true); try { conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.17) Gecko/20110421 Red Hat/3.6-1.el5_6 Firefox/3.6.17"); for (String key : conn.getHeaderFields().keySet()) { List<String> headerInfo = conn.getHeaderFields().get(key); if (headerInfo.size() > 0) { resultMap.put(key, headerInfo.get(0)); } } String contentType = conn.getContentType(); if (!(contentType == null || contentType.toLowerCase().contains("text") || contentType.toLowerCase().contains("html"))) { return resultMap; } ByteArrayOutputStream outstream = new ByteArrayOutputStream(); InputStream instream = conn.getInputStream(); synchronized (instream) { int readSize = 0; int totalSize = 0; byte[] contentByte = null; byte[] buffer = new byte[1024]; while ((readSize = instream.read(buffer)) > 0) { outstream.write(buffer, 0, readSize); totalSize += readSize; if (totalSize >= MAX_CONTENT_SIZE) { contentByte = ("[FAILD] content size is larger than " + MAX_CONTENT_SIZE + " byte.").getBytes(); } } if (contentByte == null) { contentByte = outstream.toByteArray(); } instream.close(); outstream.close(); resultMap.put(contentByteField, contentByte); } } finally { } return resultMap; } Code Sample 2: static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; Savepoint sp = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=1"; st.executeUpdate(sql); sp = conn.setSavepoint(); sql = "update user set money=money-10 where id=3"; st.executeUpdate(sql); sql = "select money from user where id=2"; rs = st.executeQuery(sql); float money = 0.0f; if (rs.next()) { money = rs.getFloat("money"); } if (money > 300) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=2"; st.executeUpdate(sql); conn.commit(); } catch (RuntimeException e) { if (conn != null && sp != null) { conn.rollback(sp); conn.commit(); } throw e; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } }
11
Code Sample 1: public static void copier(final File pFichierSource, final File pFichierDest) { FileChannel vIn = null; FileChannel vOut = null; try { vIn = new FileInputStream(pFichierSource).getChannel(); vOut = new FileOutputStream(pFichierDest).getChannel(); vIn.transferTo(0, vIn.size(), vOut); } catch (Exception e) { e.printStackTrace(); } finally { if (vIn != null) { try { vIn.close(); } catch (IOException e) { } } if (vOut != null) { try { vOut.close(); } catch (IOException e) { } } } } Code Sample 2: public static byte[] readResource(Class owningClass, String resourceName) { final URL url = getResourceUrl(owningClass, resourceName); if (null == url) { throw new MissingResourceException(owningClass.toString() + " key '" + resourceName + "'", owningClass.toString(), resourceName); } LOG.info("Loading resource '" + url.toExternalForm() + "' " + "from " + owningClass); final InputStream inputStream; try { inputStream = url.openStream(); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new RuntimeException("Should not happpen", e); } return outputStream.toByteArray(); }
00
Code Sample 1: public static final void main(String[] args) throws FileNotFoundException, IOException { ArrayList<String[]> result = new ArrayList<String[]>(); IStream is = new StreamImpl(); IOUtils.copy(new FileInputStream("H:\\7-项目预算表.xlsx"), is.getOutputStream()); int count = loadExcel(result, is, 0, 0, -1, 16, 1); System.out.println(count); for (String[] rs : result) { for (String r : rs) { System.out.print(r + "\t"); } System.out.println(); } } Code Sample 2: private void menuOpenURL() { animate = false; resetScaleCombos(); InputDialog dialog = new InputDialog(shell, "Open URL Dialog", "Enter URL of the image", "http://", new IInputValidator() { @Override public String isValid(String newText) { if (newText.startsWith("http://") || newText.startsWith("https://") || newText.startsWith("ftp://") || newText.startsWith("file://")) return newText; return null; } }); if (dialog.open() == SWT.CANCEL) return; String urlName = dialog.getValue(); Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT); shell.setCursor(waitCursor); imageCanvas.setCursor(waitCursor); try { URL url = new URL(urlName); InputStream stream = url.openStream(); loader = new ImageLoader(); if (incremental) { loader.addImageLoaderListener(new ImageLoaderListener() { public void imageDataLoaded(ImageLoaderEvent event) { incrementalDataLoaded(event); } }); incrementalThreadStart(); } imageDataArray = loader.load(stream); stream.close(); if (imageDataArray.length > 0) { currentName = urlName; fileName = null; previousButton.setEnabled(imageDataArray.length > 1); nextButton.setEnabled(imageDataArray.length > 1); animateButton.setEnabled(imageDataArray.length > 1 && loader.logicalScreenWidth > 0 && loader.logicalScreenHeight > 0); imageDataIndex = 0; displayImage(imageDataArray[imageDataIndex]); resetScrollBars(); } } catch (Exception e) { showErrorDialog("Loading", urlName, e); } finally { shell.setCursor(null); imageCanvas.setCursor(crossCursor); waitCursor.dispose(); } }
00
Code Sample 1: private String getStoreName() { try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(protectionDomain.getBytes()); final byte[] bs = digest.digest(); final StringBuffer sb = new StringBuffer(bs.length * 2); for (int i = 0; i < bs.length; i++) { final String s = Integer.toHexString(bs[i] & 0xff); if (s.length() < 2) sb.append('0'); sb.append(s); } return sb.toString(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException("Can't save credentials: digest method MD5 unavailable."); } } Code Sample 2: private static InputStream connect(String url) throws IOException { int status = 0; String currentlyActiveServer = getCurrentlyActiveServer(); try { long begin = System.currentTimeMillis(); HttpURLConnection httpConnection = (HttpURLConnection) new URL(currentlyActiveServer + url).openConnection(); httpConnection.setConnectTimeout(connectTimeOut); httpConnection.setReadTimeout(readTimeOut); httpConnection.setRequestProperty("User-Agent", USER_AGENT); InputStream in = httpConnection.getInputStream(); status = httpConnection.getResponseCode(); if (status == 200) { long elapsedTime = System.currentTimeMillis() - begin; averageConnectTime = (averageConnectTime * (averageSampleSize - 1) + elapsedTime) / averageSampleSize; if (geoNamesServerFailover != null && averageConnectTime > 5000 && !currentlyActiveServer.equals(geoNamesServerFailover)) { timeOfLastFailureMainServer = System.currentTimeMillis(); } return in; } } catch (IOException e) { return tryFailoverServer(url, currentlyActiveServer, 0, e); } IOException ioException = new IOException("status code " + status + " for " + url); return tryFailoverServer(url, currentlyActiveServer, status, ioException); }
11
Code Sample 1: public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } }
11
Code Sample 1: public static String hash(String text) throws Exception { StringBuffer hexString; MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(text.getBytes()); byte[] digest = mdAlgorithm.digest(); hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { text = Integer.toHexString(0xFF & digest[i]); if (text.length() < 2) { text = "0" + text; } hexString.append(text); } return hexString.toString(); } Code Sample 2: public static String getHash(String password, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException { logger.debug("Entering getHash with password = " + password + "\n and salt = " + salt); MessageDigest digest = MessageDigest.getInstance("SHA-512"); digest.reset(); digest.update(salt.getBytes()); byte[] input = digest.digest(password.getBytes("UTF-8")); String hashResult = String.valueOf(input); logger.debug("Exiting getHash with hasResult of " + hashResult); return hashResult; }
00
Code Sample 1: public void moveRuleUp(String language, String tag, int row) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); int max = findMaxRank(stmt, language, tag); if ((row < 2) || (row > max)) throw new IllegalArgumentException("Row number (" + row + ") was not between 2 and " + max); stmt.executeUpdate("update LanguageMorphologies set Rank = -1 " + "where Rank = " + row + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + row + "where Rank = " + (row - 1) + " and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); stmt.executeUpdate("update LanguageMorphologies set Rank = " + (row - 1) + "where Rank = -1 and MorphologyTag = '" + tag + "' and " + " LanguageName = '" + language + "'"); 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: private String[] sendRequest(String url, String requestString) throws ClickatellException, IOException { String response = null; MessageFormat responseFormat = new MessageFormat("{0}: {1}"); List idList = new LinkedList(); try { log_.debug("sendRequest: posting : " + requestString + " to " + url); URL requestURL = new URL(url); URLConnection urlConn = requestURL.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter pw = new PrintWriter(urlConn.getOutputStream()); pw.print(requestString); pw.flush(); pw.close(); InputStream is = urlConn.getInputStream(); BufferedReader responseReader = new BufferedReader(new InputStreamReader(is)); while ((response = responseReader.readLine()) != null) { Object[] objs = responseFormat.parse(response); if ("ERR".equalsIgnoreCase((String) objs[0])) { MessageFormat errorFormat = new MessageFormat("{0}: {1}, {2}"); Object[] errObjs = errorFormat.parse(response); String errorNo = (String) errObjs[1]; String description = (String) errObjs[2]; throw new ClickatellException("Clickatell error. Error " + errorNo + ", " + description, Integer.parseInt(errorNo)); } log_.debug("sendRequest: Got ID : " + ((String) objs[1])); idList.add(objs[1]); } responseReader.close(); } catch (ParseException ex) { throw new ClickatellException("Unexpected response from Clickatell. : " + response, ClickatellException.ERROR_UNKNOWN); } return (String[]) idList.toArray(new String[idList.size()]); }
00
Code Sample 1: byte[] calculateDigest(String value) { try { MessageDigest mg = MessageDigest.getInstance("SHA1"); mg.update(value.getBytes()); return mg.digest(); } catch (Exception e) { throw Bark.unchecker(e); } } Code Sample 2: private static void downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
00
Code Sample 1: public void readDirectoryFrom(String urlString) throws Exception { URL url = new URL(urlString + DIR_INFO_FIENAME); PushbackInputStream in = new PushbackInputStream(new BufferedInputStream(url.openStream())); readDataFrom(in); TextToken t = TextToken.nextToken(in); while (t != null && t.isString()) { DirectoryInfoModel dir = addDirectory(new DirectoryInfo(t.getString())); dir.setUrl(urlString + t.getString() + '/'); t = TextToken.nextToken(in); } in.close(); } Code Sample 2: public String parse() { try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains("</center>")) flag1 = true; if (flag1 && line.contains("<br><center>")) break; if (flag1) { mText.append(line); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mText.toString(); }
11
Code Sample 1: public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); } Code Sample 2: public static void copyFile(String src, String target) throws IOException { FileChannel ic = new FileInputStream(src).getChannel(); FileChannel oc = new FileOutputStream(target).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
11
Code Sample 1: static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); } Code Sample 2: public void reqservmodif(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { try { System.err.println(req.getSession().getServletContext().getRealPath("WEB-INF/syncWork")); File tempFile = File.createTempFile("localmodif-", ".medoorequest"); OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); InputStream fis = new FileInputStream(tempFile); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); tempFile.delete(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } catch (ImogSerializationException ex) { logger.error(ex.getMessage()); } }
11
Code Sample 1: public void downloadFile(OutputStream os, int fileId) throws IOException, SQLException { Connection conn = null; try { conn = ds.getConnection(); Guard.checkConnectionNotNull(conn); PreparedStatement ps = conn.prepareStatement("select * from FILE_BODIES where file_id=?"); ps.setInt(1, fileId); ResultSet rs = ps.executeQuery(); if (!rs.next()) { throw new FileNotFoundException("File with id=" + fileId + " not found!"); } Blob blob = rs.getBlob("data"); InputStream is = blob.getBinaryStream(); IOUtils.copyLarge(is, os); } finally { JdbcDaoHelper.safeClose(conn, log); } } Code Sample 2: private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); }
00
Code Sample 1: protected IRunnableWithProgress getProjectCreationRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int remainingWorkUnits = 10; monitor.beginTask("New Modulo Project Creation", remainingWorkUnits); IWorkspace ws = ResourcesPlugin.getWorkspace(); newProject = fMainPage.getProjectHandle(); IProjectDescription description = ws.newProjectDescription(newProject.getName()); String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID }; description.setNatureIds(natures); ICommand command = description.newCommand(); command.setBuilderName(JavaCore.BUILDER_ID); ICommand[] commands = { command }; description.setBuildSpec(commands); IJavaProject jproject = JavaCore.create(newProject); ModuloProject modProj = new ModuloProject(); modProj.setJavaProject(jproject); try { newProject.create(description, new SubProgressMonitor(monitor, 1)); newProject.open(new SubProgressMonitor(monitor, 1)); IFolder srcFolder = newProject.getFolder("src"); IFolder javaFolder = srcFolder.getFolder("java"); IFolder buildFolder = newProject.getFolder("build"); IFolder classesFolder = buildFolder.getFolder("classes"); modProj.createFolder(srcFolder); modProj.createFolder(javaFolder); modProj.createFolder(buildFolder); modProj.createFolder(classesFolder); IPath buildPath = newProject.getFolder("build/classes").getFullPath(); jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) }; jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); ModuleDefinition definition = new ModuleDefinition(); definition.setId(fModuloPage.getPackageName()); definition.setVersion(new VersionNumber(1, 0, 0)); definition.setMetaName(fModuloPage.getModuleName()); definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module."); definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName()); if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName()); if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName()); modProj.setDefinition(definition); modProj.createPackage(); modProj.createModuleXML(); modProj.createMainClass(); if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass(); if (fModuloPage.isStatSelectioned()) modProj.createStatClass(); modProj.createModuleProperties(); modProj.createMessagesProperties(); IFolder binFolder = newProject.getFolder("bin"); binFolder.delete(true, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { e.printStackTrace(); } finally { monitor.done(); } } }; } Code Sample 2: private void FindAvail() throws ParserConfigurationException, SQLException { Savepoint sp1; String availsql = "select xmlquery('$c/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]' "; availsql += "passing hp_administrator.availability.AVAIL as \"c\") "; availsql += " from hp_administrator.availability "; availsql += " where date = '" + booking_details.getDate() + "' and train_no like '" + booking_details.getTrain_no() + "'"; System.out.println(availsql); String availxml = ""; String seatxml = ""; String navailstr = ""; String nspavailstr = ""; String currentcoachstr = ""; String srctillstr = "", srcavailstr = "", srcmaxstr = ""; Integer srctill, srcavail, srcmax; Integer navailcoach; Integer nspavailcoach, seatstart, seatcnt, alloccnt; String routesrcstr = "", routedeststr = ""; PreparedStatement pstseat; Statement stavail, stavailupd, stseatupd, stseat; ResultSet rsavail, rsseat; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document docavail, docseattmp, docseatfin, docseat; Element rootavail, rootseat; Node n; try { stavail = conn.createStatement(); sp1 = conn.setSavepoint(); rsavail = stavail.executeQuery(availsql); if (rsavail.next()) availxml = rsavail.getString(1); System.out.println(availxml); StringBuffer StringBuffer1 = new StringBuffer(availxml); ByteArrayInputStream Bis1 = new ByteArrayInputStream(StringBuffer1.toString().getBytes("UTF-16")); docavail = db.parse(Bis1); StringWriter sw; OutputFormat formatter; formatter = new OutputFormat(); formatter.setPreserveSpace(true); formatter.setEncoding("UTF-8"); formatter.setOmitXMLDeclaration(true); XMLSerializer serializer; rootavail = docavail.getDocumentElement(); NodeList coachlist = rootavail.getElementsByTagName("coach"); Element currentcoach, minseat; Element routesrc, routedest, nextstn, dest, user, agent; NodeList nl, nl1; number_of_tickets_rem = booking_details.getNoOfPersons(); int tickpos = 0; firsttime = true; boolean enterloop; for (int i = 0; i < coachlist.getLength(); i++) { currentcoach = (Element) coachlist.item(i); currentcoachstr = currentcoach.getAttribute("number"); String coachmaxstr = currentcoach.getAttribute("coachmax"); Integer coachmax = Integer.parseInt(coachmaxstr.trim()); routesrc = (Element) currentcoach.getFirstChild(); routedest = (Element) currentcoach.getLastChild(); routedest = (Element) routedest.getPreviousSibling().getPreviousSibling().getPreviousSibling(); routesrcstr = routesrc.getNodeName(); routedeststr = routedest.getNodeName(); String seatsql = "select xmlquery('$c/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]' "; seatsql += " passing hp_administrator.book_tickets.SEAT as \"c\") from hp_administrator.book_tickets "; seatsql += " where date = '" + booking_details.getDate() + "' and train_no like '" + booking_details.getTrain_no() + "' "; System.out.println("route :" + sourcenws); System.out.println("route :" + destnnws); System.out.println("route src :" + routesrcstr); System.out.println("route dest :" + routedeststr); System.out.println(seatsql); stseat = conn.createStatement(); rsseat = stseat.executeQuery(seatsql); if (rsseat.next()) seatxml = rsseat.getString(1); StringBuffer StringBuffer2 = new StringBuffer(seatxml); ByteArrayInputStream Bis2 = new ByteArrayInputStream(StringBuffer2.toString().getBytes("UTF-16")); docseat = db.parse(Bis2); rootseat = docseat.getDocumentElement(); enterloop = false; if (routesrcstr.equals(sourcenws) && routedeststr.equals(destnnws)) { System.out.println("case 1"); navailstr = routesrc.getTextContent(); navailcoach = Integer.parseInt(navailstr.trim()); if (useragent) nspavailstr = routesrc.getAttribute("agent"); else nspavailstr = routesrc.getAttribute("user"); nspavailcoach = Integer.parseInt(nspavailstr.trim()); srctillstr = routesrc.getAttribute(sourcenws + "TILL"); srctill = Integer.parseInt(srctillstr.trim()); srcmaxstr = routesrc.getAttribute(sourcenws); srcmax = Integer.parseInt(srcmaxstr.trim()); srcavailstr = routesrc.getTextContent(); srcavail = Integer.parseInt(srcavailstr.trim()); seatstart = coachmax - srctill + 1; seatcnt = srcmax; alloccnt = srcmax - srcavail; seatstart += alloccnt; seatcnt -= alloccnt; Element seat, stn; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); if (booking_details.getNoOfPersons() <= navailcoach && booking_details.getNoOfPersons() <= nspavailcoach) { coach.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); seatno.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; navailcoach -= booking_details.getNoOfPersons(); nspavailcoach -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); int updvar = stavailupd.executeUpdate(availupdstr); if (updvar > 0) System.out.println("upda avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); updvar = stseatupd.executeUpdate(seatupdstr); if (updvar > 0) System.out.println("upda seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); updvar = stavailupd.executeUpdate(availupdstr); if (updvar > 0) System.out.println("upda" + sp + " success"); break; } while (navailcoach > 0 && nspavailcoach > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; navailcoach--; nspavailcoach--; while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + sp + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } else if (routesrcstr.equals(sourcenws) && !routedeststr.equals(destnnws)) { System.out.println("case 2"); String excesssrcstr = routesrc.getTextContent(); System.out.println(excesssrcstr); Integer excesssrc = Integer.parseInt(excesssrcstr.trim()); NodeList nl2 = currentcoach.getElementsByTagName(destnnws); Element e2 = (Element) nl2.item(0); String desttillstr = e2.getAttribute(destnnws + "TILL"); System.out.println(desttillstr); Integer desttillcnt = Integer.parseInt(desttillstr.trim()); srcmaxstr = routesrc.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); String spexcesssrcstr = "", spdesttillstr = ""; if (useragent) { spexcesssrcstr = routesrc.getAttribute("agent"); spdesttillstr = e2.getAttribute("agenttill"); } else { spexcesssrcstr = routesrc.getAttribute("user"); spdesttillstr = e2.getAttribute("usertill"); } System.out.println(spdesttillstr); System.out.println(spexcesssrcstr); Integer spdesttillcnt = Integer.parseInt(spdesttillstr.trim()); Integer spexcesssrc = Integer.parseInt(spexcesssrcstr.trim()); Element seat, stn; if (booking_details.getNoOfPersons() <= desttillcnt && booking_details.getNoOfPersons() <= spdesttillcnt) { seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; desttillcnt -= booking_details.getNoOfPersons(); spdesttillcnt -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt > 0 && booking_details.getNoOfPersons() <= spdesttillcnt + spexcesssrc) { int diff = 0; if (booking_details.getNoOfPersons() > spdesttillcnt) diff = booking_details.getNoOfPersons() - spdesttillcnt; tickpos = 0; boolean initflg = true; seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } if (spdesttillcnt != 0) { desttillcnt--; spdesttillcnt--; } System.out.println("desttillcnt=" + desttillcnt + " spdes = " + desttillcnt + "initflg =" + initflg); if (spdesttillcnt == 0 && initflg == true) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; initflg = false; seat = (Element) seat.getParentNode().getFirstChild(); } } excesssrc -= diff; spexcesssrc -= diff; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt == 0 && booking_details.getNoOfPersons() <= spexcesssrc) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; tickpos = 0; boolean initflg = true; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } System.out.println("desttillcnt=" + desttillcnt + " spdes = " + desttillcnt + "initflg =" + initflg); } excesssrc -= booking_details.getNoOfPersons(); spexcesssrc -= booking_details.getNoOfPersons(); ; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); int upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update avail success"); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(seatupdstr); stseatupd = conn.createStatement(); upst = stseatupd.executeUpdate(seatupdstr); if (upst > 0) System.out.println("update seat success"); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupd); stavailupd = conn.createStatement(); upst = stavailupd.executeUpdate(availupd); if (upst > 0) System.out.println("update " + sp + " success"); break; } NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); seatstart = 1; String sp = ""; if (useragent) sp = "agent"; else sp = "user"; while (spexcesssrc + spdesttillcnt > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; if (spdesttillcnt > 0) { seatstart = coachmax - desttillcnt + 1; desttillcnt--; spdesttillcnt--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } else if (spdesttillcnt == 0) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; excesssrc--; spexcesssrc--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } else if (!routesrcstr.equals(sourcenws) && routedeststr.equals(destnnws)) { System.out.println("case 3"); NodeList nl2 = currentcoach.getElementsByTagName(sourcenws); Element e2 = (Element) nl2.item(0); navailstr = e2.getTextContent(); System.out.println(navailstr); navailcoach = Integer.parseInt(navailstr.trim()); if (useragent) nspavailstr = e2.getAttribute("agent"); else nspavailstr = e2.getAttribute("user"); System.out.println(nspavailstr); nspavailcoach = Integer.parseInt(nspavailstr.trim()); srctillstr = e2.getAttribute(sourcenws + "TILL"); System.out.println(srctillstr); srctill = Integer.parseInt(srctillstr.trim()); srcmaxstr = e2.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); seatstart = coachmax - srctill + 1; seatcnt = srcmax; alloccnt = srcmax - navailcoach; seatstart += alloccnt; seatcnt -= alloccnt; Element seat, stn; NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); if (booking_details.getNoOfPersons() <= navailcoach && booking_details.getNoOfPersons() <= nspavailcoach) { coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; navailcoach -= booking_details.getNoOfPersons(); nspavailcoach -= booking_details.getNoOfPersons(); String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); break; } while (navailcoach > 0 && nspavailcoach > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; navailcoach--; nspavailcoach--; while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } String availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + navailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupdstr = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupdstr += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + nspavailcoach + "\""; availupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println(availupdstr); stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupdstr); } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; System.out.println("!@#------->" + seatupdstr); stseatupd = conn.createStatement(); } } else if (!routesrcstr.equals(sourcenws) && !routedeststr.equals(destnnws)) { System.out.println("case 4"); srcmaxstr = routesrc.getAttribute(sourcenws); System.out.println(srcmaxstr); srcmax = Integer.parseInt(srcmaxstr.trim()); Element seat, stn; NodeList nl2 = currentcoach.getElementsByTagName(sourcenws); Element e2 = (Element) nl2.item(0); navailstr = e2.getTextContent(); Integer excesssrc = Integer.parseInt(navailstr.trim()); nl2 = currentcoach.getElementsByTagName(destnnws); e2 = (Element) nl2.item(0); navailstr = e2.getAttribute(destnnws + "TILL"); Integer desttillcnt = Integer.parseInt(navailstr.trim()); String spexcesssrcstr = "", spdesttillstr = ""; if (useragent) { spexcesssrcstr = routesrc.getAttribute("agent"); spdesttillstr = e2.getAttribute("agenttill"); } else { spexcesssrcstr = routesrc.getAttribute("user"); spdesttillstr = e2.getAttribute("usertill"); } Integer spdesttillcnt = Integer.parseInt(spdesttillstr.trim()); Integer spexcesssrc = Integer.parseInt(spexcesssrcstr.trim()); NodeList nl3 = rootseat.getElementsByTagName("seat"); seat = (Element) nl3.item(0); boolean initflg = true; if (booking_details.getNoOfPersons() <= spdesttillcnt) { seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } number_of_tickets_rem = 0; desttillcnt -= booking_details.getNoOfPersons(); spdesttillcnt -= booking_details.getNoOfPersons(); if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } else if (booking_details.getNoOfPersons() > spdesttillcnt && spdesttillcnt > 0 && booking_details.getNoOfPersons() <= spdesttillcnt + spexcesssrc) { int diff = 0; if (booking_details.getNoOfPersons() > spdesttillcnt) diff = booking_details.getNoOfPersons() - spdesttillcnt; seatstart = coachmax - desttillcnt + 1; seatcnt = desttillcnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } if (spdesttillcnt != 0) { desttillcnt--; spdesttillcnt--; } if (spdesttillcnt == 0 && initflg == true) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; initflg = false; } } excesssrc -= diff; spexcesssrc -= diff; number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } else if (spdesttillcnt == 0 && booking_details.getNoOfPersons() <= spexcesssrc) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; coach.clear(); seatno.clear(); booking_details.coachlist.clear(); booking_details.seatlist.clear(); for (tickpos = 0; tickpos < booking_details.getNoOfPersons(); tickpos++) { coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } seatstart++; System.out.println(seat.getFirstChild().getTextContent().trim()); seatno.add(seat.getFirstChild().getTextContent().trim()); booking_details.seatlist.add(seat.getFirstChild().getTextContent().trim()); nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } } excesssrc -= booking_details.getNoOfPersons(); spexcesssrc -= booking_details.getNoOfPersons(); number_of_tickets_rem = 0; if (!firsttime) conn.rollback(sp1); String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); String sp = ""; if (useragent) sp = "agent"; else sp = "user"; availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); break; } seatstart = 1; String sp = ""; if (useragent) sp = "agent"; else sp = "user"; while (spexcesssrc + spdesttillcnt > 0 && number_of_tickets_rem > 0) { if (firsttime) { sp1 = conn.setSavepoint(); firsttime = false; } enterloop = true; if (spdesttillcnt > 0) { seatstart = coachmax - desttillcnt + 1; desttillcnt--; spdesttillcnt--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + destnnws + "TILL" + " with \"" + desttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do replace value of "; availupd += "$new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + destnnws + "/@" + sp + "till" + " with \"" + spdesttillcnt + "\" "; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } else if (spdesttillcnt == 0) { alloccnt = srcmax - excesssrc; seatstart = 1 + alloccnt; excesssrc--; spexcesssrc--; String availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + "/@" + sp + " with \"" + excesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); availupd = "update hp_administrator.availability set AVAIL = xmlquery( 'transform copy $new := $AVAIL modify do "; availupd += " replace value of $new/coach_status/class[@name=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"]/" + sourcenws + " with \"" + spexcesssrc + "\""; availupd += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stavailupd = conn.createStatement(); stavailupd.executeUpdate(availupd); } while (Integer.parseInt(seat.getFirstChild().getTextContent().trim()) < seatstart) { seat = (Element) seat.getNextSibling(); } nl3 = seat.getElementsByTagName(sourcenws); stn = (Element) nl3.item(0); while (!stn.getNodeName().equals(destnnws)) { stn.setTextContent("0"); stn = (Element) stn.getNextSibling(); } coach.add(currentcoachstr); booking_details.coachlist.add(currentcoachstr); tickpos++; number_of_tickets_rem--; } if (enterloop) { sw = new StringWriter(); serializer = new XMLSerializer(sw, formatter); serializer.serialize(docseat); String seatupdstr = "update hp_administrator.book_tickets set SEAT = xmlquery( 'transform copy $new := $SEAT "; seatupdstr += " modify do replace $new/status/class[@type=\"" + booking_details.getTclass() + "\"]/coach[@number=\"" + currentcoachstr + "\"] with " + sw.toString(); seatupdstr += " return $new') where train_no like '" + booking_details.getTrain_no() + "' and date = '" + booking_details.getDate() + "' "; stseatupd = conn.createStatement(); stseatupd.executeUpdate(seatupdstr); } } } availfin = true; } catch (SQLException e) { conn.rollback(); e.printStackTrace(); } catch (UnsupportedEncodingException e) { conn.rollback(); e.printStackTrace(); } catch (SAXException e) { conn.rollback(); e.printStackTrace(); } catch (IOException e) { conn.rollback(); e.printStackTrace(); } }
11
Code Sample 1: public void copyFile(String source, String destination, String description, boolean recursive) throws Exception { File sourceFile = new File(source); File destinationFile = new File(destination); if (!sourceFile.exists()) { throw new Exception("source file (" + source + ") does not exist!"); } if (!sourceFile.isFile()) { throw new Exception("source file (" + source + ") is not a file!"); } if (!sourceFile.canRead()) { throw new Exception("source file (" + source + ") is not readable!"); } if (destinationFile.exists()) { m_out.print(" - " + destination + " exists, removing... "); if (destinationFile.delete()) { m_out.println("REMOVED"); } else { m_out.println("FAILED"); throw new Exception("unable to delete existing file: " + sourceFile); } } m_out.print(" - copying " + source + " to " + destination + "... "); if (!destinationFile.getParentFile().exists()) { if (!destinationFile.getParentFile().mkdirs()) { throw new Exception("unable to create directory: " + destinationFile.getParent()); } } if (!destinationFile.createNewFile()) { throw new Exception("unable to create file: " + destinationFile); } FileChannel from = null; FileChannel to = null; try { from = new FileInputStream(sourceFile).getChannel(); to = new FileOutputStream(destinationFile).getChannel(); to.transferFrom(from, 0, from.size()); } catch (FileNotFoundException e) { throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e); } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } m_out.println("DONE"); } Code Sample 2: public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
11
Code Sample 1: private void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
00
Code Sample 1: public static String getTextFromUrl(final String url) throws IOException { final String lineSeparator = System.getProperty("line.separator"); InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { final StringBuilder result = new StringBuilder(); inputStreamReader = new InputStreamReader(new URL(url).openStream()); bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { result.append(line).append(lineSeparator); } return result.toString(); } finally { InputOutputUtil.close(bufferedReader, inputStreamReader); } } Code Sample 2: private static void readServicesFromUrl(Collection<String> list, URL url) throws IOException { InputStream in = url.openStream(); try { if (in == null) return; BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int idx = line.indexOf('#'); if (idx != -1) line = line.substring(0, idx); line = line.trim(); if (line.length() == 0) continue; list.add(line); } } finally { try { if (in != null) in.close(); } catch (Throwable ignore) { } } }
00
Code Sample 1: public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } } Code Sample 2: public Object[] bubblesort(Object[] tosort) { Boolean sorting; int upperlimit = tosort.length - 1; do { sorting = false; for (int s0 = 0; s0 < upperlimit; s0++) { if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) < 0) { } else if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) == 0) { Object[] tosortnew = new Object[tosort.length - 1]; for (int tmp = 0; tmp < s0; tmp++) { tosortnew[tmp] = tosort[tmp]; } for (int tmp = s0; tmp < tosortnew.length; tmp++) { tosortnew[tmp] = tosort[tmp + 1]; } tosort = tosortnew; upperlimit = upperlimit - 1; s0 = s0 - 1; } else if (tosort[s0].toString().compareTo(tosort[s0 + 1].toString()) > 0) { String swap = (String) tosort[s0]; tosort[s0] = tosort[s0 + 1]; tosort[s0 + 1] = swap; sorting = true; } } upperlimit = upperlimit - 1; } while (sorting); return tosort; }
11
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: public void write(URL exportUrl, OutputStream output) throws Exception { if (exportUrl == null || output == null) { throw new RuntimeException("null passed in for required parameters"); } MediaContent mc = new MediaContent(); mc.setUri(exportUrl.toString()); MediaSource ms = service.getMedia(mc); InputStream input = ms.getInputStream(); IOUtils.copy(input, output); }
11
Code Sample 1: protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } } Code Sample 2: public static File copyFile(File srcFile, File destFolder, FileCopyListener copyListener) { File dest = new File(destFolder, srcFile.getName()); try { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; long totalSize = srcFile.length(); boolean canceled = false; if (copyListener == null) { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } } else { while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); if (!copyListener.updateCheck(readLength, totalSize)) { canceled = true; break; } } } in.close(); out.close(); if (canceled) { dest.delete(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
11
Code Sample 1: @Test public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer, "UTF8"); fail(); } catch (NullPointerException ex) { } } Code Sample 2: @Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
00
Code Sample 1: public static void importDocumentLines(Connection conn, String originDocumentID, String destinationDocumentID) throws SQLException { boolean defaultAutoCommit = conn.getAutoCommit(); String sqlQuery = "select ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice from tbl_DocumentItem where DocumentID=?"; String sqlInsert = "insert into tbl_DocumentItem (ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice,DocumentID) values (?,?,?,?,?,?,?,?,?)"; PreparedStatement pstmt1 = null; PreparedStatement pstmt2 = null; try { pstmt1 = conn.prepareStatement(sqlQuery); pstmt2 = conn.prepareStatement(sqlInsert); conn.setAutoCommit(false); pstmt1.setString(1, originDocumentID); ResultSet rs = pstmt1.executeQuery(); while (rs.next()) { pstmt2.setInt(1, rs.getInt(1)); pstmt2.setString(2, rs.getString(2)); pstmt2.setDouble(3, rs.getDouble(3)); pstmt2.setDouble(4, rs.getDouble(4)); pstmt2.setDouble(5, rs.getDouble(5)); pstmt2.setDouble(6, rs.getDouble(6)); pstmt2.setDouble(7, rs.getDouble(7)); pstmt2.setDouble(8, rs.getDouble(8)); pstmt2.setString(9, destinationDocumentID); pstmt2.executeUpdate(); } rs.close(); conn.commit(); } catch (SQLException ex) { conn.rollback(); } finally { conn.setAutoCommit(defaultAutoCommit); if (pstmt1 != null) pstmt1.close(); if (pstmt2 != null) pstmt2.close(); } } Code Sample 2: private static String getVisitorId(String guid, String account, String userAgent, Cookie cookie) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (cookie != null && cookie.getValue() != null) { return cookie.getValue(); } String message; if (!isEmpty(guid)) { message = guid + account; } else { message = userAgent + getRandomNumber() + UUID.randomUUID().toString(); } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(message.getBytes("UTF-8"), 0, message.length()); byte[] sum = m.digest(); BigInteger messageAsNumber = new BigInteger(1, sum); String md5String = messageAsNumber.toString(16); while (md5String.length() < 32) { md5String = "0" + md5String; } return "0x" + md5String.substring(0, 16); }
00
Code Sample 1: private static BreakIterator createBreakInstance(Locale where, int kind, String rulesName, String dictionaryName) { ResourceBundle bundle = ICULocaleData.getResourceBundle("BreakIteratorRules", where); String[] classNames = bundle.getStringArray("BreakIteratorClasses"); String rules = bundle.getString(rulesName); if (classNames[kind].equals("RuleBasedBreakIterator")) { return new RuleBasedBreakIterator(rules); } else if (classNames[kind].equals("DictionaryBasedBreakIterator")) { try { Object t = bundle.getObject(dictionaryName); URL url = (URL) t; InputStream dictionary = url.openStream(); return new DictionaryBasedBreakIterator(rules, dictionary); } catch (IOException e) { } catch (MissingResourceException e) { } return new RuleBasedBreakIterator(rules); } else { throw new IllegalArgumentException("Invalid break iterator class \"" + classNames[kind] + "\""); } } Code Sample 2: protected Properties loadFile(String fileName) { Properties prop = new Properties(); try { String packageName = getClass().getName(); packageName = packageName.substring(0, packageName.lastIndexOf(".")); String src = "src"; if (mavenBuild) { src = src + File.separator + "test" + File.separator + "resources"; } packageName = src + File.separator + packageName.replace('.', File.separatorChar); packageName += File.separator; packageName += fileName; URL url0 = new File(packageName).toURI().toURL(); final InputStream input = url0.openStream(); prop.load(input); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return prop; }
00
Code Sample 1: private ProgramYek getYek(String keyFilename) { File f = new File(keyFilename); InputStream is = null; try { is = new FileInputStream(f); } catch (java.io.FileNotFoundException ee) { } catch (Exception e) { System.out.println("** Exception reading key: " + e); } if (is == null) { try { URL url = ChiselResources.getResourceByName(ProgramYek.getVidSys(), ChiselResources.LOADFROMCLASSPATH); if (url == null) { } else { is = url.openStream(); } } catch (Exception e) { System.out.println("** Exception reading key: " + e); } } ProgramYek y = null; if (is != null) { try { y = ProgramYek.read(is); } catch (Exception e) { System.out.println("** Exception reading key: " + e); } } else { File chk = new File(checkFilename); if (chk.exists()) { System.out.println("This is the evaluation version of " + appname); y = new ProgramYek(appname, "Evaluation", "", 15); ProgramYek.serialize(y, keyFilename); } } return y; } Code Sample 2: @Test public void testCascadeTraining() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("parity8.train"), new FileOutputStream(temp)); Fann fann = new FannShortcut(8, 1); Trainer trainer = new Trainer(fann); float desiredError = .00f; float mse = trainer.cascadeTrain(temp.getPath(), 30, 1, desiredError); assertTrue("" + mse, mse <= desiredError); }
11
Code Sample 1: public void copiarMidias(final File vidDir, final File imgDir) { for (int i = 0; i < getMidias().size(); i++) { try { FileChannel src = new FileInputStream(getMidias().get(i).getUrl().trim()).getChannel(); FileChannel dest; if (getMidias().get(i).getTipo().equals("video")) { FileChannel vidDest = new FileOutputStream(vidDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = vidDest; } else { FileChannel midDest = new FileOutputStream(imgDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = midDest; } dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (Exception e) { System.err.print(e.getMessage()); e.printStackTrace(); } } } Code Sample 2: public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; }
00
Code Sample 1: public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { } } } return url; } 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: private boolean copyToFile(String folder, String fileName) throws StorageException { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(folder + "/" + fileName); if (in == null) { return false; } FileOutputStream out = null; try { out = new FileOutputStream(new File(path, fileName)); IOUtils.copy(in, out); in.close(); out.flush(); } catch (Exception e) { throw new StorageException(e); } finally { if (in != null) { IOUtils.closeQuietly(in); } if (out != null) { IOUtils.closeQuietly(out); } } return true; } Code Sample 2: private static FileEntry writeEntry(Zip64File zip64File, FileEntry targetPath, File toWrite, boolean compress) { InputStream in = null; EntryOutputStream out = null; processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath.getName(), toWrite), compress); try { if (!compress) { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_STORED, getFileDate(toWrite)); } else { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_DEFLATED, getFileDate(toWrite)); } if (!targetPath.isDirectory()) { in = new FileInputStream(toWrite); IOUtils.copyLarge(in, out); in.close(); } out.flush(); out.close(); if (targetPath.isDirectory()) { log.info("[createZip] Written folder entry to zip: " + targetPath.getName()); } else { log.info("[createZip] Written file entry to zip: " + targetPath.getName()); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ZipException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return targetPath; }
00
Code Sample 1: private static <OS extends OutputStream> OS getUnzipAndDecodeOutputStream(InputStream inputStream, final OS outputStream) { final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final List<Throwable> ungzipThreadThrowableList = new LinkedList<Throwable>(); Writer decoderWriter = null; Thread ungzipThread = null; try { final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); ungzipThread = new Thread(new Runnable() { public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } }); decoderWriter = Base64.newDecoder(pipedOutputStream); ungzipThread.start(); IOUtils.copy(inputStream, decoderWriter, DVK_MESSAGE_CHARSET); decoderWriter.flush(); pipedOutputStream.flush(); } catch (IOException e) { throw new RuntimeException("failed to unzip and decode input", e); } finally { IOUtils.closeQuietly(decoderWriter); IOUtils.closeQuietly(pipedOutputStream); if (ungzipThread != null) { try { ungzipThread.join(); } catch (InterruptedException ie) { throw new RuntimeException("thread interrupted while for ungzip thread to finish", ie); } } } if (!ungzipThreadThrowableList.isEmpty()) { throw new RuntimeException("ungzip failed", ungzipThreadThrowableList.get(0)); } return outputStream; } Code Sample 2: public boolean GetExternalLanguage() { String thisURL, newURL, TheLine; boolean ReadOK = true; int SlashPos = -1; thisURL = getDocumentBase().toString(); SlashPos = thisURL.lastIndexOf("/"); newURL = thisURL.substring(0, (SlashPos + 1)) + "language.txt"; try { URL url = new URL(newURL); try { InputStream TheFile = url.openStream(); try { DataInputStream MyData = new DataInputStream(TheFile); try { while ((TheLine = MyData.readLine()) != null) { if (TheLine.substring(0, 1).compareTo("*") == 0) { if (!ExternalLanguageVariable(TheLine)) { ReadOK = false; break; } } } } catch (Exception e) { System.out.println("Error " + e.toString()); ReadOK = false; } } catch (Exception e) { System.out.println("Error " + e.toString()); ReadOK = false; } } catch (Exception f) { System.out.println("Error " + f.toString()); ReadOK = false; } } catch (Exception g) { System.out.println("Error " + g.toString()); ReadOK = false; } return ReadOK; }
11
Code Sample 1: public static void fileCopy(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: private void channelCopy(File source, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
00
Code Sample 1: public static String sendRequest(String urlstring) { URL url; String line; Log.i("DVBMonitor", "Please wait while receiving data from dvb..."); try { url = new URL(urlstring); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); if ((line = in.readLine()) != null) { return line; } else { return null; } } catch (Exception ex) { Log.e("DVBMonitor", ex.toString() + " while sending request to dvb"); return null; } } Code Sample 2: public void doActionxxx() { try { System.out.println("app: ggc"); String server_name = "http://192.168.4.3:8080/"; server_name = server_name.trim(); if (server_name.length() == 0) { server_name = "http://www.atech-software.com/"; } else { if (!server_name.startsWith("http://")) server_name = "http://" + server_name; if (!server_name.endsWith("/")) server_name = server_name + "/"; } URL url = new URL(server_name + "ATechUpdateGetFile?" + "" + "file_id=1" + "&" + "version_requested=1"); InputStream is = url.openStream(); RandomAccessFile raf = new RandomAccessFile("/home/andy/test.jpg", "rw"); ArrayList<Integer> list = new ArrayList<Integer>(); float size = 671200; long current_size = 0; System.out.println("File size: " + is.available()); byte[] array = new byte[1024]; while (is.available() > 0) { if (is.available() < 1024) { array = new byte[is.available()]; } is.read(array); raf.write(array); current_size += array.length; System.out.println("Progress: " + ((current_size / size) * 100)); } System.out.println("Size Arr: " + list.size()); CheckSumUtility csu = new CheckSumUtility(); System.out.println("Checksum: " + csu.getChecksumValue("/home/andy/test.jpg")); } catch (Exception ex) { ex.printStackTrace(); } }
11
Code Sample 1: public static String Sha1(String s) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = new byte[40]; md.update(s.getBytes("iso-8859-1"), 0, s.length()); hash = md.digest(); return toHex(hash); } catch (Exception e) { e.printStackTrace(); return null; } } Code Sample 2: public static String hexMD5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(value.getBytes("utf-8")); byte[] digest = messageDigest.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } }
00
Code Sample 1: protected InputStream acquireInputStream(String filename) throws IOException { Validate.notEmpty(filename); File f = new File(filename); if (f.exists()) { this.originalFilename = f.getName(); return new FileInputStream(f); } URL url = getClass().getClassLoader().getResource(filename); if (url == null) { if (!filename.startsWith("/")) { url = getClass().getClassLoader().getResource("/" + filename); if (url == null) { throw new IllegalArgumentException("File [" + filename + "] not found in classpath via " + getClass().getClassLoader().getClass()); } } } this.originalFilename = filename; return url.openStream(); } Code Sample 2: public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) { ActionMessages errors = new ActionMessages(); ActionMessages messages = new ActionMessages(); String returnPage = "submitPocketSampleInformationPage"; UploadForm form = (UploadForm) actForm; Integer shippingId = null; try { eHTPXXLSParser parser = new eHTPXXLSParser(); String proposalCode; String proposalNumber; String proposalName; String uploadedFileName; String realXLSPath; if (request != null) { proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE); proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER)); proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = form.getRequestFile().getFileName(); String fileName = proposalName + "_" + uploadedFileName; realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName; FormFile f = form.getRequestFile(); InputStream in = f.getInputStream(); File outputFile = new File(realXLSPath); if (outputFile.exists()) outputFile.delete(); FileOutputStream out = new FileOutputStream(outputFile); while (in.available() != 0) { out.write(in.read()); out.flush(); } out.flush(); out.close(); } else { proposalCode = "ehtpx"; proposalNumber = "1"; proposalName = proposalCode + proposalNumber.toString(); uploadedFileName = "ispyb-template41.xls"; realXLSPath = "D:\\" + uploadedFileName; } FileInputStream inFile = new FileInputStream(realXLSPath); parser.retrieveShippingId(realXLSPath); shippingId = parser.getShippingId(); String requestShippingId = form.getShippingId(); if (requestShippingId != null && !requestShippingId.equals("")) { shippingId = new Integer(requestShippingId); } ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId); if (shippingId != null) { Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :"); double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId); if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added.")); } Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>(); ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create(); ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create(); CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create(); ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0)); ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId()); for (int p = 0; p < listProteins.size(); p++) { ProteinValue prot = (ProteinValue) listProteins.get(p); Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>(); CrystalLightValue listCrystals[] = prot.getCrystals(); for (int c = 0; c < listCrystals.length; c++) { CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c]; CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey()); BlsampleLightValue listSamples[] = xtal.getBlsamples(); for (int s = 0; s < listSamples.length; s++) { BlsampleLightValue sample = listSamples[s]; listSampleName.put(sample.getName(), sample.getBlSampleId()); } } listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName); } parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId()); List listErrors = parser.getValidationErrors(); List listWarnings = parser.getValidationWarnings(); if (listErrors.size() == 0) { parser.open(realXLSPath); if (parser.getCrystals().size() == 0) { parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment")); } } Iterator errIt = listErrors.iterator(); while (errIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) errIt.next(); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveErrors(request, errors); } catch (Exception e) { } Iterator warnIt = listWarnings.iterator(); while (warnIt.hasNext()) { XlsUploadException xlsEx = (XlsUploadException) warnIt.next(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix())); } try { saveMessages(request, messages); } catch (Exception e) { } if (listErrors.size() > 0) { resetCounts(shippingId); return mapping.findForward("submitPocketSampleInformationPage"); } if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage"; String crystalDetailsXML; XtalDetails xtalDetailsWebService = new XtalDetails(); CrystalDetailsBuilder cDE = new CrystalDetailsBuilder(); CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals()); cDE.validateJAXBObject(cd); crystalDetailsXML = cDE.marshallJaxBObjToString(cd); xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML); String diffractionPlan; DiffractionPlan diffractionPlanWebService = new DiffractionPlan(); DiffractionPlanBuilder dPB = new DiffractionPlanBuilder(); Iterator it = parser.getDiffractionPlans().iterator(); while (it.hasNext()) { DiffractionPlanElement dpe = (DiffractionPlanElement) it.next(); dpe.setProjectUUID(proposalName); diffractionPlan = dPB.marshallJaxBObjToString(dpe); diffractionPlanWebService.submitDiffractionPlan(diffractionPlan); } String crystalShipping; Shipping shippingWebService = new Shipping(); CrystalShippingBuilder cSB = new CrystalShippingBuilder(); Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "ispyb@esrf.fr", "0000", "0000", null, null); Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person); DeliveryAgent deliveryAgent = parser.getDeliveryAgent(); CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars()); String shippingName; shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0); if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0); cs.setName(shippingName); crystalShipping = cSB.marshallJaxBObjToString(cs); shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId); ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName); } catch (XlsUploadException e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage())); ClientLogger.getInstance().error(e.toString()); saveErrors(request, errors); return mapping.findForward("error"); } catch (Exception e) { resetCounts(shippingId); errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString())); ClientLogger.getInstance().error(e.toString()); e.printStackTrace(); saveErrors(request, errors); return mapping.findForward("error"); } setCounts(shippingId); return mapping.findForward(returnPage); }
00
Code Sample 1: private static boolean extractFromJarUsingClassLoader(String searchString, String filename, String destinationDirectory) { ClassLoader cl = null; try { Class clClass = Class.forName("com.simontuffs.onejar.JarClassLoader"); Constructor[] constructor = clClass.getConstructors(); cl = (ClassLoader) constructor[1].newInstance(ClassLoader.getSystemClassLoader()); System.out.println("Loaded JarClassLoader. cl=" + cl.toString()); } catch (Throwable e) { cl = ClassLoader.getSystemClassLoader(); } URL liburl = cl.getResource(filename); if (liburl == null) { return false; } if (!destinationDirectory.endsWith(File.separator)) { destinationDirectory = destinationDirectory + File.separator; } try { File destFile = new File(destinationDirectory + filename); if (destFile.exists()) { destFile.delete(); } InputStream is; is = liburl.openStream(); OutputStream os = new FileOutputStream(destinationDirectory + filename); byte[] buf = new byte[4096]; int cnt = is.read(buf); while (cnt > 0) { os.write(buf, 0, cnt); cnt = is.read(buf); } os.close(); is.close(); destFile.deleteOnExit(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } Code Sample 2: private InputStream loadFromUrl(URL url, String contentType) throws IOException { Proxy proxy = null; if (isUseProxy) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); } else { proxy = Proxy.NO_PROXY; } URLConnection connection = url.openConnection(proxy); connection.setRequestProperty("Accept-Charset", DEFAULT_CHARSET); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("User-Agent", USER_AGENT); InputStream response = connection.getInputStream(); return response; }
11
Code Sample 1: public LogoutHandler(String username, String token) { try { URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=LogOut&username=" + username + "&authentication_token=" + token); URLConnection urlc = url.openConnection(); urlc.setDoOutput(false); urlc.setAllowUserInteraction(false); BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); String response = sb.toString(); if (response == null) { return; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(response)); Document dom = db.parse(is); NodeList nl = dom.getElementsByTagName("response"); String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent(); if (status.toString().equals("fail")) { return; } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: @Override public String getData(String blipApiPath, String authHeader) { try { URL url = new URL(BLIP_API_URL + blipApiPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (authHeader != null) { conn.addRequestProperty("Authorization", "Basic " + authHeader); } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuffer content = new StringBuffer(); System.out.println("Resp code " + conn.getResponseCode()); while ((line = reader.readLine()) != null) { System.out.println(">> " + line); content.append(line); } reader.close(); return content.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
00
Code Sample 1: public void appendMessage(MimeMessage oMsg) throws FolderClosedException, StoreClosedException, MessagingException { if (DebugFile.trace) { DebugFile.writeln("Begin DBFolder.appendMessage()"); DebugFile.incIdent(); } final String EmptyString = ""; if (!((DBStore) getStore()).isConnected()) { if (DebugFile.trace) DebugFile.decIdent(); throw new StoreClosedException(getStore(), "Store is not connected"); } if (0 == (iOpenMode & READ_WRITE)) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open is READ_WRITE mode"); } if ((0 == (iOpenMode & MODE_MBOX)) && (0 == (iOpenMode & MODE_BLOB))) { if (DebugFile.trace) DebugFile.decIdent(); throw new javax.mail.FolderClosedException(this, "Folder is not open in MBOX nor BLOB mode"); } String gu_mimemsg; if (oMsg.getClass().getName().equals("com.knowgate.hipermail.DBMimeMessage")) { gu_mimemsg = ((DBMimeMessage) oMsg).getMessageGuid(); if (((DBMimeMessage) oMsg).getFolder() == null) ((DBMimeMessage) oMsg).setFolder(this); } else { gu_mimemsg = Gadgets.generateUUID(); } String gu_workarea = ((DBStore) getStore()).getUser().getString(DB.gu_workarea); int iSize = oMsg.getSize(); if (DebugFile.trace) DebugFile.writeln("MimeMessage.getSize() = " + String.valueOf(iSize)); String sContentType, sContentID, sMessageID, sDisposition, sContentMD5, sDescription, sFileName, sEncoding, sSubject, sPriority, sMsgCharSeq; long lPosition = -1; try { sMessageID = oMsg.getMessageID(); if (sMessageID == null || EmptyString.equals(sMessageID)) { try { sMessageID = oMsg.getHeader("X-Qmail-Scanner-Message-ID", null); } catch (Exception ignore) { } } if (sMessageID != null) sMessageID = MimeUtility.decodeText(sMessageID); sContentType = oMsg.getContentType(); if (sContentType != null) sContentType = MimeUtility.decodeText(sContentType); sContentID = oMsg.getContentID(); if (sContentID != null) sContentID = MimeUtility.decodeText(sContentID); sDisposition = oMsg.getDisposition(); if (sDisposition != null) sDisposition = MimeUtility.decodeText(sDisposition); sContentMD5 = oMsg.getContentMD5(); if (sContentMD5 != null) sContentMD5 = MimeUtility.decodeText(sContentMD5); sDescription = oMsg.getDescription(); if (sDescription != null) sDescription = MimeUtility.decodeText(sDescription); sFileName = oMsg.getFileName(); if (sFileName != null) sFileName = MimeUtility.decodeText(sFileName); sEncoding = oMsg.getEncoding(); if (sEncoding != null) sEncoding = MimeUtility.decodeText(sEncoding); sSubject = oMsg.getSubject(); if (sSubject != null) sSubject = MimeUtility.decodeText(sSubject); sPriority = null; sMsgCharSeq = null; } catch (UnsupportedEncodingException uee) { throw new MessagingException(uee.getMessage(), uee); } BigDecimal dPgMessage = null; try { dPgMessage = getNextMessage(); } catch (SQLException sqle) { throw new MessagingException(sqle.getMessage(), sqle); } String sBoundary = getPartsBoundary(oMsg); if (DebugFile.trace) DebugFile.writeln("part boundary is \"" + (sBoundary == null ? "null" : sBoundary) + "\""); if (sMessageID == null) sMessageID = gu_mimemsg; else if (sMessageID.length() == 0) sMessageID = gu_mimemsg; Timestamp tsSent; if (oMsg.getSentDate() != null) tsSent = new Timestamp(oMsg.getSentDate().getTime()); else tsSent = null; Timestamp tsReceived; if (oMsg.getReceivedDate() != null) tsReceived = new Timestamp(oMsg.getReceivedDate().getTime()); else tsReceived = new Timestamp(new java.util.Date().getTime()); try { String sXPriority = oMsg.getHeader("X-Priority", null); if (sXPriority == null) sPriority = null; else { sPriority = ""; for (int x = 0; x < sXPriority.length(); x++) { char cAt = sXPriority.charAt(x); if (cAt >= (char) 48 || cAt <= (char) 57) sPriority += cAt; } sPriority = Gadgets.left(sPriority, 10); } } catch (MessagingException msge) { if (DebugFile.trace) DebugFile.writeln("MessagingException " + msge.getMessage()); } boolean bIsSpam = false; try { String sXSpam = oMsg.getHeader("X-Spam-Flag", null); if (sXSpam != null) bIsSpam = (sXSpam.toUpperCase().indexOf("YES") >= 0 || sXSpam.toUpperCase().indexOf("TRUE") >= 0 || sXSpam.indexOf("1") >= 0); } catch (MessagingException msge) { if (DebugFile.trace) DebugFile.writeln("MessagingException " + msge.getMessage()); } if (DebugFile.trace) DebugFile.writeln("MimeMessage.getFrom()"); Address[] aFrom = null; try { aFrom = oMsg.getFrom(); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("From AddressException " + adre.getMessage()); } InternetAddress oFrom; if (aFrom != null) { if (aFrom.length > 0) oFrom = (InternetAddress) aFrom[0]; else oFrom = null; } else oFrom = null; if (DebugFile.trace) DebugFile.writeln("MimeMessage.getReplyTo()"); Address[] aReply = null; InternetAddress oReply; try { aReply = oMsg.getReplyTo(); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("Reply-To AddressException " + adre.getMessage()); } if (aReply != null) { if (aReply.length > 0) oReply = (InternetAddress) aReply[0]; else oReply = null; } else { if (DebugFile.trace) DebugFile.writeln("no reply-to address found"); oReply = null; } if (DebugFile.trace) DebugFile.writeln("MimeMessage.getRecipients()"); Address[] oTo = null; Address[] oCC = null; Address[] oBCC = null; try { oTo = oMsg.getRecipients(MimeMessage.RecipientType.TO); oCC = oMsg.getRecipients(MimeMessage.RecipientType.CC); oBCC = oMsg.getRecipients(MimeMessage.RecipientType.BCC); } catch (AddressException adre) { if (DebugFile.trace) DebugFile.writeln("Recipient AddressException " + adre.getMessage()); } Properties pFrom = new Properties(), pTo = new Properties(), pCC = new Properties(), pBCC = new Properties(); if (DebugFile.trace) DebugFile.writeln("MimeMessage.getFlags()"); Flags oFlgs = oMsg.getFlags(); if (oFlgs == null) oFlgs = new Flags(); MimePart oText = null; ByteArrayOutputStream byOutStrm = null; File oFile = null; MboxFile oMBox = null; if ((iOpenMode & MODE_MBOX) != 0) { try { if (DebugFile.trace) DebugFile.writeln("new File(" + Gadgets.chomp(sFolderDir, File.separator) + oCatg.getStringNull(DB.nm_category, "null") + ".mbox)"); oFile = getFile(); lPosition = oFile.length(); if (DebugFile.trace) DebugFile.writeln("message position is " + String.valueOf(lPosition)); oMBox = new MboxFile(oFile, MboxFile.READ_WRITE); if (DebugFile.trace) DebugFile.writeln("new ByteArrayOutputStream(" + String.valueOf(iSize > 0 ? iSize : 16000) + ")"); byOutStrm = new ByteArrayOutputStream(iSize > 0 ? iSize : 16000); oMsg.writeTo(byOutStrm); sMsgCharSeq = byOutStrm.toString("ISO8859_1"); byOutStrm.close(); } catch (IOException ioe) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException(ioe.getMessage(), ioe); } } try { if (oMsg.getClass().getName().equals("com.knowgate.hipermail.DBMimeMessage")) oText = ((DBMimeMessage) oMsg).getBody(); else { oText = new DBMimeMessage(oMsg).getBody(); } if (DebugFile.trace) DebugFile.writeln("ByteArrayOutputStream byOutStrm = new ByteArrayOutputStream(" + oText.getSize() + ")"); byOutStrm = new ByteArrayOutputStream(oText.getSize() > 0 ? oText.getSize() : 8192); oText.writeTo(byOutStrm); if (null == sContentMD5) { MD5 oMd5 = new MD5(); oMd5.Init(); oMd5.Update(byOutStrm.toByteArray()); sContentMD5 = Gadgets.toHexString(oMd5.Final()); oMd5 = null; } } catch (IOException ioe) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("IOException " + ioe.getMessage(), ioe); } catch (OutOfMemoryError oom) { if (DebugFile.trace) DebugFile.decIdent(); throw new MessagingException("OutOfMemoryError " + oom.getMessage()); } String sSQL = "INSERT INTO " + DB.k_mime_msgs + "(gu_mimemsg,gu_workarea,gu_category,id_type,id_content,id_message,id_disposition,len_mimemsg,tx_md5,de_mimemsg,file_name,tx_encoding,tx_subject,dt_sent,dt_received,tx_email_from,nm_from,tx_email_reply,nm_to,id_priority,bo_answered,bo_deleted,bo_draft,bo_flagged,bo_recent,bo_seen,bo_spam,pg_message,nu_position,by_content) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); PreparedStatement oStmt = null; try { oStmt = oConn.prepareStatement(sSQL); oStmt.setString(1, gu_mimemsg); oStmt.setString(2, gu_workarea); if (oCatg.isNull(DB.gu_category)) oStmt.setNull(3, Types.CHAR); else oStmt.setString(3, oCatg.getString(DB.gu_category)); oStmt.setString(4, Gadgets.left(sContentType, 254)); oStmt.setString(5, Gadgets.left(sContentID, 254)); oStmt.setString(6, Gadgets.left(sMessageID, 254)); oStmt.setString(7, Gadgets.left(sDisposition, 100)); if ((iOpenMode & MODE_MBOX) != 0) { iSize = sMsgCharSeq.length(); oStmt.setInt(8, iSize); } else { if (iSize >= 0) oStmt.setInt(8, iSize); else oStmt.setNull(8, Types.INTEGER); } oStmt.setString(9, Gadgets.left(sContentMD5, 32)); oStmt.setString(10, Gadgets.left(sDescription, 254)); oStmt.setString(11, Gadgets.left(sFileName, 254)); oStmt.setString(12, Gadgets.left(sEncoding, 16)); oStmt.setString(13, Gadgets.left(sSubject, 254)); oStmt.setTimestamp(14, tsSent); oStmt.setTimestamp(15, tsReceived); if (null == oFrom) { oStmt.setNull(16, Types.VARCHAR); oStmt.setNull(17, Types.VARCHAR); } else { oStmt.setString(16, Gadgets.left(oFrom.getAddress(), 254)); oStmt.setString(17, Gadgets.left(oFrom.getPersonal(), 254)); } if (null == oReply) oStmt.setNull(18, Types.VARCHAR); else oStmt.setString(18, Gadgets.left(oReply.getAddress(), 254)); Address[] aRecipients; String sRecipientName; aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.TO); if (null != aRecipients) if (aRecipients.length == 0) aRecipients = null; if (null != aRecipients) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else { aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.CC); if (null != aRecipients) { if (aRecipients.length > 0) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else oStmt.setNull(19, Types.VARCHAR); } else { aRecipients = oMsg.getRecipients(MimeMessage.RecipientType.BCC); if (null != aRecipients) { if (aRecipients.length > 0) { sRecipientName = ((InternetAddress) aRecipients[0]).getPersonal(); if (null == sRecipientName) sRecipientName = ((InternetAddress) aRecipients[0]).getAddress(); oStmt.setString(19, Gadgets.left(sRecipientName, 254)); } else oStmt.setNull(19, Types.VARCHAR); } else { oStmt.setNull(19, Types.VARCHAR); } } } if (null == sPriority) oStmt.setNull(20, Types.VARCHAR); else oStmt.setString(20, sPriority); if (oConn.getDataBaseProduct() == JDCConnection.DBMS_ORACLE) { if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBigDecimal(21, ...)"); oStmt.setBigDecimal(21, new BigDecimal(oFlgs.contains(Flags.Flag.ANSWERED) ? "1" : "0")); oStmt.setBigDecimal(22, new BigDecimal(oFlgs.contains(Flags.Flag.DELETED) ? "1" : "0")); oStmt.setBigDecimal(23, new BigDecimal(0)); oStmt.setBigDecimal(24, new BigDecimal(oFlgs.contains(Flags.Flag.FLAGGED) ? "1" : "0")); oStmt.setBigDecimal(25, new BigDecimal(oFlgs.contains(Flags.Flag.RECENT) ? "1" : "0")); oStmt.setBigDecimal(26, new BigDecimal(oFlgs.contains(Flags.Flag.SEEN) ? "1" : "0")); oStmt.setBigDecimal(27, new BigDecimal(bIsSpam ? "1" : "0")); oStmt.setBigDecimal(28, dPgMessage); if ((iOpenMode & MODE_MBOX) != 0) oStmt.setBigDecimal(29, new BigDecimal(lPosition)); else oStmt.setNull(29, Types.NUMERIC); if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBinaryStream(30, new ByteArrayInputStream(" + String.valueOf(byOutStrm.size()) + "))"); if (byOutStrm.size() > 0) oStmt.setBinaryStream(30, new ByteArrayInputStream(byOutStrm.toByteArray()), byOutStrm.size()); else oStmt.setNull(30, Types.LONGVARBINARY); } else { if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setShort(21, ...)"); oStmt.setShort(21, (short) (oFlgs.contains(Flags.Flag.ANSWERED) ? 1 : 0)); oStmt.setShort(22, (short) (oFlgs.contains(Flags.Flag.DELETED) ? 1 : 0)); oStmt.setShort(23, (short) (0)); oStmt.setShort(24, (short) (oFlgs.contains(Flags.Flag.FLAGGED) ? 1 : 0)); oStmt.setShort(25, (short) (oFlgs.contains(Flags.Flag.RECENT) ? 1 : 0)); oStmt.setShort(26, (short) (oFlgs.contains(Flags.Flag.SEEN) ? 1 : 0)); oStmt.setShort(27, (short) (bIsSpam ? 1 : 0)); oStmt.setBigDecimal(28, dPgMessage); if ((iOpenMode & MODE_MBOX) != 0) oStmt.setBigDecimal(29, new BigDecimal(lPosition)); else oStmt.setNull(29, Types.NUMERIC); if (DebugFile.trace) DebugFile.writeln("PreparedStatement.setBinaryStream(30, new ByteArrayInputStream(" + String.valueOf(byOutStrm.size()) + "))"); if (byOutStrm.size() > 0) oStmt.setBinaryStream(30, new ByteArrayInputStream(byOutStrm.toByteArray()), byOutStrm.size()); else oStmt.setNull(30, Types.LONGVARBINARY); } if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); oStmt.close(); oStmt = null; } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(DB.k_mime_msgs + " " + sqle.getMessage(), sqle); } if ((iOpenMode & MODE_BLOB) != 0) { try { byOutStrm.close(); } catch (IOException ignore) { } byOutStrm = null; } try { Object oContent = oMsg.getContent(); if (oContent instanceof MimeMultipart) { try { saveMimeParts(oMsg, sMsgCharSeq, sBoundary, gu_mimemsg, sMessageID, dPgMessage.intValue(), 0); } catch (MessagingException msge) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(msge.getMessage(), msge.getNextException()); } } } catch (Exception xcpt) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException("MimeMessage.getContent() " + xcpt.getMessage(), xcpt); } sSQL = "SELECT " + DB.gu_contact + "," + DB.gu_company + "," + DB.tx_name + "," + DB.tx_surname + "," + DB.tx_surname + " FROM " + DB.k_member_address + " WHERE " + DB.tx_email + "=? AND " + DB.gu_workarea + "=? UNION SELECT " + DB.gu_user + ",'****************************USER'," + DB.nm_user + "," + DB.tx_surname1 + "," + DB.tx_surname2 + " FROM " + DB.k_users + " WHERE (" + DB.tx_main_email + "=? OR " + DB.tx_alt_email + "=?) AND " + DB.gu_workarea + "=?"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); PreparedStatement oAddr = null; try { oAddr = oConn.prepareStatement(sSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet oRSet; InternetAddress oInetAdr; String sTxEmail, sGuCompany, sGuContact, sGuUser, sTxName, sTxSurname1, sTxSurname2, sTxPersonal; if (oFrom != null) { oAddr.setString(1, oFrom.getAddress()); oAddr.setString(2, gu_workarea); oAddr.setString(3, oFrom.getAddress()); oAddr.setString(4, oFrom.getAddress()); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pFrom.put(oFrom.getAddress(), sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pFrom.put(oFrom.getAddress(), "null,null,null"); oRSet.close(); } if (DebugFile.trace) DebugFile.writeln("from count = " + pFrom.size()); if (oTo != null) { for (int t = 0; t < oTo.length; t++) { oInetAdr = (InternetAddress) oTo[t]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pTo.put(sTxEmail, sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pTo.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("to count = " + pTo.size()); if (oCC != null) { for (int c = 0; c < oCC.length; c++) { oInetAdr = (InternetAddress) oCC[c]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pCC.put(sTxEmail, sGuContact + "," + sGuCompany + "," + sTxPersonal); } else pCC.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("cc count = " + pCC.size()); if (oBCC != null) { for (int b = 0; b < oBCC.length; b++) { oInetAdr = (InternetAddress) oBCC[b]; sTxEmail = Gadgets.left(oInetAdr.getAddress(), 254); oAddr.setString(1, sTxEmail); oAddr.setString(2, gu_workarea); oAddr.setString(3, sTxEmail); oAddr.setString(4, sTxEmail); oAddr.setString(5, gu_workarea); oRSet = oAddr.executeQuery(); if (oRSet.next()) { sGuContact = oRSet.getString(1); if (oRSet.wasNull()) sGuContact = "null"; sGuCompany = oRSet.getString(2); if (oRSet.wasNull()) sGuCompany = "null"; if (sGuCompany.equals("****************************USER")) { sTxName = oRSet.getString(3); if (oRSet.wasNull()) sTxName = ""; sTxSurname1 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname1 = ""; sTxSurname2 = oRSet.getString(4); if (oRSet.wasNull()) sTxSurname2 = ""; sTxPersonal = Gadgets.left(sTxName + " " + sTxSurname1 + " " + sTxSurname2, 254).replace(',', ' ').trim(); } else sTxPersonal = "null"; pBCC.put(sTxEmail, sGuContact + "," + sGuCompany); } else pBCC.put(sTxEmail, "null,null,null"); oRSet.close(); } } if (DebugFile.trace) DebugFile.writeln("bcc count = " + pBCC.size()); oAddr.close(); sSQL = "INSERT INTO " + DB.k_inet_addrs + " (gu_mimemsg,id_message,tx_email,tp_recipient,gu_user,gu_contact,gu_company,tx_personal) VALUES ('" + gu_mimemsg + "','" + sMessageID + "',?,?,?,?,?,?)"; if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement(" + sSQL + ")"); oStmt = oConn.prepareStatement(sSQL); java.util.Enumeration oMailEnum; String[] aRecipient; if (!pFrom.isEmpty()) { oMailEnum = pFrom.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pFrom.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "from"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pTo.isEmpty()) { oMailEnum = pTo.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pTo.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "to"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pCC.isEmpty()) { oMailEnum = pCC.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pCC.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "cc"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setString(4, null); oStmt.setString(5, null); } else { oStmt.setString(3, null); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate()"); oStmt.executeUpdate(); } } if (!pBCC.isEmpty()) { oMailEnum = pBCC.keys(); while (oMailEnum.hasMoreElements()) { sTxEmail = (String) oMailEnum.nextElement(); aRecipient = Gadgets.split(pBCC.getProperty(sTxEmail), ','); oStmt.setString(1, sTxEmail); oStmt.setString(2, "bcc"); if (aRecipient[0].equals("null") && aRecipient[1].equals("null")) { oStmt.setNull(3, Types.CHAR); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else if (aRecipient[1].equals("****************************USER")) { oStmt.setString(3, aRecipient[0]); oStmt.setNull(4, Types.CHAR); oStmt.setNull(5, Types.CHAR); } else { oStmt.setNull(3, Types.CHAR); oStmt.setString(4, aRecipient[0].equals("null") ? null : aRecipient[0]); oStmt.setString(5, aRecipient[1].equals("null") ? null : aRecipient[1]); } if (aRecipient[2].equals("null")) oStmt.setNull(6, Types.VARCHAR); else oStmt.setString(6, aRecipient[2]); oStmt.executeUpdate(); } } oStmt.close(); oStmt = null; oStmt = oConn.prepareStatement("UPDATE " + DB.k_categories + " SET " + DB.len_size + "=" + DB.len_size + "+" + String.valueOf(iSize) + " WHERE " + DB.gu_category + "=?"); oStmt.setString(1, getCategory().getString(DB.gu_category)); oStmt.executeUpdate(); oStmt.close(); oStmt = null; if ((iOpenMode & MODE_MBOX) != 0) { if (DebugFile.trace) DebugFile.writeln("MboxFile.appendMessage(" + (oMsg.getContentID() != null ? oMsg.getContentID() : "") + ")"); oMBox.appendMessage(sMsgCharSeq); oMBox.close(); oMBox = null; } if (DebugFile.trace) DebugFile.writeln("Connection.commit()"); oConn.commit(); } catch (SQLException sqle) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oAddr) oAddr.close(); oAddr = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(sqle.getMessage(), sqle); } catch (IOException ioe) { try { if (oMBox != null) oMBox.close(); } catch (Exception ignore) { } try { if (null != oStmt) oStmt.close(); oStmt = null; } catch (Exception ignore) { } try { if (null != oAddr) oAddr.close(); oAddr = null; } catch (Exception ignore) { } try { if (null != oConn) oConn.rollback(); } catch (Exception ignore) { } throw new MessagingException(ioe.getMessage(), ioe); } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End DBFolder.appendMessage() : " + gu_mimemsg); } } Code Sample 2: public Graph<N, E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { } } }
11
Code Sample 1: public static String calculateHA2(String uri) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes("GET", ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(uri, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } } Code Sample 2: @Override public void addApplication(Application app) { logger.info("Adding a new application " + app.getName() + " by " + app.getOrganisation() + " (" + app.getEmail() + ") "); app.setRegtime(new Timestamp(new Date().getTime())); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update((app.getName() + app.getEmail() + app.getRegtime()).getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } app.setAppid(sb.toString()); } catch (NoSuchAlgorithmException ex) { java.util.logging.Logger.getLogger(ApplicationDAOImpl.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(app.toString()); SqlParameterSource parameters = new BeanPropertySqlParameterSource(app); Number appUid = insertApplication.executeAndReturnKey(parameters); app.setId(appUid.longValue()); }
11
Code Sample 1: public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public void compile(Project project) throws ProjectCompilerException { List<Resource> resources = project.getModel().getResource(); for (Resource resource : resources) { try { IOUtils.copy(srcDir.getRelative(resource.getLocation()).getInputStream(), outDir.getRelative(resource.getLocation()).getOutputStream()); } catch (IOException e) { throw new ProjectCompilerException("Resource cannot be copied. Compilation failed", e); } } }
11
Code Sample 1: public void run() { long starttime = (new Date()).getTime(); Matcher m = Pattern.compile("(\\S+);(\\d+)").matcher(Destination); boolean completed = false; if (OutFile.length() > IncommingProcessor.MaxPayload) { logger.warn("Payload is too large!"); close(); } else { if (m.find()) { Runnable cl = new Runnable() { public void run() { WaitToClose(); } }; Thread t = new Thread(cl); t.start(); S = null; try { String ip = m.group(1); int port = Integer.valueOf(m.group(2)); SerpentEngine eng = new SerpentEngine(); byte[] keybytes = new byte[eng.getBlockSize()]; byte[] ivbytes = new byte[eng.getBlockSize()]; Random.nextBytes(keybytes); Random.nextBytes(ivbytes); KeyParameter keyparm = new KeyParameter(keybytes); ParametersWithIV keyivparm = new ParametersWithIV(keyparm, ivbytes); byte[] parmbytes = BCUtils.writeParametersWithIV(keyivparm); OAEPEncoding enc = new OAEPEncoding(new ElGamalEngine(), new RIPEMD128Digest()); enc.init(true, PublicKey); byte[] encbytes = enc.encodeBlock(parmbytes, 0, parmbytes.length); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SerpentEngine())); cipher.init(true, keyivparm); byte[] inbuffer = new byte[128]; byte[] outbuffer = new byte[256]; int readlen = 0; int cryptlen = 0; FileInputStream fis = new FileInputStream(OutFile); FileOutputStream fos = new FileOutputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { if (readlen > 0) { cryptlen = cipher.processBytes(inbuffer, 0, readlen, outbuffer, 0); fos.write(outbuffer, 0, cryptlen); } readlen = fis.read(inbuffer); } cryptlen = cipher.doFinal(outbuffer, 0); if (cryptlen > 0) { fos.write(outbuffer, 0, cryptlen); } fos.close(); fis.close(); S = new Socket(ip, port); DataOutputStream dos = new DataOutputStream(S.getOutputStream()); dos.writeInt(encbytes.length); dos.write(encbytes); dos.writeLong(TmpFile.length()); fis = new FileInputStream(TmpFile); readlen = fis.read(inbuffer); while (readlen >= 0) { dos.write(inbuffer, 0, readlen); readlen = fis.read(inbuffer); } DataInputStream dis = new DataInputStream(S.getInputStream()); byte[] encipbytes = StreamUtils.readBytes(dis); cipher.init(false, keyivparm); byte[] decipbytes = new byte[encipbytes.length]; int len = cipher.processBytes(encipbytes, 0, encipbytes.length, decipbytes, 0); len += cipher.doFinal(decipbytes, len); byte[] realbytes = new byte[len]; System.arraycopy(decipbytes, 0, realbytes, 0, len); String ipstr = new String(realbytes, "ISO-8859-1"); Callback.Success(ipstr); completed = true; dos.write(0); dos.flush(); close(); } catch (Exception e) { close(); if (!completed) { e.printStackTrace(); Callback.Fail(e.getMessage()); } } } else { close(); logger.warn("Improper destination string. " + Destination); Callback.Fail("Improper destination string. " + Destination); } } CloseWait(); long newtime = (new Date()).getTime(); long timediff = newtime - starttime; logger.debug("Outgoing processor took: " + timediff); } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview); HttpGet request = new HttpGet(SERVICE_URI + "/json/getroutes/1"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); String theString = new String(""); try { HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); Vector<String> vectorOfStrings = new Vector<String>(); String tempString = new String(); String tempStringAgent = new String(); String tempStringClient = new String(); String tempStringRoute = new String(); String tempStringZone = new String(); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } stream.close(); theString = builder.toString(); JSONObject json = new JSONObject(theString); Log.i("_GetClient_", "<jsonobject> \n " + json.toString() + " \n </jsonobject>"); this.dm = new DataManipulator(this); JSONArray nameArray = json.getJSONArray("GetRoutesByAgentResult"); for (int i = 0; i < nameArray.length(); i++) { tempStringAgent = nameArray.getJSONObject(i).getString("Agent"); tempStringClient = nameArray.getJSONObject(i).getString("Client"); tempStringRoute = nameArray.getJSONObject(i).getString("Route"); tempStringZone = nameArray.getJSONObject(i).getString("Zone"); Log.i("_GetClient_", "<Agent" + i + ">" + tempStringAgent + "</Agent" + i + ">\n"); Log.i("_GetClient_", "<Client" + i + ">" + tempStringClient + "</Client" + i + ">\n"); Log.i("_GetClient_", "<Route" + i + ">" + tempStringRoute + "</Route" + i + ">\n"); Log.i("_GetClient_", "<Zone" + i + ">" + tempStringZone + "</Zone" + i + ">\n"); this.dm.insertIntoClients(tempStringAgent, tempStringClient, tempStringRoute, tempStringZone); tempString = nameArray.getJSONObject(i).getString("Client") + "\n" + nameArray.getJSONObject(i).getString("Route") + "\n" + nameArray.getJSONObject(i).getString("Zone"); vectorOfStrings.add(new String(tempString)); } int orderCount = vectorOfStrings.size(); String[] orderTimeStamps = new String[orderCount]; vectorOfStrings.copyInto(orderTimeStamps); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps)); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public boolean verify(final char[] password, final String encryptedPassword) { MessageDigest digest = null; int size = 0; String base64 = null; if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) { size = 20; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) { size = 20; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("SHA-1"); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) { size = 16; base64 = encryptedPassword.substring(5); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("Invalid algorithm"); } } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) { size = 16; base64 = encryptedPassword.substring(6); try { digest = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("Invalid algorithm"); } } else { return false; } try { final byte[] data = Base64.decodeBase64(base64.getBytes("UTF-8")); final byte[] orig = new byte[size]; System.arraycopy(data, 0, orig, 0, size); digest.reset(); digest.update(new String(password).getBytes("UTF-8")); if (data.length > size) { digest.update(data, size, data.length - size); } return MessageDigest.isEqual(digest.digest(), orig); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 Unsupported"); } }
11
Code Sample 1: public static int getNextID(int AD_Client_ID, String TableName, String trxName) { if (TableName == null || TableName.length() == 0) throw new IllegalArgumentException("TableName missing"); int retValue = -1; boolean adempiereSys = Ini.isPropertyBool(Ini.P_ADEMPIERESYS); if (adempiereSys && AD_Client_ID > 11) adempiereSys = false; if (CLogMgt.isLevel(LOGLEVEL)) s_log.log(LOGLEVEL, TableName + " - AdempiereSys=" + adempiereSys + " [" + trxName + "]"); String selectSQL = null; if (DB.isPostgreSQL()) { selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, AD_Sequence_ID " + "FROM AD_Sequence " + "WHERE Name=?" + " AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y' " + " FOR UPDATE OF AD_Sequence "; USE_PROCEDURE = false; } else if (DB.isOracle()) { selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, AD_Sequence_ID " + "FROM AD_Sequence " + "WHERE Name=?" + " AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y' " + "FOR UPDATE"; USE_PROCEDURE = true; } else { selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, AD_Sequence_ID " + "FROM AD_Sequence " + "WHERE Name=?" + " AND IsActive='Y' AND IsTableID='Y' AND IsAutoSequence='Y' "; USE_PROCEDURE = false; } Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; for (int i = 0; i < 3; i++) { try { conn = DB.getConnectionID(); if (conn == null) return -1; pstmt = conn.prepareStatement(selectSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); pstmt.setString(1, TableName); if (!USE_PROCEDURE && DB.getDatabase().isQueryTimeoutSupported()) pstmt.setQueryTimeout(QUERY_TIME_OUT); rs = pstmt.executeQuery(); if (CLogMgt.isLevelFinest()) s_log.finest("AC=" + conn.getAutoCommit() + ", RO=" + conn.isReadOnly() + " - Isolation=" + conn.getTransactionIsolation() + "(" + Connection.TRANSACTION_READ_COMMITTED + ") - RSType=" + pstmt.getResultSetType() + "(" + ResultSet.TYPE_SCROLL_SENSITIVE + "), RSConcur=" + pstmt.getResultSetConcurrency() + "(" + ResultSet.CONCUR_UPDATABLE + ")"); if (rs.next()) { MTable table = MTable.get(Env.getCtx(), TableName); int AD_Sequence_ID = rs.getInt(4); boolean gotFromHTTP = false; if (adempiereSys) { String isUseCentralizedID = MSysConfig.getValue("DICTIONARY_ID_USE_CENTRALIZED_ID", "Y"); if ((!isUseCentralizedID.equals("N")) && (!isExceptionCentralized(TableName))) { retValue = getNextOfficialID_HTTP(TableName); if (retValue > 0) { PreparedStatement updateSQL; updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNextSys = ? + 1 WHERE AD_Sequence_ID = ?"); try { updateSQL.setInt(1, retValue); updateSQL.setInt(2, AD_Sequence_ID); updateSQL.executeUpdate(); } finally { updateSQL.close(); } } gotFromHTTP = true; } } boolean queryProjectServer = false; if (table.getColumn("EntityType") != null) queryProjectServer = true; if (!queryProjectServer && MSequence.Table_Name.equalsIgnoreCase(TableName)) queryProjectServer = true; if (queryProjectServer && (adempiereSys) && (!isExceptionCentralized(TableName))) { String isUseProjectCentralizedID = MSysConfig.getValue("PROJECT_ID_USE_CENTRALIZED_ID", "N"); if (isUseProjectCentralizedID.equals("Y")) { retValue = getNextProjectID_HTTP(TableName); if (retValue > 0) { PreparedStatement updateSQL; updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNext = GREATEST(CurrentNext, ? + 1) WHERE AD_Sequence_ID = ?"); try { updateSQL.setInt(1, retValue); updateSQL.setInt(2, AD_Sequence_ID); updateSQL.executeUpdate(); } finally { updateSQL.close(); } } gotFromHTTP = true; } } if (!gotFromHTTP) { if (USE_PROCEDURE) { retValue = nextID(conn, AD_Sequence_ID, adempiereSys); } else { PreparedStatement updateSQL; int incrementNo = rs.getInt(3); if (adempiereSys) { updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNextSys = CurrentNextSys + ? WHERE AD_Sequence_ID = ?"); retValue = rs.getInt(2); } else { updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID = ?"); retValue = rs.getInt(1); } try { updateSQL.setInt(1, incrementNo); updateSQL.setInt(2, AD_Sequence_ID); updateSQL.executeUpdate(); } finally { updateSQL.close(); } } } conn.commit(); } else s_log.severe("No record found - " + TableName); break; } catch (Exception e) { s_log.log(Level.SEVERE, TableName + " - " + e.getMessage(), e); try { if (conn != null) conn.rollback(); } catch (SQLException e1) { } } finally { DB.close(rs, pstmt); pstmt = null; rs = null; if (conn != null) { try { conn.close(); } catch (SQLException e) { } conn = null; } } Thread.yield(); } return retValue; } Code Sample 2: public boolean addSiteScore(ArrayList<InitScoreTable> siteScores, InitScoreTable scoreTable, String filePath, String strTime) { boolean bResult = false; String strSql = ""; Connection conn = null; Statement stm = null; try { conn = db.getConnection(); conn.setAutoCommit(false); stm = conn.createStatement(); strSql = "delete from t_siteScore where strTaskId = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); for (int i = 0; i < siteScores.size(); i++) { InitScoreTable temp = siteScores.get(i); String tempSql = "select * from t_tagConf where strTagName='" + temp.getStrSiteScoreTagName() + "' and strTagYear='" + temp.getStrSiteScoreYear() + "' "; System.out.println(tempSql); ResultSet rst = stm.executeQuery(tempSql); if (rst.next()) { temp.setStrSiteScoreTagId(rst.getString("strId")); temp.setStrSiteinfoScoreParentId(rst.getString("strParentId")); } rst = null; } Iterator<InitScoreTable> it = siteScores.iterator(); String strCreatedTime = com.siteeval.common.Format.getDateTime(); String taskId = ""; while (it.hasNext()) { InitScoreTable thebean = it.next(); taskId = thebean.getStrSiteScoreTaskId(); String strId = UID.getID(); strSql = "INSERT INTO " + strTableName3 + "(strId,strTaskId,strTagId," + "strTagType,strTagName,strParentId,flaTagScore,strYear,datCreatedTime,strCreator) " + "VALUES('" + strId + "','" + taskId + "','" + thebean.getStrSiteScoreTagId() + "','" + thebean.getStrSiteScoreTagType() + "','" + thebean.getStrSiteScoreTagName() + "','" + thebean.getStrSiteinfoScoreParentId() + "','" + thebean.getFlaSiteScoreTagScore() + "','" + thebean.getStrSiteScoreYear() + "','" + strCreatedTime + "','" + thebean.getStrSiteScoreCreator() + "')"; stm.executeUpdate(strSql); } strSql = "update t_siteTotalScore set strSiteState=1,flaSiteScore='" + scoreTable.getFlaSiteScore() + "',flaInfoDisclosureScore='" + scoreTable.getFlaInfoDisclosureScore() + "',flaOnlineServicesScore='" + scoreTable.getFlaOnlineServicesScore() + "',flaPublicParticipationSore='" + scoreTable.getFlaPublicParticipationSore() + "',flaWebDesignScore='" + scoreTable.getFlaWebDesignScore() + "',strSiteFeature='" + scoreTable.getStrTotalScoreSiteFeature() + "',strSiteAdvantage='" + scoreTable.getStrTotalScoreSiteAdvantage() + "',strSiteFailure='" + scoreTable.getStrTotalScoreSiteFailure() + "' where strTaskId='" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); strSql = "update " + strTableName1 + " set templateUrl='" + filePath + "',dTaskBeginTime='" + strTime + "',dTaskEndTime='" + strTime + "' where strid = '" + scoreTable.getStrSiteScoreTaskId() + "'"; stm.executeUpdate(strSql); conn.commit(); bResult = true; } catch (Exception e) { try { conn.rollback(); } catch (Exception eee) { } System.out.println("������վ���ֱ���Ϣʱ���?"); } finally { try { conn.setAutoCommit(true); if (stm != null) { stm.close(); } if (conn != null) { conn.close(); } } catch (Exception ee) { } } return bResult; }
11
Code Sample 1: private void renameTo(File from, File to) { if (!from.exists()) return; if (to.exists()) to.delete(); boolean worked = false; try { worked = from.renameTo(to); } catch (Exception e) { database.logError(this, "" + e, null); } if (!worked) { database.logWarning(this, "Could not rename GEDCOM to " + to.getAbsolutePath(), null); try { to.delete(); final FileReader in = new FileReader(from); final FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); from.delete(); } catch (Exception e) { database.logError(this, "" + e, null); } } } Code Sample 2: public static void extractZipPackage(String fileName, String destinationFolder) throws Exception { if (NullStatus.isNull(destinationFolder)) { destinationFolder = ""; } new File(destinationFolder).mkdirs(); File inputFile = new File(fileName); ZipFile zipFile = new ZipFile(inputFile); Enumeration<? extends ZipEntry> oEnum = zipFile.entries(); while (oEnum.hasMoreElements()) { ZipEntry zipEntry = oEnum.nextElement(); File file = new File(destinationFolder + "/" + zipEntry.getName()); if (zipEntry.isDirectory()) { file.mkdirs(); } else { String destinationFolderName = destinationFolder + "/" + zipEntry.getName(); destinationFolderName = destinationFolderName.substring(0, destinationFolderName.lastIndexOf("/")); new File(destinationFolderName).mkdirs(); FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(zipFile.getInputStream(zipEntry), fos); fos.close(); } } }
11
Code Sample 1: @Override public InputStream getInputStream() throws IOException { if (dfos == null) { int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold(); dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION); try { IOUtils.copy(is, dfos); } finally { dfos.close(); } } return dfos.getDeferredInputStream(); } Code Sample 2: public static void invokeMvnArtifact(final IProject project, final IModuleExtension moduleExtension, final String location) throws CoreException, InterruptedException, IOException { final Properties properties = new Properties(); properties.put("archetypeGroupId", "org.nexopenframework.plugins"); properties.put("archetypeArtifactId", "openfrwk-archetype-webmodule"); final String version = org.maven.ide.eclipse.ext.Maven2Plugin.getArchetypeVersion(); properties.put("archetypeVersion", version); properties.put("artifactId", moduleExtension.getArtifact()); properties.put("groupId", moduleExtension.getGroup()); properties.put("version", moduleExtension.getVersion()); final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID); final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating WEB module using Apache Maven archetype"); File archetypePomDirectory = getDefaultArchetypePomDirectory(); try { final String dfPom = getPomFile(moduleExtension.getGroup(), moduleExtension.getArtifact()); final ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes()); final File f = new File(archetypePomDirectory, "pom.xml"); OutputStream fous = null; try { fous = new FileOutputStream(f); IOUtils.copy(bais, fous); } finally { try { if (fous != null) { fous.close(); } if (bais != null) { bais.close(); } } catch (final IOException e) { } } String goalName = "archetype:create"; boolean offline = false; try { final Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.maven.ide.eclipse.Maven2Plugin"); final Maven2Plugin plugin = (Maven2Plugin) clazz.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]); offline = plugin.getPreferenceStore().getBoolean("eclipse.m2.offline"); } catch (final ClassNotFoundException e) { Logger.logException("No class [org.maven.ide.eclipse.ext.Maven2Plugin] in classpath", e); } catch (final NoSuchMethodException e) { Logger.logException("No method getDefault", e); } catch (final Throwable e) { Logger.logException(e); } if (offline) { goalName = new StringBuffer(goalName).append(" -o").toString(); } if (!offline) { final IPreferenceStore ps = Maven2Plugin.getDefault().getPreferenceStore(); final String repositories = ps.getString(Maven2PreferenceConstants.P_M2_REPOSITORIES); final String[] repos = repositories.split(org.maven.ide.eclipse.ext.Maven2Plugin.REPO_SEPARATOR); final StringBuffer sbRepos = new StringBuffer(); for (int k = 0; k < repos.length; k++) { sbRepos.append(repos[k]); if (k != repos.length - 1) { sbRepos.append(","); } } properties.put("remoteRepositories", sbRepos.toString()); } workingCopy.setAttribute(ATTR_GOALS, goalName); workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath()); workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties)); final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout(); TimeoutLaunchConfiguration.launchWithTimeout(new NullProgressMonitor(), workingCopy, project, timeout); FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), new File(location)); FileUtils.deleteDirectory(new File(location + "/src")); FileUtils.forceDelete(new File(location, "pom.xml")); project.refreshLocal(IResource.DEPTH_INFINITE, null); } finally { FileUtils.deleteDirectory(archetypePomDirectory); Logger.log(Logger.INFO, "Invoked removing of archetype POM directory"); } }
11
Code Sample 1: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); } Code Sample 2: void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
11
Code Sample 1: public static boolean copy(File source, File target, boolean owrite) { if (!source.exists()) { log.error("Invalid input to copy: source " + source + "doesn't exist"); return false; } else if (!source.isFile()) { log.error("Invalid input to copy: source " + source + "isn't a file."); return false; } else if (target.exists() && !owrite) { log.error("Invalid input to copy: target " + target + " exists."); return false; } try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); byte buffer[] = new byte[1024]; int read = -1; while ((read = in.read(buffer, 0, 1024)) != -1) out.write(buffer, 0, read); out.flush(); out.close(); in.close(); return true; } catch (IOException e) { log.error("Copy failed: ", e); return false; } } Code Sample 2: private void show(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } }
00
Code Sample 1: public static void main(final String[] args) { final Runnable startDerby = new Runnable() { public void run() { try { final NetworkServerControl control = new NetworkServerControl(InetAddress.getByName("localhost"), 1527); control.start(new PrintWriter(System.out)); } catch (final Exception ex) { throw new RuntimeException(ex); } } }; new Thread(startDerby).start(); final Runnable startActiveMq = new Runnable() { public void run() { Main.main(new String[] { "start", "xbean:file:active-mq-config.xml" }); } }; new Thread(startActiveMq).start(); final Runnable startMailServer = new Runnable() { public void run() { final SimpleMessageListener listener = new SimpleMessageListener() { public final boolean accept(final String from, final String recipient) { return true; } public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } } }; final SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(listener)); smtpServer.start(); System.out.println("Started SMTP Server"); } }; new Thread(startMailServer).start(); } Code Sample 2: private void postObject(Object obj, String strURL) throws Exception { print("entering post object"); URL url = new URL(strURL); URLConnection urlConn = url.openConnection(); print("HttpNetworkMessageConnection.postObject:returned from url.openConnection()"); urlConn.setUseCaches(false); urlConn.setDoOutput(true); ObjectOutputStream oos = new ObjectOutputStream(urlConn.getOutputStream()); print("HttpNetworkMessageConnection.postObject:returned from urlConn.getOutputStream()"); oos.writeObject(obj); print("HttpNetworkMessageConnection.postObject:returned from writeObject()"); oos.flush(); oos.close(); InputStream is = urlConn.getInputStream(); print("HttpNetworkMessageConnection.postObject:returned from getInputStream()"); while (is.read() != -1) { } is.close(); print("exiting postObject"); }
11
Code Sample 1: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); try { FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { destinationChannel.close(); } } finally { sourceChannel.close(); } }
00
Code Sample 1: public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } } Code Sample 2: private boolean serverOK(String serverAddress, String serverPort) { boolean status = false; String serverString = serverAddress + ":" + serverPort + MolConvertInNodeModel.SERVER_WSDL_PATH; System.out.println("connecting to " + serverString + "..."); try { java.net.URL url = new java.net.URL(serverString); try { java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); status = readContents(connection); if (status) { JOptionPane.showMessageDialog(this.getPanel(), "Connection to Server is OK"); } } catch (Exception connEx) { JOptionPane.showMessageDialog(this.getPanel(), connEx.getMessage()); logger.error(connEx.getMessage()); } } catch (java.net.MalformedURLException urlEx) { JOptionPane.showMessageDialog(this.getPanel(), urlEx.getMessage()); logger.error(urlEx.getMessage()); } return status; }
11
Code Sample 1: public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[8192]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); } Code Sample 2: public void copy(String fromFileName, String toFileName) throws IOException { log.info("copy() file:" + fromFileName + " toFile:" + toFileName); File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
11
Code Sample 1: public static FileChannel getFileChannel(Object o) throws IOException { Class c = o.getClass(); try { Method m = c.getMethod("getChannel", null); return (FileChannel) m.invoke(o, null); } catch (IllegalAccessException x) { } catch (NoSuchMethodException x) { } catch (InvocationTargetException x) { if (x.getTargetException() instanceof IOException) throw (IOException) x.getTargetException(); } if (o instanceof FileInputStream) return new MyFileChannelImpl((FileInputStream) o); if (o instanceof FileOutputStream) return new MyFileChannelImpl((FileOutputStream) o); if (o instanceof RandomAccessFile) return new MyFileChannelImpl((RandomAccessFile) o); Assert.UNREACHABLE(o.getClass().toString()); return null; } Code Sample 2: private File copyFile(String fileInClassPath, String systemPath) throws Exception { InputStream is = getClass().getResourceAsStream(fileInClassPath); OutputStream os = new FileOutputStream(systemPath); IOUtils.copy(is, os); is.close(); os.close(); return new File(systemPath); }
00
Code Sample 1: public static void addClasses(final Checker checker, final ArrayList<Class<?>> list, final String packageName, final int levels, final URL url) { final File directory = new File(url.getFile()); if (directory.exists()) addClasses(checker, list, packageName, levels, directory); else try { final JarURLConnection conn = (JarURLConnection) url.openConnection(); addClasses(checker, list, levels, conn, packageName.replace('.', '/')); } catch (final IOException ioex) { System.err.println(ioex); } } Code Sample 2: public void run() { btnReintentar.setEnabled(false); try { lblEstado.setText("Conectando con servidor..."); escribir("\nConectando con servidor..."); URL url = new URL("http://apeiron.sourceforge.net/version.php"); lblEstado.setText("Obteniendo informaci�n de versi�n..."); escribir("Ok\n"); escribir("Obteniendo informaci�n sobre �ltima versi�n..."); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String linea = br.readLine(); escribir("Ok\n"); if (linea != null) { escribir("Versi�n mas reciente: " + linea + "\n"); if (Principal.version < Double.parseDouble(linea)) { lblEstado.setText("Hay una nueva versi�n: Apeiron " + linea); escribir("Puede obtener la actualizaci�n de: http://apeiron.sourceforge.net\n"); btnActualizar.setEnabled(true); setVisible(true); } else { lblEstado.setText("Usted tiene la �ltima versi�n"); } } br.close(); } catch (MalformedURLException e) { escribir("Fall�\n" + e + "\n"); e.printStackTrace(); } catch (IOException e) { escribir("Fall�\n" + e + "\n"); e.printStackTrace(); } btnReintentar.setEnabled(true); }
00
Code Sample 1: public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/tuneGridMaster.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); tune_x[i][j] = Double.parseDouble(st.nextToken()); gridmin = tune_x[i][j]; temp_prev = tune_x[i][j]; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); j++; int k = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } tune_x[i][j] = temp_new; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; k++; } gridmax = tune_x[i][j - 1]; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: @Override public InputStream getInputStream() { String url = resourceURL_; try { return new URL(url).openStream(); } catch (Exception e) { } try { return new FileInputStream("/" + url); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: private Bitmap fetchImage(String urlstr) throws Exception { URL url; url = new URL(urlstr); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setDoInput(true); c.setRequestProperty("User-Agent", "Agent"); c.connect(); InputStream is = c.getInputStream(); Bitmap img; img = BitmapFactory.decodeStream(is); return img; }
00
Code Sample 1: public static String Md5By32(String plainText) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.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)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: public Music(URL url, boolean streamingHint) throws SlickException { SoundStore.get().init(); String ref = url.getFile(); try { if (ref.toLowerCase().endsWith(".ogg")) { if (streamingHint) { sound = SoundStore.get().getOggStream(url); } else { sound = SoundStore.get().getOgg(url.openStream()); } } else if (ref.toLowerCase().endsWith(".wav")) { sound = SoundStore.get().getWAV(url.openStream()); } else if (ref.toLowerCase().endsWith(".xm") || ref.toLowerCase().endsWith(".mod")) { sound = SoundStore.get().getMOD(url.openStream()); } else if (ref.toLowerCase().endsWith(".aif") || ref.toLowerCase().endsWith(".aiff")) { sound = SoundStore.get().getAIF(url.openStream()); } else { throw new SlickException("Only .xm, .mod, .ogg, and .aif/f are currently supported."); } } catch (Exception e) { Log.error(e); throw new SlickException("Failed to load sound: " + url); } }
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: public static String getServerVersion() throws IOException { URL url; url = new URL(CHECKVERSIONURL); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(false); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("GET"); httpURLConnection.connect(); InputStream in = httpURLConnection.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); out.flush(); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); String buffer; String[] lines; String version = ""; buffer = out.toString(); lines = StringUtils.split(buffer); for (int i = 0; i < lines.length; i++) { if (lines[i].startsWith("version=")) { version = lines[i].substring(8).trim(); break; } } return version; }
11
Code Sample 1: public static void downloadJars(IProject project, String repositoryUrl, String jarDirectory, String[] jars) { try { File tmpFile = null; for (String jar : jars) { try { tmpFile = File.createTempFile("tmpPlugin_", ".zip"); URL url = new URL(repositoryUrl + jarDirectory + jar); String destFilename = new File(url.getFile()).getName(); File destFile = new File(project.getLocation().append("lib").append(jarDirectory).toFile(), destFilename); InputStream inputStream = null; FileOutputStream outputStream = null; try { URLConnection urlConnection = url.openConnection(); inputStream = urlConnection.getInputStream(); outputStream = new FileOutputStream(tmpFile); IOUtils.copy(inputStream, outputStream); } finally { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } } catch (Exception ex) { ex.printStackTrace(); } } Code Sample 2: public ManageUsers() { if (System.getProperty("user.home") != null) { dataFile = new File(System.getProperty("user.home") + File.separator + "MyRx" + File.separator + "MyRx.dat"); File dataFileDir = new File(System.getProperty("user.home") + File.separator + "MyRx"); dataFileDir.mkdirs(); } else { dataFile = new File("MyRx.dat"); } try { dataFile.createNewFile(); } catch (IOException e1) { logger.error(e1); JOptionPane.showMessageDialog(Menu.getMainMenu(), e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } File oldDataFile = new File("MyRx.dat"); if (oldDataFile.exists()) { FileChannel src = null, dst = null; try { src = new FileInputStream(oldDataFile.getAbsolutePath()).getChannel(); dst = new FileOutputStream(dataFile.getAbsolutePath()).getChannel(); dst.transferFrom(src, 0, src.size()); if (!oldDataFile.delete()) { oldDataFile.deleteOnExit(); } } catch (FileNotFoundException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e) { logger.error(e); JOptionPane.showMessageDialog(Menu.getMainMenu(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { try { src.close(); dst.close(); } catch (IOException e) { logger.error(e); } } } }
11
Code Sample 1: public void transport(File file) throws TransportException { if (file.exists()) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { transport(file); } } else if (file.isFile()) { try { FileChannel inChannel = new FileInputStream(file).getChannel(); FileChannel outChannel = new FileOutputStream(getOption("destination")).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { log.error("File transfer failed", e); } } } } Code Sample 2: private void copyFile(File orig, File dest) { byte[] buffer = new byte[1024]; try { FileInputStream fis = new FileInputStream(orig); FileOutputStream fos = new FileOutputStream(dest, true); int readBytes = 0; do { readBytes = fis.read(buffer); if (readBytes > 0) fos.write(buffer, 0, readBytes); } while (readBytes > 0); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
11
Code Sample 1: public static void main(String[] args) { final String filePath1 = "e:\\mysite\\data\\up\\itsite"; final String filePath2 = "d:\\works\\itsite\\itsite"; IOUtils.listAllFilesNoRs(new File(filePath2), new FileFilter() { @Override public boolean accept(File file) { if (file.getName().equals(".svn")) { return false; } final long modify = file.lastModified(); final long time = DateUtils.toDate("2012-03-21 17:43", "yyyy-MM-dd HH:mm").getTime(); if (modify >= time) { if (file.isFile()) { File f = new File(StringsUtils.replace(file.getAbsolutePath(), filePath2, filePath1)); f.getParentFile().mkdirs(); try { IOUtils.copyFile(file, f); } catch (IOException e) { e.printStackTrace(); } System.out.println(f.getName()); } } return true; } }); } Code Sample 2: @Override public synchronized File download_dictionary(Dictionary dict, String localfpath) { abort = false; try { URL dictionary_location = new URL(dict.getLocation()); InputStream in = dictionary_location.openStream(); FileOutputStream w = new FileOutputStream(local_cache, false); int b = 0; while ((b = in.read()) != -1) { w.write(b); if (abort) throw new Exception("Download Aborted"); } in.close(); w.close(); File lf = new File(localfpath); FileInputStream r = new FileInputStream(local_cache); FileOutputStream fw = new FileOutputStream(lf); int c; while ((c = r.read()) != -1) fw.write(c); r.close(); fw.close(); clearCache(); return lf; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidTupleOperationException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } clearCache(); return null; }
00
Code Sample 1: public String getData() throws ValueFormatException, RepositoryException, IOException { InputStream is = getStream(); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); IOUtils.closeQuietly(is); return sw.toString(); } Code Sample 2: public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/transaction/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Transaction Deleted!"); } else { response.setDone(false); response.setMessage("Delete Transaction Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }
00
Code Sample 1: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); } Code Sample 2: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; String notice; String error = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { notice = "Unknown action!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } if (action.equals("edit_events")) { String sql; String month_name = ""; int month; int year; Event event; if (request.getParameter("month") != null) { month = Integer.parseInt(request.getParameter("month")); String temp = request.getParameter("year_num"); year = Integer.parseInt(temp); int month_num = month - 1; event = new Event(year, month_num, 1); month_name = event.getMonthName(); year = event.getYearNumber(); if (month < 10) { sql = "SELECT * FROM event WHERE date LIKE '" + year + "-0" + month + "-%'"; } else { sql = "SELECT * FROM event WHERE date LIKE '" + year + "-" + month + "-%'"; } } else { event = new Event(); month_name = event.getMonthName(); month = event.getMonthNumber() + 1; year = event.getYearNumber(); sql = "SELECT * FROM event WHERE date LIKE '" + year + "-%" + month + "-%'"; } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); request.setAttribute("year", Integer.toString(year)); request.setAttribute("month", Integer.toString(month)); request.setAttribute("month_name", month_name); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_events.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving events from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_event")) { int id = Integer.parseInt(request.getParameter("id")); Event event = new Event(); event = event.getEvent(id); if (event != null) { request.setAttribute("event", event); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving event from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("save_event")) { String title = request.getParameter("title"); String description = request.getParameter("description"); String month = request.getParameter("month"); String day = request.getParameter("day"); String year = request.getParameter("year"); String start_time = ""; String end_time = ""; if (request.getParameter("all_day") == null) { String start_hour = request.getParameter("start_hour"); String start_minutes = request.getParameter("start_minutes"); String start_ampm = request.getParameter("start_ampm"); String end_hour = request.getParameter("end_hour"); String end_minutes = request.getParameter("end_minutes"); String end_ampm = request.getParameter("end_ampm"); if (Integer.parseInt(start_hour) < 10) { start_hour = "0" + start_hour; } if (Integer.parseInt(end_hour) < 10) { end_hour = "0" + end_hour; } start_time = start_hour + ":" + start_minutes + " " + start_ampm; end_time = end_hour + ":" + end_minutes + " " + end_ampm; } Event event = null; if (!start_time.equals("") && !end_time.equals("")) { event = new Event(title, description, month, day, year, start_time, end_time); } else { event = new Event(title, description, month, day, year); } if (event.saveEvent()) { notice = "Calendar event saved!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error saving calendar event."; request.setAttribute("notice", notice); request.setAttribute("event", event); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_event")) { String title = request.getParameter("title"); String description = request.getParameter("description"); String month = request.getParameter("month"); String day = request.getParameter("day"); String year = request.getParameter("year"); String start_time = ""; String end_time = ""; int id = Integer.parseInt(request.getParameter("id")); if (request.getParameter("all_day") == null) { String start_hour = request.getParameter("start_hour"); String start_minutes = request.getParameter("start_minutes"); String start_ampm = request.getParameter("start_ampm"); String end_hour = request.getParameter("end_hour"); String end_minutes = request.getParameter("end_minutes"); String end_ampm = request.getParameter("end_ampm"); if (Integer.parseInt(start_hour) < 10) { start_hour = "0" + start_hour; } if (Integer.parseInt(end_hour) < 10) { end_hour = "0" + end_hour; } start_time = start_hour + ":" + start_minutes + " " + start_ampm; end_time = end_hour + ":" + end_minutes + " " + end_ampm; } Event event = null; if (!start_time.equals("") && !end_time.equals("")) { event = new Event(title, description, month, day, year, start_time, end_time); } else { event = new Event(title, description, month, day, year); } if (event.updateEvent(id)) { notice = "Calendar event updated!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error updating calendar event."; request.setAttribute("notice", notice); request.setAttribute("event", event); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete_event")) { int id = Integer.parseInt(request.getParameter("id")); Event event = new Event(); if (event.deleteEvent(id)) { notice = "Calendar event successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_events"); dispatcher.forward(request, response); return; } else { notice = "Error deleting event from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_events"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_members")) { String sql = "SELECT * FROM person ORDER BY lname"; if (request.getParameter("member_type") != null) { String member_type = request.getParameter("member_type"); if (member_type.equals("all")) { sql = "SELECT * FROM person ORDER BY lname"; } else { sql = "SELECT * FROM person where member_type LIKE '" + member_type + "' ORDER BY lname"; } request.setAttribute("member_type", member_type); } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_members.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving members from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_person")) { int id = Integer.parseInt(request.getParameter("id")); String member_type = request.getParameter("member_type"); Person person = new Person(); person = person.getPerson(id); if (member_type.equals("student")) { Student student = person.getStudent(); request.setAttribute("student", student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_student.jsp"); dispatcher.forward(request, response); return; } else if (member_type.equals("alumni")) { Alumni alumni = person.getAlumni(); request.setAttribute("alumni", alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_alumni.jsp"); dispatcher.forward(request, response); return; } else if (member_type.equals("hospital")) { Hospital hospital = person.getHospital(id); request.setAttribute("hospital", hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_hospital.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_alumni")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Alumni cur_alumni = person.getAlumni(); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String company_name = request.getParameter("company_name"); String position = request.getParameter("position"); int mentor = 0; if (request.getParameter("mentor") != null) { mentor = 1; } String graduation_date = request.getParameter("graduation_year") + "-" + request.getParameter("graduation_month") + "-01"; String password = ""; if (request.getParameter("password") != null) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_alumni.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Alumni new_alumni = new Alumni(fname, lname, address1, address2, city, state, zip, email, password, is_admin, company_name, position, graduation_date, mentor); if (!new_alumni.getEmail().equals(cur_alumni.getEmail())) { if (new_alumni.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("alumni", new_alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_alumni.updateAlumni(person_id)) { session.setAttribute("alumni", new_alumni); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Member information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("update_hospital")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Hospital cur_hospital = person.getHospital(person_id); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String name = request.getParameter("name"); String phone = request.getParameter("phone"); String url = request.getParameter("url"); String password = ""; if (cur_hospital.getPassword() != null) { if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_hospital.getPassword(); } } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Hospital new_hospital = new Hospital(fname, lname, address1, address2, city, state, zip, email, password, is_admin, name, phone, url); if (!new_hospital.getEmail().equals(cur_hospital.getEmail())) { if (new_hospital.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("hospital", new_hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_hospital.updateHospital(person_id)) { session.setAttribute("hospital", new_hospital); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("update_student")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Student cur_student = person.getStudent(); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String start_date = request.getParameter("start_year") + "-" + request.getParameter("start_month") + "-01"; String graduation_date = ""; if (!request.getParameter("grad_year").equals("") && !request.getParameter("grad_month").equals("")) { graduation_date = request.getParameter("grad_year") + "-" + request.getParameter("grad_month") + "-01"; } String password = ""; if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_student.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Student new_student = new Student(fname, lname, address1, address2, city, state, zip, email, password, is_admin, start_date, graduation_date); if (!new_student.getEmail().equals(cur_student.getEmail())) { if (new_student.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("student", new_student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_student.updateStudent(person_id)) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("delete_person")) { int id = Integer.parseInt(request.getParameter("id")); String member_type = request.getParameter("member_type"); Person person = new Person(); person = person.getPerson(id); if (person.deletePerson(member_type)) { notice = person.getFname() + ' ' + person.getLname() + " successfully deleted from database."; request.setAttribute("notice", notice); person = null; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members&member_type=all"); dispatcher.forward(request, response); return; } } else if (action.equals("manage_pages")) { String sql = "SELECT * FROM pages WHERE parent_id=0 OR parent_id IN (SELECT id FROM pages WHERE title LIKE 'root')"; if (request.getParameter("id") != null) { int id = Integer.parseInt(request.getParameter("id")); sql = "SELECT * FROM pages WHERE parent_id=" + id; } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_pages.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("add_page")) { String sql = "SELECT id, title FROM pages WHERE parent_id=0 OR parent_id IN (SELECT id FROM pages WHERE title LIKE 'root')"; try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("save_page")) { String title = request.getParameter("title"); String content = request.getParameter("content"); Page page = null; if (request.getParameter("parent_id") != null) { int parent_id = Integer.parseInt(request.getParameter("parent_id")); page = new Page(title, content, parent_id); } else { page = new Page(title, content, 0); } if (page.savePage()) { notice = "Content page saved!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error saving the page."; request.setAttribute("page", page); request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_page")) { String sql = "SELECT * FROM pages WHERE parent_id=0"; int id = Integer.parseInt(request.getParameter("id")); Page page = new Page(); page = page.getPage(id); try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } if (page != null) { request.setAttribute("page", page); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving content page from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_page")) { int id = Integer.parseInt(request.getParameter("id")); String title = request.getParameter("title"); String content = request.getParameter("content"); int parent_id = 0; if (request.getParameter("parent_id") != null) { parent_id = Integer.parseInt(request.getParameter("parent_id")); } Page page = new Page(title, content, parent_id); if (page.updatePage(id)) { notice = "Content page was updated successfully."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error updating the content page."; request.setAttribute("notice", notice); request.setAttribute("page", page); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete_page")) { int id = Integer.parseInt(request.getParameter("id")); Page page = new Page(); if (page.deletePage(id)) { notice = "Content page (and sub pages) deleted successfully."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the content page(s)."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("list_residencies")) { Residency residency = new Residency(); dbResultSet = residency.getResidencies(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list_residencies.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("delete_residency")) { int job_id = Integer.parseInt(request.getParameter("id")); Residency residency = new Residency(); if (residency.deleteResidency(job_id)) { notice = "Residency has been successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_residency")) { int job_id = Integer.parseInt(request.getParameter("id")); Residency residency = new Residency(); dbResultSet = residency.getResidency(job_id); if (dbResultSet != null) { try { int hId = dbResultSet.getInt("hospital_id"); String hName = residency.getHospitalName(hId); request.setAttribute("hName", hName); dbResultSet.beforeFirst(); } catch (SQLException e) { error = "There was an error retreiving the residency."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_residency.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error in locating the residency you selected."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("new_residency")) { Residency residency = new Residency(); dbResultSet = residency.getHospitals(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_residency.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("add_residency")) { Person person = (Person) session.getAttribute("person"); if (person.isAdmin()) { String hName = request.getParameter("hName"); String title = request.getParameter("title"); String description = request.getParameter("description"); String start_month = request.getParameter("startDateMonth"); String start_day = request.getParameter("startDateDay"); String start_year = request.getParameter("startDateYear"); String start_date = start_year + start_month + start_day; String end_month = request.getParameter("endDateMonth"); String end_day = request.getParameter("endDateDay"); String end_year = request.getParameter("endDateYear"); String end_date = end_year + end_month + end_day; String deadline_month = request.getParameter("deadlineDateMonth"); String deadline_day = request.getParameter("deadlineDateDay"); String deadline_year = request.getParameter("deadlineDateYear"); String deadline_date = deadline_year + deadline_month + deadline_day; int hId = Integer.parseInt(request.getParameter("hId")); Residency residency = new Residency(title, start_date, end_date, deadline_date, description, hId); if (residency.saveResidency()) { notice = "Residency has been successfully saved."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error saving the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("update_residency")) { Person person = (Person) session.getAttribute("person"); int job_id = Integer.parseInt(request.getParameter("job_id")); if (person.isAdmin()) { String hName = request.getParameter("hName"); String title = request.getParameter("title"); String description = request.getParameter("description"); String start_month = request.getParameter("startDateMonth"); String start_day = request.getParameter("startDateDay"); String start_year = request.getParameter("startDateYear"); String start_date = start_year + start_month + start_day; String end_month = request.getParameter("endDateMonth"); String end_day = request.getParameter("endDateDay"); String end_year = request.getParameter("endDateYear"); String end_date = end_year + end_month + end_day; String deadline_month = request.getParameter("deadlineDateMonth"); String deadline_day = request.getParameter("deadlineDateDay"); String deadline_year = request.getParameter("deadlineDateYear"); String deadline_date = deadline_year + deadline_month + deadline_day; int hId = Integer.parseInt(request.getParameter("hId")); Residency residency = new Residency(job_id, title, start_date, end_date, deadline_date, description); if (residency.updateResidency(job_id)) { notice = "Residency has been successfully saved."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error saving the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("add_hospital")) { Person person = (Person) session.getAttribute("person"); if (person.isAdmin()) { String name = request.getParameter("name"); String url = request.getParameter("url"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String phone = request.getParameter("phone"); String lname = request.getParameter("name"); Hospital hospital = new Hospital(lname, address1, address2, city, state, zip, name, phone, url); if (!hospital.saveHospitalAdmin()) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=new_residency"); dispatcher.forward(request, response); return; } else { notice = "Unknown request. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Get Admin News List")) { News news = new News(); if (news.getNewsList() != null) { dbResultSet = news.getNewsList(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news list."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Get News List")) { News news = new News(); if (news.getNewsList() != null) { dbResultSet = news.getNewsList(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_list.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news list."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/gsu_fhce/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("detail")) { String id = request.getParameter("id"); News news = new News(); if (news.getNewsDetail(id) != null) { dbResultSet = news.getNewsDetail(id); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_detail.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news detail."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete")) { int id = 0; id = Integer.parseInt(request.getParameter("id")); News news = new News(); if (news.deleteNews(id)) { notice = "News successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } } else if (action.equals("edit")) { int id = Integer.parseInt(request.getParameter("id")); News news = new News(); news = news.getNews(id); if (news != null) { request.setAttribute("news", news); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_update.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving news from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Update News")) { String title = request.getParameter("title"); String date = (request.getParameter("year")) + (request.getParameter("month")) + (request.getParameter("day")); String content = request.getParameter("content"); int id = Integer.parseInt(request.getParameter("newsid")); News news = new News(title, date, content); if (news.updateNews(id)) { notice = "News successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Could not update news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } } else if (action.equals("Add News")) { String id = ""; String title = request.getParameter("title"); String date = request.getParameter("year") + "-" + request.getParameter("month") + "-" + request.getParameter("day"); String content = request.getParameter("content"); News news = new News(title, date, content); if (news.addNews()) { notice = "News successfully added."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Could not add news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("manage_mship")) { Mentor mentor = new Mentor(); dbResultSet = mentor.getMentorships(); if (dbResultSet != null) { request.setAttribute("result", dbResultSet); } else { notice = "There are no current mentorships."; request.setAttribute("notice", notice); } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list_mentorships.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("delete_mship")) { int mentorship_id = Integer.parseInt(request.getParameter("id")); Mentor mentor = new Mentor(); if (mentor.delMentorship(mentorship_id)) { notice = "Mentorship successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the mentorship."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } } else if (action.equals("new_mship")) { Mentor mentor = new Mentor(); ResultSet alumnis = null; ResultSet students = null; alumnis = mentor.getAlumnis(); students = mentor.getStudents(); request.setAttribute("alumni_result", alumnis); request.setAttribute("student_result", students); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/create_mship.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("create_mship")) { int student_id = Integer.parseInt(request.getParameter("student_id")); int alumni_id = Integer.parseInt(request.getParameter("alumni_id")); Mentor mentor = new Mentor(); if (mentor.addMentorship(student_id, alumni_id)) { notice = "Mentorship successfully created."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } else { notice = "There was an error creating the mentorship."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/create_mship.jsp"); dispatcher.forward(request, response); return; } } }
11
Code Sample 1: protected void initGame() { try { for (File fonte : files) { String absolutePath = outputDir.getAbsolutePath(); String separator = System.getProperty("file.separator"); String name = fonte.getName(); String destName = name.substring(0, name.length() - 3); File destino = new File(absolutePath + separator + destName + "jme"); FileInputStream reader = new FileInputStream(fonte); OutputStream writer = new FileOutputStream(destino); conversor.setProperty("mtllib", fonte.toURL()); conversor.convert(reader, writer); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } super.finish(); } Code Sample 2: private static void processFile(StreamDriver driver, String sourceName) throws Exception { String destName = sourceName + ".xml"; File dest = new File(destName); if (dest.exists()) { throw new IllegalArgumentException("File '" + destName + "' already exists!"); } FileChannel sourceChannel = new FileInputStream(sourceName).getChannel(); try { MappedByteBuffer sourceByteBuffer = sourceChannel.map(FileChannel.MapMode.READ_ONLY, 0, sourceChannel.size()); CharsetDecoder decoder = Charset.forName("ISO-8859-15").newDecoder(); CharBuffer sourceBuffer = decoder.decode(sourceByteBuffer); driver.generateXmlDocument(sourceBuffer, new FileOutputStream(dest)); } finally { sourceChannel.close(); } }
00
Code Sample 1: public long copyFileWithPaths(String userBaseDir, String sourcePath, String destinPath) throws Exception { if (userBaseDir.endsWith(sep)) { userBaseDir = userBaseDir.substring(0, userBaseDir.length() - sep.length()); } String file1FullPath = new String(); if (sourcePath.startsWith(sep)) { file1FullPath = new String(userBaseDir + sourcePath); } else { file1FullPath = new String(userBaseDir + sep + sourcePath); } String file2FullPath = new String(); if (destinPath.startsWith(sep)) { file2FullPath = new String(userBaseDir + destinPath); } else { file2FullPath = new String(userBaseDir + sep + destinPath); } long plussQuotaSize = 0; BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File fileordir = new File(file1FullPath); if (fileordir.exists()) { if (fileordir.isFile()) { File file2 = new File(file2FullPath); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (fileordir.isDirectory()) { String[] entryList = fileordir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String file1FullPathEntry = new String(file1FullPath.concat(entryList[pos])); String file2FullPathEntry = new String(file2FullPath.concat(entryList[pos])); File file2 = new File(file2FullPathEntry); if (file2.exists()) { plussQuotaSize -= file2.length(); file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(file1FullPathEntry), bufferSize); out = new BufferedOutputStream(new FileOutputStream(file2FullPathEntry), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } } } } else { throw new Exception("Source file or dir not exist ! file1FullPath = (" + file1FullPath + ")"); } return plussQuotaSize; } Code Sample 2: public String postDownloadRequest(String localFile) throws Exception { String responseString = ""; String requestString = ""; if (localFile == null) { error = true; errorStr = errorStr.concat("No local target for: " + currentFile.getRelativePath() + "\n"); return ""; } try { for (java.util.Iterator i = parameters.entrySet().iterator(); i.hasNext(); ) { java.util.Map.Entry e = (java.util.Map.Entry) i.next(); requestString = requestString + URLEncoder.encode((String) e.getKey(), "UTF-8") + "=" + URLEncoder.encode((String) e.getValue(), "UTF-8") + "&"; } URL url = new URL(urlString); URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Length", String.valueOf(requestString.length())); httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); connection.connect(); PrintWriter out = new PrintWriter(httpConn.getOutputStream()); out.println(requestString); out.close(); if (httpConn.HTTP_NOT_FOUND == httpConn.getResponseCode()) { error = true; errorStr = errorStr.concat("Cannot find file: " + currentFile.getRelativePath() + "\n"); return responseString; } String localFileName = new String(localFile); File f = new File(localFileName); File dir = new File(f.getParent()); dir.mkdirs(); FileOutputStream fis = new FileOutputStream(f); try { InputStream is = httpConn.getInputStream(); java.util.zip.GZIPInputStream gin = new java.util.zip.GZIPInputStream(new BufferedInputStream(is)); int temp; while ((temp = gin.read()) != -1) { fis.write(temp); } if (fis.getChannel().size() > 0) { fis.getChannel().truncate(fis.getChannel().size() - 1); } responseString = downloadDir + "/" + currentFile.getRelativePath(); is.close(); fis.close(); httpConn.disconnect(); } catch (IOException io) { error = true; errorStr = errorStr.concat("Cannot find file: " + currentFile.getRelativePath() + "\n"); return responseString; } } catch (java.net.ConnectException conne) { error = true; finished = true; errorStr = "Cannot connect to: " + urlString; } catch (java.io.InterruptedIOException e) { error = true; finished = true; errorStr = "Connection to Portal lost: communication is timeouted."; parentWorkflow.getMenuButtonEventHandler().stopAutomaticRefresh(); } catch (java.net.MalformedURLException e) { error = true; finished = true; errorStr = "Error in postDownloadRequest()"; } catch (Exception e) { e.printStackTrace(); error = true; finished = true; errorStr = "Error in Download: " + e.getMessage(); } return responseString; }
11
Code Sample 1: public static final void copyFile(File source, File destination) throws IOException { FileChannel sourceChannel = new FileInputStream(source).getChannel(); FileChannel targetChannel = new FileOutputStream(destination).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); } Code Sample 2: public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
11
Code Sample 1: private static void unpackEntry(File destinationFile, ZipInputStream zin, ZipEntry entry) throws Exception { if (!entry.isDirectory()) { createFolders(destinationFile.getParentFile()); FileOutputStream fis = new FileOutputStream(destinationFile); try { IOUtils.copy(zin, fis); } finally { zin.closeEntry(); fis.close(); } } else { createFolders(destinationFile); } } Code Sample 2: protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); }
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 File copyFile(File from, File to) throws IOException { FileOutputStream fos = new FileOutputStream(to); FileInputStream fis = new FileInputStream(from); FileChannel foc = fos.getChannel(); FileChannel fic = fis.getChannel(); foc.transferFrom(fic, 0, fic.size()); foc.close(); fic.close(); return to; }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS); String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_FULL_PREFIX) + Constants.SERVLET_FULL_PREFIX.length() + 1); boolean notScale = ClientUtils.toBoolean(req.getParameter(Constants.URL_PARAM_NOT_SCALE)); ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { String mimetype = fedoraAccess.getMimeTypeForStream(uuid, FedoraUtils.IMG_FULL_STREAM); if (mimetype == null) { mimetype = "image/jpeg"; } ImageMimeType loadFromMimeType = ImageMimeType.loadFromMimeType(mimetype); if (loadFromMimeType == ImageMimeType.JPEG || loadFromMimeType == ImageMimeType.PNG) { StringBuffer sb = new StringBuffer(); sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_FULL/content"); InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to close stream.", e); } finally { is = null; } } } } else { Image rawImg = KrameriusImageSupport.readImage(uuid, FedoraUtils.IMG_FULL_STREAM, this.fedoraAccess, 0, loadFromMimeType); BufferedImage scaled = null; if (!notScale) { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 1250, 1000); } else { scaled = KrameriusImageSupport.getSmallerImage(rawImg, 2500, 2000); } KrameriusImageSupport.writeImageToStream(scaled, "JPG", os); resp.setContentType(ImageMimeType.JPEG.getValue()); resp.setStatus(HttpURLConnection.HTTP_OK); } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to open full image.", e); } catch (XPathExpressionException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Unable to create XPath expression.", e); } finally { os.flush(); } } } Code Sample 2: public void actionPerformed(ActionEvent e) { int returnVal = chooser.showSaveDialog(jd); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String fileName = file.getPath(); String ext = StringUtil.getLowerExtension(fileName); if (!"png".equals(ext)) { fileName += ".png"; file = new File(fileName); } boolean doIt = true; if (file.exists()) { int i = JOptionPane.showConfirmDialog(jd, getMessage("warn_file_exist")); if (i != JOptionPane.YES_OPTION) doIt = false; } else if (!file.getParentFile().exists()) { doIt = file.getParentFile().mkdirs(); } if (doIt) { FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(imageURL.getPath()).getChannel(); dest = new FileOutputStream(fileName).getChannel(); src.transferTo(0, src.size(), dest); } catch (FileNotFoundException e1) { warn(jd, getMessage("err_no_source_file")); } catch (IOException e2) { warn(jd, getMessage("err_output_target")); } finally { try { if (src != null) src.close(); } catch (IOException e1) { } try { if (dest != null) dest.close(); } catch (IOException e1) { } src = null; dest = null; } } } }
11
Code Sample 1: public String getMarketInfo() { try { URL url = new URL("http://api.eve-central.com/api/evemon"); BufferedReader s = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String xml = ""; while ((line = s.readLine()) != null) { xml += line; } return xml; } catch (IOException ex) { ex.printStackTrace(); } return null; } Code Sample 2: public String readLines() { StringBuffer lines = new StringBuffer(); try { int HttpResult; URL url = new URL(address); URLConnection urlconn = url.openConnection(); urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; HttpResult = httpconn.getResponseCode(); if (HttpResult != HttpURLConnection.HTTP_OK) { System.out.println("�޷����ӵ�" + address); } else { BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream())); while (true) { String line = reader.readLine(); if (line == null) break; lines.append(line + "\r\n"); } reader.close(); } } catch (Exception e) { e.printStackTrace(); } return lines.toString(); }
11
Code Sample 1: private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
00
Code Sample 1: 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(); } } } Code Sample 2: public String doGet() throws MalformedURLException, IOException { uc = (HttpURLConnection) url.openConnection(); BufferedInputStream buffer = new BufferedInputStream(uc.getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int c; while ((c = buffer.read()) != -1) { bos.write(c); } bos.close(); headers = uc.getHeaderFields(); status = uc.getResponseCode(); return bos.toString(); }
11
Code Sample 1: 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(); } } Code Sample 2: public void transform(File inputMatrixFile, MatrixIO.Format inputFormat, File outputMatrixFile) throws IOException { FileChannel original = new FileInputStream(inputMatrixFile).getChannel(); FileChannel copy = new FileOutputStream(outputMatrixFile).getChannel(); copy.transferFrom(original, 0, original.size()); original.close(); copy.close(); }
11
Code Sample 1: public static String getSHA1Hash(String stringToHash) { String result = ""; MessageDigest md; try { md = MessageDigest.getInstance("SHA-1"); md.update(stringToHash.getBytes("utf-8")); byte[] hash = md.digest(); StringBuffer hashString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { int halfByte = (hash[i] >>> 4) & 0x0F; int twoHalves = 0; do { if ((0 <= halfByte) && (halfByte <= 9)) { hashString.append((char) ('0' + halfByte)); } else { hashString.append((char) ('a' + (halfByte - 10))); } halfByte = hash[i] & 0x0F; } while (twoHalves++ < 1); } result = hashString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } Code Sample 2: public static String getHash(String plaintext) { String hash = null; try { String text = plaintext; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes("UTF-8")); byte[] rawBytes = md.digest(); hash = new BASE64Encoder().encode(rawBytes); } catch (NoSuchAlgorithmException e) { } } catch (IOException e) { } return hash; }
00
Code Sample 1: public final void build() { if (!built_) { built_ = true; final boolean[] done = new boolean[] { false }; Runnable runnable = new Runnable() { public void run() { try { exists_ = true; URL url = getContentURL(); URLConnection cnx = url.openConnection(); cnx.connect(); lastModified_ = cnx.getLastModified(); length_ = cnx.getContentLength(); type_ = cnx.getContentType(); if (isDirectory()) { InputStream in = cnx.getInputStream(); BufferedReader nr = new BufferedReader(new InputStreamReader(in)); FuVectorString v = readList(nr); nr.close(); v.sort(); v.uniq(); list_ = v.toArray(); } } catch (Exception ex) { exists_ = false; } done[0] = true; } }; Thread t = new Thread(runnable, "VfsFileUrl connection " + getContentURL()); t.setPriority(Math.max(Thread.MIN_PRIORITY, t.getPriority() - 1)); t.start(); for (int i = 0; i < 100; i++) { if (done[0]) break; try { Thread.sleep(300L); } catch (InterruptedException ex) { } } if (!done[0]) { t.interrupt(); exists_ = false; canRead_ = false; FuLog.warning("VFS: fail to get " + url_); } } } Code Sample 2: public static PipeID getPipeIDForService(ServiceDescriptor descriptor) { PipeID id = null; URI uri = descriptor.getUri(); if (uri != null) { try { id = (PipeID) IDFactory.fromURI(uri); } catch (URISyntaxException e) { throw new RuntimeException("Error creating id for pipe " + uri, e); } } if (id == null) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { } String idToHash = descriptor.getName(); if (descriptor.getHost() != null) { idToHash += descriptor.getHost(); } md.update(idToHash.getBytes()); id = IDFactory.newPipeID(InfrastructurePeerGroupID, md.digest()); } return id; }
00
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 void processDeleteHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return; } DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (holdingBean.getId() == null) throw new IllegalArgumentException("holdingId is null"); processDeleteRelatedCompany(dbDyn, holdingBean, authSession); String sql = "delete from WM_LIST_HOLDING " + "where ID_HOLDING=? and ID_HOLDING in "; switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: String idList = authSession.getGrantedHoldingId(); sql += " (" + idList + ") "; break; default: sql += "(select z1.ID_ROAD from v$_read_list_road z1 where z1.user_login = ?)"; break; } ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, holdingBean.getId()); switch(dbDyn.getFamaly()) { case DatabaseManager.MYSQL_FAMALY: break; default: ps.setString(2, authSession.getUserLogin()); break; } int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
00
Code Sample 1: public ArrayList loadIndexes() { JSONObject job = new JSONObject(); ArrayList al = new ArrayList(); try { String req = job.put("OperationId", "1").toString(); InputStream is = null; String result = ""; JSONObject jArray = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.1.4:8080/newgenlibctxt/CarbonServlet"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("OperationId", "1")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } try { JSONObject jobres = new JSONObject(result); JSONArray jarr = jobres.getJSONArray("MobileIndexes"); for (int i = 0; i < jarr.length(); i++) { String indexname = jarr.getString(i); al.add(indexname); } } catch (JSONException e) { e.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } return al; } Code Sample 2: public void testBackup() throws Exception { masterJetty.stop(); copyFile(new File(CONF_DIR + "solrconfig-master1.xml"), new File(master.getConfDir(), "solrconfig.xml")); masterJetty = createJetty(master); masterClient = createNewSolrServer(masterJetty.getLocalPort()); for (int i = 0; i < 500; i++) index(masterClient, "id", i, "name", "name = " + i); masterClient.commit(); class BackupThread extends Thread { volatile String fail = null; public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } } ; } ; BackupThread backupThread = new BackupThread(); backupThread.start(); File dataDir = new File(master.getDataDir()); class CheckStatus extends Thread { volatile String fail = null; volatile String response = null; volatile boolean success = false; public void run() { String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_DETAILS; URL url; InputStream stream = null; try { url = new URL(masterUrl); stream = url.openStream(); response = IOUtils.toString(stream); if (response.contains("<str name=\"status\">success</str>")) { success = true; } stream.close(); } catch (Exception e) { fail = e.getMessage(); } finally { IOUtils.closeQuietly(stream); } } ; } ; int waitCnt = 0; CheckStatus checkStatus = new CheckStatus(); while (true) { checkStatus.run(); if (checkStatus.fail != null) { fail(checkStatus.fail); } if (checkStatus.success) { break; } Thread.sleep(200); if (waitCnt == 10) { fail("Backup success not detected:" + checkStatus.response); } waitCnt++; } if (backupThread.fail != null) { fail(backupThread.fail); } File[] files = dataDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { if (name.startsWith("snapshot")) { return true; } return false; } }); assertEquals(1, files.length); File snapDir = files[0]; IndexSearcher searcher = new IndexSearcher(new SimpleFSDirectory(snapDir.getAbsoluteFile(), null), true); TopDocs hits = searcher.search(new MatchAllDocsQuery(), 1); assertEquals(500, hits.totalHits); }
00
Code Sample 1: public static void writeToPetrify(TransitionSystem ts, Writer bw) throws IOException { File temp = new File("_temp"); BufferedWriter tw = new BufferedWriter(new FileWriter(temp)); BufferedReader tr = new BufferedReader(new FileReader(temp)); HashSet<ModelGraphVertex> sources = new HashSet<ModelGraphVertex>(); HashSet<ModelGraphVertex> dests = new HashSet<ModelGraphVertex>(); ArrayList transitions = ts.getEdges(); HashSet<String> events = new HashSet<String>(); for (int i = 0; i < transitions.size(); i++) { TransitionSystemEdge transition = (TransitionSystemEdge) transitions.get(i); events.add(replaceBadSymbols(transition.getIdentifier())); sources.add(transition.getSource()); dests.add(transition.getDest()); if (ts.getStateNameFlag() == TransitionSystem.ID) { tw.write("s" + transition.getSource().getId() + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write("s" + transition.getDest().getId() + "\n"); } else { tw.write(replaceBadSymbols(transition.getSource().getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getIdentifier()) + " "); tw.write(replaceBadSymbols(transition.getDest().getIdentifier()) + "\n"); } } tw.close(); bw.write(".model " + ts.getName().replaceAll(" ", "_") + "\n"); bw.write(".dummy "); Iterator it = events.iterator(); while (it.hasNext()) bw.write(it.next() + " "); bw.write("\n"); bw.write(".state graph" + "\n"); int c; while ((c = tr.read()) != -1) bw.write(c); tr.close(); temp.delete(); for (ModelGraphVertex dest : dests) { if (sources.contains(dest)) { sources.remove(dest); } } ModelGraphVertex source = sources.isEmpty() ? null : sources.iterator().next(); if (ts.getStateNameFlag() == TransitionSystem.ID) { if (!ts.hasExplicitEnd()) bw.write(".marking {s0}" + "\n"); else bw.write(".marking {s" + source.getId() + "}\n"); } else if (source != null) { bw.write(".marking {" + replaceBadSymbols(source.getIdentifier()) + "}\n"); } bw.write(".end"); } Code Sample 2: public static String getMD5(final String data) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(data.getBytes()); BigInteger bigInt = new BigInteger(1, m.digest()); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return e.getMessage(); } }
00
Code Sample 1: @Override public String entryToObject(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } } Code Sample 2: public SimpleParser(String filepath) throws Exception { this.path = filepath; InputStream is = null; try { if (this.path.indexOf("http") == 0) { URL url = new URL(this.path); is = url.openStream(); } else if (this.path.indexOf("<?xml") == 0) { is = new ByteArrayInputStream(filepath.getBytes(encoding)); } else { File f = new File(this.path); if (!f.exists()) { setError("File not found : " + this.path); } else { is = new FileInputStream(f); } } if (is != null) { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(is); doc.getDocumentElement().normalize(); } } catch (Exception ex) { Malgn.errorLog("{SimpleParser.constructor} Path:" + filepath + " " + ex.getMessage()); setError("Parser Error : " + ex.getMessage()); } finally { if (is != null) is.close(); } }
00
Code Sample 1: public static Properties addAttributes(Node node, String[] names, Properties props, LogEvent evt) throws ConfigurationException { if (props == null) props = new Properties(); try { MessageDigest md = MessageDigest.getInstance("MD5"); for (int i = 0; i < names.length; i++) { String value = addProperty(names[i], props, node, evt); if (value != null) { md.update(names[i].getBytes()); md.update(value.getBytes()); } } byte[] digest = md.digest(); evt.addMessage("digest " + ISOUtil.hexString(digest)); props.put(DIGEST_PROPERTY, digest); } catch (NoSuchAlgorithmException e) { throw new ConfigurationException(e); } return props; } Code Sample 2: public static BufferedImage readDicom(final URL url, final SourceImage src) { assert url != null; assert src != null; BufferedImage bi = null; try { DicomInputStream dis = new DicomInputStream(new BufferedInputStream(url.openStream())); src.read(dis); dis.close(); bi = src.getBufferedImage(); } catch (Exception exc) { System.out.println("ImageFactory::readDicom(): exc=" + exc); } return bi; }
11
Code Sample 1: @SuppressWarnings("finally") private void decompress(final File src) throws IOException { final String srcPath = src.getPath(); checkSourceFile(src); final boolean test = this.switches.contains(Switch.test); final File dst; if (test) dst = File.createTempFile("jaxlib-bzip", null); else { if (srcPath.endsWith(".bz2")) dst = new File(srcPath.substring(0, srcPath.length() - 4)); else { this.log.println("WARNING: Can't guess original name, using extension \".out\":").println(srcPath); dst = new File(srcPath + ".out"); } } if (!checkDestFile(dst)) return; final boolean showProgress = this.switches.contains(Switch.showProgress); BZip2InputStream in = null; FileOutputStream out = null; FileChannel outChannel = null; FileLock inLock = null; FileLock outLock = null; try { final FileInputStream in0 = new FileInputStream(src); final FileChannel inChannel = in0.getChannel(); final long inSize = inChannel.size(); inLock = inChannel.tryLock(0, inSize, true); if (inLock == null) throw error("source file locked by another process: " + src); in = new BZip2InputStream(new BufferedXInputStream(in0, 8192)); out = new FileOutputStream(dst); outChannel = out.getChannel(); outLock = outChannel.tryLock(); if (outLock == null) throw error("destination file locked by another process: " + dst); if (showProgress || this.verbose) { this.log.print("source: " + src).print(": size=").println(inSize); this.log.println("target: " + dst); } long pos = 0; int progress = 0; final long maxStep = showProgress ? Math.max(8192, inSize / MAX_PROGRESS) : Integer.MAX_VALUE; while (true) { final long step = outChannel.transferFrom(in, pos, maxStep); if (step <= 0) { final long a = inChannel.size(); if (a != inSize) throw error("file " + src + " has been modified concurrently by another process"); if (inChannel.position() >= inSize) { if (showProgress) { for (int i = progress; i < MAX_PROGRESS; i++) this.log.print('#'); this.log.println(" done"); } break; } } else { pos += step; if (showProgress) { final double p = (double) inChannel.position() / (double) inSize; final int newProgress = (int) (MAX_PROGRESS * p); for (int i = progress; i < newProgress; i++) this.log.print('#'); progress = newProgress; } } } final long outSize = outChannel.size(); in.close(); out.close(); if (this.verbose) { final double ratio = (outSize == 0) ? (inSize * 100) : ((double) inSize / (double) outSize); this.log.print("compressed size: ").print(inSize) .print("; decompressed size: ").print(outSize) .print("; compression ratio: ").print(ratio).println('%'); } if (!test && !this.switches.contains(Switch.keep)) { if (!src.delete()) throw error("unable to delete sourcefile: " + src); } if (test && !dst.delete()) throw error("unable to delete testfile: " + dst); } catch (final IOException ex) { IO.tryClose(in); IO.tryClose(out); IO.tryRelease(inLock); IO.tryRelease(outLock); try { this.log.println(); } finally { throw ex; } } } Code Sample 2: public void zipFile(String baseDir, String fileName, boolean encrypt) throws Exception { List fileList = getSubFiles(new File(baseDir)); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName + ".temp")); ZipEntry ze = null; byte[] buf = new byte[BUFFER]; byte[] encrypByte = new byte[encrypLength]; int readLen = 0; for (int i = 0; i < fileList.size(); i++) { if (stopZipFile) { zos.close(); File zipFile = new File(fileName + ".temp"); if (zipFile.exists()) zipFile.delete(); break; } File f = (File) fileList.get(i); if (f.getAbsoluteFile().equals(fileName + ".temp")) continue; ze = new ZipEntry(getAbsFileName(baseDir, f)); ze.setSize(f.length()); ze.setTime(f.lastModified()); zos.putNextEntry(ze); InputStream is = new BufferedInputStream(new FileInputStream(f)); readLen = is.read(buf, 0, BUFFER); if (encrypt) { if (readLen >= encrypLength) { System.arraycopy(buf, 0, encrypByte, 0, encrypLength); } else if (readLen > 0) { Arrays.fill(encrypByte, (byte) 0); System.arraycopy(buf, 0, encrypByte, 0, readLen); readLen = encrypLength; } byte[] temp = CryptionControl.getInstance().encryptoECB(encrypByte, rootKey); System.arraycopy(temp, 0, buf, 0, encrypLength); } while (readLen != -1) { zos.write(buf, 0, readLen); readLen = is.read(buf, 0, BUFFER); } is.close(); } zos.close(); File zipFile = new File(fileName + ".temp"); if (zipFile.exists()) zipFile.renameTo(new File(fileName + ".zip")); }
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 MultiValueMap<String> queryResource(String resourceName) { if (resourceName.startsWith("http://dbpedia.org/resource/")) { resourceName = resourceName.substring(28); } try { resourceName = resourceName.replace(' ', '_'); resourceName = URLEncoder.encode(resourceName, "UTF-8"); } catch (UnsupportedEncodingException exc) { } String select = prefix + " SELECT ?property ?hasValue WHERE { { " + "<http://dbpedia.org/resource/" + resourceName + "> ?property ?hasValue } FILTER (lang(?hasValue) = \"" + lang + "\" || !isLiteral(?hasValue))}"; System.out.println(select); MultiValueMap<String> resourceMap = new MultiValueMap<String>(); try { URL url = new URL(queryBase + URLEncoder.encode(select, "UTF-8")); InputStream inStream = url.openStream(); Document doc = docBuild.parse(inStream); Element table = doc.getDocumentElement(); NodeList rows = table.getElementsByTagName("tr"); for (int i = 0; i < rows.getLength(); i++) { Element row = (Element) rows.item(i); NodeList cols = row.getElementsByTagName("td"); if (cols.getLength() > 1) { Element propElem = (Element) cols.item(0); Element valElem = (Element) cols.item(1); String property = ((Text) propElem.getFirstChild()).getData(); if (property.startsWith("http://dbpedia.org/property/")) { property = property.substring(28); } else { int inx = property.indexOf('#'); if (inx == -1) { inx = property.lastIndexOf('/'); } property = property.substring(inx + 1); } String value = ((Text) valElem.getFirstChild()).getData(); if (value.startsWith("http://dbpedia.org/resource/")) { value = value.substring(28).replaceAll("_", " "); } resourceMap.addFieldValue(property, value); } } } catch (UnsupportedEncodingException exc) { exc.printStackTrace(); } catch (IOException exc) { System.err.println("Cannot retrieve record for " + resourceName); } catch (SAXException exc) { System.err.println("Cannot parse record for " + resourceName); } return resourceMap; }
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: String chooseHGVersion(String version) { String line = ""; try { URL connectURL = new URL("http://genome.ucsc.edu/cgi-bin/hgGateway?db=" + version); InputStream urlStream = connectURL.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream)); while ((line = reader.readLine()) != null) { if (line.indexOf("hgsid") != -1) { line = line.substring(line.indexOf("hgsid")); line = line.substring(line.indexOf("VALUE=\"") + 7); line = line.substring(0, line.indexOf("\"")); return line; } } } catch (Exception e) { e.printStackTrace(); } return line; }
00
Code Sample 1: public void manageRequest(Transformer transformer) throws ServletException { try { this.parser.reset(); String encodedQuery = URLEncoder.encode(this.query, "ISO-8859-1"); URL url = new URL(EXIST_SERVER + "?_query=" + encodedQuery); InputStream in = url.openStream(); Document doc = this.parser.parse(in); Source source = new DOMSource(doc); transformer.transform(source, new StreamResult(this.getOut())); } catch (TransformerException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } Code Sample 2: public static String readRss(String feed, int num) { InputStream stream = null; try { feed = appendParam(feed, "num", "" + num); System.out.println("feed=" + feed); URL url = new URL(feed); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", RSS_USER_AGENT); stream = connection.getInputStream(); return CFileHelper.readInputStream(stream); } catch (Exception e) { throw new CException(e); } finally { CFileHelper.closeStream(stream); } }
00
Code Sample 1: static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public 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 String getHashedStringMD5(String value) throws java.security.NoSuchAlgorithmException { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(value.getBytes()); byte[] buf = d.digest(); return new String(buf); } Code Sample 2: public 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) { } String randVal = "" + new Random().nextInt(); String val = timeVal + localHost + randVal; md.reset(); md.update(val.getBytes()); digest = toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { } return digest; }
11
Code Sample 1: public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } } Code Sample 2: public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
11
Code Sample 1: public static void main(String[] args) { JFileChooser askDir = new JFileChooser(); askDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); askDir.setMultiSelectionEnabled(false); int returnVal = askDir.showOpenDialog(null); if (returnVal == JFileChooser.CANCEL_OPTION) { System.exit(returnVal); } File startDir = askDir.getSelectedFile(); ArrayList<File> files = new ArrayList<File>(); goThrough(startDir, files); SearchClient client = new SearchClient("VZFo5W5i"); MyID3 singleton = new MyID3(); for (File song : files) { try { MusicMetadataSet set = singleton.read(song); IMusicMetadata meta = set.getSimplified(); String qu = song.getName(); if (meta.getAlbum() != null) { qu = meta.getAlbum(); } else if (meta.getArtist() != null) { qu = meta.getArtist(); } if (qu.length() > 2) { ImageSearchRequest req = new ImageSearchRequest(qu); ImageSearchResults res = client.imageSearch(req); if (res.getTotalResultsAvailable().doubleValue() > 1) { System.out.println("Downloading " + res.listResults()[0].getUrl()); URL url = new URL(res.listResults()[0].getUrl()); URLConnection con = url.openConnection(); con.setConnectTimeout(10000); int realSize = con.getContentLength(); if (realSize > 0) { String mime = con.getContentType(); InputStream stream = con.getInputStream(); byte[] realData = new byte[realSize]; for (int i = 0; i < realSize; i++) { stream.read(realData, i, 1); } stream.close(); ImageData imgData = new ImageData(realData, mime, qu, 0); meta.addPicture(imgData); File temp = File.createTempFile("tempsong", "mp3"); singleton.write(song, temp, set, meta); FileChannel inChannel = new FileInputStream(temp).getChannel(); FileChannel outChannel = new FileOutputStream(song).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } temp.delete(); } } } } catch (ID3ReadException e) { } catch (MalformedURLException e) { } catch (UnsupportedEncodingException e) { } catch (ID3WriteException e) { } catch (IOException e) { } catch (SearchException e) { } } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
00
Code Sample 1: public static void copy(File src, File dest) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException 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 copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } } Code Sample 2: public void run() { if (currentNode == null || currentNode.equals("")) { JOptionPane.showMessageDialog(null, "Please select a genome to download first", "Error", JOptionPane.ERROR_MESSAGE); return; } String localFile = parameter.getTemporaryFilesPath() + currentNode; String remotePath = NCBI_FTP_PATH + currentPath; String remoteFile = remotePath + "/" + currentNode; try { ftp.connect(NCBI_FTP_HOST); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); JOptionPane.showMessageDialog(null, "FTP server refused connection", "Error", JOptionPane.ERROR_MESSAGE); } ftp.login("anonymous", "anonymous@big.ac.cn"); inProgress = true; ftp.setFileType(FTPClient.BINARY_FILE_TYPE); long size = getFileSize(remotePath, currentNode); if (size == -1) throw new FileNotFoundException(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(localFile)); BufferedInputStream in = new BufferedInputStream(ftp.retrieveFileStream(remoteFile), ftp.getBufferSize()); byte[] b = new byte[1024]; long bytesTransferred = 0; int tick = 0; int oldTick = 0; int len; while ((len = in.read(b)) != -1) { out.write(b, 0, len); bytesTransferred += 1024; if ((tick = new Long(bytesTransferred * 100 / size).intValue()) > oldTick) { progressBar.setValue(tick < 100 ? tick : 99); oldTick = tick; } } in.close(); out.close(); ftp.completePendingCommand(); progressBar.setValue(100); fileDownloaded = localFile; JOptionPane.showMessageDialog(null, "File successfully downloaded", "Congratulation!", JOptionPane.INFORMATION_MESSAGE); ftp.logout(); } catch (SocketException ex) { JOptionPane.showMessageDialog(null, "Error occurs while trying to connect server", "Error", JOptionPane.ERROR_MESSAGE); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "This file is not found on the server", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Error occurs while fetching data", "Error", JOptionPane.ERROR_MESSAGE); } finally { inProgress = false; if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } }
00
Code Sample 1: @Override public void run() { try { if (!Util.isSufficienDataForUpload(recordedGeoPoints)) return; final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes()); final HttpClient httpClient = new DefaultHttpClient(); final HttpPost request = new HttpPost(UPLOADSCRIPT_URL); final MultipartEntity requestEntity = new MultipartEntity(); requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx")); httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false); request.setEntity(requestEntity); final HttpResponse response = httpClient.execute(request); final int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { logger.error("GPXUploader", "status != HttpStatus.SC_OK"); } else { final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent())); final char[] buf = new char[8 * 1024]; int read; final StringBuilder sb = new StringBuilder(); while ((read = r.read(buf)) != -1) sb.append(buf, 0, read); logger.debug("GPXUploader", "Response: " + sb.toString()); } } catch (final Exception e) { } } Code Sample 2: public static String encryptPasswd(String pass) { try { if (pass == null || pass.length() == 0) return pass; MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(pass.getBytes("UTF-8")); return Base64OutputStream.encode(sha.digest()); } catch (Throwable t) { throw new SystemException(t); } }
00
Code Sample 1: private StringBuffer hashPassword(StringBuffer password, String mode) { MessageDigest m = null; StringBuffer hash = new StringBuffer(); try { m = MessageDigest.getInstance(mode); m.update(password.toString().getBytes("UTF8")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] digest = m.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(digest[i]); if (hex.length() == 1) hex = "0" + hex; hex = hex.substring(hex.length() - 2); hash.append(hex); } return hash; } Code Sample 2: public String accessURL_Post(String url, String postStr, String encoding) throws Throwable { StringEntity entity = new StringEntity(postStr, encoding); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); HttpResponse response = client.execute(httpPost); String entuity = EntityUtils.toString(response.getEntity()); handleHeaders(response.getAllHeaders()); return entuity; }
00
Code Sample 1: public void saveToPackage() { boolean inPackage = false; String className = IconEditor.className; if (!checkPackage()) { JOptionPane.showMessageDialog(this, "No package selected. Aborting.", "Package not selected!", JOptionPane.WARNING_MESSAGE); return; } File iconFile = new File(getPackageFile().getParent() + File.separator + classIcon); File prevIconFile = new File(prevPackagePath + File.separator + classIcon); if ((IconEditor.getClassIcon() == null) || !prevIconFile.exists()) { IconEditor.setClassIcon("default.gif"); } else if (prevIconFile.exists() && (prevIconFile.compareTo(iconFile) != 0)) { FileFuncs.copyImageFile(prevIconFile, iconFile); } ci = new ClassImport(getPackageFile(), packageClassNamesList, packageClassList); for (int i = 0; i < packageClassList.size(); i++) { if (IconEditor.className.equalsIgnoreCase(packageClassList.get(i).getName())) { inPackage = true; classX = 0 - classX; classY = 0 - classY; shapeList.shift(classX, classY); packageClassList.get(i).setBoundingbox(boundingbox); packageClassList.get(i).setDescription(IconEditor.classDescription); if (IconEditor.getClassIcon() == null) { packageClassList.get(i).setIconName("default.gif"); } else { packageClassList.get(i).setIconName(IconEditor.getClassIcon()); } packageClassList.get(i).setIsRelation(IconEditor.classIsRelation); packageClassList.get(i).setName(IconEditor.className); packageClassList.get(i).setPorts(ports); packageClassList.get(i).shiftPorts(classX, classY); packageClassList.get(i).setShapeList(shapeList); if (dbrClassFields != null && dbrClassFields.getRowCount() > 0) { fields.clear(); for (int j = 0; j < dbrClassFields.getRowCount(); j++) { String fieldName = dbrClassFields.getValueAt(j, iNAME); String fieldType = dbrClassFields.getValueAt(j, iTYPE); String fieldValue = dbrClassFields.getValueAt(j, iVALUE); ClassField field = new ClassField(fieldName, fieldType, fieldValue); fields.add(field); } } packageClassList.get(i).setFields(fields); packageClassList.add(packageClassList.get(i)); packageClassList.remove(i); break; } } try { BufferedReader in = new BufferedReader(new FileReader(getPackageFile())); String str; StringBuffer content = new StringBuffer(); while ((str = in.readLine()) != null) { if (inPackage && str.trim().startsWith("<class")) { break; } else if (!inPackage) { if (str.equalsIgnoreCase("</package>")) break; content.append(str + "\n"); } else if (inPackage) content.append(str + "\n"); } if (!inPackage) { content.append(getShapesInXML(false)); } else { for (int i = 0; i < packageClassList.size(); i++) { classX = 0; classY = 0; makeClass(packageClassList.get(i)); content.append(getShapesInXML(false)); } } content.append("</package>"); in.close(); File javaFile = new File(getPackageFile().getParent() + File.separator + className + ".java"); File prevJavaFile = new File(prevPackagePath + File.separator + className + ".java"); int overwriteFile = JOptionPane.YES_OPTION; if (javaFile.exists()) { overwriteFile = JOptionPane.showConfirmDialog(null, "Java class already exists. Overwrite?"); } if (overwriteFile != JOptionPane.CANCEL_OPTION) { FileOutputStream out = new FileOutputStream(new File(getPackageFile().getAbsolutePath())); out.write(content.toString().getBytes()); out.flush(); out.close(); if (overwriteFile == JOptionPane.YES_OPTION) { String fileText = null; if (prevJavaFile.exists()) { fileText = FileFuncs.getFileContents(prevJavaFile); } else { fileText = "class " + className + " {"; fileText += "\n /*@ specification " + className + " {\n"; for (int i = 0; i < dbrClassFields.getRowCount(); i++) { String fieldName = dbrClassFields.getValueAt(i, iNAME); String fieldType = dbrClassFields.getValueAt(i, iTYPE); if (fieldType != null) { fileText += " " + fieldType + " " + fieldName + ";\n"; } } fileText += " }@*/\n \n}"; } FileFuncs.writeFile(javaFile, fileText); } JOptionPane.showMessageDialog(null, "Saved to package: " + getPackageFile().getName(), "Saved", JOptionPane.INFORMATION_MESSAGE); } } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static String machineInfo() { StringBuilder machineInfo = new StringBuilder(); try { Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement(); if ("eth0".equals(networkInterface.getDisplayName())) { for (byte b : networkInterface.getHardwareAddress()) { StringTools.appendWithDelimiter(machineInfo, String.format("%02x", b).toUpperCase(), ":"); } machineInfo.append("\n"); break; } } } catch (IOException x) { System.out.println("LicenseTools.machineInfo: " + x.getMessage()); x.printStackTrace(); } if (machineInfo.length() == 0) { return null; } String info = machineInfo.toString(); try { MessageDigest messageDigest = MessageDigest.getInstance("MD5", "SUN"); messageDigest.update(info.getBytes()); byte[] md5 = messageDigest.digest(info.getBytes()); return new String(Base64.encodeBase64(md5)); } catch (Exception x) { System.out.println("LicenseTools.machineInfo: " + x.getMessage()); x.printStackTrace(); } return null; }