List of usage examples for java.util.zip ZipOutputStream flush
public void flush() throws IOException
From source file:org.exoplatform.services.jcr.ext.artifact.ArtifactManagingServiceImpl.java
private void mapRepositoryToZipStream(Node parentNode, ZipOutputStream zout) throws RepositoryException, IOException { NodeIterator folderIterator = parentNode.getNodes(); while (folderIterator.hasNext()) { Node folder = folderIterator.nextNode(); if (folder.isNodeType("exo:artifact")) { String entryName = parentNode.getPath() + File.separator + folder.getName(); ZipEntry entry = new ZipEntry(entryName + "/"); zout.putNextEntry(entry);/*w w w . j a va 2s .c om*/ mapRepositoryToZipStream(folder, zout); } else if (folder.isNodeType("exo:file")) { String entryName = parentNode.getPath() + File.separator + folder.getName(); ZipEntry entry = new ZipEntry(entryName); if (LOG.isDebugEnabled()) { LOG.debug("Zipping " + entryName); } Node dataNode = folder.getNode("jcr:content"); Property data = dataNode.getProperty("jcr:data"); InputStream in = data.getStream(); Property lastModified = dataNode.getProperty("jcr:lastModified"); entry.setTime(lastModified.getLong()); entry.setSize(in.available()); zout.putNextEntry(entry); int count; byte[] buf = new byte[BUFFER]; while ((count = in.read(buf, 0, BUFFER)) != -1) { zout.write(buf, 0, count); } zout.flush(); in.close(); } } }
From source file:org.sakaiproject.assignment.impl.AssignmentServiceTest.java
protected void zipWithFlushing(boolean flushing) { String assignmentTitle = "Test Assignment Title"; try {//from w w w.ja v a 2s .c o m ZipOutputStream out = new ZipOutputStream(new ByteArrayOutputStream()); // create the folder structor - named after the assignment's title String root = assignmentTitle + Entity.SEPARATOR; // submission text of size 2KB String submittedText = generateBigTestString(2); // Create the ZIP file String submittersName = ""; for (int count = 0; count < userNumber; count++) { submittersName = root; String submittersString = "test user " + count; if (StringUtil.trimToNull(submittersString) != null) { submittersName = submittersName.concat(StringUtil.trimToNull(submittersString)); try { submittersName = submittersName.concat("/"); // create the folder structure - named after the submitter's name // create the text file only when a text submission is allowed String entryName = submittersName + submittersString + "_submissionText.html"; ZipEntry textEntry = new ZipEntry(entryName); out.putNextEntry(textEntry); out.write(submittedText.getBytes()); out.closeEntry(); // create the attachment file(s) // buffered stream input InputStream content = new ByteArrayInputStream(bigAttachmentContentString.getBytes()); byte data[] = new byte[1024 * 10]; BufferedInputStream bContent = new BufferedInputStream(content, data.length); ZipEntry attachmentEntry = new ZipEntry(submittersName + "Test Attachment"); out.putNextEntry(attachmentEntry); int bCount = -1; while ((bCount = bContent.read(data, 0, data.length)) != -1) { out.write(data, 0, bCount); } out.closeEntry(); content.close(); // flush or not if (flushing) { out.flush(); } } catch (IOException e) { log.debug(this + ": --IOException: Problem in creating the attachment file: submittersName=" + submittersName + " attachment reference=" + attachmentReference); } } } // for // clean up out.finish(); out.close(); } catch (IOException e) { log.debug(this + ": --IOException unable to create the zip file for assignment " + assignmentTitle); } }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override/* w w w . j a va2 s . c om*/ public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { ExceptionHandler.initialize(context); if (ExceptionHandler.needReport()) { final String fileName = ExceptionHandler.getBugReportFileAbsolutePath(); final File file = new File(fileName); final File fileZip; { String strFileZip = file.getAbsolutePath(); { int index = strFileZip.lastIndexOf('.'); if (0 < index) { strFileZip = strFileZip.substring(0, index); strFileZip += ".zip"; } } Log.d(TAG, strFileZip); fileZip = new File(strFileZip); if (fileZip.exists()) { fileZip.delete(); } } if (file.exists()) { Log.d(TAG, file.getAbsolutePath()); InputStream inStream = null; ZipOutputStream outStream = null; try { inStream = new FileInputStream(file); String strFileName = file.getAbsolutePath(); { int index = strFileName.lastIndexOf(File.separatorChar); if (0 < index) { strFileName = strFileName.substring(index + 1); } } Log.d(TAG, strFileName); outStream = new ZipOutputStream(new FileOutputStream(fileZip)); byte[] buff = new byte[8124]; { ZipEntry entry = new ZipEntry(strFileName); outStream.putNextEntry(entry); int len = 0; while (0 < (len = inStream.read(buff))) { outStream.write(buff, 0, len); } outStream.closeEntry(); } outStream.finish(); outStream.flush(); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != outStream) { try { outStream.close(); } catch (Exception e) { } } outStream = null; if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } Log.i(TAG, "zip created"); } if (file.exists()) { // upload or send e-mail InputStream inStream = null; StringBuilder sb = new StringBuilder(); try { inStream = new FileInputStream(file); byte[] buff = new byte[8124]; int readed = 0; do { readed = inStream.read(buff); for (int i = 0; i < readed; i++) { sb.append((char) buff[i]); } } while (readed >= 0); final String str = sb.toString(); Log.i(TAG, str); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if (null != defaultLocale) { if (defaultLocale.equals(Locale.JAPANESE) || defaultLocale.equals(Locale.JAPAN)) { title = ""; message = "?????????"; positive = "?"; negative = ""; needDefaultLang = false; } } if (needDefaultLang) { title = "ERROR"; message = "Got unexpected error. Do you want to send information of error."; positive = "Send"; negative = "Cancel"; } alertDialog.setTitle(title); alertDialog.setMessage(message); alertDialog.setPositiveButton(positive + " mail", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderMailClient.upload(context, file, new String[] { "diverKon+sakura@gmail.com" }); } }); alertDialog.setNeutralButton(positive + " http", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderWeb.upload(ExceptionHandlerReportApp.this, fileZip, "http://kkkon.sakura.ne.jp/android/bug"); } }); alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { ExceptionHandler.clearReport(); } }); alertDialog.show(); } // TODO separate activity for crash report //DefaultCheckerAPK.checkAPK( this, null ); } ExceptionHandler.registHandler(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("ExceptionHandler"); layout.addView(tv); Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); Button btn2 = new Button(this); btn2.setText("reinstall apk"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); if (fileApk.exists()) { foundApk = true; Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); } } if (false == foundApk) { for (int i = 0; i < 10; ++i) { File fileApk = new File("/data/app/" + context.getPackageName() + "-" + i + ".apk"); Log.d(TAG, "check apk:" + fileApk.getAbsolutePath()); if (fileApk.exists()) { Log.i(TAG, "apk found. path=" + fileApk.getAbsolutePath()); /* * // require parmission { final String strCmd = "pm install -r " + fileApk.getAbsolutePath(); try { Runtime.getRuntime().exec( strCmd ); } catch ( IOException e ) { Log.e( TAG, "got exception", e ); } } */ Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); break; } } } } }); layout.addView(btn2); Button btn3 = new Button(this); btn3.setText("check apk"); btn3.setOnClickListener(new View.OnClickListener() { private boolean checkApk(final File fileApk, final ZipEntryFilter filter) { final boolean[] result = new boolean[1]; result[0] = true; final Thread thread = new Thread(new Runnable() { @Override public void run() { if (fileApk.exists()) { ZipFile zipFile = null; try { zipFile = new ZipFile(fileApk); List<ZipEntry> list = new ArrayList<ZipEntry>(zipFile.size()); for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { ZipEntry ent = e.nextElement(); Log.d(TAG, ent.getName()); Log.d(TAG, "" + ent.getSize()); final boolean accept = filter.accept(ent); if (accept) { list.add(ent); } } Log.d(TAG, Build.CPU_ABI); // API 4 Log.d(TAG, Build.CPU_ABI2); // API 8 final String[] abiArray = { Build.CPU_ABI // API 4 , Build.CPU_ABI2 // API 8 }; String abiMatched = null; { boolean foundMatched = false; for (final String abi : abiArray) { if (null == abi) { continue; } if (0 == abi.length()) { continue; } for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abi + "/"; if (entry.getName().startsWith(prefixABI)) { abiMatched = abi; foundMatched = true; break; } } if (foundMatched) { break; } } } Log.d(TAG, "matchedAbi=" + abiMatched); if (null != abiMatched) { boolean needReInstall = false; for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abiMatched + "/"; if (entry.getName().startsWith(prefixABI)) { final String jniName = entry.getName().substring(prefixABI.length()); Log.d(TAG, "jni=" + jniName); final String strFileDst = context.getApplicationInfo().nativeLibraryDir + "/" + jniName; Log.d(TAG, strFileDst); final File fileDst = new File(strFileDst); if (!fileDst.exists()) { Log.w(TAG, "needReInstall: content missing " + strFileDst); needReInstall = true; } else { assert (entry.getSize() <= Integer.MAX_VALUE); if (fileDst.length() != entry.getSize()) { Log.w(TAG, "needReInstall: size broken " + strFileDst); needReInstall = true; } else { //org.apache.commons.io.IOUtils.contentEquals( zipFile.getInputStream( entry ), new FileInputStream(fileDst) ); final int size = (int) entry.getSize(); byte[] buffSrc = new byte[size]; { InputStream inStream = null; try { inStream = zipFile.getInputStream(entry); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffSrc, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } byte[] buffDst = new byte[(int) fileDst.length()]; { InputStream inStream = null; try { inStream = new FileInputStream(fileDst); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffDst, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } if (Arrays.equals(buffSrc, buffDst)) { Log.d(TAG, " content equal " + strFileDst); // OK } else { Log.w(TAG, "needReInstall: content broken " + strFileDst); needReInstall = true; } } } } } // for ZipEntry if (needReInstall) { // need call INSTALL APK Log.w(TAG, "needReInstall apk"); result[0] = false; } else { Log.d(TAG, "no need ReInstall apk"); } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != zipFile) { try { zipFile.close(); } catch (Exception e) { } } } } } }); thread.setName("check jni so"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "check thread.id=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now checking installation. Cancel check?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ try { thread.join(); } catch (InterruptedException e) { Log.d(TAG, "got exception", e); } return result[0]; } @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); this.checkApk(fileApk, new ZipEntryFilter() { @Override public boolean accept(ZipEntry entry) { if (entry.isDirectory()) { return false; } final String filename = entry.getName(); if (filename.startsWith("lib/")) { return true; } return false; } }); } } }); layout.addView(btn3); Button btn4 = new Button(this); btn4.setText("print dir and path"); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { { final File file = context.getCacheDir(); Log.d(TAG, "Ctx.CacheDir=" + file.getAbsoluteFile()); } { final File file = context.getExternalCacheDir(); // API 8 if (null == file) { // no permission Log.d(TAG, "Ctx.ExternalCacheDir="); } else { Log.d(TAG, "Ctx.ExternalCacheDir=" + file.getAbsolutePath()); } } { final File file = context.getFilesDir(); Log.d(TAG, "Ctx.FilesDir=" + file.getAbsolutePath()); } { final String value = context.getPackageResourcePath(); Log.d(TAG, "Ctx.PackageResourcePath=" + value); } { final String[] files = context.fileList(); if (null == files) { Log.d(TAG, "Ctx.fileList=" + files); } else { for (final String filename : files) { Log.d(TAG, "Ctx.fileList=" + filename); } } } { final File file = Environment.getDataDirectory(); Log.d(TAG, "Env.DataDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getDownloadCacheDirectory(); Log.d(TAG, "Env.DownloadCacheDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getExternalStorageDirectory(); Log.d(TAG, "Env.ExternalStorageDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getRootDirectory(); Log.d(TAG, "Env.RootDirectory=" + file.getAbsolutePath()); } { final ApplicationInfo appInfo = context.getApplicationInfo(); Log.d(TAG, "AppInfo.dataDir=" + appInfo.dataDir); Log.d(TAG, "AppInfo.nativeLibraryDir=" + appInfo.nativeLibraryDir); // API 9 Log.d(TAG, "AppInfo.publicSourceDir=" + appInfo.publicSourceDir); { final String[] sharedLibraryFiles = appInfo.sharedLibraryFiles; if (null == sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + sharedLibraryFiles); } else { for (final String fileName : sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + fileName); } } } Log.d(TAG, "AppInfo.sourceDir=" + appInfo.sourceDir); } { Log.d(TAG, "System.Properties start"); final Properties properties = System.getProperties(); if (null != properties) { for (final Object key : properties.keySet()) { String value = properties.getProperty((String) key); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.Properties end"); } { Log.d(TAG, "System.getenv start"); final Map<String, String> mapEnv = System.getenv(); if (null != mapEnv) { for (final Map.Entry<String, String> entry : mapEnv.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.getenv end"); } } }); layout.addView(btn4); Button btn5 = new Button(this); btn5.setText("check INSTALL_NON_MARKET_APPS"); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SettingsCompat.initialize(context); if (SettingsCompat.isAllowedNonMarketApps()) { Log.d(TAG, "isAllowdNonMarketApps=true"); } else { Log.d(TAG, "isAllowdNonMarketApps=false"); } } }); layout.addView(btn5); Button btn6 = new Button(this); btn6.setText("send email"); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent mailto = new Intent(); mailto.setAction(Intent.ACTION_SENDTO); mailto.setType("message/rfc822"); mailto.setData(Uri.parse("mailto:")); mailto.putExtra(Intent.EXTRA_EMAIL, new String[] { "" }); mailto.putExtra(Intent.EXTRA_SUBJECT, "[BugReport] " + context.getPackageName()); mailto.putExtra(Intent.EXTRA_TEXT, "body text"); //mailto.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); //context.startActivity( mailto ); Intent intent = Intent.createChooser(mailto, "Send Email"); if (null != intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { Log.d(TAG, "got Exception", e); } } } }); layout.addView(btn6); Button btn7 = new Button(this); btn7.setText("upload http thread"); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "brd=" + Build.BRAND); Log.d(TAG, "prd=" + Build.PRODUCT); //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); final Thread thread = new Thread(new Runnable() { @Override public void run() { Log.d(TAG, "upload thread tid=" + android.os.Process.myTid()); try { HttpPost httpPost = new HttpPost("http://kkkon.sakura.ne.jp/android/bug"); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); } Log.d(TAG, "upload finish"); } }); thread.setName("upload crash"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now uploading error information. Cancel upload?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ /* try { thread.join(); // must call. leak handle... } catch ( InterruptedException e ) { Log.d( TAG, "got Exception", e ); } */ } }); layout.addView(btn7); Button btn8 = new Button(this); btn8.setText("upload http AsyncTask"); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn8); Button btn9 = new Button(this); btn9.setText("call checkAPK"); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean result = DefaultCheckerAPK.checkAPK(ExceptionHandlerReportApp.this, null); Log.i(TAG, "checkAPK result=" + result); } }); layout.addView(btn9); setContentView(layout); }
From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java
/** * fetch data from a given url./* w w w .ja v a2s .c o m*/ * * @param url * @return byte[] * @throws SourceNotAvailableException * @throws RuntimeException * @throws AccessException */ public byte[] fetchMetadatafromURL(URL url) throws SourceNotAvailableException, RuntimeException, AccessException { byte[] input = null; URLConnection conn = null; Date retryAfter = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); try { conn = ProxyHelper.openConnection(url); HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 503: String retryAfterHeader = conn.getHeaderField("Retry-After"); if (retryAfterHeader != null) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); retryAfter = dateFormat.parse(retryAfterHeader); this.logger.debug("Source responded with 503, retry after " + retryAfter + "."); throw new SourceNotAvailableException(retryAfter); } break; case 302: String alternativeLocation = conn.getHeaderField("Location"); return fetchMetadatafromURL(new URL(alternativeLocation)); case 200: this.logger.info("Source responded with 200."); // Fetch file GetMethod method = new GetMethod(url.toString()); HttpClient client = new HttpClient(); ProxyHelper.executeMethod(client, method); input = method.getResponseBody(); httpConn.disconnect(); // Create zip file with fetched file ZipEntry ze = new ZipEntry("unapi"); ze.setSize(input.length); ze.setTime(this.currentDate()); CRC32 crc321 = new CRC32(); crc321.update(input); ze.setCrc(crc321.getValue()); zos.putNextEntry(ze); zos.write(input); zos.flush(); zos.closeEntry(); zos.close(); this.setContentType("application/zip"); this.setFileEnding(".zip"); break; case 403: throw new AccessException("Access to url " + url + " is restricted."); default: throw new RuntimeException("An error occurred during importing from external system: " + responseCode + ": " + httpConn.getResponseMessage() + "."); } } catch (AccessException e) { this.logger.error("Access denied.", e); throw new AccessException(url.toString()); } catch (Exception e) { throw new RuntimeException(e); } return baos.toByteArray(); }
From source file:it.govpay.web.rs.dars.monitoraggio.rendicontazioni.FrHandler.java
@Override public String esporta(Long idToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException { String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]"; try {/* w w w . j a va2s .c o m*/ this.log.info("Esecuzione " + methodName + " in corso..."); this.darsService.getOperatoreByPrincipal(bd); Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita); boolean eseguiRicerca = !setDomini.isEmpty(); FrBD frBD = new FrBD(bd); FrFilter filter = frBD.newFilter(); List<String> idDomini = new ArrayList<String>(); List<Long> idsToExport = new ArrayList<Long>(); idsToExport.add(idToExport); if (!setDomini.contains(-1L)) { List<Long> lstCodDomini = new ArrayList<Long>(); lstCodDomini.addAll(setDomini); idDomini.addAll(this.toListCodDomini(lstCodDomini, bd)); filter.setCodDominio(idDomini); // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi. if (eseguiRicerca) { filter.setIdFr(idsToExport); eseguiRicerca = eseguiRicerca && frBD.count(filter) > 0; } } String fileName = "Rendicontazione.zip"; if (eseguiRicerca) { Fr fr = frBD.getFr(idToExport); fileName = "Rendicontazione_" + fr.getIur() + ".zip"; ZipEntry frXml = new ZipEntry("fr.xml"); zout.putNextEntry(frXml); zout.write(fr.getXml()); zout.closeEntry(); } else { String noEntriesTxt = "/README"; ZipEntry entryTxt = new ZipEntry(noEntriesTxt); zout.putNextEntry(entryTxt); zout.write("Non sono state trovate informazioni sui flussi selezionati.".getBytes()); zout.closeEntry(); } zout.flush(); zout.close(); this.log.info("Esecuzione " + methodName + " completata."); return fileName; } catch (WebApplicationException e) { throw e; } catch (Exception e) { throw new ConsoleException(e); } }
From source file:au.org.ala.biocache.service.DownloadService.java
/** * Writes the supplied download to the supplied output stream. It will include all the appropriate citations etc. * //from w w w. j a v a 2s . c o m * @param dd * @param requestParams * @param ip * @param out * @param includeSensitive * @param fromIndex * @throws Exception */ private void writeQueryToStream(DownloadDetailsDTO dd, DownloadRequestParams requestParams, String ip, OutputStream out, boolean includeSensitive, boolean fromIndex, boolean limit) throws Exception { String filename = requestParams.getFile(); String originalParams = requestParams.toString(); //Use a zip output stream to include the data and citation together in the download ZipOutputStream zop = new ZipOutputStream(out); String suffix = requestParams.getFileType().equals("shp") ? "zip" : requestParams.getFileType(); zop.putNextEntry(new java.util.zip.ZipEntry(filename + "." + suffix)); //put the facets if ("all".equals(requestParams.getQa())) { requestParams.setFacets(new String[] { "assertions", "data_resource_uid" }); } else { requestParams.setFacets(new String[] { "data_resource_uid" }); } Map<String, Integer> uidStats = null; try { if (fromIndex) uidStats = searchDAO.writeResultsFromIndexToStream(requestParams, zop, includeSensitive, dd, limit); else uidStats = searchDAO.writeResultsToStream(requestParams, zop, 100, includeSensitive, dd); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { unregisterDownload(dd); } zop.closeEntry(); //add the Readme for the data field descriptions zop.putNextEntry(new java.util.zip.ZipEntry("README.html")); zop.write(("For more information about the fields that are being downloaded please consult <a href='" + dataFieldDescriptionURL + "'>Download Fields</a>.").getBytes()); //add the readme for the Shape file header mappings if necessary if (dd.getHeaderMap() != null) { zop.putNextEntry(new java.util.zip.ZipEntry("Shape-README.html")); zop.write( ("The name of features is limited to 10 characters. Listed below are the mappings of feature name to download field:") .getBytes()); zop.write(("<table><td><b>Feature</b></td><td><b>Download Field<b></td>").getBytes()); for (String key : dd.getHeaderMap().keySet()) { zop.write(("<tr><td>" + key + "</td><td>" + dd.getHeaderMap().get(key) + "</td></tr>").getBytes()); } zop.write(("</table>").getBytes()); //logger.debug("JSON::: " + objectMapper.writeValueAsString(dd)); } //Add the data citation to the download if (uidStats != null && !uidStats.isEmpty() && citationsEnabled) { //add the citations for the supplied uids zop.putNextEntry(new java.util.zip.ZipEntry("citation.csv")); try { getCitations(uidStats, zop, requestParams.getSep(), requestParams.getEsc()); } catch (Exception e) { logger.error(e.getMessage(), e); } zop.closeEntry(); } else { logger.debug("Not adding citation. Enabled: " + citationsEnabled + " uids: " + uidStats); } zop.flush(); zop.close(); //now construct the sourceUrl for the log event String sourceUrl = originalParams.contains("qid:") ? webservicesRoot + "?" + requestParams.toString() : webservicesRoot + "?" + originalParams; //logger.debug("UID stats : " + uidStats); //log the stats to ala logger LogEventVO vo = new LogEventVO(1002, requestParams.getReasonTypeId(), requestParams.getSourceTypeId(), requestParams.getEmail(), requestParams.getReason(), ip, null, uidStats, sourceUrl); logger.log(RestLevel.REMOTE, vo); }
From source file:it.govpay.web.rs.dars.anagrafica.domini.DominiHandler.java
@Override public String esporta(Long idToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd, ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException { String methodName = "esporta " + this.titoloServizio + "[" + idToExport + "]"; try {// w w w. j a v a2 s . c om this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di lettura this.darsService.checkDirittiServizioLettura(bd, this.funzionalita); DominiBD dominiBD = new DominiBD(bd); Dominio dominio = dominiBD.getDominio(idToExport); String fileName = "Dominio_" + dominio.getCodDominio() + ".zip"; IbanAccreditoBD ibanAccreditoDB = new IbanAccreditoBD(bd); IbanAccreditoFilter filter = ibanAccreditoDB.newFilter(); filter.setIdDominio(idToExport); List<IbanAccredito> ibans = ibanAccreditoDB.findAll(filter); final byte[] contiAccredito = DominioUtils.buildInformativaContoAccredito(dominio, ibans); ZipEntry contiAccreditoXml = new ZipEntry("contiAccredito.xml"); zout.putNextEntry(contiAccreditoXml); zout.write(contiAccredito); zout.closeEntry(); final byte[] informativa = DominioUtils.buildInformativaControparte(dominio, true); ZipEntry informativaXml = new ZipEntry("informativa.xml"); zout.putNextEntry(informativaXml); zout.write(informativa); zout.closeEntry(); zout.flush(); zout.close(); this.log.info("Esecuzione " + methodName + " completata."); return fileName; } catch (WebApplicationException e) { throw e; } catch (Exception e) { throw new ConsoleException(e); } }
From source file:org.opentestsystem.authoring.testitembank.service.impl.ApipZipInputFileExtractorService.java
private Map<String, ApipItemContent> getItemZipMap(final ApipManifest manifest, final ZipFile originalZip, final HashMap<String, ZipArchiveEntry> zipEntryMap) { final Map<String, ApipManifestResource> resourceMap = manifest.getResourceMap(); final Map<String, ApipItemContent> itemContentMap = new HashMap<String, ApipItemContent>(); final String apipRoot = findApipRootDirectoy(zipEntryMap); for (final ApipManifestResource resource : manifest.getResources()) { if (isItemResource(resource.getResourceType())) { final ApipItemContent content = new ApipItemContent(); ZipOutputStream zipOut = null; ByteArrayOutputStream byteStream = null; byte[] bytes = null; try { byteStream = new ByteArrayOutputStream(); zipOut = new ZipOutputStream(byteStream); zipOut.setLevel(ZipOutputStream.STORED); final ApipManifest itemManifest = new ApipManifest(); itemManifest.setIdentifier(manifest.getIdentifier() + "_" + resource.getIdentifier()); itemManifest.setSchema(manifest.getSchema()); itemManifest.setSchemaVersion(manifest.getSchemaVersion()); final List<ApipManifestResource> requiredResources = new ArrayList<ApipManifestResource>(); requiredResources.add(resource); final ZipArchiveEntry itemEntry = zipEntryMap .get(apipRoot + resource.getFileReference().getHref()); copyZipEntry(itemEntry, originalZip, zipOut); for (final ApipManifestDependency dependency : resource.getDependencies()) { final ApipManifestResource dependencyResource = resourceMap.get(dependency.getIdentifier()); if (dependencyResource != null) { final ZipArchiveEntry dependencyEntry = zipEntryMap .get(apipRoot + dependencyResource.getFileReference().getHref()); if (dependencyEntry == null) { if (ResourceTypePrefix.apipMetadata .isPrefixFor(dependencyResource.getResourceType()) || ResourceTypePrefix.apipItem .isPrefixFor(dependencyResource.getResourceType()) || ResourceTypePrefix.stimuli .isPrefixFor(dependencyResource.getResourceType())) { content.addError("item.invalid.zip.missingResource", new String[] { resource.getIdentifier(), dependency.getIdentifier() }); } else LOGGER.warn(String.format("Zip missing resource: %s, %s ", resource.getIdentifier(), dependency.getIdentifier())); } else { requiredResources.add(dependencyResource); copyZipEntry(dependencyEntry, originalZip, zipOut); }/*from w w w.j av a 2 s .com*/ } } itemManifest.setResources(requiredResources); final ZipEntry entry = new ZipEntry(apipRoot + IMS_MANIFEST_NAME); zipOut.putNextEntry(entry); zipXMLService.writeToManifestToOutputStream(itemManifest, zipOut); zipOut.closeEntry(); zipOut.flush(); zipOut.close(); bytes = byteStream.toByteArray(); content.setItemZip(bytes); } catch (final Exception e) { LOGGER.error("creating item zip for " + resource.getIdentifier(), e); } finally { try { if (zipOut != null) { zipOut.flush(); zipOut.close(); } if (byteStream != null) { byteStream.flush(); byteStream.close(); } } catch (final IOException e) { LOGGER.error("error closing zip.", e); } } itemContentMap.put(resource.getIdentifier(), content); } } return itemContentMap; }
From source file:org.broad.igv.feature.genome.GenomeManager.java
/** * Rewrite the {@link Globals#GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY} property to equal * the specified {@code newSequencePath}. Works by creating a temp file and renaming * * @param targetFile A .genome file, in zip format * @param newSequencePath/*from w w w. j a va 2s .c o m*/ * @return boolean indicating success or failure. * @throws IOException */ static boolean rewriteSequenceLocation(File targetFile, String newSequencePath) throws IOException { ZipFile targetZipFile = new ZipFile(targetFile); boolean success = false; File tmpZipFile = File.createTempFile("tmpGenome", ".zip"); ZipEntry propEntry = targetZipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME); InputStream propertyInputStream = null; ZipOutputStream zipOutputStream = null; Properties inputProperties = new Properties(); try { propertyInputStream = targetZipFile.getInputStream(propEntry); BufferedReader reader = new BufferedReader(new InputStreamReader(propertyInputStream)); //Copy over property.txt, only replacing a few properties inputProperties.load(reader); inputProperties.put(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY, newSequencePath); inputProperties.put(Globals.GENOME_ARCHIVE_CUSTOM_SEQUENCE_LOCATION_KEY, Boolean.TRUE.toString()); ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream(); PrintWriter propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes)); inputProperties.store(propertyFileWriter, null); propertyFileWriter.flush(); byte[] newPropertyBytes = propertyBytes.toByteArray(); Enumeration<? extends ZipEntry> entries = targetZipFile.entries(); zipOutputStream = new ZipOutputStream(new FileOutputStream(tmpZipFile)); while (entries.hasMoreElements()) { ZipEntry curEntry = entries.nextElement(); ZipEntry writeEntry = null; if (curEntry.getName().equals(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME)) { writeEntry = new ZipEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME); writeEntry.setSize(newPropertyBytes.length); zipOutputStream.putNextEntry(writeEntry); zipOutputStream.write(newPropertyBytes); continue; } else { //Because the compressed size can vary, //we generate a new ZipEntry and copy some attributes writeEntry = new ZipEntry(curEntry.getName()); writeEntry.setSize(curEntry.getSize()); writeEntry.setComment(curEntry.getComment()); writeEntry.setTime(curEntry.getTime()); } zipOutputStream.putNextEntry(writeEntry); InputStream tmpIS = null; try { tmpIS = targetZipFile.getInputStream(writeEntry); int bytes = IOUtils.copy(tmpIS, zipOutputStream); log.debug(bytes + " bytes written to " + targetFile); } finally { if (tmpIS != null) tmpIS.close(); } } } catch (Exception e) { tmpZipFile.delete(); throw new RuntimeException(e.getMessage(), e); } finally { if (propertyInputStream != null) propertyInputStream.close(); if (zipOutputStream != null) { zipOutputStream.flush(); zipOutputStream.finish(); zipOutputStream.close(); } zipOutputStream = null; System.gc(); success = true; } //This is a hack. I don't know why it's necessary, //but for some reason the output zip file seems to be corrupt //at least when called from GenomeManager.refreshArchive try { Thread.sleep(1500); } catch (InterruptedException e) { // } //Rename tmp file if (success) { targetFile.delete(); FileUtils.copyFile(tmpZipFile, targetFile); success = targetFile.exists(); tmpZipFile.delete(); } return success; }