Beispiel #1
0
 @Test
 public void test_localized_string_to_json() throws Exception {
   LocalizedString string = new LocalizedString().forLanguageTag(null, "coucou").forEn("kewkew");
   String json = objectMapper.writeValueAsString(string);
   log.debug(string.toString());
   log.debug(json);
   assertThat(string.keySet().contains(Locale.ENGLISH.toLanguageTag())).isTrue();
   assertThat(string.keySet().contains(Locale.forLanguageTag("und").toLanguageTag())).isTrue();
   LocalizedString string2 = objectMapper.readValue(json, LocalizedString.class);
   log.debug(string2.toString());
   assertThat(string2.keySet().contains(Locale.ENGLISH.toLanguageTag())).isTrue();
   assertThat(string2.keySet().contains(Locale.forLanguageTag("und").toLanguageTag())).isTrue();
 }
  @BeforeClass
  public static void beforeClass() {
    currentLocale = Locale.getDefault();

    // Turkish will generate a "dotless i" when toLowerCase is used on "I".
    Locale.setDefault(Locale.forLanguageTag("tr-TR"));
  }
  @Test
  public void testGetLanguage() {
    Page profilesPage = context.pageManager().getPage("/content/sample/en/toolbar/profiles");

    // set language in site root
    ModifiableValueMap props = this.page.getContentResource().adaptTo(ModifiableValueMap.class);
    props.put(JcrConstants.JCR_LANGUAGE, "fr_FR");

    // test get language from content
    Locale locale = profilesPage.getLanguage(false);
    assertEquals(Locale.forLanguageTag("fr-FR"), locale);

    // test get language from path
    locale = profilesPage.getLanguage(true);
    assertEquals(Locale.forLanguageTag("en"), locale);
  }
  public SessionLocaleResolver sessionLocaleResolver() {

    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    Locale defaultLocale = Locale.forLanguageTag("en_US");
    sessionLocaleResolver.setDefaultLocale(defaultLocale);

    return sessionLocaleResolver;
  }
 /**
  * Returns a UMS supported {@link java.util.Locale} from the given <code>Local</code> if it can be
  * found (<code>en</code> is translated to <code>en-US</code>, <code>zh</code> to <code>zh-Hant
  * </code> etc.). Returns <code>null</code> if a valid <code>Locale</code> cannot be found.
  *
  * @param locale Source {@link java.util.Locale}.
  * @return Resulting {@link java.util.Locale}.
  */
 public static Locale toLocale(Locale locale) {
   if (locale != null) {
     String tag = localeToLanguageTag(locale);
     if (tag != null && isValid(tag)) {
       return Locale.forLanguageTag(tag);
     }
   }
   return null;
 }
 /**
  * Returns a UMS supported {@link java.util.Locale} from the given <a
  * href="https://en.wikipedia.org/wiki/IETF_language_tag">IEFT BCP 47</a> if it can be found (
  * <code>en</code> is translated to <code>en-US</code>, <code>zh</code> to <code>zh-Hant</code>
  * etc.). Returns <code>null</code> if a valid <code>Locale</code> cannot be found.
  *
  * @param locale Source {@link java.util.Locale}.
  * @return Resulting {@link java.util.Locale}.
  */
 public static Locale toLocale(String languageTag) {
   if (languageTag != null) {
     String tag = languageTagToUMSLanguageTag(languageTag);
     if (isValid(tag)) {
       return Locale.forLanguageTag(tag);
     }
   }
   return null;
 }
Beispiel #7
0
 @Override
 public void setValue(Object value) {
   if ((value != null) && (value instanceof Number)) {
     Number numberValue = (Number) value;
     NumberFormat formater = NumberFormat.getInstance(Locale.forLanguageTag("vi"));
     value = formater.format(numberValue.doubleValue());
   }
   super.setValue(value);
 }
 public static String getMsgString(String key, HttpExchange t) {
   if (PMS.getConfiguration().useWebLang()) {
     String lang = getFirstSupportedLanguage(t);
     if (!lang.isEmpty()) {
       return Messages.getString(key, Locale.forLanguageTag(lang));
     }
   }
   return Messages.getString(key);
 }
 @Async
 public void sendSocialRegistrationValidationEmail(User user, String provider) {
   log.debug("Sending social registration validation e-mail to '{}'", user.getEmail());
   Locale locale = Locale.forLanguageTag(user.getLangKey());
   Context context = new Context(locale);
   context.setVariable("user", user);
   context.setVariable("provider", WordUtils.capitalize(provider));
   String content = templateEngine.process("socialRegistrationValidationEmail", context);
   String subject = messageSource.getMessage("email.social.registration.title", null, locale);
   sendEmail(user.getEmail(), subject, content, false, true);
 }
Beispiel #10
0
 @Async
 public void sendPasswordResetMail(User user, String baseUrl) {
   log.debug("Sending password reset e-mail to '{}'", user.getEmail());
   Locale locale = Locale.forLanguageTag(user.getLangKey());
   Context context = new Context(locale);
   context.setVariable("user", user);
   context.setVariable("baseUrl", baseUrl);
   String content = templateEngine.process("passwordResetEmail", context);
   String subject = messageSource.getMessage("email.reset.title", null, locale);
   sendEmail(user.getEmail(), subject, content, false, true);
 }
Beispiel #11
0
 public static Locale findLocale(Set<String> supportedLocales, String... localeStrings) {
   for (String localeString : localeStrings) {
     Locale result = null;
     Locale search = Locale.forLanguageTag(localeString);
     for (String languageTag : supportedLocales) {
       Locale locale = Locale.forLanguageTag(languageTag);
       if (locale.getLanguage().equals(search.getLanguage())) {
         if (locale.getCountry().equals("") && result == null) {
           result = locale;
         }
         if (locale.getCountry().equals(search.getCountry())) {
           return locale;
         }
       }
     }
     if (result != null) {
       return result;
     }
   }
   return null;
 }
Beispiel #12
0
  /**
   * Determine the effective locale for this request.
   *
   * <p>Priority 1: URL parameter "locale" Priority 2: Browser locale
   *
   * @param request
   * @return
   */
  private Locale getEffectiveLocale(final HttpServletRequest request) {

    // Overwrite locale if requested by URL parameter
    String requestedLocaleString = request.getParameter(LOCALE_KEY);
    Locale locale = request.getLocale();
    if (StringUtils.isNotBlank(requestedLocaleString)) {
      try {
        locale = LocaleUtils.toLocale(requestedLocaleString);
      } catch (IllegalArgumentException e) {
        locale = Locale.forLanguageTag(requestedLocaleString);
      }
    }

    return locale;
  }
 @Override
 protected SimpleQueryStringBuilder doReadFrom(StreamInput in) throws IOException {
   SimpleQueryStringBuilder result = new SimpleQueryStringBuilder(in.readString());
   int size = in.readInt();
   Map<String, Float> fields = new HashMap<>();
   for (int i = 0; i < size; i++) {
     String field = in.readString();
     Float weight = in.readFloat();
     fields.put(field, weight);
   }
   result.fieldsAndWeights.putAll(fields);
   result.flags = in.readInt();
   result.analyzer = in.readOptionalString();
   result.defaultOperator = Operator.readOperatorFrom(in);
   result.settings.lowercaseExpandedTerms(in.readBoolean());
   result.settings.lenient(in.readBoolean());
   result.settings.analyzeWildcard(in.readBoolean());
   String localeStr = in.readString();
   result.settings.locale(Locale.forLanguageTag(localeStr));
   result.minimumShouldMatch = in.readOptionalString();
   return result;
 }
Beispiel #14
0
  /**
   * Builds the list of locale in the preference order accepted by the client. For reminder, the
   * ACCEPT-LANGUAGE header follows this convention: <code>
   *     <pre>
   *         Accept-Language = "Accept-Language" ":"
   *         1#( language-range [ ";" "q" "=" qvalue ] )
   *         language-range  = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
   *     </pre>
   * </code>
   *
   * @param accept the ACCEPT-LANGUAGE header value
   * @return the list of locale, empty if the header is {@literal null} or non-parseable
   * @see RequestHeader#languages()
   */
  public static Locale[] getLocaleList(String accept) {
    if (accept == null || accept.length() == 0) {
      return new Locale[0];
    }

    Map<Float, List<Locale>> locales =
        new TreeMap<>(
            new Comparator<Float>() {
              @Override
              public int compare(Float o1, Float o2) {
                return o2.compareTo(o1);
              }
            });
    String[] segments = accept.split(",");
    for (String segment : segments) {
      Matcher matcher = LANGUAGE_SEGMENT_PATTERN.matcher(segment.trim());
      if (!matcher.matches()) {
        continue;
      }
      float q = 1;
      if (matcher.group(5) != null) {
        q = Float.valueOf(matcher.group(5));
      }
      List<Locale> l = locales.get(q);
      if (l == null) {
        l = new ArrayList<>();
        locales.put(q, l);
      }
      l.add(Locale.forLanguageTag(matcher.group(1)));
    }

    // Now iterates from highest q to lowest.
    List<Locale> list = new ArrayList<>();
    for (Map.Entry<Float, List<Locale>> entry : locales.entrySet()) {
      list.addAll(entry.getValue());
    }
    return list.toArray(new Locale[list.size()]);
  }
 @Test
 public void test_chrono_byLocale_iso() {
   Assert.assertEquals(Chronology.ofLocale(new Locale("ja", "JP")).getId(), "ISO");
   Assert.assertEquals(Chronology.ofLocale(Locale.forLanguageTag("ja-JP")).getId(), "ISO");
   Assert.assertEquals(Chronology.ofLocale(Locale.forLanguageTag("ja-JP-JP")).getId(), "ISO");
 }
  static boolean processLine(
      String key, String expectedValue, PrintWriter out, boolean writeNewFile) throws Exception {
    String rbName, localeName, resTag, qualifier;
    String language = "", country = "", variant = "";
    int index, oldIndex;

    index = key.indexOf("/");
    if (index == -1 || index + 1 == key.length())
      throw new Exception("Malformed input file: no slashes in \"" + key + "\"");
    rbName = key.substring(0, index);

    oldIndex = index + 1;
    index = key.indexOf("/", oldIndex);
    if (index == -1 || index + 1 == key.length())
      throw new Exception("Malformed input file: \"" + key + "\" is missing locale name");
    localeName = key.substring(oldIndex, index);
    boolean use_tag = localeName.indexOf("-") != -1;

    if (use_tag == false && localeName.length() > 0) {
      language = localeName.substring(0, 2);
      if (localeName.length() > 3) {
        country = localeName.substring(3, 5);
        if (localeName.length() > 5) variant = localeName.substring(6);
      }
    }

    oldIndex = index + 1;
    index = key.indexOf("/", oldIndex);
    if (index == -1) index = key.length();
    resTag = key.substring(oldIndex, index);

    // TimeZone name may have "/" in it, for example "Asia/Taipei", so use "Asia\/Taipei in
    // LocaleData.
    if (resTag.endsWith("\\")) {
      resTag = resTag.substring(0, resTag.length() - 1);
      oldIndex = index;
      index = key.indexOf("/", oldIndex + 1);
      if (index == -1) index = key.length();
      resTag += key.substring(oldIndex, index);
    }

    if (index < key.length() - 1) qualifier = key.substring(index + 1);
    else qualifier = "";

    String retrievedValue = null;
    Object resource = null;
    try {
      String fullName = null;
      if (rbName.equals("CalendarData")
          || rbName.equals("CurrencyNames")
          || rbName.equals("LocaleNames")
          || rbName.equals("TimeZoneNames")) {
        fullName = "sun.util.resources." + rbName;
      } else {
        fullName = "sun.text.resources." + rbName;
      }
      Locale locale;
      if (use_tag) {
        locale = Locale.forLanguageTag(localeName);
      } else {
        locale = new Locale(language, country, variant);
      }
      ResourceBundle bundle =
          ResourceBundle.getBundle(
              fullName,
              locale,
              ResourceBundle.Control.getNoFallbackControl(Control.FORMAT_DEFAULT));
      resource = bundle.getObject(resTag);
    } catch (MissingResourceException e) {
    }

    if (resource != null) {
      if (resource instanceof String) {
        retrievedValue = (String) resource;
      } else if (resource instanceof String[]) {
        int element = Integer.valueOf(qualifier).intValue();
        String[] stringList = (String[]) resource;
        if (element >= 0 || element < stringList.length) retrievedValue = stringList[element];
      } else if (resource instanceof String[][]) {
        String[][] stringArray = (String[][]) resource;
        int slash = qualifier.indexOf("/");
        if (slash == -1) {
          for (int i = 0; i < stringArray.length; i++) {
            if (stringArray[i][0].equals(qualifier)) retrievedValue = stringArray[i][1];
          }
        } else {
          int row = Integer.valueOf(qualifier.substring(0, slash)).intValue();
          int column = Integer.valueOf(qualifier.substring(slash + 1)).intValue();
          if (row >= 0
              || row < stringArray.length
              || column >= 0
              || column < stringArray[row].length) retrievedValue = stringArray[row][column];
        }
      }
    }

    if (retrievedValue == null || !retrievedValue.equals(expectedValue)) {
      if (retrievedValue == null) retrievedValue = "<MISSING!>";

      if (writeNewFile) out.println(key + "=" + retrievedValue);
      else {
        out.println("Mismatch in " + key + ":");
        out.println("  file = \"" + expectedValue + "\"");
        out.println("   jvm = \"" + retrievedValue + "\"");
      }
      return false;
    } else {
      if (writeNewFile) out.println(key + "=" + expectedValue);
    }
    return true;
  }
@Component
@Profile("speechSynthesisApp")
public class SpeechSynthesisRouter extends RouteBuilder {

  public static final int SAMPLE_RATE = 16000;
  public static final Duration MESSAGE_EXPIRATION = Duration.standardMinutes(1);
  public static final Locale INDONESIAN = Locale.forLanguageTag("id-ID");
  /** id1 voice is quieter than default English */
  public static final int INDONESIAN_AMPLITUDE = 180;

  private static final Logger log = LoggerFactory.getLogger(SpeechSynthesisRouter.class);
  private static final DefaultExecutor executor = new DefaultExecutor();
  private static final File LINUX_MBROLA_SHARE_FOLDER = new File("/usr/share/mbrola");
  private static final File mbrolaShareFolder =
      LINUX_MBROLA_SHARE_FOLDER.exists() ? LINUX_MBROLA_SHARE_FOLDER : new File("C:/mbroladb");

  @Inject private Environment env;
  @Inject private ToJson toJson;
  @Inject private AsError asError;
  @Inject private ProducerTemplate producer;
  @Inject private SpeechProsody speechProsody;
  @Inject private EmotionProsodies emotionProsodies;

  private String ffmpegExecutable;

  @PostConstruct
  public void init() {
    ffmpegExecutable =
        !new File("/usr/bin/ffmpeg").exists() && new File("/usr/bin/avconv").exists()
            ? "avconv"
            : env.getRequiredProperty("ffmpeg.bin");
    log.info("libav autodetection result: We will use '{}'", ffmpegExecutable);
  }

  protected Status processCommunicateAction(
      final Exchange exchange, final CommunicateAction communicateAction) throws IOException {
    final EmotionKind emotionKind =
        Optional.ofNullable(communicateAction.getEmotionKind()).orElse(EmotionKind.NEUTRAL);
    final Locale lang = Optional.ofNullable(communicateAction.getInLanguage()).orElse(Locale.US);
    log.info("Got speech lang-legacy={}: {}", lang.getLanguage(), communicateAction);
    final String avatarId = Optional.ofNullable(communicateAction.getAvatarId()).orElse("nao1");

    // final File wavFile = File.createTempFile("lumen-speech-synthesis_", ".wav");
    //                        final File oggFile = File.createTempFile("lumen-speech-synthesis_",
    // ".ogg");
    try {
      byte[] wavBytes = null;
      if (INDONESIAN.getLanguage().equals(lang.getLanguage())) {
        // Expressive speech (for now, Indonesian only)
        try {
          PhonemeDoc phonemeDoc;
          if (EmotionKind.NEUTRAL == emotionKind) {
            phonemeDoc = speechProsody.performNeutral(communicateAction.getObject());
          } else {
            try {
              final EmotionProsody emotionProsody =
                  emotionProsodies
                      .getEmotion(emotionKind)
                      .orElseThrow(
                          () ->
                              new SpeechSynthesisException(
                                  "Emotion " + emotionKind + " not supported"));
              phonemeDoc = speechProsody.perform(communicateAction.getObject(), emotionProsody);
            } catch (Exception e) {
              log.error(
                  "Cannot speak with emotion "
                      + emotionKind
                      + ", falling back to NEUTRAL: "
                      + communicateAction.getObject(),
                  e);
              phonemeDoc = speechProsody.performNeutral(communicateAction.getObject());
            }
          }

          try (final ByteArrayInputStream objectIn =
                  new ByteArrayInputStream(phonemeDoc.toString().getBytes(StandardCharsets.UTF_8));
              final ByteArrayOutputStream wavStream = new ByteArrayOutputStream();
              final ByteArrayOutputStream err = new ByteArrayOutputStream()) {
            final CommandLine cmdLine = new CommandLine("mbrola");
            cmdLine.addArgument("-v");
            cmdLine.addArgument(String.valueOf(INDONESIAN_AMPLITUDE / 100f));
            cmdLine.addArgument(new File(mbrolaShareFolder, "id1/id1").toString());
            cmdLine.addArgument("-");
            cmdLine.addArgument("-.wav");
            executor.setStreamHandler(new PumpStreamHandler(wavStream, err, objectIn));
            final int executed;
            try {
              executed = executor.execute(cmdLine);
              wavBytes = wavStream.toByteArray();
            } finally {
              log.info("{}: {}", cmdLine, err.toString());
            }
          }
        } catch (Exception e) {
          log.error(
              "Cannot speak Indonesian using prosody engine, falling back to direct espeak: "
                  + communicateAction.getObject(),
              e);
        }
      }
      if (wavBytes == null) {
        // Neutral speech using direct espeak
        try {
          wavBytes = performEspeak(communicateAction, lang);
        } catch (Exception e) {
          if (!Locale.US.getLanguage().equals(lang.getLanguage())) {
            // Indonesian sometimes fails especially "k-k", e.g. "baik koq".
            // retry using English as last resort, as long as it says something!
            log.error(
                "Cannot speak using "
                    + lang.toLanguageTag()
                    + ", falling back to English (US): "
                    + communicateAction.getObject(),
                e);
            wavBytes = performEspeak(communicateAction, Locale.US);
          } else {
            throw e;
          }
        }
      }

      log.info("espeak/mbrola generated {} bytes WAV", wavBytes.length);
      try (final ByteArrayInputStream wavIn = new ByteArrayInputStream(wavBytes);
          final ByteArrayOutputStream bos = new ByteArrayOutputStream();
          final ByteArrayOutputStream err = new ByteArrayOutputStream()) {
        // flac.exe doesn't support mp3, and that's a problem for now (note: mp3 patent is expiring)
        final CommandLine cmdLine = new CommandLine(ffmpegExecutable);
        cmdLine.addArgument("-i");
        cmdLine.addArgument("-"); // cmdLine.addArgument(wavFile.toString());
        cmdLine.addArgument("-ar");
        cmdLine.addArgument(String.valueOf(SAMPLE_RATE));
        cmdLine.addArgument("-ac");
        cmdLine.addArgument("1");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("ogg");
        // without this you'll get FLAC instead, which browsers do not support
        cmdLine.addArgument("-acodec");
        cmdLine.addArgument("libvorbis");
        //                                cmdLine.addArgument("-y"); // happens, weird!
        //                                cmdLine.addArgument(oggFile.toString());
        cmdLine.addArgument("-");
        executor.setStreamHandler(new PumpStreamHandler(bos, err, wavIn));
        final int executed;
        try {
          executed = executor.execute(cmdLine);
        } finally {
          log.info("{}: {}", cmdLine, err.toString());
        }
        //                                Preconditions.checkState(oggFile.exists(), "Cannot convert
        // %s bytes WAV to OGG",
        //                                        wavBytes.length);

        // Send
        //                                final byte[] audioContent =
        // FileUtils.readFileToByteArray(oggFile);
        final byte[] audioContent = bos.toByteArray();
        final String audioContentType = "audio/ogg";

        final AudioObject audioObject = new AudioObject();
        audioObject.setTranscript(communicateAction.getObject());
        audioObject.setInLanguage(lang);
        audioObject.setMediaLayer(MediaLayer.SPEECH);
        audioObject.setContentType(audioContentType + "; rate=" + SAMPLE_RATE);
        audioObject.setContentUrl(
            "data:" + audioContentType + ";base64," + Base64.encodeBase64String(audioContent));
        audioObject.setContentSize((long) audioContent.length);
        //
        // audioObject.setName(FilenameUtils.getName(oggFile.getName()));
        audioObject.setName("lumen-speech-" + new DateTime() + ".ogg");
        audioObject.setDateCreated(new DateTime());
        audioObject.setDatePublished(audioObject.getDateCreated());
        audioObject.setDateModified(audioObject.getDateCreated());
        audioObject.setUploadDate(audioObject.getDateCreated());
        final String audioOutUri =
            "rabbitmq://dummy/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&skipQueueDeclare=true&routingKey="
                + AvatarChannel.AUDIO_OUT.key(avatarId);
        log.info("Sending {} to {} ...", audioObject, audioOutUri);
        producer.sendBodyAndHeader(
            audioOutUri,
            toJson.getMapper().writeValueAsBytes(audioObject),
            RabbitMQConstants.EXPIRATION,
            String.valueOf(MESSAGE_EXPIRATION.getMillis()));
      }
    } finally {
      //                            oggFile.delete();
      // wavFile.delete();
    }

    // reply
    log.trace("Exchange {} is {}", exchange.getIn().getMessageId(), exchange.getPattern());
    final Status status = new Status();
    exchange.getOut().setBody(status);
    return status;
    //                        final String replyTo = exchange.getIn().getHeader("rabbitmq.REPLY_TO",
    // String.class);
    //                        if (replyTo != null) {
    //                            log.debug("Sending reply to {} ...", replyTo);
    //                            exchange.getOut().setHeader("rabbitmq.ROUTING_KEY", replyTo);
    //                            exchange.getOut().setHeader("rabbitmq.EXCHANGE_NAME", "");
    //                            exchange.getOut().setHeader("recipients",
    //
    // "rabbitmq://dummy/dummy?connectionFactory=#amqpConnFactory&autoDelete=false,log:OUT." +
    // LumenChannel.SPEECH_SYNTHESIS);
    //                        } else {
    //                            exchange.getOut().setHeader("recipients");
    //                        }
  }

  protected byte[] performEspeak(CommunicateAction communicateAction, Locale lang)
      throws IOException {
    byte[] wavBytes;
    try (final ByteArrayInputStream objectIn =
            new ByteArrayInputStream(
                communicateAction.getObject().getBytes(StandardCharsets.UTF_8));
        final ByteArrayOutputStream wavStream = new ByteArrayOutputStream();
        final ByteArrayOutputStream err = new ByteArrayOutputStream()) {
      final CommandLine cmdLine = new CommandLine("espeak");
      cmdLine.addArgument("-b");
      cmdLine.addArgument("1"); // UTF-8
      cmdLine.addArgument("-m"); // SSML markup
      cmdLine.addArgument("-s");
      cmdLine.addArgument("130");
      if (INDONESIAN.getLanguage().equals(lang.getLanguage())) {
        cmdLine.addArgument("-v");
        cmdLine.addArgument(SpeechProsody.MBROLA_ID1_VOICE);
        cmdLine.addArgument("-a");
        cmdLine.addArgument(String.valueOf(INDONESIAN_AMPLITUDE));
      } else if ("ar".equals(lang.getLanguage())) {
        cmdLine.addArgument("-v");
        cmdLine.addArgument(SpeechProsody.MBROLA_AR1_VOICE);
      }
      //                                cmdLine.addArgument("-w");
      //                                cmdLine.addArgument(wavFile.toString());
      cmdLine.addArgument("--stdin");
      cmdLine.addArgument("--stdout");
      // cmdLine.addArgument(communicateAction.getObject());
      executor.setStreamHandler(new PumpStreamHandler(wavStream, err, objectIn));
      final int executed;
      try {
        executed = executor.execute(cmdLine);
        wavBytes = wavStream.toByteArray();
      } finally {
        log.info("{}: {}", cmdLine, err.toString());
      }
    }
    return wavBytes;
  }

  @Override
  public void configure() throws Exception {
    onException(Exception.class).bean(asError).bean(toJson).handled(true);
    errorHandler(new LoggingErrorHandlerBuilder(log));

    // lumen.speech.synthesis
    from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=speech-synthesis:"
            + LumenChannel.SPEECH_SYNTHESIS.key()
            + "&routingKey="
            + LumenChannel.SPEECH_SYNTHESIS.key())
        .to(
            "log:IN."
                + LumenChannel.SPEECH_SYNTHESIS.key()
                + "?showHeaders=true&showAll=true&multiline=true")
        .process(
            exchange -> {
              final LumenThing thing =
                  toJson
                      .getMapper()
                      .readValue(exchange.getIn().getBody(byte[].class), LumenThing.class);
              if (thing instanceof CommunicateAction) {
                final CommunicateAction communicateAction = (CommunicateAction) thing;
                processCommunicateAction(exchange, communicateAction);
              } else {
                // do not reply
                exchange.getOut().setBody(null);
              }
            })
        .bean(toJson);
    // .to("log:OUT." + LumenChannel.SPEECH_SYNTHESIS);
    // avatar.*.chat.outbox
    from("rabbitmq://localhost/amq.topic?connectionFactory=#amqpConnFactory&exchangeType=topic&autoDelete=false&queue=speech-synthesis:"
            + AvatarChannel.CHAT_OUTBOX.wildcard()
            + "&routingKey="
            + AvatarChannel.CHAT_OUTBOX.wildcard())
        .to(
            "log:"
                + SpeechSynthesisRouter.class.getName()
                + "."
                + AvatarChannel.CHAT_OUTBOX.wildcard()
                + "?level=DEBUG&showHeaders=true&showBody=false&multiline=true")
        .process(
            exchange -> {
              final String avatarId =
                  AvatarChannel.getAvatarId(
                      (String) exchange.getIn().getHeader(RabbitMQConstants.ROUTING_KEY));
              final LumenThing thing =
                  toJson
                      .getMapper()
                      .readValue(exchange.getIn().getBody(byte[].class), LumenThing.class);
              if (thing instanceof CommunicateAction) {
                final CommunicateAction communicateAction = (CommunicateAction) thing;
                if (Boolean.TRUE == communicateAction.getUsedForSynthesis()) {
                  processCommunicateAction(exchange, communicateAction);
                } else {
                  // do not reply
                  exchange.getOut().setBody(null);
                }
              }
              // we never reply anyway
              exchange.setPattern(ExchangePattern.InOnly);
            });
  }
}
 private void receiveHello(JsonNode data) {
   if (!data.path(LOCALE).isMissingNode()) {
     this.connection.setLocale(Locale.forLanguageTag(data.path(LOCALE).asText()));
   }
 }
Beispiel #19
0
  public static Locale getLocale(
      RealmModel realm, UserModel user, UriInfo uriInfo, HttpHeaders httpHeaders) {
    if (!realm.isInternationalizationEnabled()) {
      return Locale.ENGLISH;
    }

    // 0. kc_locale query parameter
    if (uriInfo != null && uriInfo.getQueryParameters().containsKey(KC_LOCALE_PARAM)) {
      String localeString = uriInfo.getQueryParameters().getFirst(KC_LOCALE_PARAM);
      Locale locale = findLocale(realm.getSupportedLocales(), localeString);
      if (locale != null) {
        if (user != null) {
          user.setAttribute(UserModel.LOCALE, locale.toLanguageTag());
        }
        return locale;
      } else {
        LOGGER.infof("Locale %s is not supported.", localeString);
      }
    }

    // 1. Locale cookie
    if (httpHeaders != null && httpHeaders.getCookies().containsKey(LOCALE_COOKIE)) {
      String localeString = httpHeaders.getCookies().get(LOCALE_COOKIE).getValue();
      Locale locale = findLocale(realm.getSupportedLocales(), localeString);
      if (locale != null) {
        if (user != null && user.getAttribute(UserModel.LOCALE) == null) {
          user.setAttribute(UserModel.LOCALE, locale.toLanguageTag());
        }
        return locale;
      } else {
        LOGGER.infof("Locale %s is not supported.", localeString);
      }
    }

    // 2. User profile
    if (user != null && user.getAttributes().containsKey(UserModel.LOCALE)) {
      String localeString = user.getAttribute(UserModel.LOCALE);
      Locale locale = findLocale(realm.getSupportedLocales(), localeString);
      if (locale != null) {

        return locale;
      } else {
        LOGGER.infof("Locale %s is not supported.", localeString);
      }
    }

    // 3. ui_locales query parameter
    if (uriInfo != null && uriInfo.getQueryParameters().containsKey(UI_LOCALES_PARAM)) {
      String localeString = uriInfo.getQueryParameters().getFirst(UI_LOCALES_PARAM);
      Locale locale = findLocale(realm.getSupportedLocales(), localeString.split(" "));
      if (locale != null) {
        return locale;
      } else {
        LOGGER.infof("Locale %s is not supported.", localeString);
      }
    }

    // 4. Accept-Language http header
    if (httpHeaders != null
        && httpHeaders.getAcceptableLanguages() != null
        && !httpHeaders.getAcceptableLanguages().isEmpty()) {
      for (Locale l : httpHeaders.getAcceptableLanguages()) {
        String localeString = l.toLanguageTag();
        Locale locale = findLocale(realm.getSupportedLocales(), localeString);
        if (locale != null) {
          return locale;
        } else {
          LOGGER.infof("Locale %s is not supported.", localeString);
        }
      }
    }

    // 5. Default realm locale
    if (realm.getDefaultLocale() != null) {
      return Locale.forLanguageTag(realm.getDefaultLocale());
    }

    return Locale.ENGLISH;
  }
Beispiel #20
0
 @Override
 public Locale getLocale() {
   return (locale == null && settings != null)
       ? locale = Locale.forLanguageTag(settings.getLocale().replaceAll("_", "-"))
       : locale;
 }
  /**
   * This method must be called in a context synchronized on {@link #translationsStatistics}.
   *
   * <p>The sorting places the default/recommended choice on top of the list, and then tried to
   * place other relevant choices close to the top in descending order by relevance. The rest of the
   * list is alphabetical by the preferred/currently selected language's language names. The sorting
   * is done following these rules:
   *
   * <ul>
   *   <li>The base language (en-US) and the language closest matching <code>preferredLocale</code>
   *       is looked up. If the closest matching language has a coverage greater or equal to {@link
   *       #recommendedTranslatePct} or an approval greater or equal to {@link
   *       #recommendedApprovedPct} it will be placed on top. If not, the base language will be
   *       placed on top. Whichever of these is not placed on top is placed second. If a closely
   *       matching language cannot be found, only the base language will be placed on top.
   *   <li>A search for related languages is performed. Related is defined by either having the same
   *       language code (e.g "en") or the same country code as <code>preferredLocale</code>.
   *       Related languages are then sorted descending by coverage and put after that or those
   *       language(s) placed on top.
   *   <li>The rest of the languages are listed alphabetically based on their localized (from
   *       currently chosen language) names.
   * </ul>
   *
   * If the localized language name differs from the English language name, the English language
   * name is shown in parenthesis. This is to help in case the localized names are incomprehensible
   * to the user.
   */
  private static void createSortedList(Locale preferredLocale) {
    if (preferredLocale == null) {
      throw new IllegalArgumentException("preferredLocale cannot be null");
    }
    if (lastpreferredLocale == null || !lastpreferredLocale.equals(preferredLocale)) {
      // Populate
      lastpreferredLocale = preferredLocale;
      sortedLanguages.clear();
      populateTranslationsStatistics();
      for (String tag : UMS_BCP47_CODES) {
        LanguageEntry entry = new LanguageEntry();
        entry.tag = tag;
        entry.name = Messages.getString("Language." + tag, preferredLocale);
        if (!entry.name.equals(Messages.getRootString("Language." + tag))) {
          entry.name += " (" + Messages.getRootString("Language." + tag) + ")";
        }
        entry.locale = Locale.forLanguageTag(tag);
        if (tag.equals("en-US")) {
          entry.coveragePercent = 100;
          entry.approvedPercent = 100;
        } else {
          TranslationStatistics stats = translationsStatistics.get(tag);
          if (stats != null) {
            if (entry.locale.getLanguage().equals("en") && stats.wordsTranslated > 0) {
              /* Special case for English language variants that only
               * overrides the strings that differ from US English.
               * We cannot find coverage for these */
              entry.coveragePercent = 100;
              entry.approvedPercent = 100;
            } else {
              entry.coveragePercent = stats.translated;
              entry.approvedPercent = stats.approved;
            }
          } else {
            entry.coveragePercent = 0;
            entry.approvedPercent = 0;
            LOGGER.debug("Warning: Could not find language statistics for {}", entry.name);
          }
        }

        if (entry.coveragePercent >= minimumTranslatePct) {
          sortedLanguages.add(entry);
        }
      }

      // Sort
      Collections.sort(sortedLanguages);

      // Put US English first
      LanguageEntry baseLanguage = getSortedLanguageByTag("en-US");
      if (baseLanguage == null) {
        throw new IllegalStateException(
            "Languages.createSortedList encountered an impossible situation");
      }
      if (sortedLanguages.remove(baseLanguage)) {
        sortedLanguages.add(0, baseLanguage);
      }
      ;

      // Put matched language first or second depending on coverage
      LanguageEntry preferredLanguage = getSortedLanguageByLocale(preferredLocale);
      if (preferredLanguage != null && !preferredLanguage.tag.equals("en-US")) {
        if (sortedLanguages.remove(preferredLanguage) && isRecommended(preferredLanguage)) {
          sortedLanguages.add(0, preferredLanguage);
        } else {
          /* This could constitute a bug if sortedLanguages.remove(entry)
           * returned false, but that should be impossible */
          sortedLanguages.add(1, preferredLanguage);
        }
      }

      // Put related language(s) close to top
      List<LanguageEntry> relatedLanguages = new ArrayList<>();
      for (LanguageEntry entry : sortedLanguages) {
        if (entry != baseLanguage
            && entry != preferredLanguage
            && (!preferredLocale.getCountry().isEmpty()
                    && preferredLocale.getCountry().equals(entry.locale.getCountry())
                || !preferredLocale.getLanguage().isEmpty()
                    && preferredLocale.getLanguage().equals(entry.locale.getLanguage()))) {
          relatedLanguages.add(entry);
        }
      }
      if (relatedLanguages.size() > 0) {
        sortedLanguages.removeAll(relatedLanguages);
        Collections.sort(relatedLanguages, new LanguageEntryCoverageComparator());
        sortedLanguages.addAll(
            preferredLanguage == null || preferredLanguage.equals(baseLanguage) ? 1 : 2,
            relatedLanguages);
      }
    }
  }
Beispiel #22
0
public class ProductDisplay extends JPanel
    implements ActionListener, Transferable, DragSourceListener, DragGestureListener {
  private static final IMatDataHandler IDH = IMatDataHandler.getInstance();
  SpinnerModel stModel =
      new SpinnerNumberModel(new Integer(1), new Integer(1), null, new Integer(1));
  SpinnerModel kgModel =
      new SpinnerNumberModel(new Double(0.1), new Double(0.1), null, new Double(0.1));
  private Product product;
  private JPanel panel;
  private JLabel titleLabel;
  private JSpinner qSpinner;
  private JLabel suffixLabel;
  private JButton buyButton;
  private JLabel sumLabel;
  private JLabel priceLabel;
  private JPanel panel_1;
  private JLabel imageLabel;
  private boolean list;

  private ActionListener listener;
  private JButton favButton;

  private DragSource source;
  private TransferHandler handler;
  private DataFlavor flavor;

  private PropertyChangeSupport ps;

  private static NumberFormat format =
      NumberFormat.getCurrencyInstance(Locale.forLanguageTag("sv-SE"));

  /** Create the panel. */
  public ProductDisplay(Product p, boolean featured, boolean list, ActionListener al) {
    addMouseListener(new ThisMouseListener());
    setBackground(Color.WHITE);
    listener = al;
    product = p;
    setBorder(new LineBorder(Color.LIGHT_GRAY));
    setLayout(new BorderLayout(0, 0));
    this.list = list;

    panel = new JPanel();
    panel.setBackground(Color.WHITE);
    add(panel, BorderLayout.CENTER);
    GroupLayout gl_panel = new GroupLayout(panel);

    if (list) {
      setPreferredSize(new Dimension(900, 52));
      titleLabel = new JLabel("Label");
      titleLabel.setFont(new Font("SansSerif", Font.BOLD, 12));

      buyButton =
          new JButton(
              new ImageIcon(ProductStripe.class.getResource("/imat/resources/buyButtonMini.PNG")));
      buyButton.setPreferredSize(new Dimension(40, 20));
      buyButton.setOpaque(false);
      buyButton.setFont(new Font("SansSerif", Font.BOLD, 12));

      priceLabel = new JLabel("Desc");
      priceLabel.setFont(new Font("SansSerif", Font.PLAIN, 10));

      sumLabel = new JLabel("0,00 kr");
      sumLabel.setFont(new Font("SansSerif", Font.BOLD, 10));
      sumLabel.setHorizontalAlignment(SwingConstants.RIGHT);

      qSpinner = new JSpinner();
      qSpinner.addChangeListener(new QSpinnerChangeListener());
      qSpinner.setFont(new Font("SansSerif", Font.BOLD, 10));

      suffixLabel = new JLabel("st");
      suffixLabel.setFont(new Font("SansSerif", Font.PLAIN, 10));

      favButton = new JButton("");
      favButton.setPreferredSize(new Dimension(20, 20));
      favButton.setMinimumSize(new Dimension(20, 20));
      favButton.addActionListener(this);
      favButton.setActionCommand("fav");
      favButton.setFont(new Font("Dialog", Font.BOLD, 10));
      if (IDH.isFavorite(product)) {
        favButton.setIcon(
            new ImageIcon(ProductDisplay.class.getResource("/imat/resources/favmini.PNG")));
        favButton.setToolTipText("Ta bort favorit");
      } else {
        favButton.setIcon(
            new ImageIcon(ProductDisplay.class.getResource("/imat/resources/unfavmini.PNG")));
        favButton.setToolTipText("Lägg till som favorit");
      }
      gl_panel = new GroupLayout(panel);
      gl_panel.setHorizontalGroup(
          gl_panel
              .createParallelGroup(Alignment.LEADING)
              .addGroup(
                  gl_panel
                      .createSequentialGroup()
                      .addContainerGap()
                      .addGroup(
                          gl_panel
                              .createParallelGroup(Alignment.LEADING)
                              .addComponent(priceLabel)
                              .addComponent(titleLabel))
                      .addPreferredGap(ComponentPlacement.RELATED)
                      .addGroup(
                          gl_panel
                              .createParallelGroup(Alignment.TRAILING)
                              .addGroup(
                                  gl_panel
                                      .createSequentialGroup()
                                      .addComponent(
                                          favButton,
                                          GroupLayout.PREFERRED_SIZE,
                                          GroupLayout.DEFAULT_SIZE,
                                          GroupLayout.PREFERRED_SIZE)
                                      .addPreferredGap(ComponentPlacement.RELATED)
                                      .addComponent(
                                          qSpinner,
                                          GroupLayout.PREFERRED_SIZE,
                                          48,
                                          GroupLayout.PREFERRED_SIZE)
                                      .addGap(3)
                                      .addComponent(
                                          suffixLabel,
                                          GroupLayout.PREFERRED_SIZE,
                                          26,
                                          GroupLayout.PREFERRED_SIZE)
                                      .addGap(2)
                                      .addComponent(
                                          buyButton,
                                          GroupLayout.PREFERRED_SIZE,
                                          GroupLayout.DEFAULT_SIZE,
                                          GroupLayout.PREFERRED_SIZE))
                              .addComponent(
                                  sumLabel, GroupLayout.DEFAULT_SIZE, 776, Short.MAX_VALUE))
                      .addContainerGap()));
      gl_panel.setVerticalGroup(
          gl_panel
              .createParallelGroup(Alignment.LEADING)
              .addGroup(
                  gl_panel
                      .createSequentialGroup()
                      .addContainerGap()
                      .addGroup(
                          gl_panel
                              .createParallelGroup(Alignment.TRAILING)
                              .addComponent(
                                  buyButton,
                                  GroupLayout.PREFERRED_SIZE,
                                  GroupLayout.DEFAULT_SIZE,
                                  GroupLayout.PREFERRED_SIZE)
                              .addGroup(
                                  gl_panel
                                      .createParallelGroup(Alignment.LEADING, false)
                                      .addComponent(favButton, 0, 0, Short.MAX_VALUE)
                                      .addGroup(
                                          Alignment.TRAILING,
                                          gl_panel
                                              .createParallelGroup(Alignment.BASELINE)
                                              .addComponent(titleLabel)
                                              .addComponent(suffixLabel)
                                              .addComponent(qSpinner))))
                      .addPreferredGap(ComponentPlacement.RELATED)
                      .addGroup(
                          gl_panel
                              .createParallelGroup(Alignment.BASELINE)
                              .addComponent(priceLabel)
                              .addComponent(sumLabel))
                      .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
    } else {
      titleLabel = new JLabel("Label");
      titleLabel.setFont(new Font("SansSerif", Font.BOLD, 18));

      qSpinner = new JSpinner();
      qSpinner.setFont(new Font("SansSerif", Font.BOLD, 12));
      qSpinner.addChangeListener(new QSpinnerChangeListener());

      suffixLabel = new JLabel("st");
      suffixLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));

      buyButton =
          new JButton(
              new ImageIcon(
                  ProductDisplay.class.getResource("/imat/resources/buyButton60x30.PNG")));
      buyButton.setMaximumSize(new Dimension(60, 30));
      buyButton.setMinimumSize(new Dimension(60, 30));
      buyButton.setPreferredSize(new Dimension(60, 30));
      buyButton.setOpaque(false);
      buyButton.setFont(new Font("SansSerif", Font.BOLD, 12));

      sumLabel = new JLabel("Sum");
      sumLabel.setHorizontalAlignment(SwingConstants.RIGHT);

      priceLabel = new JLabel("Desc");
      priceLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));

      favButton = new JButton("");
      favButton.setPreferredSize(new Dimension(32, 32));
      favButton.setMinimumSize(new Dimension(32, 32));

      favButton.addActionListener(this);
      favButton.setActionCommand("fav");
      if (IDH.isFavorite(product)) {
        favButton.setIcon(
            new ImageIcon(ProductDisplay.class.getResource("/imat/resources/fav.PNG")));
        favButton.setToolTipText("Ta bort favorit");
      } else {
        favButton.setIcon(
            new ImageIcon(ProductDisplay.class.getResource("/imat/resources/unfav.PNG")));
        favButton.setToolTipText("Lägg till som favorit");
      }
      gl_panel = new GroupLayout(panel);
      gl_panel.setHorizontalGroup(
          gl_panel
              .createParallelGroup(Alignment.LEADING)
              .addGroup(
                  gl_panel
                      .createSequentialGroup()
                      .addContainerGap()
                      .addGroup(
                          gl_panel
                              .createParallelGroup(Alignment.LEADING)
                              .addComponent(titleLabel)
                              .addGroup(
                                  Alignment.TRAILING,
                                  gl_panel
                                      .createSequentialGroup()
                                      .addGroup(
                                          gl_panel
                                              .createParallelGroup(Alignment.LEADING)
                                              .addGroup(
                                                  gl_panel
                                                      .createSequentialGroup()
                                                      .addComponent(
                                                          qSpinner,
                                                          GroupLayout.PREFERRED_SIZE,
                                                          48,
                                                          GroupLayout.PREFERRED_SIZE)
                                                      .addPreferredGap(ComponentPlacement.RELATED)
                                                      .addComponent(suffixLabel)
                                                      .addPreferredGap(ComponentPlacement.RELATED)
                                                      .addComponent(
                                                          sumLabel,
                                                          GroupLayout.DEFAULT_SIZE,
                                                          110,
                                                          Short.MAX_VALUE)
                                                      .addPreferredGap(ComponentPlacement.RELATED))
                                              .addGroup(
                                                  gl_panel
                                                      .createSequentialGroup()
                                                      .addComponent(priceLabel)
                                                      .addGap(103)))
                                      .addGroup(
                                          gl_panel
                                              .createParallelGroup(Alignment.TRAILING)
                                              .addComponent(
                                                  buyButton,
                                                  GroupLayout.PREFERRED_SIZE,
                                                  GroupLayout.DEFAULT_SIZE,
                                                  GroupLayout.PREFERRED_SIZE)
                                              .addComponent(
                                                  favButton,
                                                  GroupLayout.PREFERRED_SIZE,
                                                  GroupLayout.DEFAULT_SIZE,
                                                  GroupLayout.PREFERRED_SIZE))))
                      .addContainerGap()));
      gl_panel.setVerticalGroup(
          gl_panel
              .createParallelGroup(Alignment.TRAILING)
              .addGroup(
                  gl_panel
                      .createSequentialGroup()
                      .addGroup(
                          gl_panel
                              .createParallelGroup(Alignment.TRAILING)
                              .addGroup(
                                  gl_panel
                                      .createSequentialGroup()
                                      .addContainerGap()
                                      .addComponent(titleLabel)
                                      .addPreferredGap(ComponentPlacement.RELATED)
                                      .addComponent(priceLabel)
                                      .addPreferredGap(
                                          ComponentPlacement.RELATED, 27, Short.MAX_VALUE))
                              .addGroup(
                                  gl_panel
                                      .createSequentialGroup()
                                      .addContainerGap()
                                      .addComponent(
                                          favButton,
                                          GroupLayout.PREFERRED_SIZE,
                                          GroupLayout.DEFAULT_SIZE,
                                          GroupLayout.PREFERRED_SIZE)
                                      .addPreferredGap(ComponentPlacement.UNRELATED)))
                      .addGroup(
                          gl_panel
                              .createParallelGroup(Alignment.TRAILING)
                              .addGroup(
                                  gl_panel
                                      .createParallelGroup(Alignment.BASELINE)
                                      .addComponent(
                                          qSpinner,
                                          GroupLayout.PREFERRED_SIZE,
                                          GroupLayout.DEFAULT_SIZE,
                                          GroupLayout.PREFERRED_SIZE)
                                      .addComponent(suffixLabel)
                                      .addComponent(sumLabel))
                              .addComponent(
                                  buyButton,
                                  GroupLayout.PREFERRED_SIZE,
                                  GroupLayout.DEFAULT_SIZE,
                                  GroupLayout.PREFERRED_SIZE))
                      .addContainerGap()));
    }

    Component[] tmp = qSpinner.getComponents();
    for (Component c : tmp) {
      c.addMouseListener(new ThisMouseListener());
    }
    favButton.addMouseListener(new ThisMouseListener());
    buyButton.addMouseListener(new ThisMouseListener());

    panel.setLayout(gl_panel);

    panel_1 = new JPanel();
    panel_1.setBackground(Color.WHITE);
    add(panel_1, BorderLayout.WEST);

    imageLabel = new JLabel("");
    imageLabel.setBorder(new LineBorder(new Color(128, 128, 128), 2));
    panel_1.add(imageLabel);

    // Set labels and image according to the product
    titleLabel.setText(product.getName());
    priceLabel.setText(format.format(p.getPrice()) + p.getUnit().substring(2));

    // Add actions for the buy button
    buyButton.setActionCommand("buy");
    buyButton.addActionListener(this);

    // Drag and drop!

    handler = new DragHandler();
    try {
      flavor =
          new DataFlavor(
              DataFlavor.javaSerializedObjectMimeType
                  + ";class=se.chalmers.ait.dat215.project.ShoppingItem");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    setTransferHandler(handler);

    source = new DragSource();
    source.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);
    addMouseListener(
        new MouseAdapter() {
          @Override
          public void mousePressed(MouseEvent e) {
            ProductDisplay.this
                .getTransferHandler()
                .exportAsDrag(ProductDisplay.this, e, TransferHandler.COPY);
          }
        });

    if (list) {
      imageLabel.setIcon(IDH.getImageIcon(p, new Dimension(67, 50)));
    } else {
      if (featured) {
        //				this.setPreferredSize(new Dimension(300, 10));
        titleLabel.setFont(new Font("SansSerif", Font.BOLD, 27));
        priceLabel.setFont(new Font("SansSerif", Font.PLAIN, 18));
        imageLabel.setIcon(IDH.getImageIcon(p, new Dimension(200, 150)));
      } else {
        imageLabel.setIcon(IDH.getImageIcon(p, new Dimension(140, 105)));
      }
    }

    if (p.getUnitSuffix().equals("kg")) {
      qSpinner.setModel(kgModel);
      suffixLabel.setText(p.getUnitSuffix());
    } else {
      qSpinner.setModel(stModel);
      suffixLabel.setText("st");
    }
    favButton.setVisible(false);
    favButton.setContentAreaFilled(false);
    favButton.setBorderPainted(false);
    updateSum();
  }

  public ShoppingItem getItem() {
    return new ShoppingItem(product, getAmount());
  }

  private double getAmount() {
    Object q = qSpinner.getValue();
    return (q instanceof Double) ? (double) q : (int) q;
  }

  private double getTotal() {
    return getAmount() * product.getPrice();
  }

  public void updateSum() {
    sumLabel.setText(format.format(getTotal()));
  }

  private class QSpinnerChangeListener implements ChangeListener {
    public void stateChanged(ChangeEvent arg0) {
      updateSum();
    }
  }

  private class ThisMouseListener extends MouseAdapter {
    @Override
    public void mouseEntered(MouseEvent e) {
      panel.setBackground(new Color(230, 230, 230));
      favButton.setVisible(true);
    }

    @Override
    public void mouseExited(MouseEvent e) {
      panel.setBackground(null);
      favButton.setVisible(false);
    }
  }

  @Override
  public void actionPerformed(ActionEvent evt) {
    if (evt.getActionCommand().equals("buy")) {
      evt.setSource(getItem());
      listener.actionPerformed(evt);
    } else if (evt.getActionCommand().equals("fav")) {
      if (IDH.isFavorite(product)) {
        IDH.removeFavorite(product);
        if (list) {
          favButton.setIcon(
              new ImageIcon(ProductDisplay.class.getResource("/imat/resources/unfavmini.PNG")));
        } else {
          favButton.setIcon(
              new ImageIcon(ProductDisplay.class.getResource("/imat/resources/unfav.PNG")));
        }
        favButton.setToolTipText("Lägg till som favorit");
        listener.actionPerformed(evt);
      } else {
        IDH.addFavorite(product);
        if (list) {
          favButton.setIcon(
              new ImageIcon(ProductDisplay.class.getResource("/imat/resources/favmini.PNG")));
        } else {
          favButton.setIcon(
              new ImageIcon(ProductDisplay.class.getResource("/imat/resources/fav.PNG")));
        }
        listener.actionPerformed(evt);
        favButton.setToolTipText("Ta bort som favorit");
      }
      listener.actionPerformed(evt);
    }
  }

  @Override
  public Object getTransferData(DataFlavor flavor) {
    if (flavor.equals(this.flavor)) {
      return getItem();
    }
    throw new IllegalArgumentException();
  }

  @Override
  public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] {flavor};
  }

  @Override
  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return flavor.equals(this.flavor);
  }

  @Override
  public void dragGestureRecognized(DragGestureEvent dge) {
    source.startDrag(dge, DragSource.DefaultCopyDrop, this, this);
    // System.out.println(getItem().getProduct().getName() + " " + getItem().getAmount());
  }

  public void dragDropEnd(DragSourceDropEvent dsde) {}

  public void dragEnter(DragSourceDragEvent dsde) {}

  public void dragExit(DragSourceEvent dse) {}

  public void dragOver(DragSourceDragEvent dsde) {}

  public void dropActionChanged(DragSourceDragEvent dsde) {}
}
 /**
  * If the user already set a lang cookie, return its value, else check the lang in the request
  * (browser dependant)
  *
  * @return
  */
 public static Locale getUserLocale() {
   return Locale.forLanguageTag(
       CookieUtils.readNonNull(SessionBean.langCookieName, getRequestedLocale().getLanguage()));
 }
Beispiel #24
0
/**
 * Manager loads settings from file and instantiates all components of FreeNono like the audio
 * subsystem, highscore manager, ... Nonograms are loaded through collection provider and at the end
 * UI is made visible.
 *
 * @author Christian Wichmann
 */
public final class Manager {

  private static Logger logger = Logger.getLogger(Manager.class);

  private static final String DEFAULT_NONOGRAM_PATH = "./nonograms";
  private static final String DEFAULT_NONOGRAM_PATH_WINDOWS =
      System.getProperty("user.dir") + Tools.FILE_SEPARATOR + "nonograms";
  private static final String DEFAULT_NONOGRAM_PATH_LINUX = "/usr/share/freenono/nonograms";
  private static final String DEFAULT_NONOGRAM_PATH_DEBIAN = "/usr/share/games/freenono/nonograms";

  private static final String USER_NONOGRAM_PATH =
      System.getProperty("user.home")
          + Tools.FILE_SEPARATOR
          + ".FreeNono"
          + Tools.FILE_SEPARATOR
          + "nonograms";
  private static final String DEFAULT_SETTINGS_FILE =
      System.getProperty("user.home")
          + Tools.FILE_SEPARATOR
          + ".FreeNono"
          + Tools.FILE_SEPARATOR
          + "freenono.xml";

  @SuppressWarnings("unused")
  private static final String DEFAULT_NONO_SERVER = "http://127.0.0.1";

  /** Gives path to save thumbnail images for already solved nonograms. */
  public static final String DEFAULT_THUMBNAILS_PATH =
      System.getProperty("user.home")
          + Tools.FILE_SEPARATOR
          + ".FreeNono"
          + Tools.FILE_SEPARATOR
          + "thumbnails";

  /**
   * Defines locales for all supported languages. The neutral locale <code>Locale.ROOT</code>
   * indicates to use the systems default locale.
   */
  public static final Locale[] SUPPORTED_LANGUAGES = {
    Locale.GERMAN,
    Locale.ENGLISH,
    Locale.JAPANESE,
    Locale.forLanguageTag("ES"),
    Locale.forLanguageTag("SI"),
    Locale.forLanguageTag("RU"),
    Locale.ROOT
  };

  // TODO make directory hidden under windows
  // with Java 7:
  // Path path = FileSystems.getDefault().getPath("/j", "sa");
  // Files.setAttribute(path, "dos:hidden", true);

  private final SplashScreen splash;
  private Graphics2D splashGraphics = null;
  private int alreadyLoadedCourses = 0;
  private int numberOfCourses = 100;

  private MainUI mainUI = null;
  private GameEventHelper eventHelper = null;
  private AudioProvider audioProvider = null;
  private Game currentGame = null;
  private Settings settings = null;
  private String settingsFile = DEFAULT_SETTINGS_FILE;
  private final SettingsSerializer settingsSerializer = new XMLSettingsSerializer();
  private final List<CollectionProvider> nonogramProvider = new ArrayList<CollectionProvider>();

  private final GameAdapter gameAdapter =
      new GameAdapter() {
        @Override
        public void optionsChanged(final ProgramControlEvent e) {

          // When an options is changed, save config file.
          saveSettings(new File(settingsFile));
        }

        @Override
        public void programControl(final ProgramControlEvent e) {

          switch (e.getPct()) {
            case START_GAME:
              break;

            case STOP_GAME:
              break;

            case RESTART_GAME:
              break;

            case PAUSE_GAME:
              break;

            case RESUME_GAME:
              break;

            case NONOGRAM_CHOSEN:
              // If new nonogram was chosen remove old event helper from
              // game object and instantiate new game object!
              // TODO should the nonogram be distributed this way?!
              if (currentGame != null) {
                currentGame.removeEventHelper();
              }
              currentGame = createGame(e.getPattern());
              break;

            case QUIT_PROGRAMM:
              quitProgram();
              break;

            case OPTIONS_CHANGED:
              break;

            case SHOW_ABOUT:
              break;

            case SHOW_OPTIONS:
              break;

            default:
              break;
          }
        }
      };

  /** Initializes manager and all subsystems using the default settings file. */
  public Manager() {

    splash = SplashScreen.getSplashScreen();

    initialize();
  }

  /** Initializes manager and all subsystems. */
  private void initialize() {

    /*
     * Disable java's own logging facility (java.util.logging) to prevent third party libraries
     * to clutter the console output. All error in libraries should be handled and logged in
     * FreeNono itself.
     */
    LogManager.getLogManager().reset();

    // load settings from file
    loadSettings(settingsFile);
    if (!settings.getGameLocale().equals(Locale.ROOT)) {
      Locale.setDefault(settings.getGameLocale());
    }

    createSplashscreen();

    updateSplashscreen(Messages.getString("Splashscreen.Building"), false);

    // Get instance to allow time for connecting to NonoWeb in background
    if (settings.shouldActivateChat()) {
      NonoWebConnectionManager.getInstance();
    }

    // instantiate GameEventHelper and add own gameAdapter
    eventHelper = new GameEventHelper();
    eventHelper.addGameListener(gameAdapter);

    settings.setEventHelper(eventHelper);

    // instantiate audio provider for game sounds
    audioProvider = new AudioProvider(eventHelper, settings);

    // instantiate highscore manager
    HighscoreManager.getInstance(settings).setEventHelper(eventHelper);

    // set game event helper for statistics manager
    SimpleStatistics.getInstance().setEventHelper(eventHelper);

    preloadLibraries();

    updateSplashscreen(Messages.getString("Splashscreen.Loading"), true);

    // instantiate collection provider for all nonogram sources
    instantiateProvider();

    /*
     * Instantiate achievement manager AFTER collection provider are ready because they are
     * needed for class AchievementMeterCompleteness.
     */
    AchievementManager.getInstance(eventHelper, nonogramProvider);

    updateSplashscreen(Messages.getString("Splashscreen.Starting"), false);

    // Setup chat handler for NonoWeb connection that has been created in
    // background
    if (settings.shouldActivateChat()) {
      setupChat();
    }
  }

  /** Loads libraries before they are used so that the about and help dialog are shown faster. */
  private void preloadLibraries() {

    try {
      Class.forName("org.xhtmlrenderer.simple.XHTMLPanel");
      Class.forName("org.xhtmlrenderer.simple.FSScrollPane");
    } catch (final ClassNotFoundException e) {
      logger.error("Could not preload libraries.");
    }
  }

  /** Sets up the connection to NonoWeb to be used by the chat system. (See {@link ChatHandler}) */
  private void setupChat() {

    final ChatHandler chatHandler = NonoWebConnectionManager.getInstance().getChatHandler();
    chatHandler.setOwnChatName(settings.getPlayerName());
  }

  /** Starts the swing UI of FreeNono and close the splash screen. */
  public void startSwingUI() {

    // start swing UI
    SwingUtilities.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            // set look and feel to new (since Java SE 6 Update 10 release
            // standard and instantiate mainUI
            try {
              for (final LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                  UIManager.setLookAndFeel(info.getClassName());
                  break;
                }
              }
            } catch (final ClassNotFoundException e) {
              logger.warn("Could not set look and feel.");
            } catch (final InstantiationException e) {
              logger.warn("Could not set look and feel.");
            } catch (final IllegalAccessException e) {
              logger.warn("Could not set look and feel.");
            } catch (final UnsupportedLookAndFeelException e1) {
              logger.warn("Could not set look and feel.");
            }

            mainUI = new MainUI(eventHelper, settings, nonogramProvider);
            mainUI.setVisible(true);
          }
        });

    // close splashscreen
    closeSplashscreen();
  }

  /*
   * Methods concerning the splash screen.
   */

  /** Creates and initializes a splash screen based on image shown by vm while starting. */
  private void createSplashscreen() {

    // Create splash screen only when not yet happened.
    if (splash != null) {

      splashGraphics = splash.createGraphics();

      if (splashGraphics != null) {

        final Color splashscreenColor = new Color(85, 85, 85);
        final int versionX = 38;
        final int versionY = 126;
        final float versionFontSize = 18;
        final String versionString = RunUI.class.getPackage().getSpecificationVersion();

        splashGraphics.setRenderingHint(
            RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        splashGraphics.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        splashGraphics.setRenderingHint(
            RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        splashGraphics.setRenderingHint(
            RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        splashGraphics.setColor(splashscreenColor);
        splashGraphics.setFont(FontFactory.createSplashscreenFont().deriveFont(versionFontSize));

        splashGraphics.setPaintMode();
        splashGraphics.drawString("Version " + versionString, versionX, versionY);
        splash.update();

        splashGraphics.setFont(FontFactory.createSplashscreenFont());
      }
    }
  }

  /**
   * Updates splash screen with message.
   *
   * @param message message to display in splash screen.
   * @param drawProgressBar whether to draw the progress bar or not
   */
  private void updateSplashscreen(final String message, final boolean drawProgressBar) {

    if (splashGraphics != null) {
      // update message
      final int splashWidth = 700;
      final int splashHeight = 250;
      final int splashStringX = 38;
      final int splashStringY = 360;
      splashGraphics.setComposite(AlphaComposite.Clear);
      splashGraphics.fillRect(0, splashHeight, splashWidth, splashHeight);
      splashGraphics.setPaintMode();
      splashGraphics.drawString(message, splashStringX, splashStringY);

      if (drawProgressBar) {
        // update progress bar
        final int progressBarX = 38;
        final int progressBarY = 364;
        final int progressBarHeight = 4;
        final int progressBarWidth = (int) (200. / numberOfCourses * alreadyLoadedCourses);
        splashGraphics.fillRect(progressBarX, progressBarY, progressBarWidth, progressBarHeight);
      }
      splash.update();
    }
  }

  /** Closes splash screen. */
  private void closeSplashscreen() {

    if (splash != null) {
      try {
        splash.close();
      } catch (final IllegalStateException e) {
        logger.warn("Could not close splashscreen.");
      }
    }
  }

  /*
   * Methods concerning the loading and saving of data.
   */

  /** Instantiate nonogram provider. */
  private void instantiateProvider() {

    if (Tools.isRunningJavaWebStart()) {
      /*
       * Get nonograms from jar file.
       */
      nonogramProvider.add(
          new CollectionFromJar(Messages.getString("Manager.LocalNonogramsProvider")));

      /*
       * Get nonograms by seed provider.
       */
      nonogramProvider.add(
          new CollectionFromSeed(Messages.getString("Manager.SeedNonogramProvider")));

    } else {
      /*
       * Get nonograms from distribution.
       */
      final CollectionFromFilesystem collection1 =
          new CollectionFromFilesystem(
              getNonogramPath(), Messages.getString("Manager.LocalNonogramsProvider"), false);

      collection1.startLoading(
          new CollectionListener() {
            @Override
            public void collectionLoading(final CollectionEvent e) {
              numberOfCourses = e.getCoursesInCollection();
              alreadyLoadedCourses = e.getCoursesAlreadyLoaded();
              updateSplashscreen(Messages.getString("Splashscreen.LoadingLocal"), true);
            }

            @Override
            public void collectionChanged(final CollectionEvent e) {}
          });
      nonogramProvider.add(collection1);

      /*
       * Get users nonograms from home directory.
       */
      numberOfCourses = 0;
      alreadyLoadedCourses = 0;
      final CollectionFromFilesystem collection2 =
          new CollectionFromFilesystem(
              USER_NONOGRAM_PATH, Messages.getString("Manager.UserNonogramsProvider"), false);

      collection2.startLoading(
          new CollectionListener() {
            @Override
            public void collectionLoading(final CollectionEvent e) {
              numberOfCourses = e.getCoursesInCollection();
              alreadyLoadedCourses = e.getCoursesAlreadyLoaded();
              updateSplashscreen(Messages.getString("Splashscreen.LoadingUser"), true);
            }

            @Override
            public void collectionChanged(final CollectionEvent e) {}
          });
      nonogramProvider.add(collection2);

      /*
       * Get nonograms by seed provider.
       */
      nonogramProvider.add(
          new CollectionFromSeed(Messages.getString("Manager.SeedNonogramProvider")));
    }

    // get nonograms from NonoServer
    // nonogramProvider.add(new CollectionFromServer(DEFAULT_NONO_SERVER,
    // "NonoServer"));
  }

  /**
   * Get local nonogram path according to OS.
   *
   * @return Local nonogram path.
   */
  private String getNonogramPath() {

    final String os = System.getProperty("os.name");

    String nonogramPath = DEFAULT_NONOGRAM_PATH;

    if ("Linux".equals(os)) {
      final File f1 = new File(DEFAULT_NONOGRAM_PATH);
      final File f2 = new File(DEFAULT_NONOGRAM_PATH_DEBIAN);
      if (f1.isDirectory()) {
        nonogramPath = DEFAULT_NONOGRAM_PATH;
      } else if (f2.isDirectory()) {
        nonogramPath = DEFAULT_NONOGRAM_PATH_DEBIAN;
      } else {
        nonogramPath = DEFAULT_NONOGRAM_PATH_LINUX;
      }
    } else if (os.startsWith("Windows")) {
      nonogramPath = DEFAULT_NONOGRAM_PATH_WINDOWS;
    }

    return nonogramPath;
  }

  /**
   * Load settings from given settings file.
   *
   * @param settingsFile settings file to use
   */
  private void loadSettings(final String settingsFile) {

    if (settingsFile == null || "".equals(settingsFile)) {
      throw new IllegalArgumentException("Parameter settingsFile is invalid.");
    }

    this.settingsFile = settingsFile;
    final File file = new File(settingsFile);

    try {
      settings = settingsSerializer.load(file);

    } catch (final SettingsFormatException e) {
      // if SettingsFormatException was thrown file exists and can be
      // accessed
      file.delete();
      settings = new Settings();
      logger.error("SettingsFormatException when loading settings file.");
    }

    settings.setEventHelper(eventHelper);
  }

  /**
   * Save settings to file.
   *
   * @param file File to save the settings.
   */
  private void saveSettings(final File file) {

    settingsSerializer.save(this.settings, file);
  }

  /*
   * Methods concerning the program flow.
   */

  /**
   * Creates a new game using given nonogram.
   *
   * @param nonogram nonogram to use for new game
   * @return created game model
   */
  private Game createGame(final Nonogram nonogram) {

    // create new Game instance
    final Game g = new Game(eventHelper, nonogram, settings);

    return g;
  }

  /** Quit program. */
  private void quitProgram() {

    logger.debug("program exited by user.");

    audioProvider.closeAudio();
    audioProvider.removeEventHelper();

    // TODO Is this call necessary?
    System.exit(0);
  }

  /** Restarts FreeNono. Not yet usable! */
  @SuppressWarnings("unused")
  private void restartProgram() {

    mainUI.removeEventHelper();
    mainUI.setVisible(false);
    mainUI.dispose();
    mainUI = null;

    Locale.setDefault(settings.getGameLocale());
    Messages.loadResourceBundle();
    FontFactory.resetFonts();

    // initialize();
    startSwingUI();
  }
}
 @Test
 public void test_chrono_byLocale_fullTag_japaneseCalendarFromElsewhere() {
   Chronology test = Chronology.ofLocale(Locale.forLanguageTag("en-US-u-ca-japanese"));
   Assert.assertEquals(test.getId(), "Japanese");
   Assert.assertEquals(test, JapaneseChronology.INSTANCE);
 }
 public Locale getLocale() {
   return Locale.forLanguageTag(userLanguage);
 }
 /** {@inheritDoc} */
 @Override
 public Locale getLocale() {
   return Locale.forLanguageTag(getCulture());
 }
 /** Will support only 3 locales for the moment. */
 private static Set<Locale> getSupportedLocales() {
   Set<Locale> locales = new HashSet<Locale>();
   locales.add(Locale.forLanguageTag("ca-es"));
   locales.add(Locale.forLanguageTag("da-dk"));
   locales.add(Locale.forLanguageTag("de-de"));
   locales.add(Locale.forLanguageTag("en-au"));
   locales.add(Locale.forLanguageTag("en-ca"));
   locales.add(Locale.forLanguageTag("en-gb"));
   locales.add(Locale.forLanguageTag("en-in"));
   locales.add(Locale.forLanguageTag("en-us"));
   locales.add(Locale.forLanguageTag("es-es"));
   locales.add(Locale.forLanguageTag("es-mx"));
   locales.add(Locale.forLanguageTag("fi-fi"));
   locales.add(Locale.forLanguageTag("fr-ca"));
   locales.add(Locale.forLanguageTag("fr-fr"));
   locales.add(Locale.forLanguageTag("it-it"));
   locales.add(Locale.forLanguageTag("ja-jp"));
   locales.add(Locale.forLanguageTag("ko-kr"));
   locales.add(Locale.forLanguageTag("nb-no"));
   locales.add(Locale.forLanguageTag("nl-nl"));
   locales.add(Locale.forLanguageTag("pl-pl"));
   locales.add(Locale.forLanguageTag("pt-br"));
   locales.add(Locale.forLanguageTag("pt-pt"));
   locales.add(Locale.forLanguageTag("ru-ru"));
   locales.add(Locale.forLanguageTag("sv-se"));
   locales.add(Locale.forLanguageTag("zh-cn"));
   locales.add(Locale.forLanguageTag("zh-hk"));
   locales.add(Locale.forLanguageTag("zh-tw"));
   return locales;
 }