Exemple #1
0
 private static void tryResUrls(Picture picture) {
   String hi_res = "";
   String url = picture.media_url.toString();
   for (String ending : Main.endings) {
     try {
       hi_res = url.replace(url.substring(url.lastIndexOf("_"), url.lastIndexOf(".")), ending);
       URL hi_url = new URL(hi_res);
       File hi_name = Helper.extractMediaFileNameFromURL(hi_url);
       if (hi_name.equals(picture.media_name)) {
         picture.hi_url = hi_url;
         picture.hi_name = hi_name;
         picture.downloaded_hi = true;
         break;
       } else {
         boolean success = Helper.downloadFileFromURLToFileInTemp(hi_url, hi_name);
         if (success) {
           picture.hi_url = hi_url;
           picture.hi_name = hi_name;
           picture.downloaded_hi = true;
           Helper.moveTempImageToStore(hi_name, new File(Main.blogdir, picture.md5_id));
           break;
         }
       }
     } catch (MalformedURLException ex) {
       Main.error(String.format("Attempted hi res url %s is a malformed URL.", hi_res));
     }
   }
 }
  /**
   * Reset the commit order from the session's descriptors. This uses the constraint dependencies in
   * the descriptor's mappings, to decide which descriptors are dependent on which other
   * descriptors. Multiple computations of the commit order should produce the same ordering. This
   * is done to improve performance on unit of work writes through decreasing the stack size, and
   * acts as a deadlock avoidance mechanism.
   */
  public void initializeCommitOrder() {
    Vector descriptors = Helper.buildVectorFromMapElements(getSession().getDescriptors());

    // Must ensure uniqueness, some descriptor my be register twice for interfaces.
    descriptors = Helper.addAllUniqueToVector(new Vector(descriptors.size()), descriptors);
    Object[] descriptorsArray = new Object[descriptors.size()];
    for (int index = 0; index < descriptors.size(); index++) {
      descriptorsArray[index] = descriptors.elementAt(index);
    }
    Arrays.sort(descriptorsArray, new DescriptorCompare());
    descriptors = new Vector(descriptors.size());
    for (int index = 0; index < descriptorsArray.length; index++) {
      descriptors.addElement(descriptorsArray[index]);
    }

    CommitOrderCalculator calculator = new CommitOrderCalculator(getSession());
    calculator.addNodes(descriptors);
    calculator.calculateMappingDependencies();
    calculator.orderCommits();
    descriptors = calculator.getOrderedDescriptors();

    calculator = new CommitOrderCalculator(getSession());
    calculator.addNodes(descriptors);
    calculator.calculateSpecifiedDependencies();
    calculator.orderCommits();

    setCommitOrder(calculator.getOrderedClasses());
  }
Exemple #3
0
  @Start
  public void start() {
    Log.debug("Start WSChan");
    clients = new HashMap<>();
    if (path == null) {
      path = "";
    }

    ContainerRoot model = modelService.getPendingModel();
    if (model == null) {
      model = modelService.getCurrentModel().getModel();
    }
    Channel thisChan = (Channel) model.findByPath(context.getPath());
    Set<String> inputPaths = Helper.getProvidedPortsPath(thisChan, context.getNodeName());
    Set<String> outputPaths = Helper.getRequiredPortsPath(thisChan, context.getNodeName());

    for (String path : inputPaths) {
      // create input WSMsgBroker clients
      createInputClient(path + "_" + context.getInstanceName());
    }

    for (String path : outputPaths) {
      // create output WSMsgBroker clients
      createOutputClient(path + "_" + context.getInstanceName());
    }
  }
Exemple #4
0
 private void updateCacheFromLdap()
     throws ChaiUnavailableException, ChaiOperationException, PwmOperationalException,
         PwmUnrecoverableException {
   LOGGER.debug(
       PwmConstants.REPORTING_SESSION_LABEL,
       "beginning process to updating user cache records from ldap");
   if (status != STATUS.OPEN) {
     return;
   }
   cancelFlag = false;
   reportStatus = new ReportStatusInfo(settings.getSettingsHash());
   reportStatus.setInProgress(true);
   reportStatus.setStartDate(new Date());
   try {
     final Queue<UserIdentity> allUsers = new LinkedList<>(getListOfUsers());
     reportStatus.setTotal(allUsers.size());
     while (status == STATUS.OPEN && !allUsers.isEmpty() && !cancelFlag) {
       final Date startUpdateTime = new Date();
       final UserIdentity userIdentity = allUsers.poll();
       try {
         if (updateCachedRecordFromLdap(userIdentity)) {
           reportStatus.setUpdated(reportStatus.getUpdated() + 1);
         }
       } catch (Exception e) {
         String errorMsg =
             "error while updating report cache for " + userIdentity.toString() + ", cause: ";
         errorMsg +=
             e instanceof PwmException
                 ? ((PwmException) e).getErrorInformation().toDebugStr()
                 : e.getMessage();
         final ErrorInformation errorInformation;
         errorInformation = new ErrorInformation(PwmError.ERROR_REPORTING_ERROR, errorMsg);
         LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, errorInformation.toDebugStr());
         reportStatus.setLastError(errorInformation);
         reportStatus.setErrors(reportStatus.getErrors() + 1);
       }
       reportStatus.setCount(reportStatus.getCount() + 1);
       reportStatus.getEventRateMeter().markEvents(1);
       final TimeDuration totalUpdateTime = TimeDuration.fromCurrent(startUpdateTime);
       if (settings.isAutoCalcRest()) {
         avgTracker.addSample(totalUpdateTime.getTotalMilliseconds());
         Helper.pause(avgTracker.avgAsLong());
       } else {
         Helper.pause(settings.getRestTime().getTotalMilliseconds());
       }
     }
     if (cancelFlag) {
       reportStatus.setLastError(
           new ErrorInformation(
               PwmError.ERROR_SERVICE_NOT_AVAILABLE, "report cancelled by operator"));
     }
   } finally {
     reportStatus.setFinishDate(new Date());
     reportStatus.setInProgress(false);
   }
   LOGGER.debug(
       PwmConstants.REPORTING_SESSION_LABEL,
       "update user cache process completed: " + JsonUtil.serialize(reportStatus));
 }
Exemple #5
0
 protected static void reset() {
   Helper.removeDirectoryIfItExists(Helper.temp);
   Helper.removeDirectoryIfItExists(blogdir);
   Main.post_post_hash.clear();
   Main.pic_pic_hash.clear();
   Main.pic_post_hash.clear();
   Main.dup_post_list.clear();
 }
 /**
  * Print out some details about a segment. This is far from all the available information.
  *
  * @param segment the segment to be displayed
  * @param fmt the formatter to use to display the data
  */
 public void printLeg(AirSegment segment, Formatter fmt) {
   Date dep = Helper.dateFromISO8601(segment.getDepartureTime());
   fmt.format(
       "AIR Departing from %3s to %3s on %Tc\n",
       segment.getOrigin(), segment.getDestination(), dep);
   fmt.format(
       "         Flight [%2s]#%4s  Flight time: %s minutes\n",
       segment.getCarrier(), segment.getFlightNumber(), segment.getFlightTime());
   fmt.format(
       "                           Arrive %Tc\n",
       Helper.dateFromISO8601(segment.getArrivalTime()));
 }
Exemple #7
0
  @Override
  public void init(PwmApplication pwmApplication) throws PwmException {
    status = STATUS.OPENING;
    this.pwmApplication = pwmApplication;

    if (pwmApplication.getApplicationMode() == PwmApplication.MODE.READ_ONLY) {
      LOGGER.debug(
          PwmConstants.REPORTING_SESSION_LABEL,
          "application mode is read-only, will remain closed");
      status = STATUS.CLOSED;
      return;
    }

    if (pwmApplication.getLocalDB() == null
        || LocalDB.Status.OPEN != pwmApplication.getLocalDB().status()) {
      LOGGER.debug(PwmConstants.REPORTING_SESSION_LABEL, "LocalDB is not open, will remain closed");
      status = STATUS.CLOSED;
      return;
    }

    if (!pwmApplication.getConfig().readSettingAsBoolean(PwmSetting.REPORTING_ENABLE)) {
      LOGGER.debug(
          PwmConstants.REPORTING_SESSION_LABEL,
          "reporting module is not enabled, will remain closed");
      status = STATUS.CLOSED;
      clear();
      return;
    }

    try {
      userCacheService = new UserCacheService();
      userCacheService.init(pwmApplication);
    } catch (Exception e) {
      LOGGER.error(PwmConstants.REPORTING_SESSION_LABEL, "unable to init cache service");
      status = STATUS.CLOSED;
      return;
    }

    settings = ReportSettings.readSettingsFromConfig(pwmApplication.getConfig());
    summaryData = ReportSummaryData.newSummaryData(settings.getTrackDays());

    executorService =
        Executors.newSingleThreadScheduledExecutor(
            Helper.makePwmThreadFactory(
                Helper.makeThreadName(pwmApplication, this.getClass()) + "-", true));

    String startupMsg = "report service started";
    LOGGER.debug(startupMsg);

    executorService.submit(new InitializationTask());

    status = STATUS.OPEN;
  }
Exemple #8
0
  @Override
  public void dispatch(String o, final Callback callback) {
    ContainerRoot model = modelService.getCurrentModel().getModel();
    Channel thisChan = (Channel) model.findByPath(context.getPath());
    Set<String> outputPaths = Helper.getRequiredPortsPath(thisChan, context.getNodeName());

    // create a list of destination paths
    Set<String> destPaths = new HashSet<>();
    // process remote paths in order to add _<chanName> to the paths
    // (WsMsgBroker protocol)
    // add processed remote path to dest
    destPaths.addAll(
        channelContext
            .getRemotePortPaths()
            .stream()
            .map(remotePath -> remotePath + "_" + context.getInstanceName())
            .collect(Collectors.toList()));
    // add local connected inputs to dest
    Set<String> providedPaths =
        Helper.getProvidedPortsPath(thisChan, context.getNodeName())
            .stream()
            .map(s -> s + "_" + context.getInstanceName())
            .collect(Collectors.toSet());

    destPaths.addAll(providedPaths);
    // create the array that will store the dest
    String[] dest = new String[destPaths.size()];
    // convert list to array
    destPaths.toArray(dest);

    for (final String outputPath : outputPaths) {
      WSMsgBrokerClient client = this.clients.get(outputPath + "_" + context.getInstanceName());
      if (client != null) {
        if (callback != null) {
          client.send(
              o,
              dest,
              (from, o1) -> {
                CallbackResult result = new CallbackResult();
                result.setPayload(o1.toString());
                result.setOriginChannelPath(context.getPath());
                result.setOriginPortPath(outputPath);
                callback.onSuccess(result);
              });
        } else {
          client.send(o, dest);
        }
      } else {
        createInputClient(outputPath + "_" + context.getInstanceName());
      }
    }
  }
Exemple #9
0
  /**
   * The transaction performs a transfer of the amount from a submitter to a recipient. This is the
   * same as performing a contribution of the submitter and then a payout to the recipient.
   *
   * @param sender the name of the participant who lost the amount
   * @param amount the amount of the transfer
   * @param comment a <code>String</code> to make the transaction recognizable
   * @param recipient the name of the participant who got the amount
   * @return the entry id of the transaction or -1 in case the transaction failed or -2 if the
   *     transaction violates the 'no negative total' rule
   */
  public int performTransfer(String sender, double amount, String comment, String recipient) {
    boolean internal = isInternal(sender);
    if (internal) {
      if (breaksDebtLimit(amount)) return -2;
    }

    int transactionCode = 2;
    int flags = composeFlags(transactionCode, false);

    int entryId = addEntry(sender, amount, currency, comment, flags);
    if (entryId < 0) return -1;

    flags = composeFlags(transactionCode, sender.equals(recipient));
    long rowId =
        addRecord(entryId, recipient, -amount, currency, Helper.timestampNow(), comment, flags);
    if (rowId < 0) {
      removeEntry(entryId);
      return -1;
    }

    Log.i(
        TAG,
        String.format(
            "entry %d: %s transfer %f %s for '%s' to %s",
            entryId, sender, amount, currency, comment, recipient));

    return entryId;
  }
 /** Return any tables that are defined by this expression (and not its base). */
 @Override
 public List<DatabaseTable> getOwnedTables() {
   ClassDescriptor descriptor = getDescriptor();
   List<DatabaseTable> tables = null;
   if (descriptor == null) {
     List additionalTables = getAdditionalTables();
     if (additionalTables == null) {
       return null;
     } else {
       return new ArrayList(additionalTables);
     }
   } else if (descriptor.isAggregateDescriptor()) {
     return null;
   } else if ((descriptor.getHistoryPolicy() != null)
       && (getAsOfClause() != null && getAsOfClause().getValue() != null)) {
     tables = descriptor.getHistoryPolicy().getHistoricalTables();
   } else if (isUsingOuterJoinForMultitableInheritance()) {
     tables = descriptor.getInheritancePolicy().getAllTables();
   } else {
     tables = descriptor.getTables();
   }
   List additionalTables = getAdditionalTables();
   if (additionalTables != null) {
     tables = new Vector(tables);
     Helper.addAllUniqueToList(tables, additionalTables);
     return tables;
   }
   return tables;
 }
Exemple #11
0
 @Override
 public void run() {
   try {
     initTempData();
   } catch (LocalDBException | PwmUnrecoverableException e) {
     LOGGER.error(
         PwmConstants.REPORTING_SESSION_LABEL, "error during initialization: " + e.getMessage());
     status = STATUS.CLOSED;
     return;
   }
   final long secondsUntilNextDredge =
       settings.getJobOffsetSeconds()
           + TimeDuration.fromCurrent(Helper.nextZuluZeroTime()).getTotalSeconds();
   executorService.scheduleAtFixedRate(
       new DredgeTask(),
       secondsUntilNextDredge,
       TimeDuration.DAY.getTotalSeconds(),
       TimeUnit.SECONDS);
   executorService.scheduleAtFixedRate(
       new RolloverTask(),
       secondsUntilNextDredge + 1,
       TimeDuration.DAY.getTotalSeconds(),
       TimeUnit.SECONDS);
   executorService.submit(new RolloverTask());
 }
 public String getFieldNameByTitleControl(Object _fieldtitlemodel) {
   String sTitleModelName =
       (String) Helper.getUnoPropertyValue(_fieldtitlemodel, PropertyNames.PROPERTY_NAME);
   String sindex = JavaTools.getSuffixNumber(sTitleModelName);
   return (String)
       CurUnoDialog.getControlProperty(this.SOLABELPREFIX + sindex, PropertyNames.PROPERTY_LABEL);
 }
  /** INTERNAL: */
  public String toString() {
    StringWriter writer = new StringWriter();
    writer.write(Helper.getShortClassName(getClass()));
    writer.write("(");

    for (int index = 0; index < getFields().size(); index++) {
      writer.write(Helper.cr());
      writer.write("\t");
      writer.write(String.valueOf((getFields().elementAt(index))));
      writer.write(" => ");
      writer.write(String.valueOf((getValues().elementAt(index))));
    }
    writer.write(")");

    return writer.toString();
  }
Exemple #14
0
  /**
   * The transaction registers multiple submissions. This transaction as a whole is not allowed if
   * it causes a negative total.
   *
   * @param deals a <code>ShareMap</code> containing the deals of participants involved
   * @param comment a <code>String</code> to make the transactions recognizable
   * @return the entry id of the transaction or -1 in case the transaction failed or -2 if the
   *     transactions in the sum violate the 'no negative total' rule
   */
  public int performMultiple(ShareMap deals, String comment) {
    if (breaksDebtLimit(-deals.sum())) return -2;

    int transactionCode = 4;
    int flags = composeFlags(transactionCode, false);

    int entryId = getNewEntryId();

    if (entryId > -1) {
      for (Map.Entry<String, Double> share : deals.rawMap.entrySet())
        if (addRecord(
                entryId,
                share.getKey(),
                share.getValue(),
                currency,
                Helper.timestampNow(),
                comment,
                flags)
            < 0) {
          removeEntry(entryId);
          return -1;
        }

      Log.i(
          TAG,
          String.format("entry %d: '%s' submissions : %s", entryId, comment, deals.toString()));
    }

    return entryId;
  }
  // Add each possible state in the currentNode.sons list.
  public void createSons() { // Tested
    SimulatedPlanetWars simpw = this.getSim();
    for (Planet myPlanet : simpw.MyPlanets()) {

      // avoid planets with only one ship
      if (myPlanet.NumShips() <= 1) continue;

      // We create a son for each of the possible situations
      for (Planet notMyPlanet : simpw.NotMyPlanets()) {

        // Create simulation environment for this son
        SimulatedPlanetWars simpw2 = new SimulatedPlanetWars(simpw);
        int value = Helper.Dcalculation(myPlanet, notMyPlanet);
        simpw2.IssueOrder(myPlanet, notMyPlanet);
        simpw2.simulateGrowth();
        simpw2.simulateFirstBotAttack();
        simpw2.simulateGrowth();

        MyNode son;
        if (this.isRoot()) {
          son = new MyNode(this, simpw2, value, myPlanet, notMyPlanet);
        } else {
          son =
              new MyNode(
                  this,
                  simpw2,
                  value,
                  this.getSource(),
                  this.getDest()); // We only need to know from where to where we want to send our
          // ships to get the best turn
        }
        this.addSon(son);
      }
    }
  }
Exemple #16
0
  /**
   * The transaction registers the negated sum of the shares as an expense by a group of
   * contributors. Additionally all the shares in the map are registered with the same entry id.
   * Those names in the deals map that are empty <code>String</code> trigger transfers of internal
   * amounts. Such an internal transfer is not allowed if the transaction causes a negative total.
   *
   * @param deals the names of the contributors and their contributions who expended an amount
   *     matching the negated sum of the deals
   * @param comment a <code>String</code> to make the transaction recognizable
   * @param shares a <code>ShareMap</code> containing the shares of participants involved
   * @return the entry id of the transaction or a negative value in case the transaction failed
   */
  public int performComplexExpense(ShareMap deals, String comment, ShareMap shares) {
    int entryId = -1;

    int transactionCode = 3;
    int flags = composeFlags(transactionCode, true);

    double amount = deals.sum();
    if (Math.abs(amount + shares.sum()) < ShareUtil.delta) {
      if (deals.option != null)
        switch (deals.option) {
          default:
            setDebtLimit(1000. * deals.option);
            break;
        }

      if (deals.rawMap.containsKey(kitty))
        entryId = performTransfer(kitty, -deals.rawMap.get(kitty), comment, kitty);
      else entryId = getNewEntryId();

      Collection<String> dealers = ShareUtil.filter(deals.rawMap.keySet(), true, ShareUtil.isKitty);

      for (String name : dealers) {
        long rowId =
            addRecord(
                entryId,
                name,
                deals.rawMap.get(name),
                currency,
                Helper.timestampNow(),
                comment,
                flags);
        if (rowId < 0) {
          entryId = -1;
          break;
        }
      }
    } else
      Log.w(
          TAG,
          String.format(
              "the sum of the deals (%f) for '%s' doesn't match the sum of the shares (%f)",
              amount, comment, shares.sum()));

    if (entryId > -1) {
      if (allocate(flags, entryId, shares.rawMap)) {
        Log.i(
            TAG,
            String.format(
                "entry %d: %s expended %f %s for '%s' shared by %s",
                entryId, deals.toString(), Math.abs(amount), currency, comment, shares.toString()));
      } else {
        removeEntry(entryId);
        entryId = -1;
      }
    }

    if (entryId < 0) removeEntry(entryId);

    return entryId;
  }
 private static void initSqrLookup() {
   if (sqrLookup == null) {
     sqrLookup = new int[sizeSqrLookup];
     for (int i = 0; i < sizeSqrLookup; i++) {
       sqrLookup[i] = Helper.sqr(i);
     }
   }
 }
  /** INTERNAL: Return the type for a specified implementor */
  protected Object getTypeForImplementor(Class implementor) {
    Object type = getTypeIndicatorTranslation().get(implementor);
    if (type == Helper.getNullWrapper()) {
      type = null;
    }

    return type;
  }
 /** Return the string for logging purposes. */
 public String getLogString(Accessor accessor) {
   StringWriter writer = new StringWriter();
   writer.write("Executing ");
   writer.write(toString());
   writer.write(Helper.cr());
   writer.write("\tspec => ");
   writer.write(String.valueOf(getInteractionSpec()));
   writer.write(Helper.cr());
   writer.write("\tproperties => ");
   writer.write(String.valueOf(getProperties()));
   writer.write(Helper.cr());
   writer.write("\txml => ");
   Element dom = createInputDOM((EISAccessor) accessor);
   EISDOMRecord record = new EISDOMRecord(dom);
   record.transformToWriter(writer);
   return writer.toString();
 }
  /** PUBLIC: Add a type indicator conversion to this mapping. */
  public void addClassIndicator(Class implementer, Object typeIndicator) {
    if (typeIndicator == null) {
      typeIndicator = Helper.getNullWrapper();
    }

    getTypeIndicatorTranslation().put(implementer, typeIndicator);
    getTypeIndicatorTranslation().put(typeIndicator, implementer);
  }
Exemple #21
0
 public static void save() {
   Main.status("Saving databases.");
   File file = new File(blogdir, "picpic.db");
   List<Object> objects = new ArrayList<>();
   objects.add(Main.post_post_hash);
   Helper.saveObjectToFile(file, objects);
   Main.status("Done saving databases.");
 }
  /**
   * INTERNAL: Extract the direct values from the specified field value. Return them in a vector.
   * The field value better be an Array.
   */
  public Vector buildDirectValuesFromFieldValue(Object fieldValue) throws DatabaseException {

    if (fieldValue == null) {
      return null;
    }

    return Helper.vectorFromArray((Object[]) fieldValue);
  }
 /**
  * INTERNAL: Appends an Oracle specific Timestamp, if usesNativeSQL is true otherwise use the ODBC
  * format. Native Format: to_timestamp ('1997-11-06 10:35:45.656' , 'yyyy-mm-dd hh:mm:ss.ff')
  */
 protected void appendTimestamp(java.sql.Timestamp timestamp, Writer writer) throws IOException {
   if (usesNativeSQL()) {
     writer.write("to_timestamp('");
     writer.write(Helper.printTimestamp(timestamp));
     writer.write("','yyyy-mm-dd HH24:MI:SS.FF')");
   } else {
     super.appendTimestamp(timestamp, writer);
   }
 }
Exemple #24
0
 private static void handlePost(Post post) {
   Main.post_post_hash.put(post, post);
   for (Picture picture : post.pictures) {
     Helper.downloadFileFromURLToFileInTemp(picture.thumb_url, picture.thumb_name);
     picture.md5_id = Helper.createMD5FromFileInTemp(picture.thumb_name);
     Helper.moveTempImageToStore(picture.thumb_name, new File(Main.blogdir, picture.md5_id));
     if (!Main.pic_pic_hash.containsKey(picture)) {
       Main.pic_pic_hash.put(picture, picture);
       Main.pic_post_hash.put(picture, post);
       Helper.downloadFileFromURLToFileInTemp(picture.media_url, picture.media_name);
       Helper.moveTempImageToStore(picture.media_name, new File(Main.blogdir, picture.md5_id));
     } else {
       if (!post.equals(Main.pic_post_hash.get(picture))) {
         dup_post_list.put(post, Main.pic_post_hash.get(picture));
       }
     }
   }
 }
Exemple #25
0
  /** @hide */
  public int addEntry(String name, double amount, String currency, String comment, int flags) {
    int entryId = getNewEntryId();

    long rowId = addRecord(entryId, name, amount, currency, Helper.timestampNow(), comment, flags);
    if (rowId < 0) {
      removeEntry(entryId);
      entryId = -1;
    }

    return entryId;
  }
  private Color interpolateColor(
      final Stop LOWER_BOUND, final Stop UPPER_BOUND, final double POSITION) {
    final double POS =
        (POSITION - LOWER_BOUND.getOffset()) / (UPPER_BOUND.getOffset() - LOWER_BOUND.getOffset());

    final double DELTA_RED =
        (UPPER_BOUND.getColor().getRed() - LOWER_BOUND.getColor().getRed()) * POS;
    final double DELTA_GREEN =
        (UPPER_BOUND.getColor().getGreen() - LOWER_BOUND.getColor().getGreen()) * POS;
    final double DELTA_BLUE =
        (UPPER_BOUND.getColor().getBlue() - LOWER_BOUND.getColor().getBlue()) * POS;
    final double DELTA_OPACITY =
        (UPPER_BOUND.getColor().getOpacity() - LOWER_BOUND.getColor().getOpacity()) * POS;

    double red = Helper.clamp(0d, 1d, (LOWER_BOUND.getColor().getRed() + DELTA_RED));
    double green = Helper.clamp(0d, 1d, (LOWER_BOUND.getColor().getGreen() + DELTA_GREEN));
    double blue = Helper.clamp(0d, 1d, (LOWER_BOUND.getColor().getBlue() + DELTA_BLUE));
    double opacity = Helper.clamp(0d, 1d, (LOWER_BOUND.getColor().getOpacity() + DELTA_OPACITY));

    return Color.color(red, green, blue, opacity);
  }
 public void forgotPassword(final String email) throws UserNotFoundException, MailException {
   final Query query =
       entityManager.createQuery("select u from UserImpl u where u.email=:cryptedMail");
   query.setParameter("cryptedMail", CipherHelper.cipher(email));
   final List<UserImpl> list = query.getResultList();
   if (list.isEmpty()) throw new UserNotFoundException();
   for (final UserImpl user : list) {
     final String password = Helper.randomstring();
     user.setPassword(password);
     MailSender.forgotPasswordMail(user.getName(), password, email);
     entityManager.merge(user);
   }
 }
  /** INTERNAL: Return the implementor for a specified type */
  protected Object getImplementorForType(Object type, AbstractSession session) {
    if (type == null) {
      return getTypeIndicatorTranslation().get(Helper.getNullWrapper());
    }

    // Must ensure the type is the same, i.e. Integer != BigDecimal.
    try {
      type = session.getDatasourcePlatform().convertObject(type, getTypeField().getType());
    } catch (ConversionException e) {
      throw ConversionException.couldNotBeConverted(this, getDescriptor(), e);
    }

    return getTypeIndicatorTranslation().get(type);
  }
 /**
  * INTERNAL: Build the appropriate field value for the specified set of direct values. The
  * database better be expecting an ARRAY.
  */
 public Object buildFieldValueFromDirectValues(
     Vector directValues, String elementDataTypeName, AbstractSession session)
     throws DatabaseException {
   Object[] fields = Helper.arrayFromVector(directValues);
   try {
     ((DatabaseAccessor) session.getAccessor()).incrementCallCount(session);
     java.sql.Connection connection = ((DatabaseAccessor) session.getAccessor()).getConnection();
     return session.getPlatform().createArray(elementDataTypeName, fields, session, connection);
   } catch (java.sql.SQLException ex) {
     throw DatabaseException.sqlException(ex, session, false);
   } finally {
     ((DatabaseAccessor) session.getAccessor()).decrementCallCount();
   }
 }
  public void printJourney(RailJourney journey, Formatter fmt) {
    Date dep = Helper.dateFromISO8601(journey.getDepartureTime());

    fmt.format(
        "RAIL (%s) From %s to %s on %Tc\n",
        journey.getJourneyDirection(),
        journey.getOriginStationName(),
        journey.getDestinationStationName(),
        dep);

    List<RailSegmentRef> onThisJourney = journey.getRailSegmentRef();
    for (Iterator<RailSegmentRef> rsIter = onThisJourney.iterator(); rsIter.hasNext(); ) {
      RailSegment railSegment = railSegments.get(rsIter.next().getKey());
      if (railSegment.getOperatingCompany() == null) {
        fmt.format("         METRO");
      } else {
        fmt.format(
            "         %s[%2s] Train #%4s  ",
            railSegment.getOperatingCompany().getName(),
            railSegment.getOperatingCompany().getCode(),
            railSegment.getTrainNumber());
      }
      fmt.format(
          " --- From "
              + railSegment.getOriginStationName()
              + " to "
              + railSegment.getDestinationStationName());
      if (railSegment.getTravelTime() != null) {
        fmt.format("Travel time: %s minutes\n", railSegment.getTravelTime());
      } else {
        fmt.format("\n");
      }
    }
    fmt.format(
        "                           Arrive %Tc\n",
        Helper.dateFromISO8601(journey.getArrivalTime()));
  }