@Override protected File doInBackground(ImageFile... params) { Log.i(TAG, "------------------ start compress file ------------------"); ImageFile srcFileInfo = params[0]; Bitmap.CompressFormat format = mCompressFormat; if (format == null) { format = CompressFormatUtils.parseFormat(srcFileInfo.mSrcFilePath); } Log.i(TAG, "use compress format:" + format.name()); File outputFile = CommonUtils.generateExternalImageCacheFile(mContext, CompressFormatUtils.getExt(format)); File srcFile = new File(srcFileInfo.mSrcFilePath); boolean isCompress = compressImageFile( srcFileInfo.mSrcFilePath, outputFile.getPath(), mMaxWidth, mMaxHeight, mQuality, format); if (!isCompress) { // 没有压缩,直接copy CommonUtils.copy(srcFile, outputFile); } if (srcFileInfo.mDeleteSrc) { srcFile.delete(); } return outputFile; }
@Override protected List<String> doInBackground(ImageFile... params) { Log.i(TAG, "------------------ start compress file ------------------"); List<String> outs = new ArrayList<>(params.length); for (ImageFile srcFileInfo : params) { Bitmap.CompressFormat format = mCompressFormat; if (format == null) { format = CompressFormatUtils.parseFormat(srcFileInfo.mSrcFilePath); } File outputFile = CommonUtils.generateExternalImageCacheFile( mContext, CompressFormatUtils.getExt(format)); File srcFile = new File(srcFileInfo.mSrcFilePath); boolean isCompress = compressImageFile( srcFileInfo.mSrcFilePath, outputFile.getPath(), mMaxWidth, mMaxHeight, mQuality, format); if (!isCompress) { // 没有压缩,直接copy CommonUtils.copy(srcFile, outputFile); } if (srcFileInfo.mDeleteSrc) { //noinspection ResultOfMethodCallIgnored srcFile.delete(); } outs.add(outputFile.getPath()); } return outs; }
public void compress(String fileName, boolean deleteSrc) { if (mMaxHeight <= 0 || mMaxWidth <= 0) { if (mCallback != null) { File outputFile = CommonUtils.generateExternalImageCacheFile(mContext, ".jpg"); CommonUtils.copy(new File(fileName), outputFile); mCallback.onCallBack(outputFile); } } else { ImageFile srcImageFile = new ImageFile(fileName, deleteSrc); new CompressTask().execute(srcImageFile); } }
/** * Returns the runtime property with the given name. * * @param propertyName * @param defaultValue * @return */ public static String getSystemProperty(String property, String defaultValue) { String value = null; if (CommonUtils.isNullOrEmpty(value)) { value = System.getProperty(property); } if (CommonUtils.isNullOrEmpty(value)) { value = System.getenv(property); } return value != null ? value : defaultValue; }
protected final String constructServiceUrl( final HttpServletRequest request, final HttpServletResponse response) throws ServletException { // return CommonUtils.constructServiceUrl(request, response, this.service, // this.serverName, this.artifactParameterName, this.encodeServiceUrl); return CommonUtils.constructServiceUrl( request, response, this.service, CommonUtils.obtainServerName(request), this.artifactParameterName, this.encodeServiceUrl); }
private static void verifyDifficulty( StoredBlock prevBlock, Block added, BigInteger calcDiff, NetworkParameters params) { if (calcDiff.compareTo(params.getMaxTarget()) > 0) { log.info("Difficulty hit proof of work limit: {}", calcDiff.toString(16)); calcDiff = params.getMaxTarget(); } int accuracyBytes = (int) (added.getDifficultyTarget() >>> 24) - 3; final BigInteger receivedDifficulty = added.getDifficultyTargetAsInteger(); // The calculated difficulty is to a higher precision than received, so reduce here. final BigInteger mask = BigInteger.valueOf(0xFFFFFFL).shiftLeft(accuracyBytes * 8); calcDiff = calcDiff.and(mask); if (CoinDefinition.TEST_NETWORK_STANDARD.equals(params.getStandardNetworkId())) { if (calcDiff.compareTo(receivedDifficulty) != 0) { throw new VerificationException( "Network provided difficulty bits do not match what was calculated: " + receivedDifficulty.toString(16) + " vs " + calcDiff.toString(16)); } } else { final int height = prevBlock.getHeight() + 1; if (height <= 68589) { long nBitsNext = added.getDifficultyTarget(); long calcDiffBits = (accuracyBytes + 3) << 24; calcDiffBits |= calcDiff.shiftRight(accuracyBytes * 8).longValue(); final double n1 = CommonUtils.convertBitsToDouble(calcDiffBits); final double n2 = CommonUtils.convertBitsToDouble(nBitsNext); if (Math.abs(n1 - n2) > n1 * 0.2) { throw new VerificationException( "Network provided difficulty bits do not match what was calculated: " + receivedDifficulty.toString(16) + " vs " + calcDiff.toString(16)); } } else { if (calcDiff.compareTo(receivedDifficulty) != 0) { throw new VerificationException( "Network provided difficulty bits do not match what was calculated: " + receivedDifficulty.toString(16) + " vs " + calcDiff.toString(16)); } } } }
@Override protected void onPreExecute() { super.onPreExecute(); if (isProgress) { CommonUtils.displayProgressDialog(context, "Fetching a fancy joke"); } }
public FavurlShowDiskCache(Context context) { File cacheDir = CommonUtils.getDiskCacheDir(context, Constants.FAVURL_CACHE_DIR); if (!cacheDir.exists()) { cacheDir.mkdirs(); } try { diskCache = DiskLruCache.open( cacheDir, CommonUtils.getAppVersion(context), 1, Constants.BITMAP_CACHE_MAX_SIZE); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private Normalizer[] getNorms(List<String> norms) { Normalizer[] norms2 = new Normalizer[norms.size()]; for (int i = 0; i < norms2.length; i++) { norms2[i] = (Normalizer) CommonUtils.getInstance(norms.get(i)); } return norms2; }
private static StringRequest get() { StringRequest sr = new StringRequest( Request.Method.GET, parameters.appHost + "?" + CommonUtils.map2String(parameters.params), successListener, errorListener); return sr; }
@Override protected void onPostExecute(String result) { Log.d("Result", result); if (isProgress) CommonUtils.dismissProgressDialog(); Intent intent = new Intent(context, JokeDisplayActivity.class); intent.putExtra(JokeDisplayActivity.INTENT_TAG, result); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.gplus_signin); btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in); btnSignOut = (Button) findViewById(R.id.btn_sign_out); btnStart = (Button) findViewById(R.id.btn_launch_app); btnOnTime = (Button) findViewById(R.id.btn_note_on_time); btnOffTime = (Button) findViewById(R.id.btn_note_off_time); btnEntryStn = (Button) findViewById(R.id.btn_entry_station); btnExitStn = (Button) findViewById(R.id.btn_exit_station); imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic); txtName = (TextView) findViewById(R.id.txtName); txtFileUpload = (TextView) findViewById(R.id.txt_file_upload); txtDatasent = (TextView) findViewById(R.id.txtDatasent); imgAppName = (ImageView) findViewById(R.id.imgappname); imgAppIcon = (ImageView) findViewById(R.id.imgicon); context = getApplicationContext(); // Button click listeners btnStart.setOnClickListener(this); btnEntryStn.setOnClickListener(this); btnExitStn.setOnClickListener(this); btnOnTime.setOnClickListener(this); btnOffTime.setOnClickListener(this); btnSignIn.setOnClickListener(this); btnSignOut.setOnClickListener(this); sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // Initializing google plus api client mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(Plus.SCOPE_PLUS_LOGIN) .build(); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // opening file to record time of entry and exit logFile = new File(CommonUtils.getFilepath("TimeLog.txt")); try { timeBuf = new BufferedWriter(new FileWriter(logFile, true)); Log.i("File opened:", "Preparing to write data"); isBufferWriterOpen = true; } catch (IOException e) { e.printStackTrace(); } }
public static Set<SqlParams<?>> filtreToSqlparams(final FiltreForm filtreForm) { Set<SqlParams<?>> args = new HashSet<SqlParams<?>>(); int anneeDebut = filtreForm.getAnneeDebut(); if (anneeDebut > 0) { args.add( new SqlParams<Date>( dateFabrication, SUPERIOR_OR_EQUALS, CommonUtils.toSqlDate(1, 0, anneeDebut))); } int anneeFin = filtreForm.getAnneeFin(); if (anneeFin > 0) { args.add( new SqlParams<Date>( dateFabrication, INFERIOR_OR_EQUALS, CommonUtils.toSqlDate(1, 0, anneeFin))); } Set<String> couleur = filtreForm.getCouleur(); if (CommonUtils.isNotNullOrEmpty(couleur)) { args.add(new SqlParams<String>("couleur", EQUALS, couleur)); } Set<String> etat = filtreForm.getEtat(); if (CommonUtils.isNotNullOrEmpty(etat)) { args.add(new SqlParams<String>(Props.etat, EQUALS, etat)); } String marque = filtreForm.getMarque(); if (isNotNullOrEmpty(marque)) { args.add(new SqlParams<String>(Props.marque, EQUALS, marque)); } int prixMaximum = filtreForm.getPrixMaximum(); if (prixMaximum > 0) { args.add(new SqlParams<Double>(montantHt, INFERIOR_OR_EQUALS, getMontantHT(prixMaximum))); } int prixMinimum = filtreForm.getPrixMinimum(); if (prixMinimum > 0) { args.add(new SqlParams<Double>(montantHt, SUPERIOR_OR_EQUALS, getMontantHT(prixMinimum))); } Set<String> categorie = toSelection(filtreForm.getCategoriesTree()); if (CommonUtils.isNotNullOrEmpty(categorie)) { args.add(new SqlParams<String>(Props.categorie, EQUALS, categorie)); } return args; }
/** 解析一个TLV,返回Value的字节数组,可以使用getTag()方法获取当前的TAG,没有数据可解析或解析错误时返回null */ public byte[] parseOneTlv() { try { // tag try { CommonUtils.readBytes(mDataStream, mTagData); } catch (Exception e) { // 获取tag失败,返回null clearTlv(); return null; } // length CommonUtils.readBytes(mDataStream, mLengthData); mLength = ByteArrayUtils.toInt(mLengthData); // value mValueData = new byte[mLength]; CommonUtils.readBytes(mDataStream, mValueData); } catch (IOException e) { // Should never happen clearTlv(); e.printStackTrace(); } return mValueData; }
protected String getDCNodeDN(SSOToken token, String orgDN) throws AMException { try { String domainName = getCanonicalDomain(token, orgDN); if (domainName != null) { DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN)); String dcNodeDN = dcTree.mapDomainToDN(domainName); return CommonUtils.formatToRFC(dcNodeDN); } else { return null; } } catch (InvalidDCRootException e) { debug.error("DCTree.getDCNodeDN(): Invalid DC root ", e); throw new AMException(AMSDKBundle.getString("343"), "343"); } catch (UMSException e) { debug.error("DCTree.getDCNodeDN(): Unable to get dc node dn " + "for: " + orgDN, e); throw new AMException(AMSDKBundle.getString("344"), "344"); } }
public static Document parseXml(String xmlData) throws Exception { if (xmlData == null) { return null; } // Parse xml data. if (LOG.isDebugEnabled()) { LOG.debug("Parsing xml data:\n" + xmlData); } DocumentBuilderFactory factory = createDocumentBuilderFactory(); DocumentBuilder builder = null; StringReader stringReader = null; Document document = null; try { builder = factory.newDocumentBuilder(); stringReader = new StringReader(xmlData); InputSource inputSource = new InputSource(stringReader); document = builder.parse(inputSource); } finally { CommonUtils.closeQuietly(stringReader); } return document; }
/** * Gets the parameters from the input string. * * @param text The input string. * @param numbers The list of line numbers. * @return A map containing the directive parameters. * @throws AraraException Something wrong happened, to be caught in the higher levels. */ private static Map<String, Object> getParameters(String text, List<Integer> numbers) throws AraraException { if (text == null) { return new HashMap<String, Object>(); } Yaml yaml = new Yaml( new Constructor(), new Representer(), new DumperOptions(), new DirectiveResolver()); try { @SuppressWarnings("unchecked") HashMap<String, Object> map = yaml.loadAs(text, HashMap.class); return map; } catch (MarkedYAMLException exception) { throw new AraraException( messages.getMessage( Messages.ERROR_VALIDATE_YAML_EXCEPTION, CommonUtils.getCollectionElements(numbers, "(", ")", ", ")), exception); } }
private boolean internetConnectionCheck() { if (CommonUtils.isInternetAvailable(context) < 0) { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("File Upload Failed"); alertDialog.setCancelable(false); alertDialog.setMessage( "No internet connection. Please switch on your Wi-Fi or Mobile Data for Uploading Data"); alertDialog.setPositiveButton( "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog // Toast.makeText(getApplicationContext(),"You clicked on YES", // Toast.LENGTH_SHORT).show(); } }); alertDialog.show(); return false; } else { return true; } }
public static boolean copyFile(String filename, File fromDir, File toDir) { log.debug("Copying:" + filename); boolean ok = false; try { // ensure the target dir exists or FileNotFoundException is thrown creating dst FileChannel toDir.mkdir(); File fromFile = new File(fromDir, filename); File targetFile = new File(toDir, filename); // don't worry if tofile exists, allow overwrite if (fromFile.exists()) { long fromFileSize = fromFile.length(); log.debug("Source file length:" + fromFileSize); if (fromFileSize > CommonUtils.getFreeSpace(toDir.getPath())) { // not enough room on SDcard ok = false; } else { // move the file FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dst = new FileOutputStream(targetFile).getChannel(); try { dst.transferFrom(src, 0, src.size()); ok = true; } finally { src.close(); dst.close(); } } } else { // fromfile does not exist ok = false; } } catch (Exception e) { log.error("Error moving file to sd card", e); } return ok; }
private static JSONObject addRequiredParams(JSONObject postParams) { try { postParams.put("apiKey", CommonUtils.replaceWithJSONNull(ZeTarget.getApiKey())); postParams.put("userId", CommonUtils.replaceWithJSONNull(ZeTarget.getUserId())); postParams.put("deviceId", CommonUtils.replaceWithJSONNull(ZeTarget.getDeviceId())); postParams.put("sdkId", CommonUtils.replaceWithJSONNull(Constants.Z_SDK_ID)); postParams.put("deviceModel", CommonUtils.replaceWithJSONNull(DeviceDetails.getModel())); postParams.put( "appVersion", CommonUtils.replaceWithJSONNull(ZeTarget.deviceDetails.getVersionName())); return postParams; } catch (Exception e) { if (ZeTarget.isDebuggingOn()) { Log.e(TAG, "Exception: " + e); } } return postParams; }
/** * Generates a directive from a directive assembler. * * @param assembler The directive assembler. * @return The corresponding directive. * @throws AraraException Something wrong happened, to be caught in the higher levels. */ public static Directive generateDirective(DirectiveAssembler assembler) throws AraraException { String regex = (String) ConfigurationController.getInstance().get("directives.pattern"); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(assembler.getText()); if (matcher.find()) { Directive directive = new Directive(); directive.setIdentifier(matcher.group(1)); directive.setParameters(getParameters(matcher.group(3), assembler.getLineNumbers())); Conditional conditional = new Conditional(); conditional.setType(getType(matcher.group(5))); conditional.setCondition(getCondition(matcher.group(6))); directive.setConditional(conditional); directive.setLineNumbers(assembler.getLineNumbers()); logger.info(messages.getMessage(Messages.LOG_INFO_POTENTIAL_DIRECTIVE_FOUND, directive)); return directive; } else { throw new AraraException( messages.getMessage( Messages.ERROR_VALIDATE_INVALID_DIRECTIVE_FORMAT, CommonUtils.getCollectionElements(assembler.getLineNumbers(), "(", ")", ", "))); } }
public boolean _GetRdReserve() { setErrmsg(MSGID + "予約一覧取得は無効です。"); final String sysDir = getUser(); final String iniFile = sysDir + File.separator + "TVTest.ini"; File d = new File(sysDir); if (!d.exists() || !d.isDirectory()) { String msg = ERRID + "指定のディレクトリがみつからないか、あるいはディレクトリではありません:" + sysDir; setErrmsg(msg); // System.out.println(msg); return (false); } String DriverDirectory = null; ArrayList<String> Drivers = new ArrayList<String>(); String buf = CommonUtils.read4file(iniFile, false, "Unicode"); if (buf == null) { String msg = ERRID + "設定ファイルが取得できませんでした:" + iniFile; setErrmsg(msg); // System.out.println(msg); return false; } String[] sa = buf.split("[\r\n]+"); for (String str : sa) { Matcher ma = Pattern.compile("^DriverDirectory=(.+?)\\s*$", Pattern.DOTALL).matcher(str); if (ma.find()) { DriverDirectory = ma.group(1); if (getDebug()) System.out.println(DBGID + "ドライバーディレクトリの取得: " + ma.group(1)); continue; } ma = Pattern.compile("^Driver=(.+?)\\.dll").matcher(str); if (ma.find()) { Drivers.add(ma.group(1)); if (getDebug()) System.out.println(DBGID + "ドライバーの追加: " + ma.group(1)); continue; } ma = Pattern.compile("^Driver\\d+_FileName=(.+?)\\.dll").matcher(str); if (ma.find()) { Drivers.add(ma.group(1)); if (getDebug()) System.out.println(DBGID + "ドライバーの追加: " + ma.group(1)); continue; } } for (String Driver : Drivers) { String ch2File = null; if (Driver.contains(File.separator)) { ch2File = Driver + ".ch2"; } else { ch2File = DriverDirectory + File.separator + Driver + ".ch2"; } File f = new File(ch2File); if (!f.exists() || !f.isFile()) { String msg = ERRID + "チャンネル設定ファイルがみつかりません:" + ch2File; setErrmsg(msg); // System.out.println(msg); continue; } buf = CommonUtils.read4file(ch2File, false, thisEncoding); if (buf == null) { String msg = ERRID + "チャンネル設定ファイルが取得できませんでした:" + ch2File; setErrmsg(msg); // System.out.println(msg); return false; } sa = buf.split("[\r\n]+"); for (String str : sa) { if (str.startsWith(";")) { continue; } String[] da = str.split(","); if (da.length < 4) { continue; } if (da[7].equals("17168") || da[7].equals("17169")) { da[0] = "臨)" + da[0]; } String val = text2value(chvalue, da[0]); if (val == null || val.length() == 0) { TextValueSet tn; String chid; try { chid = ContentIdEDCB.getChId( Integer.valueOf(da[6]), Integer.valueOf(da[7]), Integer.valueOf(da[5])); } catch (NumberFormatException e) { String msg = ERRID + "iniファイルの内容が不正です:" + ch2File; setErrmsg(msg); // System.out.println(msg); return false; } tn = new TextValueSet(); tn.setText(da[0]); tn.setValue(String.valueOf(Long.decode("0x" + chid))); chvalue.add(tn); tn = new TextValueSet(); tn.setText(da[0]); tn.setValue(Driver + ".dll," + da[6] + ":" + da[7] + ":" + da[5]); chtype.add(tn); if (getDebug()) System.out.println(DBGID + "設定の追加: " + tn.getText() + "=" + tn.getValue()); } } } return (true); }
/** * Validates the list of directives, returning a new list. * * @param directives The list of directives. * @return A new list of directives. * @throws AraraException Something wrong happened, to be caught in the higher levels. */ public static List<Directive> validate(List<Directive> directives) throws AraraException { ArrayList<Directive> result = new ArrayList<Directive>(); for (Directive directive : directives) { Map<String, Object> parameters = directive.getParameters(); if (parameters.containsKey("file")) { throw new AraraException( messages.getMessage( Messages.ERROR_VALIDATE_FILE_IS_RESERVED, CommonUtils.getCollectionElements(directive.getLineNumbers(), "(", ")", ", "))); } if (parameters.containsKey("reference")) { throw new AraraException( messages.getMessage( Messages.ERROR_VALIDATE_REFERENCE_IS_RESERVED, CommonUtils.getCollectionElements(directive.getLineNumbers(), "(", ")", ", "))); } if (parameters.containsKey("files")) { Object holder = parameters.get("files"); if (holder instanceof List) { @SuppressWarnings("unchecked") List<Object> files = (List<Object>) holder; parameters.remove("files"); if (files.isEmpty()) { throw new AraraException( messages.getMessage( Messages.ERROR_VALIDATE_EMPTY_FILES_LIST, CommonUtils.getCollectionElements(directive.getLineNumbers(), "(", ")", ", "))); } for (Object file : files) { Map<String, Object> map = new HashMap<String, Object>(); for (String key : parameters.keySet()) { map.put(key, parameters.get(key)); } File representation = CommonUtils.getCanonicalFile(String.valueOf(file)); map.put("reference", representation); map.put("file", representation.getName()); Directive addition = new Directive(); Conditional conditional = new Conditional(); conditional.setCondition(directive.getConditional().getCondition()); conditional.setType(directive.getConditional().getType()); addition.setIdentifier(directive.getIdentifier()); addition.setConditional(conditional); addition.setParameters(map); addition.setLineNumbers(directive.getLineNumbers()); result.add(addition); } } else { throw new AraraException( messages.getMessage( Messages.ERROR_VALIDATE_FILES_IS_NOT_A_LIST, CommonUtils.getCollectionElements(directive.getLineNumbers(), "(", ")", ", "))); } } else { File representation = (File) ConfigurationController.getInstance().get("execution.reference"); parameters.put("file", representation.getName()); parameters.put("reference", representation); directive.setParameters(parameters); result.add(directive); } } logger.info(messages.getMessage(Messages.LOG_INFO_VALIDATED_DIRECTIVES)); logger.info( DisplayUtils.displayOutputSeparator( messages.getMessage(Messages.LOG_INFO_DIRECTIVES_BLOCK))); for (Directive directive : result) { logger.info(directive.toString()); } logger.info(DisplayUtils.displaySeparator()); return result; }
protected void onPostExecute(Bitmap image) { if (image != null) { iv.setImageBitmap(image); ImageCache.getInstance().put(thumbnailPath, image); iv.setClickable(true); iv.setTag(thumbnailPath); iv.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (thumbnailPath != null) { // Intent intent = new Intent(activity, // ShowBigImage.class); // File file = new File(localFullSizePath); // if (file.exists()) { // Uri uri = Uri.fromFile(file); // intent.putExtra("uri", uri); // } else { // // The local full size pic does not exist yet. // // ShowBigImage needs to download it from the server // // first // intent.putExtra("remotepath", remotePath); // } // if (message.getChatType() != ChatType.Chat) { // // delete the image from server after download // } // if (message != null // && message.direct == EMMessage.Direct.RECEIVE // && !message.isAcked // && message.getChatType() != ChatType.GroupChat // && message.getChatType() != ChatType.ChatRoom) { // message.isAcked = true; // try { // // 看了大图后发个已读回执给对方 // EMChatManager.getInstance().ackMessageRead( // message.getFrom(), message.getMsgId()); // } catch (Exception e) { // e.printStackTrace(); // } // } // activity.startActivity(intent); // TODO } } }); } else { if (message.status == EMMessage.Status.FAIL) { if (CommonUtils.isNetWorkConnected(activity)) { new Thread( new Runnable() { @Override public void run() { EMChatManager.getInstance().asyncFetchMessage(message); } }) .start(); } } } }
@Override protected Document doInBackground(RouteParams... params) { if (params.length == 0) return null; RouteParams par = params[0]; String cached = null, xmlstring = null; if (!par.force_download) cached = getCached(par.train_number); if (cached != null && checkTable(cached, par.departure, par.deptime) && checkTable(cached, par.arrival, par.arrtime)) xmlstring = cached; else { if (!CommonUtils.onlineCheckSilent()) return null; isCached = false; publishProgress(); String data = "start=yes&REQTrain_name=" + par.train_number + "&date=" + par.date + "&time=" + par.deptime + "&sTI=1&dirInput=" + par.arrival + "&L=vs_java3&input=" + par.departure + "&boardType=" + par.type; String url = "http://rozklad.sitkol.pl/bin/stboard.exe/pn"; try { DefaultHttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(url); client.removeRequestInterceptorByClass( org.apache.http.protocol.RequestExpectContinue.class); client.removeRequestInterceptorByClass(org.apache.http.protocol.RequestUserAgent.class); request.addHeader("Content-Type", "text/plain"); request.setEntity(new StringEntity(data)); InputStream inputStream = client.execute(request).getEntity().getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } xmlstring = new String(content.toByteArray()); xmlstring = xmlstring.replace("< ", "<"); saveInCache(par.train_number, xmlstring); } catch (Exception e) { return null; } } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader("<a>" + xmlstring + "</a>")); return db.parse(inStream); } catch (Exception e) { return null; } }
private static boolean isNotNullOrEmpty(final String value) { return CommonUtils.isNotNullOrEmpty(value) && !Consts.tousValue.equals(value); }
/** MD5方法计算DeviceID 产生32位的16进制数据,总长为 */ public String getsDeviceIdMD5() { String longID = IMEI + IMSI + TEL + WLAN_MAC + BLUETOOTH_MAC; sDeviceID = CommonUtils.cryptMD5(longID); return sDeviceID; }
/** * 获取error message * * @author Frank * @date 2015-9-24 上午10:15:29 * @param errorCode * @return * @return String */ public static String getMessage(String errorCode) { return CommonUtils.formatStr(errorMsgMap.get(errorCode)); }
/** * 密码MD5加密 @Description * * @author sunhanbin * @date 2015-9-11下午9:50:55 * @param password * @return */ public static String passwordMd5(String password) { return CommonUtils.generateMD5(Constants.MD5_SALT + password); }
/** * Initialization method. Called by Filter's init method or by Spring. Similar in concept to the * InitializingBean interface's afterPropertiesSet(); */ public void init() { CommonUtils.assertNotNull(this.artifactParameterName, "artifactParameterName cannot be null."); CommonUtils.assertNotNull(this.serviceParameterName, "serviceParameterName cannot be null."); // CommonUtils.assertTrue(CommonUtils.isNotEmpty(this.serverName) || // CommonUtils.isNotEmpty(this.service), "serverName or service must be set."); }