List of usage examples for java.lang RuntimeException printStackTrace
public void printStackTrace()
From source file:com.dngames.mobilewebcam.PhotoSettings.java
@Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (key == "cam_refresh") { int new_refresh = getEditInt(mContext, prefs, "cam_refresh", 60); String msg = "Camera refresh set to " + new_refresh + " seconds!"; if (MobileWebCam.gIsRunning) { if (!mNoToasts && new_refresh != mRefreshDuration) { try { Toast.makeText(mContext.getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } catch (RuntimeException e) { e.printStackTrace(); }//from w w w. jav a2 s . co m } } else if (new_refresh != mRefreshDuration) { MobileWebCam.LogI(msg); } } // get all preferences for (Field f : getClass().getFields()) { { BooleanPref bp = f.getAnnotation(BooleanPref.class); if (bp != null) { try { f.setBoolean(this, prefs.getBoolean(bp.key(), bp.val())); } catch (Exception e) { Log.e("MobileWebCam", "Exception: " + bp.key() + " <- " + bp.val()); e.printStackTrace(); } } } { EditIntPref ip = f.getAnnotation(EditIntPref.class); if (ip != null) { try { int eval = getEditInt(mContext, prefs, ip.key(), ip.val()) * ip.factor(); if (ip.max() != Integer.MAX_VALUE) eval = Math.min(eval, ip.max()); if (ip.min() != Integer.MIN_VALUE) eval = Math.max(eval, ip.min()); f.setInt(this, eval); } catch (Exception e) { e.printStackTrace(); } } } { IntPref ip = f.getAnnotation(IntPref.class); if (ip != null) { try { int eval = prefs.getInt(ip.key(), ip.val()) * ip.factor(); if (ip.max() != Integer.MAX_VALUE) eval = Math.min(eval, ip.max()); if (ip.min() != Integer.MIN_VALUE) eval = Math.max(eval, ip.min()); f.setInt(this, eval); } catch (Exception e) { // handle wrong set class e.printStackTrace(); Editor edit = prefs.edit(); edit.remove(ip.key()); edit.putInt(ip.key(), ip.val()); edit.commit(); try { f.setInt(this, ip.val()); } catch (IllegalArgumentException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } } } } { EditFloatPref fp = f.getAnnotation(EditFloatPref.class); if (fp != null) { try { float eval = getEditFloat(mContext, prefs, fp.key(), fp.val()); if (fp.max() != Float.MAX_VALUE) eval = Math.min(eval, fp.max()); if (fp.min() != Float.MIN_VALUE) eval = Math.max(eval, fp.min()); f.setFloat(this, eval); } catch (Exception e) { e.printStackTrace(); } } } { StringPref sp = f.getAnnotation(StringPref.class); if (sp != null) { try { f.set(this, prefs.getString(sp.key(), getDefaultString(mContext, sp))); } catch (Exception e) { e.printStackTrace(); } } } } mCustomImageScale = Enum.valueOf(ImageScaleMode.class, prefs.getString("custompicscale", "CROP")); mAutoStart = prefs.getBoolean("autostart", false); mCameraStartupEnabled = prefs.getBoolean("cam_autostart", true); mShutterSound = prefs.getBoolean("shutter", true); mDateTimeColor = GetPrefColor(prefs, "datetime_color", "#FFFFFFFF", Color.WHITE); mDateTimeShadowColor = GetPrefColor(prefs, "datetime_shadowcolor", "#FF000000", Color.BLACK); mDateTimeBackgroundColor = GetPrefColor(prefs, "datetime_backcolor", "#80FF0000", Color.argb(0x80, 0xFF, 0x00, 0x00)); mDateTimeBackgroundLine = prefs.getBoolean("datetime_fillline", true); mDateTimeX = prefs.getInt("datetime_x", 98); mDateTimeY = prefs.getInt("datetime_y", 98); mDateTimeAlign = Paint.Align.valueOf(prefs.getString("datetime_imprintalign", "RIGHT")); mDateTimeFontScale = (float) prefs.getInt("datetime_fontsize", 6); mTextColor = GetPrefColor(prefs, "text_color", "#FFFFFFFF", Color.WHITE); mTextShadowColor = GetPrefColor(prefs, "text_shadowcolor", "#FF000000", Color.BLACK); mTextBackgroundColor = GetPrefColor(prefs, "text_backcolor", "#80FF0000", Color.argb(0x80, 0xFF, 0x00, 0x00)); mTextBackgroundLine = prefs.getBoolean("text_fillline", true); mTextX = prefs.getInt("text_x", 2); mTextY = prefs.getInt("text_y", 2); mTextAlign = Paint.Align.valueOf(prefs.getString("text_imprintalign", "LEFT")); mTextFontScale = (float) prefs.getInt("infotext_fontsize", 6); mTextFontname = prefs.getString("infotext_fonttypeface", ""); mStatusInfoColor = GetPrefColor(prefs, "statusinfo_color", "#FFFFFFFF", Color.WHITE); mStatusInfoShadowColor = GetPrefColor(prefs, "statusinfo_shadowcolor", "#FF000000", Color.BLACK); mStatusInfoX = prefs.getInt("statusinfo_x", 2); mStatusInfoY = prefs.getInt("statusinfo_y", 98); mStatusInfoAlign = Paint.Align.valueOf(prefs.getString("statusinfo_imprintalign", "LEFT")); mStatusInfoBackgroundColor = GetPrefColor(prefs, "statusinfo_backcolor", "#00000000", Color.TRANSPARENT); mStatusInfoFontScale = (float) prefs.getInt("statusinfo_fontsize", 6); mStatusInfoBackgroundLine = prefs.getBoolean("statusinfo_fillline", false); mGPSColor = GetPrefColor(prefs, "gps_color", "#FFFFFFFF", Color.WHITE); mGPSShadowColor = GetPrefColor(prefs, "gps_shadowcolor", "#FF000000", Color.BLACK); mGPSX = prefs.getInt("gps_x", 98); mGPSY = prefs.getInt("gps_y", 2); mGPSAlign = Paint.Align.valueOf(prefs.getString("gps_imprintalign", "RIGHT")); mGPSBackgroundColor = GetPrefColor(prefs, "gps_backcolor", "#00000000", Color.TRANSPARENT); mGPSFontScale = (float) prefs.getInt("gps_fontsize", 6); mGPSBackgroundLine = prefs.getBoolean("gps_fillline", false); mImprintPictureX = prefs.getInt("imprint_picture_x", 0); mImprintPictureY = prefs.getInt("imprint_picture_y", 0); mNightAutoConfigEnabled = prefs.getBoolean("night_auto_enabled", false); mSetNightConfiguration = prefs.getBoolean("cam_nightconfiguration", false); // override night camera parameters (read again with postfix) getCurrentNightSettings(); mFilterPicture = false; //***prefs.getBoolean("filter_picture", false); mFilterType = getEditInt(mContext, prefs, "filter_sel", 0); if (mImprintPicture) { if (mImprintPictureURL.length() == 0) { // sdcard image File path = new File(Environment.getExternalStorageDirectory() + "/MobileWebCam/"); if (path.exists()) { synchronized (gImprintBitmapLock) { if (gImprintBitmap != null) gImprintBitmap.recycle(); gImprintBitmap = null; File file = new File(path, "imprint.png"); try { FileInputStream in = new FileInputStream(file); gImprintBitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e) { Toast.makeText(mContext, "Error: unable to read imprint bitmap " + file.getName() + "!", Toast.LENGTH_SHORT).show(); gImprintBitmap = null; } catch (OutOfMemoryError e) { Toast.makeText(mContext, "Error: imprint bitmap " + file.getName() + " too large!", Toast.LENGTH_LONG).show(); gImprintBitmap = null; } } } } else { DownloadImprintBitmap(); } synchronized (gImprintBitmapLock) { if (gImprintBitmap == null) { // last resort: resource default try { gImprintBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.imprint); } catch (OutOfMemoryError e) { Toast.makeText(mContext, "Error: default imprint bitmap too large!", Toast.LENGTH_LONG) .show(); gImprintBitmap = null; } } } } mNoToasts = prefs.getBoolean("no_messages", false); mFullWakeLock = prefs.getBoolean("full_wakelock", true); switch (getEditInt(mContext, prefs, "camera_mode", 1)) { case 0: mMode = Mode.MANUAL; break; case 2: mMode = Mode.HIDDEN; break; case 3: mMode = Mode.BACKGROUND; break; case 1: default: mMode = Mode.NORMAL; break; } }
From source file:com.healthcit.cacure.dao.CouchDBDao.java
private void doHttp(HttpUriRequest request, OutputStream os) throws Exception { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = null; try {//from w ww . j a va 2 s .c o m instream = entity.getContent(); IOUtils.copy(instream, os); } catch (RuntimeException ex) { request.abort(); throw ex; } finally { try { instream.close(); os.close(); } catch (IOException ex) { ex.printStackTrace(); } } httpclient.getConnectionManager().shutdown(); } }
From source file:com.izforge.izpack.panels.shortcut.ShortcutPanelLogic.java
/** * Creates all shortcuts based on the information in shortcuts. *///from w ww.j ava 2 s .c om private void createShortcuts(List<ShortcutData> shortcuts) { if (!createShortcuts) { return; } String groupName; List<String> startMenuShortcuts = new ArrayList<String>(); for (ShortcutData data : shortcuts) { try { groupName = this.groupName + data.subgroup; shortcut.setUserType(userType); shortcut.setLinkName(data.name); shortcut.setLinkType(data.type); shortcut.setArguments(data.commandLine); shortcut.setDescription(data.description); shortcut.setIconLocation(data.iconFile, data.iconIndex); shortcut.setShowCommand(data.initialState); shortcut.setTargetPath(data.target); shortcut.setWorkingDirectory(data.workingDirectory); shortcut.setEncoding(data.deskTopEntryLinux_Encoding); shortcut.setMimetype(data.deskTopEntryLinux_MimeType); shortcut.setRunAsAdministrator(data.runAsAdministrator); shortcut.setTerminal(data.deskTopEntryLinux_Terminal); shortcut.setTerminalOptions(data.deskTopEntryLinux_TerminalOptions); shortcut.setType(data.deskTopEntryLinux_Type); shortcut.setKdeSubstUID(data.deskTopEntryLinux_X_KDE_SubstituteUID); shortcut.setKdeUserName(data.deskTopEntryLinux_X_KDE_UserName); shortcut.setURL(data.deskTopEntryLinux_URL); shortcut.setTryExec(data.TryExec); shortcut.setCategories(data.Categories); shortcut.setCreateForAll(data.createForAll); shortcut.setUninstaller(uninstallData); if (data.addToGroup) { shortcut.setProgramGroup(groupName); } else { shortcut.setProgramGroup(""); } shortcut.save(); if (data.type == Shortcut.APPLICATIONS || data.addToGroup) { if (shortcut instanceof com.izforge.izpack.util.os.Unix_Shortcut) { com.izforge.izpack.util.os.Unix_Shortcut unixcut = (com.izforge.izpack.util.os.Unix_Shortcut) shortcut; String f = unixcut.getWrittenFileName(); if (f != null) { startMenuShortcuts.add(f); } } } // add the file and directory name to the file list String fileName = shortcut.getFileName(); files.add(0, fileName); File file = new File(fileName); File base = new File(shortcut.getBasePath()); Vector<File> intermediates = new Vector<File>(); execFiles.add(new ExecutableFile(fileName, ExecutableFile.UNINSTALL, ExecutableFile.IGNORE, new ArrayList<OsModel>(), false)); files.add(fileName); while ((file = file.getParentFile()) != null) { if (file.equals(base)) { break; } intermediates.add(file); } if (file != null) { Enumeration<File> filesEnum = intermediates.elements(); while (filesEnum.hasMoreElements()) { files.add(0, filesEnum.nextElement().toString()); } } } catch (Exception ignored) { } } if (OsVersion.IS_UNIX) { writeXDGMenuFile(startMenuShortcuts, this.groupName, programGroupIconFile, programGroupComment); } shortcut.execPostAction(); try { if (execFiles != null) { // // TODO: Hi Guys, // TODO The following commented lines sometimes produces an uncatchable // nullpointer Exception! // TODO evaluate for what reason the files should exec. // TODO if there is a serious explanation, why to do that, // TODO the code must be more robust //FileExecutor executor = new FileExecutor(execFiles); // evaluate executor.executeFiles( ExecutableFile.NEVER, null ); } } catch (NullPointerException nep) { nep.printStackTrace(); } catch (RuntimeException cannot) { cannot.printStackTrace(); } shortcut.cleanUp(); }
From source file:es.pode.buscar.negocio.buscar.servicios.SrvBuscarServiceImpl.java
/** * @see es.pode.buscar.negocio.servicios.SrvBuscarService#solicitarMetadato(es.pode.buscar.negocio.servicios.ParametroMetadatoVO) * @param es.pode.buscar.negocio.servicios.ParametroMetadatoVO Este VO alberga los parametros necesarios para consultar los metadatos de un ODE dado * @return es.pode.buscar.negocio.servicios.MetadatoBasicoVO Esta clase representa la meta informacion de un ODE *//*from www. j a v a 2 s .com*/ protected es.pode.buscar.negocio.buscar.servicios.MetadatoBasicoVO handleSolicitarMetadato( es.pode.buscar.negocio.buscar.servicios.ParametroMetadatoVO parametros) throws java.lang.Exception { try { if (logger.isDebugEnabled()) logger.debug("SrvBuscarServiceImpl - handleSolicitarMetadato:Buscando metadatos para MEC[" + parametros.getIdentificadorODE() + "] en el idioma[" + parametros.getIdioma() + "]"); DocVO documentoBusqueda = this.getSrvBuscadorService().busquedaMEC(parametros.getIdentificadorODE(), parametros.getIdioma()); if (documentoBusqueda != null) { if (logger.isDebugEnabled()) { logger.debug("SrvBuscarServiceImpl - handleSolicitarMetadato:Encontrados metadatos para MEC[" + parametros.getIdentificadorODE() + "] en el idioma[" + parametros.getIdioma() + "]"); logger.debug("SrvBuscarServiceImpl - handleSolicitarMetadato: MetadatoBasico= Licencias-" + documentoBusqueda.getLicencias() + " Titulo-" + documentoBusqueda.getTitulo() + " Descripcion-" + documentoBusqueda.getDescripcion() + " Formato-" + documentoBusqueda.getFormato() + " Destinatarios-" + documentoBusqueda.getDestinatarios() + " Idioma-" + documentoBusqueda.getIdioma() + " Ambito-" + documentoBusqueda.getAmbito() + " Valoracion-" + documentoBusqueda.getValoracion() + " LocalizadorODE-" + documentoBusqueda.getLocalizadorODE() + " IdentificadorODE-" + documentoBusqueda.getIdentificadorODE() + " Imagen-" + documentoBusqueda.getImagen() + " NivelAgregacion-" + documentoBusqueda.getNivelAgregacion() + " Tamanio-" + documentoBusqueda.getTamanio() + " conSinSecuencia-" + documentoBusqueda.getConSinSecuencia()); } String[] ambitosTraducidos = null; if (documentoBusqueda.getAmbito() != null && documentoBusqueda.getAmbito().length > 0 && !documentoBusqueda.getAmbito().equals(AMBITO_UNIVERSAL)) { String[] ambitos = documentoBusqueda.getAmbito(); ambitosTraducidos = new String[ambitos.length]; NodoVO[] nodos = this.getSrvNodoService().listarNodos(); if (nodos != null) { for (int j = 0; j < ambitos.length; j++) { boolean encontrado = false; for (int i = 0; i < nodos.length; i++) { if (nodos[i].getIdNodo().equals(ambitos[j])) { ambitosTraducidos[j] = nodos[i].getNodo(); encontrado = true; } else if (DependentServerProperties.getInstance().getProperty(IDENTIFICADOR_NODO) .equals(ambitos[j])) { ambitosTraducidos[j] = DependentServerProperties.getInstance().getServerOn(); encontrado = true; } } if (!encontrado) { ambitosTraducidos[j] = ambitos[j]; } } } } return new MetadatoBasicoVO(documentoBusqueda.getLicencias(), documentoBusqueda.getTitulo(), documentoBusqueda.getDescripcion(), documentoBusqueda.getFormato(), documentoBusqueda.getDestinatarios(), documentoBusqueda.getIdioma(), (ambitosTraducidos != null) ? ambitosTraducidos : documentoBusqueda.getAmbito(), documentoBusqueda.getValoracion(), documentoBusqueda.getLocalizadorODE(), documentoBusqueda.getIdentificadorODE(), documentoBusqueda.getImagen(), documentoBusqueda.getNivelAgregacion(), documentoBusqueda.getTamanio(), documentoBusqueda.getConSinSecuencia(), documentoBusqueda.getFechaPublicacion(), documentoBusqueda.getHoraPublicacion(), documentoBusqueda.getSize(), array2String(documentoBusqueda.getTipoRecurso(), ","), documentoBusqueda.getAnnotation()); } else { logger.error("SrvBuscarServiceImpl - handleSolicitarMetadato:Error buscando metadatos para MEC[" + parametros.getIdentificadorODE() + "] en el idioma[" + parametros.getIdioma() + "]. No hay resultados disponibles."); throw new Exception( "SrvBuscarServiceImpl - handleSolicitarMetadato:Error buscando metadatos para MEC[" + parametros.getIdentificadorODE() + "] en el idioma[" + parametros.getIdioma() + "]. No hay resultados disponibles."); } } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new Exception( "SrvBuscarServiceImpl - handleSolicitarMetadato:Excepcion buscando metadatos para MEC[" + parametros.getIdentificadorODE() + "] en el idioma[" + parametros.getIdioma() + "].", e); } }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.Analyzer.java
/** * Generates the analysis of all data recorded in this analyzer. * /*from w w w . jav a 2 s . c om*/ * @return an object storing the results of the analysis */ public AnalyzerResults getAnalysis() { if (data.isEmpty()) { return new AnalyzerResults(); } Problem problem = null; try { problem = getProblemInstance(); //instantiate the reference set NondominatedPopulation referenceSet = getReferenceSet(); //setup the quality indicators List<Indicator> indicators = new ArrayList<Indicator>(); if (includeHypervolume) { indicators.add(new Hypervolume(problem, referenceSet)); } if (includeGenerationalDistance) { indicators.add(new GenerationalDistance(problem, referenceSet)); } if (includeInvertedGenerationalDistance) { indicators.add(new InvertedGenerationalDistance(problem, referenceSet)); } if (includeAdditiveEpsilonIndicator) { indicators.add(new AdditiveEpsilonIndicator(problem, referenceSet)); } if (includeMaximumParetoFrontError) { indicators.add(new MaximumParetoFrontError(problem, referenceSet)); } if (includeSpacing) { indicators.add(new Spacing(problem)); } if (includeContribution) { if (epsilon == null) { indicators.add(new Contribution(referenceSet)); } else { indicators.add(new Contribution(referenceSet, epsilon)); } } if (includeR1) { indicators.add(new R1Indicator(problem, R1Indicator.getDefaultSubdivisions(problem), referenceSet)); } if (includeR2) { indicators.add(new R2Indicator(problem, R2Indicator.getDefaultSubdivisions(problem), referenceSet)); } if (includeR3) { indicators.add(new R3Indicator(problem, R3Indicator.getDefaultSubdivisions(problem), referenceSet)); } if (indicators.isEmpty()) { System.err.println("no indicators selected"); return new AnalyzerResults(); } //generate the aggregate sets Map<String, NondominatedPopulation> aggregateSets = new HashMap<String, NondominatedPopulation>(); if (showAggregate) { for (String algorithm : data.keySet()) { NondominatedPopulation aggregateSet = newArchive(); for (NondominatedPopulation set : data.get(algorithm)) { aggregateSet.addAll(set); } aggregateSets.put(algorithm, aggregateSet); } } //precompute the individual seed metrics, as they are used both //for descriptive statistics and statistical significance tests AnalyzerResults analyzerResults = new AnalyzerResults(); for (String algorithm : data.keySet()) { AlgorithmResult algorithmResult = new AlgorithmResult(algorithm); for (Indicator indicator : indicators) { String indicatorName = indicator.getClass().getSimpleName(); List<NondominatedPopulation> sets = data.get(algorithm); double[] values = new double[sets.size()]; for (int i = 0; i < sets.size(); i++) { values[i] = indicator.evaluate(sets.get(i)); } algorithmResult.add(new IndicatorResult(indicatorName, values)); if (showAggregate) { algorithmResult.get(indicatorName) .setAggregateValue(indicator.evaluate(aggregateSets.get(algorithm))); } } analyzerResults.add(algorithmResult); } //precompute the statistical significance of the medians if (showStatisticalSignificance) { List<String> algorithms = new ArrayList<String>(data.keySet()); for (Indicator indicator : indicators) { String indicatorName = indicator.getClass().getSimpleName(); //insufficient number of samples, skip test if (algorithms.size() < 2) { continue; } KruskalWallisTest kwTest = new KruskalWallisTest(algorithms.size()); for (int i = 0; i < algorithms.size(); i++) { String algorithm = algorithms.get(i); double[] values = analyzerResults.get(algorithm).get(indicatorName).getValues(); kwTest.addAll(values, i); } try { if (!kwTest.test(significanceLevel)) { for (int i = 0; i < algorithms.size() - 1; i++) { for (int j = i + 1; j < algorithms.size(); j++) { analyzerResults.get(algorithms.get(i)).get(indicatorName) .addIndifferentAlgorithm(algorithms.get(j)); analyzerResults.get(algorithms.get(j)).get(indicatorName) .addIndifferentAlgorithm(algorithms.get(i)); } } } else { for (int i = 0; i < algorithms.size() - 1; i++) { for (int j = i + 1; j < algorithms.size(); j++) { MannWhitneyUTest mwTest = new MannWhitneyUTest(); mwTest.addAll( analyzerResults.get(algorithms.get(i)).get(indicatorName).getValues(), 0); mwTest.addAll( analyzerResults.get(algorithms.get(j)).get(indicatorName).getValues(), 1); if (!mwTest.test(significanceLevel)) { analyzerResults.get(algorithms.get(i)).get(indicatorName) .addIndifferentAlgorithm(algorithms.get(j)); analyzerResults.get(algorithms.get(j)).get(indicatorName) .addIndifferentAlgorithm(algorithms.get(i)); } } } } } catch (RuntimeException e) { e.printStackTrace(); } } } return analyzerResults; } finally { if (problem != null) { problem.close(); } } }
From source file:com.cyberway.issue.crawler.frontier.AdaptiveRevisitFrontier.java
protected synchronized void innerFinished(CrawlURI curi) { try {/* ww w . j av a 2s .c om*/ innerBatchFlush(); if (curi.isSuccess()) { successDisposition(curi); } else if (needsPromptRetry(curi)) { // Consider statuses which allow nearly-immediate retry // (like deferred to allow precondition to be fetched) reschedule(curi, false); } else if (needsRetrying(curi)) { // Consider errors which can be retried reschedule(curi, true); controller.fireCrawledURINeedRetryEvent(curi); } else if (isDisregarded(curi)) { // Check for codes that mean that while the crawler did // manage to get it it must be disregarded for any reason. disregardDisposition(curi); } else { // In that case FAILURE, note & log failureDisposition(curi); } // New items might be available, let waiting threads know // More then one queue might have become available due to // scheduling of items outside the parent URIs host, so we // wake all waiting threads. notifyAll(); } catch (RuntimeException e) { curi.setFetchStatus(S_RUNTIME_EXCEPTION); // store exception temporarily for logging logger.warning("RTE in innerFinished() " + e.getMessage()); e.printStackTrace(); curi.putObject(A_RUNTIME_EXCEPTION, e); failureDisposition(curi); } catch (AttributeNotFoundException e) { logger.severe(e.getMessage()); } }
From source file:com.connectsdk.service.DLNAService.java
@Override public void getVolume(final VolumeListener listener) { String method = "GetVolume"; String instanceId = "0"; String channel = "Master"; Map<String, String> params = new LinkedHashMap<String, String>(); params.put("Channel", channel); String payload = getMessageXml(RENDERING_CONTROL_URN, method, instanceId, params); ResponseListener<Object> responseListener = new ResponseListener<Object>() { @Override// w w w. j a v a 2 s .c o m public void onSuccess(Object response) { String currentVolume = parseData((String) response, "CurrentVolume"); int iVolume = 0; try { //noinspection ResultOfMethodCallIgnored Integer.parseInt(currentVolume); } catch (RuntimeException ex) { ex.printStackTrace(); } float fVolume = (float) (iVolume / 100.0); Util.postSuccess(listener, fVolume); } @Override public void onError(ServiceCommandError error) { Util.postError(listener, error); } }; ServiceCommand<VolumeListener> request = new ServiceCommand<VolumeListener>(this, method, payload, responseListener); request.send(); }
From source file:org.coltram.nsd.upnp.UPnPProcessor.java
public void exposeService(String serviceType, String friendlyName, String deviceType, String serviceId, JSONObject service, AtomConnection connection, String serviceImplementationName) throws JSONException { ActionList actionList;//from ww w . j av a2 s . c o m try { actionList = new ActionList(service.getJSONArray("actionList"), connection, serviceImplementationName, service.optJSONArray("eventList")); } catch (RuntimeException e) { // error in service description, translated to runtimeexception, so stop processing return; } try { GenericService exposedService = new GenericService<GenericService>( ServiceType.valueOf(serviceType.substring(5)), ServiceId.valueOf(serviceId), actionList, false); exposedService.setManager(new ServiceManager<GenericService>(exposedService, GenericService.class)); LocalDevice newDevice = new LocalDevice(new DeviceIdentity(new UDN(friendlyName)), DeviceType.valueOf(deviceType), new DeviceDetails(friendlyName), exposedService); //Logger.logln("exposeService " + serviceType); coltramManager.getConnectionManager().getUpnpService().getRegistry().addDevice(newDevice); connection.add(newDevice); serviceId = newDevice.getIdentity().getUdn().getIdentifierString() + exposedService.getReference().getServiceId().toString(); connection.setExposedService(serviceId); log.finer("exposed Service: friendlyName=" + friendlyName + ", type=" + deviceType + ", serviceId=" + serviceId + ", serviceImplementationName=" + serviceImplementationName); } catch (ValidationException e) { e.printStackTrace(); } }
From source file:com.aviary.android.feather.sdk.widget.AviaryWorkspace.java
@Override protected void dispatchDraw(Canvas canvas) { boolean restore = false; int restoreCount = 0; if (mItemCount < 1) return;/* w w w .j ava2 s . com*/ if (mCurrentScreen < 0) return; boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING && mNextScreen == INVALID_SCREEN; // If we are not scrolling or flinging, draw only the current screen if (fastDraw) { try { drawChild(canvas, getChildAt(mCurrentScreen - mFirstPosition), getDrawingTime()); } catch (RuntimeException e) { e.printStackTrace(); } } else { final long drawingTime = getDrawingTime(); final float scrollPos = (float) getScrollX() / getTotalWidth(); final int leftScreen = (int) scrollPos; final int rightScreen = leftScreen + 1; if (leftScreen >= 0) { try { drawChild(canvas, getChildAt(leftScreen - mFirstPosition), drawingTime); } catch (RuntimeException e) { e.printStackTrace(); } } if (scrollPos != leftScreen && rightScreen < mItemCount) { try { drawChild(canvas, getChildAt(rightScreen - mFirstPosition), drawingTime); } catch (RuntimeException e) { e.printStackTrace(); } } } // let's draw the edges only if we have more than 1 page if (mEdgeGlowLeft != null && mItemCount > 1) { drawEdges(canvas); } if (restore) { canvas.restoreToCount(restoreCount); } }
From source file:com.ibm.iotf.client.AbstractClient.java
/** * Call to the connectUsingCertificate() method is made, when the User chooses to connect to the Watson * IoT Platform using Client Certificate as the preferred Authentication mechanism. The Device Properties * file allows you enable either Token based or Certificate based or both mechanisms to authenticate. * However, setting the value to either 'True' or 'False' against the parameter 'Use-Secure-Certificate', * facilitates usage of Certificates for authentication or not, respectively. * Setting the value of parameter 'Use-Secure-Certificate' to 'True' in the Device.Properties file will * make a call to the following method. *///from www .j a v a 2 s .c om private void connectUsingCertificate() { final String METHOD = "connectUsingCertificate"; String protocol = null; int port = getPortNumber(); if (isWebSocket()) { protocol = "wss://"; // If there is no port specified use default if (port == -1) { port = WSS_PORT; } } else { protocol = "ssl://"; // If there is no port specified use default if (port == -1) { port = MQTTS_PORT; } } String mqttServer = getMQTTServer(); if (mqttServer != null) { serverURI = protocol + mqttServer + ":" + port; } else { serverURI = protocol + getOrgId() + "." + MESSAGING + "." + this.getDomain() + ":" + port; } try { mqttAsyncClient = new MqttAsyncClient(serverURI, clientId, DATA_STORE); mqttAsyncClient.setCallback(mqttCallback); mqttClientOptions = new MqttConnectOptions(); if (clientUsername != null) { mqttClientOptions.setUserName(clientUsername); } if (clientPassword != null) { mqttClientOptions.setPassword(clientPassword.toCharArray()); } mqttClientOptions.setCleanSession(this.isCleanSession()); if (this.keepAliveInterval != -1) { mqttClientOptions.setKeepAliveInterval(this.keepAliveInterval); } mqttClientOptions.setMaxInflight(getMaxInflight()); mqttClientOptions.setAutomaticReconnect(isAutomaticReconnect()); /* This isn't needed as the production messaging.internetofthings.ibmcloud.com * certificate should already be in trust chain. * * See: * http://stackoverflow.com/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection * https://gerrydevstory.com/2014/05/01/trusting-x509-base64-pem-ssl-certificate-in-java/ * http://stackoverflow.com/questions/12501117/programmatically-obtain-keystore-from-pem * https://gist.github.com/sharonbn/4104301 * * CertificateFactory cf = CertificateFactory.getInstance("X.509"); * InputStream certFile = AbstractClient.class.getResourceAsStream("messaging.pem"); * Certificate ca = cf.generateCertificate(certFile); * * KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); * keyStore.load(null, null); * keyStore.setCertificateEntry("ca", ca); * TrustManager trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore); * SSLContext sslContext = SSLContextUtils.createSSLContext("TLSv1.2", null, trustManager); * */ SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); String serverCert = null; String clientCert = null; String clientCertKey = null; String certPassword = null; //Validate the availability of Server Certificate if (trimedValue(options.getProperty("Server-Certificate")) != null) { if (trimedValue(options.getProperty("Server-Certificate")).contains(".pem") || trimedValue(options.getProperty("Server-Certificate")).contains(".der") || trimedValue(options.getProperty("Server-Certificate")).contains(".cer")) { serverCert = trimedValue(options.getProperty("Server-Certificate")); } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Only PEM, DER & CER certificate formats are supported at this point of time"); throw new RuntimeException( "Only PEM, DER & CER certificate formats are supported at this point of time"); } } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Value for Server Certificate is missing, using default one"); } //Validate the availability of Client Certificate if (trimedValue(options.getProperty("Client-Certificate")) != null) { if (trimedValue(options.getProperty("Client-Certificate")).contains(".pem") || trimedValue(options.getProperty("Client-Certificate")).contains(".der") || trimedValue(options.getProperty("Client-Certificate")).contains(".cer")) { clientCert = trimedValue(options.getProperty("Client-Certificate")); } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Only PEM, DER & CER certificate formats are supported at this point of time"); throw new RuntimeException( "Only PEM, DER & CER certificate formats are supported at this point of time"); } } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Value for Client Certificate is missing"); throw new RuntimeException("Value for Client Certificate is missing"); } //Validate the availability of Client Certificate Key if (trimedValue(options.getProperty("Client-Key")) != null) { if (trimedValue(options.getProperty("Client-Key")).contains(".key")) { clientCertKey = trimedValue(options.getProperty("Client-Key")); } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Only Certificate key in .key format is supported at this point of time"); return; } } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Value for Client Key is missing"); return; } //Validate the availability of Certificate Password try { if (trimedValue(options.getProperty("Certificate-Password")) != null) { certPassword = trimedValue(options.getProperty("Certificate-Password")); } else { certPassword = ""; } } catch (RuntimeException e) { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Value for Certificate Password is missing", e); throw e; } mqttClientOptions .setSocketFactory(getSocketFactory(serverCert, clientCert, clientCertKey, certPassword)); } catch (Exception e) { LoggerUtility.warn(CLASS_NAME, METHOD, "Unable to configure TLSv1.2 connection: " + e.getMessage()); e.printStackTrace(); throw new RuntimeException(e.getMessage()); } }