List of usage examples for java.util Locale equals
@Override public boolean equals(Object obj)
From source file:org.openmrs.Concept.java
/** * Returns concept name depending of locale, type (short, fully specified, etc) and tag. * Searches in the locale, and then the locale's parent if nothing is found. * //from w w w. ja v a 2 s. c o m * @param ofType find a name of this type (optional) * @param havingTag find a name with this tag (optional) * @param locale find a name with this locale (required) * @return a name that matches the arguments, or null if none is found. If there are multiple * matches and one is locale_preferred, that will be returned, otherwise a random one of * the matches will be returned. * @since 1.9 **/ public ConceptName getName(Locale locale, ConceptNameType ofType, ConceptNameTag havingTag) { Collection<ConceptName> namesInLocale = getNames(locale); if (!namesInLocale.isEmpty()) { List<ConceptName> matches = new ArrayList<ConceptName>(); for (ConceptName candidate : namesInLocale) { if ((ofType == null || ofType.equals(candidate.getConceptNameType())) && (havingTag == null || candidate.hasTag(havingTag))) { matches.add(candidate); } } // if we have any matches, we'll return one of them if (matches.size() == 1) { return matches.get(0); } else if (matches.size() > 1) { for (ConceptName match : matches) { if (match.isLocalePreferred()) { return match; } } // none was explicitly marked as preferred return matches.get(0); } } // if we reach here, there were no matching names, so try to look in the parent locale Locale parent = new Locale(locale.getLanguage()); if (!parent.equals(locale)) { return getName(parent, ofType, havingTag); } else { return null; } }
From source file:org.openmrs.Concept.java
/** * Returns the preferred description for a locale. * /*from ww w . jav a2 s.co m*/ * @param locale the language and country in which the description is used * @param exact true/false to return only exact locale (no default locale) * @return the appropriate description, or null if not found * @should return match on locale exactly * @should return match on language only * @should not return match on language only if exact match exists * @should not return language only match for exact matches */ public ConceptDescription getDescription(Locale locale, boolean exact) { log.debug("Getting ConceptDescription for locale: " + locale); ConceptDescription foundDescription = null; if (locale == null) { locale = LocaleUtility.getDefaultLocale(); } Locale desiredLocale = locale; ConceptDescription defaultDescription = null; for (Iterator<ConceptDescription> i = getDescriptions().iterator(); i.hasNext();) { ConceptDescription availableDescription = i.next(); Locale availableLocale = availableDescription.getLocale(); if (availableLocale.equals(desiredLocale)) { foundDescription = availableDescription; break; // skip out now because we found an exact locale match } if (!exact && LocaleUtility.areCompatible(availableLocale, desiredLocale)) { foundDescription = availableDescription; } if (availableLocale.equals(LocaleUtility.getDefaultLocale())) { defaultDescription = availableDescription; } } if (foundDescription == null) { // no description with the given locale was found. // return null if exact match desired if (exact) { log.debug("No concept description found for concept id " + conceptId + " for locale " + desiredLocale.toString()); } else { // returning default description locale ("en") if exact match // not desired if (defaultDescription == null) { log.debug("No concept description found for default locale for concept id " + conceptId); } else { foundDescription = defaultDescription; } } } return foundDescription; }
From source file:org.openmrs.Concept.java
/** * Gets the synonyms in the given locale. Returns a list of names from the same language with * the preferred synonym sorted first, or an empty list if none found. * /*from w w w. j av a2 s. c om*/ * @param locale * @return Collection of ConceptNames which are synonyms for the Concept in the given locale */ public Collection<ConceptName> getSynonyms(Locale locale) { List<ConceptName> syns = new Vector<ConceptName>(); ConceptName preferredConceptName = null; for (ConceptName possibleSynonymInLoc : getSynonyms()) { if (locale.equals(possibleSynonymInLoc.getLocale())) { if (possibleSynonymInLoc.isPreferred()) { preferredConceptName = possibleSynonymInLoc; } else { syns.add(possibleSynonymInLoc); } } } // Add preferred name first in the list. if (preferredConceptName != null) { syns.add(0, preferredConceptName); } log.debug("returning: " + syns); return syns; }
From source file:net.e_fas.oss.tabijiman.MapsActivity.java
public void exec(Locale locale) throws IOException, JSONException { JSONArray datas;// w w w . j a va 2s.co m String line; data = new ArrayList<>(); assetManager = Init_context.getResources().getAssets(); // assets/initFrameJSON.json input = assetManager.open("initFrameJSON.json"); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); jsonString = stringBuilder.toString(); json = new JSONObject(jsonString); String Hash = AppSetting.Encrypt(String.valueOf(json)); e_print("new Hash >> " + Hash + "\nstore Hash >> " + AppSetting.getUdInitHash()); if (AppSetting.isHashChanged(Hash, AppSetting.getUdInitHash())) { e_print("make a new init data"); AppSetting.setUdInitHash(Hash); if (locale.equals(Locale.JAPAN)) { datas = json.getJSONObject("results").getJSONObject("bindings").getJSONArray("jp"); } else { datas = json.getJSONObject("results").getJSONObject("bindings").getJSONArray("en"); } e_print("datas_count >> " + datas.length()); for (int i = 0; i < datas.length(); i++) { temp = new HashMap<>(); temp.put("name", datas.getJSONObject(i).getJSONObject("name").getString("value")); temp.put("desc", datas.getJSONObject(i).getJSONObject("desc").getString("value")); temp.put("img", datas.getJSONObject(i).getJSONObject("img").getString("value")); temp.put("lat", datas.getJSONObject(i).getJSONObject("lat").getString("value")); temp.put("lng", datas.getJSONObject(i).getJSONObject("lng").getString("value")); if (!datas.getJSONObject(i).isNull("area")) { temp.put("area", datas.getJSONObject(i).getJSONObject("area").getString("value")); } print("initFrame_temp " + i + " >> " + temp); data.add(temp); } InsertFrame(data); } else { e_print("Already Inserted Init Data"); } }
From source file:org.opencms.ade.sitemap.CmsVfsSitemapService.java
/** * Helper method for removing all locales except one from a container page.<p> * /* w ww .j a va 2 s . c om*/ * @param page the container page to proces * @param localeToKeep the locale which should be kept * * @throws CmsXmlException if something goes wrong */ private void removeAllLocalesExcept(CmsXmlContainerPage page, Locale localeToKeep) throws CmsXmlException { List<Locale> locales = page.getLocales(); for (Locale locale : locales) { if (!locale.equals(localeToKeep)) { page.removeLocale(locale); } } }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override// www .j av a2s . c o m public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { ExceptionHandler.initialize(context); if (ExceptionHandler.needReport()) { final String fileName = ExceptionHandler.getBugReportFileAbsolutePath(); final File file = new File(fileName); final File fileZip; { String strFileZip = file.getAbsolutePath(); { int index = strFileZip.lastIndexOf('.'); if (0 < index) { strFileZip = strFileZip.substring(0, index); strFileZip += ".zip"; } } Log.d(TAG, strFileZip); fileZip = new File(strFileZip); if (fileZip.exists()) { fileZip.delete(); } } if (file.exists()) { Log.d(TAG, file.getAbsolutePath()); InputStream inStream = null; ZipOutputStream outStream = null; try { inStream = new FileInputStream(file); String strFileName = file.getAbsolutePath(); { int index = strFileName.lastIndexOf(File.separatorChar); if (0 < index) { strFileName = strFileName.substring(index + 1); } } Log.d(TAG, strFileName); outStream = new ZipOutputStream(new FileOutputStream(fileZip)); byte[] buff = new byte[8124]; { ZipEntry entry = new ZipEntry(strFileName); outStream.putNextEntry(entry); int len = 0; while (0 < (len = inStream.read(buff))) { outStream.write(buff, 0, len); } outStream.closeEntry(); } outStream.finish(); outStream.flush(); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != outStream) { try { outStream.close(); } catch (Exception e) { } } outStream = null; if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } Log.i(TAG, "zip created"); } if (file.exists()) { // upload or send e-mail InputStream inStream = null; StringBuilder sb = new StringBuilder(); try { inStream = new FileInputStream(file); byte[] buff = new byte[8124]; int readed = 0; do { readed = inStream.read(buff); for (int i = 0; i < readed; i++) { sb.append((char) buff[i]); } } while (readed >= 0); final String str = sb.toString(); Log.i(TAG, str); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if (null != defaultLocale) { if (defaultLocale.equals(Locale.JAPANESE) || defaultLocale.equals(Locale.JAPAN)) { title = ""; message = "?????????"; positive = "?"; negative = ""; needDefaultLang = false; } } if (needDefaultLang) { title = "ERROR"; message = "Got unexpected error. Do you want to send information of error."; positive = "Send"; negative = "Cancel"; } alertDialog.setTitle(title); alertDialog.setMessage(message); alertDialog.setPositiveButton(positive + " mail", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderMailClient.upload(context, file, new String[] { "diverKon+sakura@gmail.com" }); } }); alertDialog.setNeutralButton(positive + " http", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderWeb.upload(ExceptionHandlerReportApp.this, fileZip, "http://kkkon.sakura.ne.jp/android/bug"); } }); alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { ExceptionHandler.clearReport(); } }); alertDialog.show(); } // TODO separate activity for crash report //DefaultCheckerAPK.checkAPK( this, null ); } ExceptionHandler.registHandler(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("ExceptionHandler"); layout.addView(tv); Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); Button btn2 = new Button(this); btn2.setText("reinstall apk"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); if (fileApk.exists()) { foundApk = true; Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); } } if (false == foundApk) { for (int i = 0; i < 10; ++i) { File fileApk = new File("/data/app/" + context.getPackageName() + "-" + i + ".apk"); Log.d(TAG, "check apk:" + fileApk.getAbsolutePath()); if (fileApk.exists()) { Log.i(TAG, "apk found. path=" + fileApk.getAbsolutePath()); /* * // require parmission { final String strCmd = "pm install -r " + fileApk.getAbsolutePath(); try { Runtime.getRuntime().exec( strCmd ); } catch ( IOException e ) { Log.e( TAG, "got exception", e ); } } */ Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); break; } } } } }); layout.addView(btn2); Button btn3 = new Button(this); btn3.setText("check apk"); btn3.setOnClickListener(new View.OnClickListener() { private boolean checkApk(final File fileApk, final ZipEntryFilter filter) { final boolean[] result = new boolean[1]; result[0] = true; final Thread thread = new Thread(new Runnable() { @Override public void run() { if (fileApk.exists()) { ZipFile zipFile = null; try { zipFile = new ZipFile(fileApk); List<ZipEntry> list = new ArrayList<ZipEntry>(zipFile.size()); for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { ZipEntry ent = e.nextElement(); Log.d(TAG, ent.getName()); Log.d(TAG, "" + ent.getSize()); final boolean accept = filter.accept(ent); if (accept) { list.add(ent); } } Log.d(TAG, Build.CPU_ABI); // API 4 Log.d(TAG, Build.CPU_ABI2); // API 8 final String[] abiArray = { Build.CPU_ABI // API 4 , Build.CPU_ABI2 // API 8 }; String abiMatched = null; { boolean foundMatched = false; for (final String abi : abiArray) { if (null == abi) { continue; } if (0 == abi.length()) { continue; } for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abi + "/"; if (entry.getName().startsWith(prefixABI)) { abiMatched = abi; foundMatched = true; break; } } if (foundMatched) { break; } } } Log.d(TAG, "matchedAbi=" + abiMatched); if (null != abiMatched) { boolean needReInstall = false; for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abiMatched + "/"; if (entry.getName().startsWith(prefixABI)) { final String jniName = entry.getName().substring(prefixABI.length()); Log.d(TAG, "jni=" + jniName); final String strFileDst = context.getApplicationInfo().nativeLibraryDir + "/" + jniName; Log.d(TAG, strFileDst); final File fileDst = new File(strFileDst); if (!fileDst.exists()) { Log.w(TAG, "needReInstall: content missing " + strFileDst); needReInstall = true; } else { assert (entry.getSize() <= Integer.MAX_VALUE); if (fileDst.length() != entry.getSize()) { Log.w(TAG, "needReInstall: size broken " + strFileDst); needReInstall = true; } else { //org.apache.commons.io.IOUtils.contentEquals( zipFile.getInputStream( entry ), new FileInputStream(fileDst) ); final int size = (int) entry.getSize(); byte[] buffSrc = new byte[size]; { InputStream inStream = null; try { inStream = zipFile.getInputStream(entry); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffSrc, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } byte[] buffDst = new byte[(int) fileDst.length()]; { InputStream inStream = null; try { inStream = new FileInputStream(fileDst); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffDst, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } if (Arrays.equals(buffSrc, buffDst)) { Log.d(TAG, " content equal " + strFileDst); // OK } else { Log.w(TAG, "needReInstall: content broken " + strFileDst); needReInstall = true; } } } } } // for ZipEntry if (needReInstall) { // need call INSTALL APK Log.w(TAG, "needReInstall apk"); result[0] = false; } else { Log.d(TAG, "no need ReInstall apk"); } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != zipFile) { try { zipFile.close(); } catch (Exception e) { } } } } } }); thread.setName("check jni so"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "check thread.id=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now checking installation. Cancel check?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ try { thread.join(); } catch (InterruptedException e) { Log.d(TAG, "got exception", e); } return result[0]; } @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); this.checkApk(fileApk, new ZipEntryFilter() { @Override public boolean accept(ZipEntry entry) { if (entry.isDirectory()) { return false; } final String filename = entry.getName(); if (filename.startsWith("lib/")) { return true; } return false; } }); } } }); layout.addView(btn3); Button btn4 = new Button(this); btn4.setText("print dir and path"); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { { final File file = context.getCacheDir(); Log.d(TAG, "Ctx.CacheDir=" + file.getAbsoluteFile()); } { final File file = context.getExternalCacheDir(); // API 8 if (null == file) { // no permission Log.d(TAG, "Ctx.ExternalCacheDir="); } else { Log.d(TAG, "Ctx.ExternalCacheDir=" + file.getAbsolutePath()); } } { final File file = context.getFilesDir(); Log.d(TAG, "Ctx.FilesDir=" + file.getAbsolutePath()); } { final String value = context.getPackageResourcePath(); Log.d(TAG, "Ctx.PackageResourcePath=" + value); } { final String[] files = context.fileList(); if (null == files) { Log.d(TAG, "Ctx.fileList=" + files); } else { for (final String filename : files) { Log.d(TAG, "Ctx.fileList=" + filename); } } } { final File file = Environment.getDataDirectory(); Log.d(TAG, "Env.DataDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getDownloadCacheDirectory(); Log.d(TAG, "Env.DownloadCacheDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getExternalStorageDirectory(); Log.d(TAG, "Env.ExternalStorageDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getRootDirectory(); Log.d(TAG, "Env.RootDirectory=" + file.getAbsolutePath()); } { final ApplicationInfo appInfo = context.getApplicationInfo(); Log.d(TAG, "AppInfo.dataDir=" + appInfo.dataDir); Log.d(TAG, "AppInfo.nativeLibraryDir=" + appInfo.nativeLibraryDir); // API 9 Log.d(TAG, "AppInfo.publicSourceDir=" + appInfo.publicSourceDir); { final String[] sharedLibraryFiles = appInfo.sharedLibraryFiles; if (null == sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + sharedLibraryFiles); } else { for (final String fileName : sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + fileName); } } } Log.d(TAG, "AppInfo.sourceDir=" + appInfo.sourceDir); } { Log.d(TAG, "System.Properties start"); final Properties properties = System.getProperties(); if (null != properties) { for (final Object key : properties.keySet()) { String value = properties.getProperty((String) key); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.Properties end"); } { Log.d(TAG, "System.getenv start"); final Map<String, String> mapEnv = System.getenv(); if (null != mapEnv) { for (final Map.Entry<String, String> entry : mapEnv.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.getenv end"); } } }); layout.addView(btn4); Button btn5 = new Button(this); btn5.setText("check INSTALL_NON_MARKET_APPS"); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SettingsCompat.initialize(context); if (SettingsCompat.isAllowedNonMarketApps()) { Log.d(TAG, "isAllowdNonMarketApps=true"); } else { Log.d(TAG, "isAllowdNonMarketApps=false"); } } }); layout.addView(btn5); Button btn6 = new Button(this); btn6.setText("send email"); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent mailto = new Intent(); mailto.setAction(Intent.ACTION_SENDTO); mailto.setType("message/rfc822"); mailto.setData(Uri.parse("mailto:")); mailto.putExtra(Intent.EXTRA_EMAIL, new String[] { "" }); mailto.putExtra(Intent.EXTRA_SUBJECT, "[BugReport] " + context.getPackageName()); mailto.putExtra(Intent.EXTRA_TEXT, "body text"); //mailto.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); //context.startActivity( mailto ); Intent intent = Intent.createChooser(mailto, "Send Email"); if (null != intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { Log.d(TAG, "got Exception", e); } } } }); layout.addView(btn6); Button btn7 = new Button(this); btn7.setText("upload http thread"); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "brd=" + Build.BRAND); Log.d(TAG, "prd=" + Build.PRODUCT); //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); final Thread thread = new Thread(new Runnable() { @Override public void run() { Log.d(TAG, "upload thread tid=" + android.os.Process.myTid()); try { HttpPost httpPost = new HttpPost("http://kkkon.sakura.ne.jp/android/bug"); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); } Log.d(TAG, "upload finish"); } }); thread.setName("upload crash"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now uploading error information. Cancel upload?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ /* try { thread.join(); // must call. leak handle... } catch ( InterruptedException e ) { Log.d( TAG, "got Exception", e ); } */ } }); layout.addView(btn7); Button btn8 = new Button(this); btn8.setText("upload http AsyncTask"); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn8); Button btn9 = new Button(this); btn9.setText("call checkAPK"); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean result = DefaultCheckerAPK.checkAPK(ExceptionHandlerReportApp.this, null); Log.i(TAG, "checkAPK result=" + result); } }); layout.addView(btn9); setContentView(layout); }
From source file:com.aurel.track.item.history.HistorySaverBL.java
/** * Gets the localized field changes/*from w w w . j a v a2s . c om*/ * @param afterItemSaveEventParam * @param locale * @param history true for history, false for e-mail * @return */ public static SortedMap<Integer, FieldChange> getLocalizedFieldChanges( AfterItemSaveEventParam afterItemSaveEventParam, Locale locale, boolean history) { SortedMap<Integer, FieldChange> fieldChangeMap = new TreeMap<Integer, FieldChange>(); TWorkItemBean workItemBean = afterItemSaveEventParam.getWorkItemNew(); TWorkItemBean workItemBeanOriginal = afterItemSaveEventParam.getWorkItemOld(); Map<Integer, TFieldConfigBean> fieldConfigsMap = afterItemSaveEventParam.getFieldConfigs(); Set<Integer> explicitHistoryFields = getHardCodedExplicitHistoryFields(); //the attachment changes are also explicitly historized Set<Integer> attachmentHistoryFields = HistoryLoaderBL.getAttachmentHistoryFields(); for (Integer fieldID : afterItemSaveEventParam.getInterestingFields()) { FieldChange fieldChange = new FieldChange(); fieldChange.setFieldID(fieldID); //pseudo fields:attachment history if (attachmentHistoryFields.contains(fieldID)) { String fieldLabel = null; if (history) { fieldLabel = LocalizeUtil.getLocalizedTextFromApplicationResources( HistoryLoaderBL.getHistoryFieldKey(fieldID), locale); } else { fieldLabel = LocalizeUtil.getLocalizedTextFromApplicationResources( "admin.customize.automail.trigger.lbl.fieldType.attachment", locale); } fieldChange.setLocalizedFieldLabel(fieldLabel); fieldChange.setExplicitHistory(true); String newStringValue = workItemBean.getAttachment(); fieldChange.setNewShowValue(newStringValue); if (workItemBeanOriginal != null) { String oldStringValue = workItemBeanOriginal.getAttachment(); fieldChange.setOldShowValue(oldStringValue); fieldChange.setChanged(EqualUtils.notEqual(newStringValue, oldStringValue)); } else { fieldChange.setChanged(true); } } else { IFieldTypeRT fieldType = FieldTypeManager.getFieldTypeRT(fieldID); Object newValue = workItemBean.getAttribute(fieldID); Object oldValue = null; if (workItemBeanOriginal != null) { oldValue = workItemBeanOriginal.getAttribute(fieldID); } TFieldConfigBean fieldConfigBean = fieldConfigsMap.get(fieldID); String fieldLabel = fieldConfigBean.getLabel(); if (locale != null && !locale.equals(afterItemSaveEventParam.getLocale())) { fieldLabel = FieldRuntimeBL.localizeFieldConfig(fieldConfigBean.getObjectID(), locale); if (fieldLabel == null) { LOGGER.debug("Field label is null for locale " + locale + " fall back to " + fieldConfigBean.getLabel()); fieldLabel = fieldConfigBean.getLabel(); } } fieldChange.setLocalizedFieldLabel(fieldLabel); fieldChange.setExplicitHistory( explicitHistoryFields.contains(fieldID) || fieldConfigBean.isHistoryString()); //get the new value to show fieldChange.setNewShowValue(fieldType.getShowValue(newValue, locale)); if ((workItemBeanOriginal != null && fieldType.valueModified(newValue, oldValue)) || //the rare case when the comment field is present on the create screen (workItemBeanOriginal == null && fieldID.intValue() == SystemFields.COMMENT && newValue != null && !"".equals(newValue))) { //get the old value to show and set the changed flag. //the old value and change flag is set only by edit mode when the value is really changed //or by create mode when Comment is specified fieldChange.setOldShowValue(fieldType.getShowValue(oldValue, locale)); fieldChange.setChanged(true); LOGGER.debug("FieldID " + fieldID + " oldValue " + oldValue + " newValue " + newValue); } } fieldChangeMap.put(fieldID, fieldChange); } return fieldChangeMap; }
From source file:org.openmrs16.Concept.java
/** * Returns the name which is explicitly marked as preferred for a given locale. If the country * is specified in the locale, then the language of the name must match and the name must have a * tag indicating that it is preferred in the locale's country. If no country is specified, then * the name must have a tag indicating that it is preferred in the locale's language * //from ww w. ja v a 2 s . com * @param forLocale locale for which to return a preferred name * @return preferred name for the locale, or null if none is tagged as such * @should support plain preferred * @should match to best name */ public ConceptName getPreferredName(Locale forLocale) { // fail early if this concept has no names defined if (getNames().size() == 0) { if (log.isDebugEnabled()) log.debug("there are no names defined for: " + conceptId); return null; } if (log.isDebugEnabled()) log.debug("Getting preferred conceptName for locale: " + forLocale); ConceptName preferredName = null; // name which exactly match the locale // and is preferred if (forLocale == null) forLocale = Context.getLocale(); // Don't presume en_US; ConceptNameTag desiredLanguageTag = ConceptNameTag.preferredLanguageTagFor(forLocale); ConceptNameTag desiredCountryTag = ConceptNameTag.preferredCountryTagFor(forLocale); for (ConceptName possibleName : getCompatibleNames(forLocale)) { if (forLocale.equals(possibleName.getLocale()) && possibleName.hasTag(ConceptNameTag.PREFERRED)) { preferredName = possibleName; break; } if (desiredCountryTag != null) { // country was specified, exact match must be preferred in country if (possibleName.hasTag(desiredCountryTag)) { preferredName = possibleName; break; } } else { // no country specified, so only worry about matching language if (possibleName.hasTag(desiredLanguageTag)) { preferredName = possibleName; break; } } if ((preferredName == null) && possibleName.hasTag(ConceptNameTag.PREFERRED)) { preferredName = possibleName; } } if (log.isDebugEnabled()) { if (preferredName == null) { log.warn("No preferred concept name found for concept id " + conceptId + " in locale " + forLocale); } } return preferredName; }
From source file:org.ofbiz.order.shoppingcart.ShoppingCartEvents.java
/** Gets or creates the shopping cart object */ public static ShoppingCart getCartObject(HttpServletRequest request, Locale locale, String currencyUom) { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); ShoppingCart cart = (ShoppingCart) request.getAttribute("shoppingCart"); HttpSession session = request.getSession(true); if (cart == null) { cart = (ShoppingCart) session.getAttribute("shoppingCart"); } else {/* ww w .j a v a 2s. c om*/ session.setAttribute("shoppingCart", cart); } if (cart == null) { cart = new WebShoppingCart(request, locale, currencyUom); session.setAttribute("shoppingCart", cart); } else { if (locale != null && !locale.equals(cart.getLocale())) { cart.setLocale(locale); } if (currencyUom != null && !currencyUom.equals(cart.getCurrency())) { try { cart.setCurrency(dispatcher, currencyUom); } catch (CartItemModifyException e) { Debug.logError(e, "Unable to modify currency in cart", module); } } } return cart; }
From source file:com.mobiletin.inputmethod.indic.LatinIME.java
@SuppressWarnings("deprecation") private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInputView(editorInfo, restarting); mRichImm.clearSubtypeCaches();// w w w . ja v a2s. co m final KeyboardSwitcher switcher = mKeyboardSwitcher; switcher.updateKeyboardTheme(); final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); // If we are starting input in a different text field from before, we'll have to reload // settings, so currentSettingsValues can't be final. SettingsValues currentSettingsValues = mSettings.getCurrent(); if (editorInfo == null) { Log.e(TAG, "Null EditorInfo in onStartInputView()"); if (DebugFlags.DEBUG_ENABLED) { throw new NullPointerException("Null EditorInfo in onStartInputView()"); } return; } if (DEBUG) { Log.d(TAG, "onStartInputView: editorInfo:" + String.format("inputType=0x%08x imeOptions=0x%08x", editorInfo.inputType, editorInfo.imeOptions)); Log.d(TAG, "All caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) + ", sentence caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) + ", word caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); } Log.e(TAG, "Starting input. Cursor position = " + editorInfo.initialSelStart + "," + editorInfo.initialSelEnd); // TODO: Consolidate these checks with {@link InputAttributes}. if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead"); } if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); } // In landscape mode, this method gets called without the input view being created. if (mainKeyboardView == null) { return; } // Forward this event to the accessibility utilities, if enabled. final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); if (accessUtils.isTouchExplorationEnabled()) { accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); } final boolean inputTypeChanged = !currentSettingsValues.isSameInputType(editorInfo); final boolean isDifferentTextField = !restarting || inputTypeChanged; if (isDifferentTextField) { mSubtypeSwitcher.updateParametersOnStartInputView(); } // The EditorInfo might have a flag that affects fullscreen mode. // Note: This call should be done by InputMethodService? updateFullscreenMode(); // ALERT: settings have not been reloaded and there is a chance they may be stale. // In the practice, if it is, we should have gotten onConfigurationChanged so it should // be fine, but this is horribly confusing and must be fixed AS SOON AS POSSIBLE. // In some cases the input connection has not been reset yet and we can't access it. In // this case we will need to call loadKeyboard() later, when it's accessible, so that we // can go into the correct mode, so we need to do some housekeeping here. final boolean needToCallLoadKeyboardLater; final Suggest suggest = mInputLogic.mSuggest; if (!currentSettingsValues.mHasHardwareKeyboard) { // The app calling setText() has the effect of clearing the composing // span, so we should reset our state unconditionally, even if restarting is true. // We also tell the input logic about the combining rules for the current subtype, so // it can adjust its combiners if needed. mInputLogic.startInput(mSubtypeSwitcher.getCombiningRulesExtraValueOfCurrentSubtype(), currentSettingsValues); // Note: the following does a round-trip IPC on the main thread: be careful final Locale currentLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); if (null != currentLocale && !currentLocale.equals(suggest.getLocale())) { // TODO: Do this automatically. resetSuggest(); } // TODO[IL]: Can the following be moved to InputLogic#startInput? if (!mInputLogic.mConnection.resetCachesUponCursorMoveAndReturnSuccess(editorInfo.initialSelStart, editorInfo.initialSelEnd, false /* shouldFinishComposition */)) { // Sometimes, while rotating, for some reason the framework tells the app we are not // connected to it and that means we can't refresh the cache. In this case, schedule // a refresh later. // We try resetting the caches up to 5 times before giving up. mHandler.postResetCaches(isDifferentTextField, 5 /* remainingTries */); // mLastSelection{Start,End} are reset later in this method, no need to do it here needToCallLoadKeyboardLater = true; } else { // When rotating, initialSelStart and initialSelEnd sometimes are lying. Make a best // effort to work around this bug. mInputLogic.mConnection.tryFixLyingCursorPosition(); mHandler.postResumeSuggestions(true /* shouldIncludeResumedWordInSuggestions */, true /* shouldDelay */); needToCallLoadKeyboardLater = false; } } else { // If we have a hardware keyboard we don't need to call loadKeyboard later anyway. needToCallLoadKeyboardLater = false; } if (isDifferentTextField || !currentSettingsValues.hasSameOrientation(getResources().getConfiguration())) { loadSettings(); } if (isDifferentTextField) { mainKeyboardView.closing(); currentSettingsValues = mSettings.getCurrent(); if (currentSettingsValues.mAutoCorrectionEnabledPerUserSettings) { suggest.setAutoCorrectionThreshold(currentSettingsValues.mAutoCorrectionThreshold); } switcher.loadKeyboard(editorInfo, currentSettingsValues, getCurrentAutoCapsState(), getCurrentRecapitalizeState()); if (needToCallLoadKeyboardLater) { // If we need to call loadKeyboard again later, we need to save its state now. The // later call will be done in #retryResetCaches. switcher.saveKeyboardState(); } } else if (restarting) { // TODO: Come up with a more comprehensive way to reset the keyboard layout when // a keyboard layout set doesn't get reloaded in this method. switcher.resetKeyboardStateToAlphabet(getCurrentAutoCapsState(), getCurrentRecapitalizeState()); // In apps like Talk, we come here when the text is sent and the field gets emptied and // we need to re-evaluate the shift state, but not the whole layout which would be // disruptive. // Space state must be updated before calling updateShiftState switcher.requestUpdatingShiftState(getCurrentAutoCapsState(), getCurrentRecapitalizeState()); } // This will set the punctuation suggestions if next word suggestion is off; // otherwise it will clear the suggestion strip. setNeutralSuggestionStrip(); mHandler.cancelUpdateSuggestionStrip(); mainKeyboardView.setMainDictionaryAvailability(mDictionaryFacilitator.hasInitializedMainDictionary()); mainKeyboardView.setKeyPreviewPopupEnabled(currentSettingsValues.mKeyPreviewPopupOn, currentSettingsValues.mKeyPreviewPopupDismissDelay); mainKeyboardView.setSlidingKeyInputPreviewEnabled(currentSettingsValues.mSlidingKeyInputPreviewEnabled); mainKeyboardView.setGestureHandlingEnabledByUser(currentSettingsValues.mGestureInputEnabled, currentSettingsValues.mGestureTrailEnabled, currentSettingsValues.mGestureFloatingPreviewTextEnabled); // Contextual dictionary should be updated for the current application. mContextualDictionaryUpdater.onStartInputView(editorInfo.packageName); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); }