Package org.languagetool

Examples of org.languagetool.Language


  throws IOException {
    String[] finalMatch = null;
    //final List<Match> suggestionMatches = rule.getSuggestionMatches();
    if (suggestionMatches.get(start) != null) {
      final int len = phraseLen(index);
      final Language language = rule.language;
      if (len == 1) {
        final int skippedTokens = nextTokenPos - tokenIndex;
        suggestionMatches.get(start).setToken(tokens, tokenIndex - 1, skippedTokens);
        suggestionMatches.get(start).setSynthesizer(language.getSynthesizer());
        finalMatch = suggestionMatches.get(start).toFinalString(language);
        if (suggestionMatches.get(start).checksSpelling()
                && finalMatch.length == 1
                && "".equals(finalMatch[0])) {
            finalMatch = new String[1];
            finalMatch[0] = "<mistake/>";
        }
               
      } else {
        final List<String[]> matchList = new ArrayList<>();
        for (int i = 0; i < len; i++) {
          final int skippedTokens = nextTokenPos - (tokenIndex + i);
          suggestionMatches.get(start).setToken(tokens, tokenIndex - 1 + i, skippedTokens);
          suggestionMatches.get(start)
                  .setSynthesizer(language.getSynthesizer());
          matchList.add(suggestionMatches.get(start).toFinalString(language));
        }
        return combineLists(matchList.toArray(new String[matchList.size()][]),
            new String[matchList.size()], 0, language);
      }
View Full Code Here


      print("Auto-detected language of text with length " + text.length() + " is not reasonably certain, using '" + fallbackLanguage + "' as fallback");
      return Language.getLanguageForShortName(fallbackLanguage);
    }
   
    final LanguageIdentifier identifier = new LanguageIdentifier(text);
    Language lang;
    try {
      lang = Language.getLanguageForShortName(identifier.getLanguage());
    } catch (IllegalArgumentException e) {
      // fall back to English
      lang = Language.getLanguageForLocale(Locale.ENGLISH);
    }
    if (lang.getDefaultLanguageVariant() != null) {
      lang = lang.getDefaultLanguageVariant();
    }
    return lang;
  }
View Full Code Here

      throw new TextTooLongException("Your text is " + text.length() + " characters long, which longer " +
              "than this server's limit of " + maxTextLength + " characters. Please consider submitting a shorter text.");
    }
    //print("Check start: " + text.length() + " chars, " + langParam);
    final boolean autoDetectLanguage = getLanguageAutoDetect(parameters);
    final Language lang = getLanguage(text, parameters.get("language"), autoDetectLanguage);
    final String motherTongueParam = parameters.get("motherTongue");
    final Language motherTongue = motherTongueParam != null ? Language.getLanguageForShortName(motherTongueParam) : null;
    final boolean useEnabledOnly = "yes".equals(parameters.get("enabledOnly"));
    final String enabledParam = parameters.get("enabled");
    final List<String> enabledRules = new ArrayList<>();
    if (enabledParam != null) {
      enabledRules.addAll(Arrays.asList(enabledParam.split(",")));
    }
   
    final String disabledParam = parameters.get("disabled");
    final List<String> disabledRules = new ArrayList<>();
    if (disabledParam != null) {
      disabledRules.addAll(Arrays.asList(disabledParam.split(",")));
    }

    if (disabledRules.size() > 0 && useEnabledOnly) {
      throw new IllegalArgumentException("You cannot specify disabled rules using enabledOnly=yes");
    }
   
    final boolean useQuerySettings = enabledRules.size() > 0 || disabledRules.size() > 0;
    final QueryParams params = new QueryParams(enabledRules, disabledRules, useEnabledOnly, useQuerySettings);
   
    final Future<List<RuleMatch>> future = executorService.submit(new Callable<List<RuleMatch>>() {
      @Override
      public List<RuleMatch> call() throws Exception {
        return getRuleMatches(text, parameters, lang, motherTongue, params);
      }
    });
    final List<RuleMatch> matches;
    if (maxCheckTimeMillis < 0) {
      matches = future.get();
    } else {
      try {
        matches = future.get(maxCheckTimeMillis, TimeUnit.MILLISECONDS);
      } catch (TimeoutException e) {
        throw new RuntimeException("Text checking took longer than allowed maximum of " + maxCheckTimeMillis +
                " milliseconds (handleCount: " + handleCount + ", queue size: " + workQueue.size() +
                ", language: " + lang.getShortNameWithCountryAndVariant() +
                ", " + text.length() + " characters of text)", e);
      }
    }
   
    setCommonHeaders(httpExchange);
    String xmlResponse = getXmlResponse(text, lang, motherTongue, matches);
    String messageSent = "sent";
    String languageMessage = lang.getShortNameWithCountryAndVariant();
    final String referrer = httpExchange.getRequestHeaders().getFirst("Referer");
    try {
      httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, xmlResponse.getBytes(ENCODING).length);
      httpExchange.getResponseBody().write(xmlResponse.getBytes(ENCODING));
      if (motherTongue != null) {
        languageMessage += " (mother tongue: " + motherTongue.getShortNameWithCountryAndVariant() + ")";
      }
    } catch (IOException exception) {
      // the client is disconnected
      messageSent = "notSent: " + exception.getMessage();
    }
View Full Code Here

      return autoDetect;
    }
  }

  private Language getLanguage(String text, String langParam, boolean autoDetect) {
    final Language lang;
    if (autoDetect) {
      lang = detectLanguageOfString(text, langParam);
      print("Auto-detected language: " + lang.getShortNameWithCountryAndVariant());
    } else {
      if (afterTheDeadlineMode) {
        lang = afterTheDeadlineLanguage;
      } else {
        lang = Language.getLanguageForShortName(langParam);
View Full Code Here

import org.languagetool.rules.WordRepeatRule;

public class RuleLinkTest extends TestCase {

  public void testBuildDeactivationLink() {
    final Language language = new English();
    final RuleLink ruleLink = RuleLink.buildDeactivationLink(new WordRepeatRule(TestTools.getMessages(language.getShortName()), language));
    assertEquals("WORD_REPEAT_RULE", ruleLink.getId());
    assertEquals("http://languagetool.org/deactivate/WORD_REPEAT_RULE", ruleLink.toString());
  }
View Full Code Here

    assertEquals("WORD_REPEAT_RULE", ruleLink.getId());
    assertEquals("http://languagetool.org/deactivate/WORD_REPEAT_RULE", ruleLink.toString());
  }

  public void testBuildReactivationLink() {
    final Language language = new English();
    final RuleLink ruleLink = RuleLink.buildReactivationLink(new WordRepeatRule(TestTools.getMessages(language.getShortName()), language));
    assertEquals("WORD_REPEAT_RULE", ruleLink.getId());
    assertEquals("http://languagetool.org/reactivate/WORD_REPEAT_RULE", ruleLink.toString());
  }
View Full Code Here

      public void treeStructureChanged(TreeModelEvent e) {
      }
    });
    configTree = new JTree(treeModel);

    Language lang = config.getLanguage();
    if (lang == null) {
      lang = Language.getLanguageForLocale(Locale.getDefault());
    }
    configTree.applyComponentOrientation(
      ComponentOrientation.getOrientation(lang.getLocale()));

    configTree.setRootVisible(false);
    configTree.setEditable(false);
    configTree.setCellRenderer(new CheckBoxTreeCellRenderer());
    TreeListener.install(configTree);
    checkBoxPanel.add(configTree, cons);

    MouseAdapter ma = new MouseAdapter() {
      private void handlePopupEvent(MouseEvent e) {
        final JTree tree = (JTree) e.getSource();

        TreePath path = tree.getPathForLocation(e.getX(), e.getY());
        if (path == null) {
          return;
        }

        DefaultMutableTreeNode node
                = (DefaultMutableTreeNode) path.getLastPathComponent();

        TreePath[] paths = tree.getSelectionPaths();

        boolean isSelected = false;
        if (paths != null) {
          for (TreePath selectionPath : paths) {
            if (selectionPath.equals(path)) {
              isSelected = true;
            }
          }
        }
        if (!isSelected) {
          tree.setSelectionPath(path);
        }
        if (node.isLeaf()) {
          JPopupMenu popup = new JPopupMenu();
          final JMenuItem aboutRuleMenuItem = new JMenuItem(messages.getString("guiAboutRuleMenu"));
          aboutRuleMenuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
              RuleNode node = (RuleNode) tree.getSelectionPath().getLastPathComponent();
              Rule rule = node.getRule();
              Language lang = config.getLanguage();
              if(lang == null) {
                lang = Language.getLanguageForLocale(Locale.getDefault());
              }
              Tools.showRuleInfoDialog(tree, messages.getString("guiAboutRuleTitle"),
                      rule.getDescription(), rule, messages,
                      lang.getShortNameWithCountryAndVariant());
            }
          });
          popup.add(aboutRuleMenuItem);
          popup.show(tree, e.getX(), e.getY());
        }
      }

      @Override
      public void mousePressed(MouseEvent e) {
        if (e.isPopupTrigger()) {
          handlePopupEvent(e);
        }
      }

      @Override
      public void mouseReleased(MouseEvent e) {
        if (e.isPopupTrigger()) {
          handlePopupEvent(e);
        }
      }
    };
    configTree.addMouseListener(ma);
    final JPanel treeButtonPanel = new JPanel();
    cons = new GridBagConstraints();
    cons.gridx = 0;
    cons.gridy = 0;
    final JButton expandAllButton = new JButton(messages.getString("guiExpandAll"));
    treeButtonPanel.add(expandAllButton, cons);
    expandAllButton.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        TreeNode root = (TreeNode) configTree.getModel().getRoot();
        TreePath parent = new TreePath(root);
        for (Enumeration categ = root.children(); categ.hasMoreElements();) {
          TreeNode n = (TreeNode) categ.nextElement();
          TreePath child = parent.pathByAddingChild(n);
          configTree.expandPath(child);
        }
      }
    });

    cons.gridx = 1;
    cons.gridy = 0;
    final JButton collapseAllButton = new JButton(messages.getString("guiCollapseAll"));
    treeButtonPanel.add(collapseAllButton, cons);
    collapseAllButton.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        TreeNode root = (TreeNode) configTree.getModel().getRoot();
        TreePath parent = new TreePath(root);
        for (Enumeration categ = root.children(); categ.hasMoreElements();) {
          TreeNode n = (TreeNode) categ.nextElement();
          TreePath child = parent.pathByAddingChild(n);
          configTree.collapsePath(child);
        }
      }
    });

    final JPanel motherTonguePanel = new JPanel();
    motherTonguePanel.add(new JLabel(messages.getString("guiMotherTongue")), cons);
    motherTongueBox = new JComboBox(getPossibleMotherTongues());
    if (config.getMotherTongue() != null) {
      motherTongueBox.setSelectedItem(config.getMotherTongue().getTranslatedName(messages));
    }
    motherTongueBox.addItemListener(new ItemListener() {

      @Override
      public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
          Language motherTongue;
          if (motherTongueBox.getSelectedItem() instanceof String) {
            motherTongue = getLanguageForLocalizedName(motherTongueBox.getSelectedItem().toString());
          } else {
            motherTongue = (Language) motherTongueBox.getSelectedItem();
          }
View Full Code Here

public class SuggestionExtractorTool {

  private void writeIgnoreTokensForLanguages() throws IOException {
    final Map<Language, Set<String>> map = getLanguageToIgnoreTokensMapping();
    for (Map.Entry<Language, Set<String>> entry : map.entrySet()) {
      final Language language = entry.getKey();
      final File langDir = getLanguageDir(language);
      final File hunspellDir = new File(langDir, "hunspell");
      if (!hunspellDir.exists()) {
        System.out.println("No directory " + hunspellDir + " found, ignoring language " + language);
        continue;
      }
      final File ignoreFile;
      if (language.isVariant()) {
        ignoreFile = new File(hunspellDir, "ignore-" + language.getCountries()[0] + ".txt");
      } else {
        ignoreFile = new File(hunspellDir, "ignore.txt");
      }
      final Set<String> tokens = entry.getValue();
      try (FileOutputStream fos = new FileOutputStream(ignoreFile)) {
View Full Code Here

            noErrorCount++;
          }
        }
      }
      System.out.println(lang + ": " + noErrorCount + " out of " + tokenCount + " words ignored because they are known to spellchecker anyway");
      final Language noVariantLanguage = lang.getDefaultLanguageVariant() == null ? lang : lang.getDefaultLanguageVariant();
      final Set<String> existingTokens = langToIgnoreTokens.get(noVariantLanguage);
      if (existingTokens != null) {
        existingTokens.addAll(suggestionTokens);
      } else {
        langToIgnoreTokens.put(noVariantLanguage, suggestionTokens);
View Full Code Here

  private synchronized ProofreadingResult doGrammarCheckingInternal(
      final String paraText, final Locale locale, final ProofreadingResult paRes, int[] footnotePositions) {

    if (!StringTools.isEmpty(paraText) && hasLocale(locale)) {
      Language langForShortName = getLanguage(locale);
      if (!langForShortName.equals(docLanguage) || langTool == null || recheck) {
        docLanguage = langForShortName;
        initLanguageTool();
      }

      final Set<String> disabledRuleIds = config.getDisabledRuleIds();
View Full Code Here

TOP

Related Classes of org.languagetool.Language

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.