/** Creates an AudioInputStream from a sound from an input stream */ public AudioInputStream getAudioInputStream(InputStream is) { try { if (!is.markSupported()) { is = new BufferedInputStream(is); } // open the source stream AudioInputStream source = AudioSystem.getAudioInputStream(is); // convert to playback format return AudioSystem.getAudioInputStream(playbackFormat, source); } catch (UnsupportedAudioFileException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } return null; }
/* * launch process config input: className and args */ public void launchProcessConfig(String className, String[] args) throws SecurityException, NoSuchMethodException { try { Class<?> processClass = Class.forName(className); // System.out.print("processClass is " + processClass.toString()); MigratableProcess process; process = (MigratableProcess) processClass.getConstructor(String[].class).newInstance((Object) args); // process = (MigratableProcess) processClass.newInstance(); System.out.println("MP is " + process.toString()); processList.add(process); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TestProcess test = new TestProcess(); catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void setEntity(java.lang.Object ent) { Method[] methods = ent.getClass().getDeclaredMethods(); box.removeAll(); for (Method m : methods) { if (m.getName().toLowerCase().startsWith("get")) { String attName = m.getName().substring(3); Object result; try { result = m.invoke(ent, new Object[] {}); String value = "null"; if (result != null) value = result.toString(); JPanel attPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); attPane.add(new JLabel(attName + " : " + m.getReturnType().getName() + " = " + value)); box.add(attPane); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
/** * @param path * @return byte or null */ public byte[] getFile(String path) { Log.d(TAG, "get file " + path); // NON-NLS File f = new File(getFullCachePath(path)); if (!f.exists()) { Log.w(TAG, "file: " + f.toString() + " not exists"); // NON-NLS return null; } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); FileInputStream fileInputStream = new FileInputStream(f); byte[] buf = new byte[1024]; int numRead = 0; while ((numRead = fileInputStream.read(buf)) != -1) out.write(buf, 0, numRead); fileInputStream.close(); return out.toByteArray(); } catch (FileNotFoundException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (StreamCorruptedException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (IOException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (IllegalArgumentException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (RuntimeException e) { // не позволим кэшу убить нашу программу Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (Exception e) { // не позволим кэшу убить нашу программу Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } }
/** * Updates a resource on the ckan server. * * @param resource ckan resource object * @return the updated resource * @throws JackanException */ public synchronized CkanResource updateResource(CkanResource resource, Boolean checkConsistency) { if (ckanToken == null) { throw new JackanException( "Tried to update resource" + resource.getName() + ", but ckan token was not set!"); } // check consistance with original version of the to be updated resource if (checkConsistency) { CkanResource originalResource = getResource(resource.getId()); for (Field f : originalResource.getClass().getDeclaredFields()) { f.setAccessible(true); String fieldName; try { if ((f.get(originalResource) != null) && (f.get(resource) == null) && (!f.getName().equals("created"))) { fieldName = f.getName(); // if(!fieldName.equals("created")){ f.set(resource, f.get(originalResource)); System.out.println("Not a null: " + fieldName + " Value: "); // //}; // System.out.println("Not a null: "+fieldName+ " Value: "); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // System.out.println("After consistance checking resource is consist of: // "+resource.toString()); ObjectMapper objectMapper = CkanClient.getObjectMapper(); String json = null; try { json = objectMapper.writeValueAsString(resource); } catch (IOException e) { throw new JackanException("Couldn't serialize the provided CkanResourceMinimized!", e); } return postHttp( ResourceResponse.class, "/api/3/action/resource_update", json, ContentType.APPLICATION_JSON) .result; }
/** * Checks weather values of a target attribute are significantly different * * @return */ public boolean targetSignDifferent() { boolean res = false; int att = -1; String att_name; String att_name2; ClusStatistic targetStat = m_StatManager.getStatistic(ClusAttrType.ATTR_USE_TARGET); if (targetStat instanceof ClassificationStat) { for (int i = 0; i < targetStat.getNbNominalAttributes(); i++) { att_name = ((ClassificationStat) targetStat).getAttribute(i).getName(); for (int j = 0; j < m_ClassStat.getNbNominalAttributes(); j++) { att_name2 = m_ClassStat.getAttribute(j).getName(); if (att_name.equals(att_name2)) { att = j; break; } } if (SignDifferentNom(att)) { res = true; break; // TODO: If one target att significant, the whole rule significant!? } } // System.out.println("Target sign. testing: " + res); return res; } else if (targetStat instanceof RegressionStat) { for (int i = 0; i < targetStat.getNbNumericAttributes(); i++) { att_name = ((RegressionStat) targetStat).getAttribute(i).getName(); for (int j = 0; j < m_RegStat.getNbNumericAttributes(); j++) { att_name2 = m_RegStat.getAttribute(j).getName(); if (att_name.equals(att_name2)) { att = j; break; } } try { if (SignDifferentNum(att)) { res = true; break; // TODO: If one target att significant, the whole rule significant!? } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (MathException e) { e.printStackTrace(); } } return res; } else { // TODO: Classification and regression return true; } }
public static String resolveRelativePath(String relativePath, String base) { /*System.out.println("==============="); System.out.println(relativePath); System.out.println(base);*/ // keep simple cases as they were if ((base == null) || (new File(relativePath).isAbsolute())) { // System.out.println("1"); return relativePath; } if (base.startsWith("http")) { try { // System.out.println("2a"); return new URI(base).resolve(relativePath).toString(); } catch (URISyntaxException ex) { ex.printStackTrace(); } } if (!(relativePath.startsWith(".."))) { // System.out.println("2b"); File parentFile = new File(base).getParentFile(); if (parentFile == null) { return relativePath; } URI uri2 = parentFile.toURI(); String modRelPath = relativePath.replaceAll(" ", "%20"); // String modRelPath = relativePath; try { URI absoluteURI = uri2.resolve(modRelPath); return new File(absoluteURI).getAbsolutePath(); } catch (IllegalArgumentException use) { use.printStackTrace(); return relativePath; } } // the relative Path starts with .. String UP = ".." + System.getProperty("file.separator"); String OTHER = "../"; if (relativePath.startsWith(UP) || relativePath.startsWith(OTHER)) { String newBase = new File(base).getParent(); String newRelative = relativePath.substring(3); // System.out.println("3"); return resolveRelativePath(newRelative, newBase); } // no can do // System.out.println("4"); return relativePath; }
/** * Function that creates a "ARCHIVE" folder that is going to contain all the archives that will be * created by this program. * * @return folder that is going to contain all the archives that will be created by this program */ private File createArchive() { archiveDirectory = null; try { String homePath = System.getProperty("user.home"); archiveDirectory = new File(homePath + File.separatorChar + "Archive"); if (!archiveDirectory.exists()) archiveDirectory.mkdir(); } catch (SecurityException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } return archiveDirectory; }
public static Integer getProcessID(Process p) { try { Field f = p.getClass().getDeclaredField("pid"); f.setAccessible(true); Integer s = (Integer) f.get(p); return s; } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
public void play() { try { mp.setDataSource( Environment.getExternalStorageDirectory() + "/pathofthefile/" + FirstSettings_two.file_video); mp.prepare(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } mp.start(); }
protected synchronized Message receiveMessage() throws IOException { if (messageBuffer.size() > 0) { Message m = (Message) messageBuffer.get(0); messageBuffer.remove(0); return m; } try { InetSocketAddress remoteAddress = (InetSocketAddress) channel.receive(receiveBuffer); if (remoteAddress != null) { int len = receiveBuffer.position(); receiveBuffer.rewind(); receiveBuffer.get(buf, 0, len); try { IP address = IP.fromInetAddress(remoteAddress.getAddress()); int port = remoteAddress.getPort(); extractor.appendData(buf, 0, len, new SocketDescriptor(address, port)); receiveBuffer.clear(); extractor.updateAvailableMessages(); return extractor.nextMessage(); } catch (EOFException exc) { exc.printStackTrace(); System.err.println(buf.length + ", " + len); } catch (InvocationTargetException exc) { exc.printStackTrace(); } catch (IllegalAccessException exc) { exc.printStackTrace(); } catch (InstantiationException exc) { exc.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvalidCompressionMethodException e) { e.printStackTrace(); } } } catch (ClosedChannelException exc) { if (isKeepAlive()) { throw exc; } } return null; }
/** * The main method. * * @param args the arguments */ public static void main(String[] args) { Questionnaire quiz = new Questionnaire(); try { quiz.initQuestionnaire("question_tolkien.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } new QuestionnaireUI(quiz); }
/** Returns a number of attributes with significantly different distributions */ public int signDifferent() { int sign_diff = 0; // Nominal attributes for (int i = 0; i < m_ClassStat.getNbAttributes(); i++) { if (SignDifferentNom(i)) { sign_diff++; } } // Numeric attributes for (int i = 0; i < m_RegStat.getNbAttributes(); i++) { try { if (SignDifferentNum(i)) { sign_diff++; } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (MathException e) { e.printStackTrace(); } } System.out.println("Nb.sig.atts: " + sign_diff); return sign_diff; }
public static SDCardInfo getSDCardInfo() { String sDcString = Environment.getExternalStorageState(); if (sDcString.equals(Environment.MEDIA_MOUNTED)) { File pathFile = Environment.getExternalStorageDirectory(); try { android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath()); // 获取SDCard上BLOCK总数 long nTotalBlocks = statfs.getBlockCount(); // 获取SDCard上每个block的SIZE long nBlocSize = statfs.getBlockSize(); // 获取可供程序使用的Block的数量 long nAvailaBlock = statfs.getAvailableBlocks(); // 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块) long nFreeBlock = statfs.getFreeBlocks(); SDCardInfo info = new SDCardInfo(); // 计算SDCard 总容量大小MB info.total = nTotalBlocks * nBlocSize; // 计算 SDCard 剩余大小MB info.free = nAvailaBlock * nBlocSize; return info; } catch (IllegalArgumentException e) { e.printStackTrace(); } } return null; }
@Override public void onCreate(Bundle savedInstanceState) { // System.loadLibrary("luajava-1.1"); // 設定橫向螢幕 this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); this.getWindow() .setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); this.getWindow() .setFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); L = LuaStateFactory.newLuaState(); L.pushJavaObject(this); L.setGlobal("activity"); res = getResources(); conf = res.getConfiguration(); conf.locale = Locale.TAIWAN; res.updateConfiguration(conf, null); super.onCreate(savedInstanceState); setContentView(R.layout.main); appobject = this.getApplicationContext(); surfaceView = (SurfaceView) findViewById(R.id.surfaceView1); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //////////////////////////////////////////////////////////////////////////////////////////// /*bitmap2 = BitmapFactory.decodeResource( getResources() , R.raw.line ); surfaceView2 = (SurfaceView)findViewById(R.id.surface_level ); surfaceHolder2 = surfaceView2.getHolder(); SurfaceHolder.Callback level_callback = new SurfaceHolder.Callback() { public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { //需要 on_level_change(new float[3]); } public void surfaceCreated(SurfaceHolder holder) { } public void surfaceDestroyed(SurfaceHolder holder) { } }; surfaceHolder2.addCallback( level_callback ); surfaceHolder2.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); */ ////////////////////////////////////////////////////////////////////////////////////////// /* sensormanager = (SensorManager) getSystemService(SENSOR_SERVICE); sensors = sensormanager.getSensorList(Sensor.TYPE_ORIENTATION); SensorEventListener sl =new SensorEventListener () { public void onAccuracyChanged(Sensor sensor, int accuracy) { //不需要 } public void onSensorChanged(SensorEvent event) { on_level_change(event.values); } }; sensormanager.registerListener ( sl , sensors.get(0) , SensorManager.SENSOR_DELAY_GAME ); */ ///////////////////////////////////////////////////////////////////// Button run_script = (Button) this.findViewById(R.id.run_script); run_script.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { if (is_video == true) { print_screen(res.getString(R.string.video_rec_ing)); return; } if (is_audio == true) { print_screen(res.getString(R.string.audio_rec_ing)); return; } if (lua_file == "") { print_screen(res.getString(R.string.file_load_no)); return; } File f = new File("/sdcard/ez_Lua_Script_Camera/lua_scripts/" + lua_file); if (f.exists() == false) { print_screen(res.getString(R.string.file_load_fail)); return; } ((TextView) findViewById(R.id.lua_file_screen)).setText(lua_file); all_pics = 0; ((TextView) findViewById(R.id.shutter_times_screen)).setText("拍攝張數 : 00000"); (new lua_run()).start(); } }); Button about = (Button) this.findViewById(R.id.about); about.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { if (is_video == true) { print_screen(res.getString(R.string.video_rec_ing)); return; } if (is_audio == true) { print_screen(res.getString(R.string.audio_rec_ing)); return; } if (is_script_running == true) { print_screen(res.getString(R.string.script_running)); return; } Intent i = new Intent( Intent.ACTION_VIEW, Uri.parse("http://dl.dropbox.com/u/61164954/homepage/ez_LSC/index.htm")); startActivity(i); } }); Button audio_c = (Button) this.findViewById(R.id.audio); audio_c.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { if (is_script_running == true) { print_screen(res.getString(R.string.script_running)); return; } if (is_video == true) { print_screen(res.getString(R.string.video_rec_ing)); return; } if (is_audio == false) { print_screen(res.getString(R.string.audio_rec_start)); CharSequence cs = res.getString(R.string.stop); Button keepa = (Button) findViewById(R.id.audio); keepa.setText(cs); is_audio = true; (new audio()).start(); } else { arecorder.stop(); is_audio = false; print_screen(res.getString(R.string.audio_rec_end)); CharSequence xcs = res.getString(R.string.audio_rec); Button keepax = (Button) findViewById(R.id.audio); keepax.setText(xcs); camera.startPreview(); } } }); Button movie = (Button) this.findViewById(R.id.movie); movie.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { if (is_script_running == true) { print_screen(res.getString(R.string.script_running)); return; } if (is_audio == true) { print_screen(res.getString(R.string.audio_rec_ing)); return; } if (is_video == false) { print_screen(res.getString(R.string.video_rec_start)); CharSequence cs = res.getString(R.string.stop); Button keepa = (Button) findViewById(R.id.movie); keepa.setText(cs); parameters.setFocusMode("continuous-video"); camera.setParameters(parameters); is_video = true; (new video()).start(); } else { recorder.stop(); is_video = false; print_screen(res.getString(R.string.video_rec_end)); CharSequence xcs = res.getString(R.string.video_rec); Button keepax = (Button) findViewById(R.id.movie); keepax.setText(xcs); camera.lock(); camera.release(); camera = Camera.open(); parameters = camera.getParameters(); parameters.setPreviewSize(640, 480); parameters.setPreviewFrameRate(30); parameters.setJpegQuality(100); parameters.setFocusMode("continuous-video"); parameters.setPictureSize(2048, 1536); camera.setParameters(parameters); try { camera.setPreviewDisplay(surfaceHolder); } catch (IOException e) { } camera.startPreview(); } } }); Button lua = (Button) this.findViewById(R.id.lua); lua.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { if (is_script_running == true) { print_screen(res.getString(R.string.script_running)); return; } if (is_audio == true) { print_screen(res.getString(R.string.audio_rec_ing)); return; } if (is_video == true) { print_screen(res.getString(R.string.video_rec_ing)); return; } show_choose_Dialog(); } }); test_caller(); load_config(); try { player.setDataSource("/sdcard/ez_Lua_Script_Camera/sound/shuttersound.ogg"); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { shutter_trigger.setDataSource("/sdcard/ez_Lua_Script_Camera/sound/trigger.wav"); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void setEntity(Plan ent, Map attributes) { Map currentMap = (Map) RenderComponentManager.retrieveIDs("Plan", ent.getPrefs(attributes).getView()); current = ent.getPrefs(attributes).getView(); if (ent != null && currentMap.get("_attributes_") != null && currentMap.get("_attributes_") instanceof ingenias.editor.rendererxml.AttributesPanel) { ((ingenias.editor.rendererxml.AttributesPanel) currentMap.get("_attributes_")).setEntity(ent); } if (currentMap.get("Tasks") != null && currentMap.get("Tasks") instanceof ingenias.editor.rendererxml.CollectionPanel) { try { ((ingenias.editor.rendererxml.CollectionPanel) currentMap.get("Tasks")) .setCollection("Tasks", ent.Tasks, ent.Tasks.getType()); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } if (currentMap.get("Tasks") != null && currentMap.get("Tasks") instanceof ingenias.editor.rendererxml.CollectionPanel) { try { ((ingenias.editor.rendererxml.CollectionPanel) currentMap.get("Tasks")) .setCollection("Tasks", ent.Tasks, ent.Tasks.getType()); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } if (currentMap.get("Tasks") != null) { if (ent != null && ent.getTasks() != null) { if (currentMap.get("Tasks") instanceof javax.swing.JLabel) { ((javax.swing.JLabel) (currentMap).get("Tasks")).setText(ent.getTasks().toString()); } else { if (currentMap.get("Tasks") instanceof javax.swing.text.JTextComponent) ((javax.swing.text.JTextComponent) (currentMap).get("Tasks")) .setText(ent.getTasks().toString()); } } else { if (currentMap.get("Tasks") instanceof javax.swing.JLabel) ((javax.swing.JLabel) (currentMap).get("Tasks")).setText(""); else { if (!(currentMap.get("Tasks") instanceof ingenias.editor.rendererxml.CollectionPanel)) ((javax.swing.text.JTextComponent) (currentMap).get("Tasks")).setText(""); } } } if (currentMap.get("Id") != null) { if (ent != null && ent.getId() != null) { if (currentMap.get("Id") instanceof javax.swing.JLabel) { ((javax.swing.JLabel) (currentMap).get("Id")).setText(ent.getId().toString()); } else { if (currentMap.get("Id") instanceof javax.swing.text.JTextComponent) ((javax.swing.text.JTextComponent) (currentMap).get("Id")) .setText(ent.getId().toString()); } } else { if (currentMap.get("Id") instanceof javax.swing.JLabel) ((javax.swing.JLabel) (currentMap).get("Id")).setText(""); else { if (!(currentMap.get("Id") instanceof ingenias.editor.rendererxml.CollectionPanel)) ((javax.swing.text.JTextComponent) (currentMap).get("Id")).setText(""); } } } }
@Override protected void download() { File destination = new File(request.getDestination()); final boolean fileExists = destination.exists(); if (request.isDeleteOnFailure() && fileExists) { Log.w(TAG, "File already exists"); if (request.getFeedfileType() != FeedImage.FEEDFILETYPE_FEEDIMAGE) { onFail(DownloadError.ERROR_FILE_EXISTS, null); return; } else { onSuccess(); return; } } HttpClient httpClient = AntennapodHttpClient.getHttpClient(); RandomAccessFile out = null; InputStream connection = null; try { HttpGet httpGet = new HttpGet(URIUtil.getURIFromRequestUrl(request.getSource())); // add authentication information String userInfo = httpGet.getURI().getUserInfo(); if (userInfo != null) { String[] parts = userInfo.split(":"); if (parts.length == 2) { httpGet.addHeader( BasicScheme.authenticate( new UsernamePasswordCredentials(parts[0], parts[1]), "UTF-8", false)); } } else if (!StringUtils.isEmpty(request.getUsername()) && request.getPassword() != null) { httpGet.addHeader( BasicScheme.authenticate( new UsernamePasswordCredentials(request.getUsername(), request.getPassword()), "UTF-8", false)); } // add range header if necessary if (fileExists) { request.setSoFar(destination.length()); httpGet.addHeader(new BasicHeader("Range", "bytes=" + request.getSoFar() + "-")); if (BuildConfig.DEBUG) Log.d(TAG, "Adding range header: " + request.getSoFar()); } HttpResponse response = httpClient.execute(httpGet); HttpEntity httpEntity = response.getEntity(); int responseCode = response.getStatusLine().getStatusCode(); Header contentEncodingHeader = response.getFirstHeader("Content-Encoding"); final boolean isGzip = contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip"); if (BuildConfig.DEBUG) Log.d(TAG, "Response code is " + responseCode); if (responseCode / 100 != 2 || httpEntity == null) { final DownloadError error; final String details; if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { error = DownloadError.ERROR_UNAUTHORIZED; details = String.valueOf(responseCode); } else { error = DownloadError.ERROR_HTTP_DATA_ERROR; details = String.valueOf(responseCode); } onFail(error, details); return; } if (!StorageUtils.storageAvailable(PodcastApp.getInstance())) { onFail(DownloadError.ERROR_DEVICE_NOT_FOUND, null); return; } connection = new BufferedInputStream(AndroidHttpClient.getUngzippedContent(httpEntity)); Header[] contentRangeHeaders = (fileExists) ? response.getHeaders("Content-Range") : null; if (fileExists && responseCode == HttpStatus.SC_PARTIAL_CONTENT && contentRangeHeaders != null && contentRangeHeaders.length > 0) { String start = contentRangeHeaders[0] .getValue() .substring("bytes ".length(), contentRangeHeaders[0].getValue().indexOf("-")); request.setSoFar(Long.valueOf(start)); Log.d(TAG, "Starting download at position " + request.getSoFar()); out = new RandomAccessFile(destination, "rw"); out.seek(request.getSoFar()); } else { destination.delete(); destination.createNewFile(); out = new RandomAccessFile(destination, "rw"); } byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; request.setStatusMsg(R.string.download_running); if (BuildConfig.DEBUG) Log.d(TAG, "Getting size of download"); request.setSize(httpEntity.getContentLength() + request.getSoFar()); if (BuildConfig.DEBUG) Log.d(TAG, "Size is " + request.getSize()); if (request.getSize() < 0) { request.setSize(DownloadStatus.SIZE_UNKNOWN); } long freeSpace = StorageUtils.getFreeSpaceAvailable(); if (BuildConfig.DEBUG) Log.d(TAG, "Free space is " + freeSpace); if (request.getSize() != DownloadStatus.SIZE_UNKNOWN && request.getSize() > freeSpace) { onFail(DownloadError.ERROR_NOT_ENOUGH_SPACE, null); return; } if (BuildConfig.DEBUG) Log.d(TAG, "Starting download"); while (!cancelled && (count = connection.read(buffer)) != -1) { out.write(buffer, 0, count); request.setSoFar(request.getSoFar() + count); request.setProgressPercent( (int) (((double) request.getSoFar() / (double) request.getSize()) * 100)); } if (cancelled) { onCancelled(); } else { // check if size specified in the response header is the same as the size of the // written file. This check cannot be made if compression was used if (!isGzip && request.getSize() != DownloadStatus.SIZE_UNKNOWN && request.getSoFar() != request.getSize()) { onFail( DownloadError.ERROR_IO_ERROR, "Download completed but size: " + request.getSoFar() + " does not equal expected size " + request.getSize()); return; } onSuccess(); } } catch (IllegalArgumentException e) { e.printStackTrace(); onFail(DownloadError.ERROR_MALFORMED_URL, e.getMessage()); } catch (SocketTimeoutException e) { e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, e.getMessage()); } catch (UnknownHostException e) { e.printStackTrace(); onFail(DownloadError.ERROR_UNKNOWN_HOST, e.getMessage()); } catch (IOException e) { e.printStackTrace(); onFail(DownloadError.ERROR_IO_ERROR, e.getMessage()); } catch (NullPointerException e) { // might be thrown by connection.getInputStream() e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, request.getSource()); } finally { IOUtils.closeQuietly(out); AntennapodHttpClient.cleanup(); } }
public Object __parse_response__(String resp) throws RemoteException { JsonParser parser = new JsonParser(); JsonElement main_response = (JsonElement) parser.parse(resp); if (main_response.isJsonArray()) { List<Object> res = new Vector<Object>(); for (Object o : main_response.getAsJsonArray()) { res.add(__parse_response__(gson.toJson(o))); } return res; } JsonObject response = main_response.getAsJsonObject(); if (response.has("error")) { JsonObject e = response.get("error").getAsJsonObject().get("data").getAsJsonObject(); throw new RemoteException(e.get("exception").getAsString(), e.get("message").getAsString()); } JsonElement value = response.get("result"); String valuestr = gson.toJson(response.get("result")); if (valuestr.contains("hash:")) { Class<? extends RpcClient> klass = this.getClass(); try { Constructor<? extends RpcClient> m = klass.getDeclaredConstructor(String.class, String.class); String new_endpoint = gson.fromJson(value, String.class); return m.newInstance(this.base_endpoint, new_endpoint.replace("hash:", "")); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } else if (valuestr.contains("funcs")) { return gson.fromJson(valuestr, Interface.class); } if (value.isJsonPrimitive()) { JsonPrimitive val = value.getAsJsonPrimitive(); if (val.isBoolean()) { return val.getAsBoolean(); } else if (val.isNumber()) { return val.getAsNumber(); } else if (val.isString()) { DateTimeFormatter dtparser = ISODateTimeFormat.dateHourMinuteSecond(); try { return dtparser.parseDateTime(val.getAsString()); } catch (Exception ex) { } return val.getAsString(); } else { return null; } } else if (value.isJsonNull()) { return null; } else if (value.isJsonObject() && !value.getAsJsonObject().has("__meta__")) { return gson.fromJson(value, HashMap.class); } else if (value.isJsonArray()) { if (value.getAsJsonArray().size() == 0) return new LinkedList(); JsonElement obj = value.getAsJsonArray().get(0); if (obj.isJsonObject()) { if (!obj.getAsJsonObject().has("__meta__")) { return gson.fromJson(value, LinkedList.class); } } } return __resolve_references__(valuestr); }
/** * @param path * @param t * @return */ public List<?> getList(String path, java.lang.reflect.Type t) { Log.d(TAG, "get list " + path); // NON-NLS File f = new File(getFullCachePath(path)); if (!f.exists()) { Log.w(TAG, "file: " + f.toString() + " not exists"); // NON-NLS return null; } List<?> list; try { StringBuffer fileData = new StringBuffer(); BufferedReader reader = new BufferedReader(new FileReader(f)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); } reader.close(); String json = fileData.toString(); Log.d(TAG, "cache: " + json); // NON-NLS list = gson.fromJson(json, t); } catch (FileNotFoundException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (StreamCorruptedException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (IOException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (JsonSyntaxException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (IllegalArgumentException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (RuntimeException e) { // не позволим кэшу убить нашу программу Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (Exception e) { // не позволим кэшу убить нашу программу Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } return list; }
public <T> T get(String path, Class<T> c) { Log.d(TAG, "get " + path); // NON-NLS File f = new File(getFullCachePath(path)); if (!f.exists()) { Log.w(TAG, "file: " + f.toString() + " not exists"); // NON-NLS return null; } T object; try { StringBuffer fileData = new StringBuffer(); BufferedReader reader = new BufferedReader(new FileReader(f)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); } reader.close(); String json = fileData.toString(); Log.d(TAG, "cache: " + json); // NON-NLS object = getGson().fromJson(json, c); } catch (FileNotFoundException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (StreamCorruptedException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (IOException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (JsonSyntaxException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (IllegalArgumentException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (RuntimeException e) { // не позволим кэшу убить нашу программу Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (Exception e) { // не позволим кэшу убить нашу программу Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } if (object.getClass().toString().equals(c.toString())) return object; else return null; }
public boolean connect(Onion options, OobdBus receiveListener) { msgReceiver = receiveListener; System.out.println("Starting Bluetooth Detection and Device Pairing"); if (mBluetoothAdapter == null) { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.w(this.getClass().getSimpleName(), "Bluetooth not supported."); return false; } if (!mBluetoothAdapter.isEnabled()) { Log.w(this.getClass().getSimpleName(), "Bluetooth switched off."); return false; } } obdDevice = mBluetoothAdapter.getRemoteDevice(BTAddress); if (obdDevice != null) { // Get a BluetoothSocket to connect // with the given BluetoothDevice try { Log.v(this.getClass().getSimpleName(), "Device " + obdDevice.getName()); java.lang.reflect.Method m = obdDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); // "createInsecureRfcommSocket", new Class[] { int.class }); serialPort = null; serialPort = (BluetoothSocket) m.invoke(obdDevice, 1); if (serialPort != null) { try { mBluetoothAdapter.cancelDiscovery(); serialPort.connect(); Log.d("OOBD:Bluetooth", "Bluetooth connected"); inputStream = serialPort.getInputStream(); outputStream = serialPort.getOutputStream(); OOBDApp.getInstance().displayToast("Bluetooth connected"); myThread = new Thread() { @Override public void run() { byte[] buffer = new byte[1024]; // buffer store // for the // stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an // exception occurs Log.d("OOBD:Bluetooth", "receiver task runs"); while (true) { if (inputStream != null) { try { // Read from the InputStream bytes = inputStream.read(buffer); if (bytes > 0) { Log.v(this.getClass().getSimpleName(), "Debug: received something"); String recString = new String(buffer); recString = recString.substring(0, bytes); msgReceiver.receiveString(recString); } } catch (IOException e) { break; } } else { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }; myThread.start(); return true; } catch (IOException ex) { Log.e(this.getClass().getSimpleName(), "Error: Could not connect to socket.", ex); OOBDApp.getInstance().displayToast("Bluetooth NOT connected!"); } } else { Log.e("OOBD:Bluetooth", "Bluetooth NOT connected!"); OOBDApp.getInstance().displayToast("Bluetooth NOT connected!"); if (serialPort != null) { try { serialPort.close(); } catch (IOException closeEx) { } } return false; } // do not yet connect. Connect before calling the // socket. } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; }