Example #1
0
  // Filter Class
  public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    dataList.clear();
    if (charText.length() == 0) {
      dataList.addAll(arraylist);
    } else {
      for (TeamMebmersListInnerModel wp : arraylist) {
        String input = wp.getFname() + wp.getLname();
        input = input.replace(" ", "");

        charText = charText.replace(" ", "");
        if (input.toLowerCase(Locale.getDefault()).contains(charText)) {
          dataList.add(wp);
        }
      }
    }

    if (dataList.size() == 0) {
      txtvNoResultFound.setVisibility(View.VISIBLE);
      mListView.setVisibility(View.GONE);
    } else {
      mListView.setVisibility(View.VISIBLE);
      txtvNoResultFound.setVisibility(View.GONE);
    }

    notifyDataSetChanged();
  }
Example #2
0
 public void setFeature(String name, boolean value)
     throws SAXNotRecognizedException, SAXNotSupportedException {
   if (name == null) {
     throw new NullPointerException(
         JAXPValidationMessageFormatter.formatMessage(
             Locale.getDefault(), "FeatureNameNull", null));
   }
   if (name.equals(XMLConstants.FEATURE_SECURE_PROCESSING)) {
     fSecurityManager = value ? new SecurityManager() : null;
     fXMLSchemaLoader.setProperty(SECURITY_MANAGER, fSecurityManager);
     return;
   }
   try {
     fXMLSchemaLoader.setFeature(name, value);
   } catch (XMLConfigurationException e) {
     String identifier = e.getIdentifier();
     if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
       throw new SAXNotRecognizedException(
           SAXMessageFormatter.formatMessage(
               Locale.getDefault(), "feature-not-recognized", new Object[] {identifier}));
     } else {
       throw new SAXNotSupportedException(
           SAXMessageFormatter.formatMessage(
               Locale.getDefault(), "feature-not-supported", new Object[] {identifier}));
     }
   }
 }
Example #3
0
  /**
   * Finds a suitable analyser class for file name.
   *
   * @param file The file name to get the analyzer for
   * @return the analyzer factory to use
   */
  public static FileAnalyzerFactory find(String file) {
    String path = file;
    int i;

    // Get basename of the file first.
    if (((i = path.lastIndexOf(File.separatorChar)) > 0) && (i + 1 < path.length())) {
      path = path.substring(i + 1);
    }

    int dotpos = path.lastIndexOf('.');
    if (dotpos >= 0) {
      FileAnalyzerFactory factory;

      // Try matching the prefix.
      if (dotpos > 0) {
        factory = pre.get(path.substring(0, dotpos).toUpperCase(Locale.getDefault()));
        if (factory != null) {
          return factory;
        }
      }

      // Now try matching the suffix. We kind of consider this order (first
      // prefix then suffix) to be workable although for sure there can be
      // cases when this does not work.
      factory = ext.get(path.substring(dotpos + 1).toUpperCase(Locale.getDefault()));
      if (factory != null) {
        return factory;
      }
    }

    // file doesn't have any of the prefix or extensions we know, try full match
    return FILE_NAMES.get(path.toUpperCase(Locale.getDefault()));
  }
  /** {@inheritDoc} */
  public synchronized void removeColumn(TalendColumn column) {

    ResourceBundle rb = ResourceBundle.getBundle("TalendBridge", Locale.getDefault());

    int index = columnsList.indexOf(column);
    if (index == -1) {
      return;
    }

    if (columnImpls.get(column).isKey() && (!rowList.isEmpty() || !rowdraft.isEmpty())) {
      throw new IllegalStateException(
          String.format(
              Locale.getDefault(),
              rb.getString("exception.cannotRemoveKey"),
              column.getName(),
              name));
    }

    TalendColumnImpl c;
    for (index = index + 1; index < columnsList.size(); index++) {
      c = columnsList.get(index);
      c.index--;
    }

    for (TalendRowImpl row : rowList) {
      row.setValue(column, null, true);
    }

    columnsList.remove((TalendColumnImpl) column);
    columns.remove(column.getName());
    columnImpls.remove(column);
  }
  /**
   * Gets the display name for the specified Timezone ID. If the ID matches the list of IDs that
   * need to be have their default display names overriden, use the pre-set display name from
   * R.arrays.
   *
   * @param id The timezone ID.
   * @param daylightTime True for daylight time, false for standard time
   * @return The display name of the timezone. This will just use the default display name, except
   *     that certain timezones have poor defaults, and should use the pre-set override labels from
   *     R.arrays.
   */
  private String getDisplayName(TimeZone tz, boolean daylightTime) {
    if (mOverrideIds == null || mOverrideLabels == null) {
      // Just in case they somehow didn't get loaded correctly.
      return tz.getDisplayName(daylightTime, TimeZone.LONG, Locale.getDefault());
    }

    for (int i = 0; i < mOverrideIds.length; i++) {
      if (tz.getID().equals(mOverrideIds[i])) {
        if (mOverrideLabels.length > i) {
          return mOverrideLabels[i];
        }
        Log.e(
            TAG,
            "timezone_rename_ids len="
                + mOverrideIds.length
                + " timezone_rename_labels len="
                + mOverrideLabels.length);
        break;
      }
    }

    // If the ID doesn't need to have the display name overridden, or if the labels were
    // malformed, just use the default.
    return tz.getDisplayName(daylightTime, TimeZone.LONG, Locale.getDefault());
  }
Example #6
0
 /**
  * Reads the properties of this action from a resource bundle of given base name.
  *
  * @throws MissingResourceException if no resource bundle could be found from <code>
  *     resourceBaseName</code>.
  */
 private void readActionPropertyValues(
     String resourceBaseName, String actionPrefix, ClassLoader pluginClassLoader) {
   ResourceBundle resource;
   if (pluginClassLoader != null) {
     resource = ResourceBundle.getBundle(resourceBaseName, Locale.getDefault(), pluginClassLoader);
   } else {
     resource = ResourceBundle.getBundle(resourceBaseName, Locale.getDefault());
   }
   String propertyPrefix = actionPrefix + ".";
   putPropertyValue(Property.NAME, getOptionalString(resource, propertyPrefix + Property.NAME));
   putPropertyValue(
       Property.SHORT_DESCRIPTION,
       getOptionalString(resource, propertyPrefix + Property.SHORT_DESCRIPTION));
   String smallIcon = getOptionalString(resource, propertyPrefix + Property.SMALL_ICON);
   if (smallIcon != null) {
     if (smallIcon.startsWith("/")) {
       smallIcon = smallIcon.substring(1);
     }
     putPropertyValue(Property.SMALL_ICON, new ResourceURLContent(pluginClassLoader, smallIcon));
   }
   String mnemonicKey = getOptionalString(resource, propertyPrefix + Property.MNEMONIC);
   if (mnemonicKey != null) {
     putPropertyValue(Property.MNEMONIC, Character.valueOf(mnemonicKey.charAt(0)));
   }
   String toolBar = getOptionalString(resource, propertyPrefix + Property.TOOL_BAR);
   if (toolBar != null) {
     putPropertyValue(Property.TOOL_BAR, Boolean.valueOf(toolBar));
   }
   putPropertyValue(Property.MENU, getOptionalString(resource, propertyPrefix + Property.MENU));
 }
 /**
  * Configuration method invoked by framework while initializing Class. Following are the
  * parameters used :
  *
  * <p>
  *
  * <blockquote>
  *
  * <pre>
  * resource-file - oneinc-resource.properties
  * validation-file - validation-rules.xml
  * </pre>
  *
  * </blockquote>
  *
  * <p>This method initialize the ValidatorResources by reading the validation-file passed and then
  * initialize different forms defined in this file. It also initialize the validation resource
  * bundle i.e. oneinc-resource.properties from where user friendly message would be picked in case
  * of validation failure.
  *
  * <p>Member-variable needs to be initialized/assigned once while initializing the class, and is
  * being passed from the XML is initialized in this method.
  *
  * <p>In XML, use the following tag to define the property:
  *
  * <p>&lt;property name="resource-file" value="oneinc-resource" /&gt;
  *
  * <p>corresponding code to get the property is as follow:
  *
  * <p>String resourceName = cfg.get("resource-file");
  *
  * @param cfg - Configuration object holds the property defined in the XML.
  * @throws ConfigurationException
  */
 public void setConfiguration(Configuration cfg) throws ConfigurationException {
   try {
     String resourceName = cfg.get("resource-file");
     apps = ResourceBundle.getBundle(resourceName);
     validationFileName = cfg.get("validation-file");
     InputStream in = null;
     in = BaseValidation.class.getClassLoader().getResourceAsStream(validationFileName);
     try {
       resources = new ValidatorResources(in);
       form = resources.getForm(Locale.getDefault(), "ValidateBean");
       provForm = resources.getForm(Locale.getDefault(), "ValidateProvBean");
     } finally {
       if (in != null) {
         in.close();
       }
     }
     prepareTxnMap();
   } catch (FileNotFoundException e) {
     throw new ConfigurationException(e.getLocalizedMessage(), e);
   } catch (IOException e) {
     throw new ConfigurationException(e.getLocalizedMessage(), e);
   } catch (Exception e) {
     throw new ConfigurationException(e.getLocalizedMessage(), e);
   }
 }
Example #8
0
 private static ResourceBundle getBundleImpl(String bundleName, Locale locale, ClassLoader loader)
     throws MissingResourceException {
   if (bundleName != null) {
     ResourceBundle bundle;
     if (!locale.equals(Locale.getDefault())) {
       String localeName = locale.toString();
       if (localeName.length() > 0) {
         localeName = UNDER_SCORE + localeName;
       }
       if ((bundle = handleGetBundle(bundleName, localeName, false, loader)) != null) {
         return bundle;
       }
     }
     String localeName = Locale.getDefault().toString();
     if (localeName.length() > 0) {
       localeName = UNDER_SCORE + localeName;
     }
     if ((bundle = handleGetBundle(bundleName, localeName, true, loader)) != null) {
       return bundle;
     }
     throw new MissingResourceException(
         Messages.getString("luni.3A", bundleName, locale),
         bundleName + '_' + locale, // $NON-NLS-1$
         EMPTY_STRING);
   }
   throw new NullPointerException();
 }
Example #9
0
 /** 扩展卡不可用时直接从网络获取图片 */
 public byte[] httpGetUrlAsByte(String url) {
   try {
     int stateCode;
     HttpGet httpGet = new HttpGet(url);
     httpGet.setHeader(
         "Accept-Language",
         (Locale.getDefault().getLanguage() + "-" + Locale.getDefault().getCountry())
             .toLowerCase());
     HttpResponse httpResponse = defaultHttpClient.execute(httpGet);
     stateCode = httpResponse.getStatusLine().getStatusCode();
     HttpEntity httpEntity = httpResponse.getEntity();
     if (httpEntity != null && stateCode == 200) {
       if (httpResponse.getEntity().getContentEncoding() == null
           || httpResponse
                   .getEntity()
                   .getContentEncoding()
                   .getValue()
                   .toLowerCase()
                   .indexOf("gzip")
               < 0) {
         InputStream is = httpEntity.getContent();
         byte[] byt = readInStream(is);
         return byt;
       } else {
         InputStream is =
             new GZIPInputStream(new ByteArrayInputStream(EntityUtils.toByteArray(httpEntity)));
         byte[] byt = readInStream(is);
         return byt;
       }
     }
   } catch (IOException e) {
   } catch (NullPointerException ex) {
   }
   return null;
 }
  @Test
  public void shouldValidateForGracePeriodWithDIPBInterestTypeAndVariableInstallments() {
    ActionMessageMatcher actionMessageMatcher =
        new ActionMessageMatcher(
            ProductDefinitionConstants.INVALID_INTEREST_TYPE_FOR_GRACE_PERIODS);

    loanPrdActionForm.setGracePeriodType(GraceType.PRINCIPALONLYGRACE.getValueAsString());
    loanPrdActionForm.setCanConfigureVariableInstallments(true);
    loanPrdActionForm.setInterestTypes(InterestType.FLAT.getValueAsString());
    loanPrdActionForm.validateInterestTypeForGracePeriods(errors, Locale.getDefault());
    Mockito.verify(errors).add(Mockito.anyString(), Mockito.argThat(actionMessageMatcher));
    Mockito.reset(errors);

    loanPrdActionForm.setGracePeriodType(GraceType.PRINCIPALONLYGRACE.getValueAsString());
    loanPrdActionForm.setCanConfigureVariableInstallments(false);
    loanPrdActionForm.setInterestTypes(InterestType.DECLINING_PB.getValueAsString());
    loanPrdActionForm.validateInterestTypeForGracePeriods(errors, Locale.getDefault());
    Mockito.verify(errors).add(Mockito.anyString(), Mockito.argThat(actionMessageMatcher));
    Mockito.reset(errors);

    loanPrdActionForm.setGracePeriodType(GraceType.GRACEONALLREPAYMENTS.getValueAsString());
    loanPrdActionForm.setCanConfigureVariableInstallments(true);
    loanPrdActionForm.setInterestTypes(InterestType.COMPOUND.getValueAsString());
    loanPrdActionForm.validateInterestTypeForGracePeriods(errors, Locale.getDefault());
    Mockito.verify(errors).add(Mockito.anyString(), Mockito.argThat(actionMessageMatcher));
    Mockito.reset(errors);

    loanPrdActionForm.setGracePeriodType(GraceType.NONE.getValueAsString());
    loanPrdActionForm.setCanConfigureVariableInstallments(false);
    loanPrdActionForm.setInterestTypes(InterestType.DECLINING_EPI.getValueAsString());
    loanPrdActionForm.validateInterestTypeForGracePeriods(errors, Locale.getDefault());
    Mockito.verifyZeroInteractions(errors);
    Mockito.reset(errors);
  }
  @Test
  public void testTimeDateDefaults() {
    assertEquals(
        FastDateFormat.getDateTimeInstance(
            FastDateFormat.LONG, FastDateFormat.MEDIUM, Locale.CANADA),
        FastDateFormat.getDateTimeInstance(
            FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getDefault(), Locale.CANADA));

    assertEquals(
        FastDateFormat.getDateTimeInstance(
            FastDateFormat.LONG, FastDateFormat.MEDIUM, TimeZone.getTimeZone("America/New_York")),
        FastDateFormat.getDateTimeInstance(
            FastDateFormat.LONG,
            FastDateFormat.MEDIUM,
            TimeZone.getTimeZone("America/New_York"),
            Locale.getDefault()));

    assertEquals(
        FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.MEDIUM),
        FastDateFormat.getDateTimeInstance(
            FastDateFormat.LONG,
            FastDateFormat.MEDIUM,
            TimeZone.getDefault(),
            Locale.getDefault()));
  }
  private void updateDisplay(boolean announce) {
    if (mDayOfWeekView != null) {
      mDayOfWeekView.setText(
          mCalendar
              .getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault())
              .toUpperCase(Locale.getDefault()));
    }

    mSelectedMonthTextView.setText(
        mCalendar
            .getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault())
            .toUpperCase(Locale.getDefault()));
    mSelectedDayTextView.setText(DAY_FORMAT.format(mCalendar.getTime()));
    mYearView.setText(YEAR_FORMAT.format(mCalendar.getTime()));

    // Accessibility.
    long millis = mCalendar.getTimeInMillis();
    mAnimator.setDateMillis(millis);
    int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
    String monthAndDayText = DateUtils.formatDateTime(getActivity(), millis, flags);
    mMonthAndDayView.setContentDescription(monthAndDayText);

    if (announce) {
      flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
      String fullDateText = DateUtils.formatDateTime(getActivity(), millis, flags);
      Utils.tryAccessibilityAnnounce(mAnimator, fullDateText);
    }
  }
Example #13
0
  /**
   * Loads the bundle (if not already loaded).
   *
   * @param name The name of the bundle to load.
   */
  private static void loadBundle(String name) {
    if (bundles.containsKey(name)) {
      return;
    }
    String resource = BUNDLES_PATH + "." + name;
    ResourceBundle bundle = null;
    try {
      LOG.debug("Loading " + resource);
      Locale locale = Locale.getDefault();
      bundle = ResourceBundle.getBundle(resource, locale);
    } catch (MissingResourceException e1) {
      LOG.debug("Resource " + resource + " not found in the default class loader.");

      Iterator iter = classLoaders.iterator();
      while (iter.hasNext()) {
        ClassLoader cl = (ClassLoader) iter.next();
        try {
          LOG.debug("Loading " + resource + " from " + cl);
          bundle = ResourceBundle.getBundle(resource, Locale.getDefault(), cl);
          break;
        } catch (MissingResourceException e2) {
          LOG.debug("Resource " + resource + " not found in " + cl);
        }
      }
    }

    bundles.put(name, bundle);
  }
  private PdfPTable footer() {

    PdfPTable footer = new PdfPTable(1);
    footer.setTotalWidth(523);
    Font colorLetra = new Font();
    colorLetra.setColor(new BaseColor(Color.white));
    colorLetra.setSize(8);

    PdfPCell cell =
        new PdfPCell(
            new Paragraph(
                messageSource.getMessage("generaPdf.pdf.DireccionPart1", null, Locale.getDefault()),
                colorLetra));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(new BaseColor(0, 0, 0));
    footer.addCell(cell);
    cell =
        new PdfPCell(
            new Paragraph(
                messageSource.getMessage("generaPdf.pdf.DireccionPart2", null, Locale.getDefault()),
                colorLetra));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(new BaseColor(0, 0, 0));
    footer.addCell(cell);
    cell =
        new PdfPCell(
            new Paragraph(
                messageSource.getMessage("generaPdf.pdf.DireccionPart3", null, Locale.getDefault()),
                colorLetra));
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setBackgroundColor(new BaseColor(0, 0, 0));
    footer.addCell(cell);
    return footer;
  }
  /**
   * for ES to initialize the user dictionary.
   *
   * @param configFile
   */
  public void init(Path configFile) {
    String abspath = configFile.toAbsolutePath().toString();
    System.out.println("initialize user dictionary:" + abspath);
    synchronized (WordDictionary.class) {
      if (loadedPath.contains(abspath)) return;

      DirectoryStream<Path> stream;
      try {
        stream =
            Files.newDirectoryStream(
                configFile, String.format(Locale.getDefault(), "*%s", USER_DICT_SUFFIX));
        for (Path path : stream) {
          System.err.println(
              String.format(Locale.getDefault(), "loading dict %s", path.toString()));
          singleton.loadUserDict(path);
        }
        loadedPath.add(abspath);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
        System.err.println(
            String.format(
                Locale.getDefault(), "%s: load user dict failure!", configFile.toString()));
      }
    }
  }
    @Override
    public int compare(File filea, File fileb) {

      return ((filea.isFile() ? "a" : "b") + filea.getName().toLowerCase(Locale.getDefault()))
          .compareTo(
              (fileb.isFile() ? "a" : "b") + fileb.getName().toLowerCase(Locale.getDefault()));
    }
 public String a(PageHours paramPageHours, Resources paramResources) {
   GraphQLTimeRange localGraphQLTimeRange = paramPageHours.b();
   PageHours.Status localStatus = paramPageHours.a();
   String str1 = a(localGraphQLTimeRange.start);
   String str2 = a(localGraphQLTimeRange.end);
   String str4;
   if (localStatus == PageHours.Status.OPEN)
     str4 = paramResources.getString(2131361836, new Object[] {str1, str2});
   while (true) {
     return str4;
     Calendar localCalendar = Calendar.getInstance(a, Locale.getDefault());
     localCalendar.setTime(new Date(1000L * paramPageHours.d()));
     int i = localCalendar.get(7);
     localCalendar.setTime(new Date(1000L * localGraphQLTimeRange.start));
     int j = localCalendar.get(7);
     String str3 = localCalendar.getDisplayName(7, 2, Locale.getDefault());
     int k = (7 + (j - i)) % 7;
     if (k == 0) {
       str4 = paramResources.getString(2131361837, new Object[] {str1, str2});
       continue;
     }
     if (k == 1) {
       str4 = paramResources.getString(2131361838, new Object[] {str1, str2});
       continue;
     }
     if (k < 5) {
       str4 = paramResources.getString(2131361839, new Object[] {str3, str1, str2});
       continue;
     }
     str4 = paramResources.getString(2131361840, new Object[] {str3, str1, str2});
   }
 }
Example #18
0
  /**
   * AJAX Called once user is submitting upload form
   *
   * @param model
   * @param file - Uploaded file
   * @param comment - Comment for uploaded file
   * @return
   */
  @RequestMapping(method = RequestMethod.POST)
  public @ResponseBody JsonResponse uploadAction(
      @Valid @ModelAttribute(value = "image") Image image,
      @RequestParam(value = "captcha_challenge", required = true) String challenge,
      @RequestParam(value = "captcha_response", required = true) String response,
      BindingResult result,
      HttpServletRequest paramHttpServletRequest) {
    JsonResponse jsonResponse = new JsonResponse();
    String remoteAddr = paramHttpServletRequest.getRemoteAddr();
    ReCaptchaResponse reCaptchaResponse = recaptcha.checkAnswer(remoteAddr, challenge, response);
    if (!reCaptchaResponse.isValid()) {
      jsonResponse.setCaptchaError(
          context.getMessage("error.bad.captcha", null, Locale.getDefault()));
      return jsonResponse;
    }

    prepareImage(image);
    (new ImageValidator()).validate(image, result);
    if (!result.hasErrors()) {
      try {
        image.setBytes(image.getFile().getBytes());
        image.setContentType(image.getFile().getContentType());
        image = imageService.saveImage(image);
        jsonResponse.setResponse(paramHttpServletRequest.getRequestURL() + image.getId());
      } catch (Exception e) {
        log.error(e.getMessage());
      }
    } else {
      for (ObjectError error : result.getAllErrors()) {
        jsonResponse.appendError(context.getMessage(error.getCode(), null, Locale.getDefault()));
      }
    }
    return jsonResponse;
  }
Example #19
0
  public Lang() {
    // Warning this can be null. - ToDo check it
    final ClassLoader classLoader = ScoreboardStats.getInstance().getClassLoaderBypass();

    defaultMessages = ResourceBundle.getBundle("messages", Locale.getDefault(), classLoader);
    utfCharacters = ResourceBundle.getBundle("characters", Locale.getDefault(), classLoader);
  }
  /**
   * 消息分发,选择跳转到哪个fragment
   *
   * @param intent
   */
  private void enterFragment(Intent intent) {
    String tag = null;

    if (intent != null) {
      Fragment fragment = null;

      if (intent.getExtras() != null && intent.getExtras().containsKey(RongConst.EXTRA.CONTENT)) {
        String fragmentName = intent.getExtras().getString(RongConst.EXTRA.CONTENT);
        fragment = Fragment.instantiate(this, fragmentName);
      } else if (intent.getData() != null) {

        if (intent.getData().getPathSegments().get(0).equals("conversation")) {
          tag = "conversation";
          String fragmentName = ConversationFragment.class.getCanonicalName();
          fragment = Fragment.instantiate(this, fragmentName);

        } else if (intent.getData().getLastPathSegment().equals("conversationlist")) {
          tag = "conversationlist";
          String fragmentName = ConversationListFragment.class.getCanonicalName();
          fragment = Fragment.instantiate(this, fragmentName);
        } else if (intent.getData().getLastPathSegment().equals("subconversationlist")) {
          tag = "subconversationlist";
          String fragmentName = SubConversationListFragment.class.getCanonicalName();
          fragment = Fragment.instantiate(this, fragmentName);
          SubConversationListFragment sub = (SubConversationListFragment) fragment;
          sub.setAdapter(new SubConversationListAdapterEx(RongContext.getInstance()));
        } else if (intent.getData().getPathSegments().get(0).equals("friend")) {
          tag = "friend";
          String fragmentName = FriendMultiChoiceFragment.class.getCanonicalName();
          fragment = Fragment.instantiate(this, fragmentName);
          ActionBar actionBar = getSupportActionBar();
          actionBar.hide(); // 隐藏ActionBar
        }

        targetId = intent.getData().getQueryParameter("targetId");
        targetIds = intent.getData().getQueryParameter("targetIds");
        mDiscussionId = intent.getData().getQueryParameter("discussionId");

        if (targetId != null) {
          mConversationType =
              Conversation.ConversationType.valueOf(
                  intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
        } else if (targetIds != null) {
          mConversationType =
              Conversation.ConversationType.valueOf(
                  intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
        }
      }

      if ("tag".equals(tag)) {
        showRealTimeLocationBar(null); // RealTimeLocation
      }

      if (fragment != null) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.de_content, fragment, tag);
        transaction.addToBackStack(null).commitAllowingStateLoss();
      }
    }
  }
 public void set(SearchBookContentsResult result) {
   pageNumberView.setText(result.getPageNumber());
   String snippet = result.getSnippet();
   if (snippet.length() > 0) {
     if (result.getValidSnippet()) {
       String lowerQuery = SearchBookContentsResult.getQuery().toLowerCase(Locale.getDefault());
       String lowerSnippet = snippet.toLowerCase(Locale.getDefault());
       Spannable styledSnippet = new SpannableString(snippet);
       StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
       int queryLength = lowerQuery.length();
       int offset = 0;
       while (true) {
         int pos = lowerSnippet.indexOf(lowerQuery, offset);
         if (pos < 0) {
           break;
         }
         styledSnippet.setSpan(boldSpan, pos, pos + queryLength, 0);
         offset = pos + queryLength;
       }
       snippetView.setText(styledSnippet);
     } else {
       // This may be an error message, so don't try to bold the query terms within it
       snippetView.setText(snippet);
     }
   } else {
     snippetView.setText("");
   }
 }
Example #22
0
  private void doTestDisplayNames(Locale inLocale, int compareIndex, boolean defaultIsFrench) {
    if (defaultIsFrench && !Locale.getDefault().getLanguage().equals("fr"))
      errln(
          "Default locale should be French, but it's really " + Locale.getDefault().getLanguage());
    else if (!defaultIsFrench && !Locale.getDefault().getLanguage().equals("en"))
      errln(
          "Default locale should be English, but it's really " + Locale.getDefault().getLanguage());

    for (int i = 0; i <= MAX_LOCALES; i++) {
      Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]);
      logln("  Testing " + testLocale + "...");

      String testLang;
      String testCtry;
      String testVar;
      String testName;

      if (inLocale == null) {
        testLang = testLocale.getDisplayLanguage();
        testCtry = testLocale.getDisplayCountry();
        testVar = testLocale.getDisplayVariant();
        testName = testLocale.getDisplayName();
      } else {
        testLang = testLocale.getDisplayLanguage(inLocale);
        testCtry = testLocale.getDisplayCountry(inLocale);
        testVar = testLocale.getDisplayVariant(inLocale);
        testName = testLocale.getDisplayName(inLocale);
      }

      String expectedLang;
      String expectedCtry;
      String expectedVar;
      String expectedName;

      expectedLang = dataTable[compareIndex][i];
      if (expectedLang.equals("") && defaultIsFrench) expectedLang = dataTable[DLANG_EN][i];
      if (expectedLang.equals("")) expectedLang = dataTable[DLANG_ROOT][i];

      expectedCtry = dataTable[compareIndex + 1][i];
      if (expectedCtry.equals("") && defaultIsFrench) expectedCtry = dataTable[DCTRY_EN][i];
      if (expectedCtry.equals("")) expectedCtry = dataTable[DCTRY_ROOT][i];

      expectedVar = dataTable[compareIndex + 2][i];
      if (expectedVar.equals("") && defaultIsFrench) expectedVar = dataTable[DVAR_EN][i];
      if (expectedVar.equals("")) expectedVar = dataTable[DVAR_ROOT][i];

      expectedName = dataTable[compareIndex + 3][i];
      if (expectedName.equals("") && defaultIsFrench) expectedName = dataTable[DNAME_EN][i];
      if (expectedName.equals("")) expectedName = dataTable[DNAME_ROOT][i];

      if (!testLang.equals(expectedLang))
        errln("Display language mismatch: " + testLang + " versus " + expectedLang);
      if (!testCtry.equals(expectedCtry))
        errln("Display country mismatch: " + testCtry + " versus " + expectedCtry);
      if (!testVar.equals(expectedVar))
        errln("Display variant mismatch: " + testVar + " versus " + expectedVar);
      if (!testName.equals(expectedName))
        errln("Display name mismatch: " + testName + " versus " + expectedName);
    }
  }
  /** {@inheritDoc} */
  public void commit() {
    ResourceBundle rb = ResourceBundle.getBundle("TalendBridge", Locale.getDefault());

    if (waitToTruncate == true) {
      rowList.clear();
      return;
    }

    for (TalendRowImpl row : rowdraft) {
      if ((index.size() - 1) > 0 && index.contains(row.getKeySet())) {
        throw new IllegalStateException(
            String.format(Locale.getDefault(), rb.getString("exception.duplicateKey"), name));
      }
    }
    rowList.addAll(rowdraft);
    for (TalendRowImpl row : rowdraft) {
      if (row.presentInTable == false) {
        // index.put(row.getKeySet(), 1);
        index.add(row.getKeySet());
      }
      row.presentInTable = true;
      row.save();
    }
    rowdraft.clear();
  }
  public Authentication authenticate(Authentication auth) throws UsernameNotFoundException {

    /** Init a database user object */
    try {
      employeeEntity = employeeDao.findByLogin(auth.getName());
    } catch (RuntimeException e) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.no_user", new Object[] {"userName"}, "Access denied", Locale.getDefault()));
    }

    /** Checking if user account is active */
    if (employeeEntity.getActive() == 0) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.expired", new Object[] {"active"}, "Access denied", Locale.getDefault()));
    }

    /** Compare passwords Make sure to encode the password first before comparing */
    if (!passwordEncoder.isPasswordValid(
        employeeEntity.getPassword(), (String) auth.getCredentials(), null)) {
      throw new BadCredentialsException(
          this.messageSource.getMessage(
              "auth.wrong", new Object[] {"password"}, "Access denied", Locale.getDefault()));
    }

    /**
     * main logic of Authentication manager
     *
     * @return UsernamePasswordAuthenticationToken
     */
    userAccessLogger.debug("User is located!");
    return new UsernamePasswordAuthenticationToken(
        auth.getName(), auth.getCredentials(), getAuthorities(employeeEntity.getAdmin()));
  }
  /**
   * Creates and returns a FacesMessage for the specified Locale.
   *
   * @param context - the <code>FacesContext</code> for the current request
   * @param messageId - the key of the message in the resource bundle
   * @param params - substittion parameters
   * @return a localized <code>FacesMessage</code> with the severity of FacesMessage.SEVERITY_ERROR
   */
  protected static FacesMessage getMessage(
      FacesContext context, String messageId, Object... params) {

    if (context == null || messageId == null) {
      throw new NullPointerException(" context " + context + " messageId " + messageId);
    }
    Locale locale;
    // viewRoot may not have been initialized at this point.
    if (context.getViewRoot() != null) {
      locale = context.getViewRoot().getLocale();
    } else {
      locale = Locale.getDefault();
    }

    if (null == locale) {
      throw new NullPointerException(" locale is null ");
    }

    FacesMessage message = getMessage(locale, messageId, params);
    if (message != null) {
      return message;
    }
    locale = Locale.getDefault();
    return (getMessage(locale, messageId, params));
  }
  /** Get the keycode value for AM and PM in the current language. */
  private int getAmOrPmKeyCode(int amOrPm) {
    // Cache the codes.
    if (mAmKeyCode == -1 || mPmKeyCode == -1) {
      // Find the first character in the AM/PM text that is unique.
      KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
      char amChar;
      char pmChar;
      for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) {
        amChar = mAmText.toLowerCase(Locale.getDefault()).charAt(i);
        pmChar = mPmText.toLowerCase(Locale.getDefault()).charAt(i);
        if (amChar != pmChar) {
          KeyEvent[] events = kcm.getEvents(new char[] {amChar, pmChar});
          // There should be 4 events: a down and up for both AM and PM.
          if (events != null && events.length == 4) {
            mAmKeyCode = events[0].getKeyCode();
            mPmKeyCode = events[2].getKeyCode();
          } else {
            Log.e(TAG, "Unable to find keycodes for AM and PM.");
          }
          break;
        }
      }
    }
    if (amOrPm == AM) {
      return mAmKeyCode;
    } else if (amOrPm == PM) {
      return mPmKeyCode;
    }

    return -1;
  }
Example #27
0
 public void setProperty(String name, Object object)
     throws SAXNotRecognizedException, SAXNotSupportedException {
   if (name == null) {
     throw new NullPointerException(
         JAXPValidationMessageFormatter.formatMessage(
             Locale.getDefault(), "ProperyNameNull", null));
   }
   if (name.equals(SECURITY_MANAGER)) {
     fSecurityManager = (SecurityManager) object;
     fXMLSchemaLoader.setProperty(SECURITY_MANAGER, fSecurityManager);
     return;
   } else if (name.equals(XMLGRAMMAR_POOL)) {
     throw new SAXNotSupportedException(
         SAXMessageFormatter.formatMessage(
             Locale.getDefault(), "property-not-supported", new Object[] {name}));
   }
   try {
     fXMLSchemaLoader.setProperty(name, object);
   } catch (XMLConfigurationException e) {
     String identifier = e.getIdentifier();
     if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
       throw new SAXNotRecognizedException(
           SAXMessageFormatter.formatMessage(
               Locale.getDefault(), "property-not-recognized", new Object[] {identifier}));
     } else {
       throw new SAXNotSupportedException(
           SAXMessageFormatter.formatMessage(
               Locale.getDefault(), "property-not-supported", new Object[] {identifier}));
     }
   }
 }
  public void loadUserDict(Path userDict, Charset charset) {
    try {
      BufferedReader br = Files.newBufferedReader(userDict, charset);
      long s = System.currentTimeMillis();
      int count = 0;
      while (br.ready()) {
        String line = br.readLine();
        String[] tokens = line.split("[\t ]+");

        if (tokens.length < 2) continue;

        String word = tokens[0];
        double freq = Double.valueOf(tokens[1]);
        word = addWord(word);
        freqs.put(word, Math.log(freq / total));
        count++;
      }
      System.out.println(
          String.format(
              Locale.getDefault(),
              "user dict %s load finished, tot words:%d, time elapsed:%dms",
              userDict.toString(),
              count,
              System.currentTimeMillis() - s));
      br.close();
    } catch (IOException e) {
      System.err.println(
          String.format(Locale.getDefault(), "%s: load user dict failure!", userDict.toString()));
    }
  }
  public static String loadMessage(final String code, final Object[] parameters) {
    // default message
    String errorMessage = "";
    try {
      // get access to the error messages bundle
      final ResourceBundle messagesBundle =
          ResourceBundle.getBundle(ERRORS_BUNDLE, Locale.getDefault());
      // construct the error message
      errorMessage = code + " - " + messagesBundle.getString(MESSAGE_PREFIX + code);

      // get access to the error message parameters bundle
      final ResourceBundle parametersBundle =
          ResourceBundle.getBundle(PARAMETERS_BUNDLE, Locale.getDefault());
      // loop for all parameters
      for (int i = 0; i < parameters.length; i++) {
        // get parameter value
        final String parameterValue =
            parametersBundle.getString(PARAMETER_PREFIX + (String) parameters[i]);
        // replace parameter placeholder in the error message string
        errorMessage = errorMessage.replaceAll("\\{" + (i + 1) + "}", parameterValue);
      }
    } catch (Exception e) {
      // log the exception
      LOGGER.warning(e);
    }

    return errorMessage;
  }
    private SelectChartExpressionAction(final Class expressionType) {
      this.expressionType = expressionType;

      final ExpressionRegistry expressionRegistry = ExpressionRegistry.getInstance();
      final ExpressionMetaData metaData =
          expressionRegistry.getExpressionMetaData(expressionType.getName());
      putValue(
          Action.NAME, metaData.getMetaAttribute("short-name", Locale.getDefault())); // NON-NLS

      final String defaultIcon = metaData.getMetaAttribute("icon", Locale.getDefault()); // NON-NLS
      if (defaultIcon != null) {
        final URL defaultIconUrl = LegacyChartEditorDialog.class.getResource(defaultIcon);
        if (defaultIconUrl != null) {
          standardIcon = new ImageIcon(defaultIconUrl);
          putValue(Action.SMALL_ICON, standardIcon);
        }
      }

      final String selectedIconProperty =
          metaData.getMetaAttribute("selected-icon", Locale.getDefault()); // NON-NLS
      if (selectedIconProperty != null) {
        final URL selectedIconUrl = LegacyChartEditorDialog.class.getResource(selectedIconProperty);
        if (selectedIconUrl != null) {
          selectedIcon = new ImageIcon(selectedIconUrl);
        }
      }
    }