コード例 #1
0
  /**
   * @param powerController
   * @return
   */
  public static IntermediateHotelState parseSensorInputs() {
    String sensorInputLine = SCANNER.nextLine();
    if (sensorInputLine.isEmpty()) {
      throw new IllegalArgumentException(INPUT_STRING_MALFORMED_FORMAT);
    } else if (sensorInputLine.equalsIgnoreCase(INPUT_STRING_EXIT)) {
      closeInputStream();
      System.out.println("Terminating...");
      System.exit(0);
    }
    String floorNumberString = RegexUtils.getMatchAtGroupIfExists(1, sensorInputLine);
    String subCorridorNumberString = RegexUtils.getMatchAtGroupIfExists(2, sensorInputLine);
    if (Objects.isNull(floorNumberString) || Objects.isNull(subCorridorNumberString)) {
      // Nothing can be done. Sensor inputs are possibly malformed.
      throw new IllegalArgumentException(INPUT_STRING_MALFORMED_FORMAT);
    }
    boolean turnOnLightBulbSwitch;
    if (sensorInputLine.startsWith(INPUT_STRING_NO_MOVEMENT_PREFIX)) {
      // Motion apparently ended after a minute.
      turnOnLightBulbSwitch = false;
    } else {
      // Motion Detected.
      turnOnLightBulbSwitch = true;
    }

    return new IntermediateHotelState(
        Integer.parseInt(floorNumberString),
        Integer.parseInt(subCorridorNumberString),
        turnOnLightBulbSwitch);
  }
コード例 #2
0
  /**
   * Construct the <code>User</code> with the details required by {@link
   * org.springframework.security.authentication.dao.DaoAuthenticationProvider}.
   *
   * @param username the username presented to the <code>DaoAuthenticationProvider</code>
   * @param password the password that should be presented to the <code>DaoAuthenticationProvider
   *     </code>
   * @param enabled set to <code>true</code> if the user is enabled
   * @param accountNonExpired set to <code>true</code> if the account has not expired
   * @param credentialsNonExpired set to <code>true</code> if the credentials have not expired
   * @param accountNonLocked set to <code>true</code> if the account is not locked
   * @param authorities the authorities that should be granted to the caller if they presented the
   *     correct username and password and the user is enabled. Not null.
   * @throws IllegalArgumentException if a <code>null</code> value was passed either as a parameter
   *     or as an element in the <code>GrantedAuthority</code> collection
   */
  public JakdukPrincipal(
      String username,
      String id,
      String password,
      String nickname,
      CommonConst.ACCOUNT_TYPE providerId,
      boolean enabled,
      boolean accountNonExpired,
      boolean credentialsNonExpired,
      boolean accountNonLocked,
      Collection<? extends GrantedAuthority> authorities) {

    if (Objects.isNull(username) || Objects.isNull(password))
      throw new IllegalArgumentException("Cannot pass null or empty values to constructor");

    this.username = username;
    this.nickname = nickname;
    this.id = id;
    this.password = password;
    this.providerId = providerId;
    this.enabled = enabled;
    this.accountNonExpired = accountNonExpired;
    this.credentialsNonExpired = credentialsNonExpired;
    this.accountNonLocked = accountNonLocked;
    this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
  }
コード例 #3
0
  public <E> void printLeafToRootPath(BinaryTreeNode<E> root) {
    if (Objects.isNull(root)) return;

    Queue<BinaryTreeNode<E>> queue = new LinkedQueue<>();
    Map<BinaryTreeNode<E>, BinaryTreeNode<E>> childParentMap = new LinkedHashMap<>();
    queue.enQueue(root);
    childParentMap.put(root, null);

    while (!queue.isEmpty()) {
      BinaryTreeNode<E> node = queue.deQueue();

      /** current node is leaf node (because it's both children are null. * */
      if (Objects.isNull(node.getLeft()) && Objects.isNull(node.getRight())) {
        printPath(node, childParentMap);
        continue;
        /** No need of further computation * */
      }

      if (!Objects.isNull(node.getLeft())) {
        queue.enQueue(node.getLeft());
        childParentMap.put(node.getLeft(), node);
      }

      if (!Objects.isNull(node.getRight())) {
        queue.enQueue(node.getRight());
        childParentMap.put(node.getRight(), node);
      }
    }
  }
コード例 #4
0
 // -------->
 // original code:
 // ftp://ftp.oreilly.de/pub/examples/english_examples/jswing2/code/goodies/Mapper.java
 // modified by terai
 //     private Hashtable<Object, ArrayList<KeyStroke>> buildReverseMap(InputMap im) {
 //         Hashtable<Object, ArrayList<KeyStroke>> h = new Hashtable<>();
 //         if (Objects.isNull(im.allKeys())) {
 //             return h;
 //         }
 //         for (KeyStroke ks: im.allKeys()) {
 //             Object name = im.get(ks);
 //             if (h.containsKey(name)) {
 //                 h.get(name).add(ks);
 //             } else {
 //                 ArrayList<KeyStroke> keylist = new ArrayList<>();
 //                 keylist.add(ks);
 //                 h.put(name, keylist);
 //             }
 //         }
 //         return h;
 //     }
 private void loadBindingMap(Integer focusType, InputMap im, ActionMap am) {
   if (Objects.isNull(im.allKeys())) {
     return;
   }
   ActionMap tmpAm = new ActionMap();
   for (Object actionMapKey : am.allKeys()) {
     tmpAm.put(actionMapKey, am.get(actionMapKey));
   }
   for (KeyStroke ks : im.allKeys()) {
     Object actionMapKey = im.get(ks);
     Action action = am.get(actionMapKey);
     if (Objects.isNull(action)) {
       model.addBinding(new Binding(focusType, "____" + actionMapKey.toString(), ks.toString()));
     } else {
       model.addBinding(new Binding(focusType, actionMapKey.toString(), ks.toString()));
     }
     tmpAm.remove(actionMapKey);
   }
   if (Objects.isNull(tmpAm.allKeys())) {
     return;
   }
   for (Object actionMapKey : tmpAm.allKeys()) {
     model.addBinding(new Binding(focusType, actionMapKey.toString(), ""));
   }
 }
コード例 #5
0
  private static int testIsNull() {
    int errors = 0;

    errors += Objects.isNull(null) ? 0 : 1;
    errors += Objects.isNull(Objects.class) ? 1 : 0;

    return errors;
  }
コード例 #6
0
 /**
  * Ge {@link ServiceProvider}. If necessary the {@link ServiceProvider} will be lazily loaded.
  *
  * @return the {@link ServiceProvider} used.
  */
 static ServiceProvider getServiceProvider() {
   if (Objects.isNull(serviceProviderDelegate)) {
     synchronized (LOCK) {
       if (Objects.isNull(serviceProviderDelegate)) {
         serviceProviderDelegate = loadDefaultServiceProvider();
       }
     }
   }
   return serviceProviderDelegate;
 }
コード例 #7
0
ファイル: BSTChecker.java プロジェクト: hrishikesh-kumar/ds
  public <E extends Comparable> boolean isBST(BinaryTreeNode<E> node) {
    if (Objects.isNull(node)) return true;

    if (!Objects.isNull(node.getLeft())
        && node.getData().compareTo(findMin(node.getLeft()).getData()) < 0) return false;

    if (!Objects.isNull(node.getRight())
        && node.getData().compareTo(findMax(node.getRight()).getData()) > 0) return false;

    if (!isBST(node.getLeft()) || !isBST(node.getRight())) return false;

    return true;
  }
コード例 #8
0
  @ApiOperation(
      value = "SNS 기반 회원 가입시 필요한 회원 프로필 정보",
      produces = "application/json",
      response = UserProfileForm.class)
  @RequestMapping(value = "/social/attempted", method = RequestMethod.GET)
  public UserProfileForm loginSocialUser(NativeWebRequest request) {

    Connection<?> connection = providerSignInUtils.getConnectionFromSession(request);

    if (Objects.isNull(connection)) throw new ServiceException(ServiceError.CANNOT_GET_SNS_PROFILE);

    ConnectionKey connectionKey = connection.getKey();

    CommonConst.ACCOUNT_TYPE convertProviderId =
        CommonConst.ACCOUNT_TYPE.valueOf(connectionKey.getProviderId().toUpperCase());
    UserProfile existUser =
        userService.findUserProfileByProviderIdAndProviderUserId(
            convertProviderId, connectionKey.getProviderUserId());
    org.springframework.social.connect.UserProfile socialProfile = connection.fetchUserProfile();

    String username = null;
    if (Objects.nonNull(socialProfile.getName())) {
      username = socialProfile.getName();
    } else if (Objects.nonNull(socialProfile.getUsername())) {
      username = socialProfile.getUsername();
    } else {
      if (Objects.nonNull(socialProfile.getFirstName())) {
        username = socialProfile.getFirstName();
      }
      if (Objects.nonNull(socialProfile.getLastName())) {
        username =
            Objects.isNull(username)
                ? socialProfile.getLastName()
                : ' ' + socialProfile.getLastName();
      }
    }

    UserProfileForm user = new UserProfileForm();
    user.setEmail(socialProfile.getEmail());
    user.setUsername(username);

    if (Objects.nonNull(existUser)) {
      user.setId(existUser.getId());
      user.setAbout(existUser.getAbout());

      if (Objects.nonNull(existUser.getSupportFC()))
        user.setFootballClub(existUser.getSupportFC().getId());
    }

    return user;
  }
コード例 #9
0
  /**
   * Create predicate that filters by CurrencyUnit.
   *
   * @param currencies the target {@link javax.money.CurrencyUnit} instances
   * @return the predicate from CurrencyUnit
   */
  public static Predicate<MonetaryAmount> filterByExcludingCurrency(CurrencyUnit... currencies) {

    if (Objects.isNull(currencies) || currencies.length == 0) {
      return m -> true;
    }
    return isCurrency(currencies).negate();
  }
コード例 #10
0
  /**
   * Create predicate that filters by CurrencyUnit.
   *
   * @param currencies the target {@link javax.money.CurrencyUnit}
   * @return the predicate from CurrencyUnit
   */
  public static Predicate<MonetaryAmount> isCurrency(CurrencyUnit... currencies) {

    if (Objects.isNull(currencies) || currencies.length == 0) {
      return m -> true;
    }
    Predicate<MonetaryAmount> predicate = null;

    for (CurrencyUnit currencyUnit : currencies) {
      if (Objects.isNull(predicate)) {
        predicate = m -> m.getCurrency().equals(currencyUnit);
      } else {
        predicate = predicate.or(m -> m.getCurrency().equals(currencyUnit));
      }
    }
    return predicate;
  }
コード例 #11
0
ファイル: DebugTheme.java プロジェクト: McSwede/XIV
  @Override
  public void renderSlider(
      String name,
      float value,
      float x,
      float y,
      float width,
      float height,
      float sliderX,
      boolean overElement,
      Element element) {
    if (Objects.isNull(font)) {
      font = new NahrFont("Comic Sans MS", 18);
    }

    element.setWidth(96);
    element.setHeight(this.getElementHeight());

    RenderUtils.drawBorderedRect(
        x, y + 1, x + element.getWidth(), y + height, 0x801E1E1E, 0xFF212121);
    RenderUtils.drawGradientRect(x, y + 1, x + sliderX, y + height, 0xFF5AACEB, 0xFF1466A5);

    font.drawString(name, x + 2, y - 1, NahrFont.FontType.SHADOW_THIN, 0xFFFFF0F0);
    font.drawString(
        value + "",
        x + element.getWidth() - font.getStringWidth(value + "") - 2,
        y - 1,
        NahrFont.FontType.SHADOW_THIN,
        0xFFFFF0F0);
  }
コード例 #12
0
  public FileNameRenderer(JTable table) {
    Border b = UIManager.getBorder("Table.noFocusBorder");
    if (Objects.isNull(b)) { // Nimbus???
      Insets i = focusCellHighlightBorder.getBorderInsets(textLabel);
      b = BorderFactory.createEmptyBorder(i.top, i.left, i.bottom, i.right);
    }
    noFocusBorder = b;

    p.setOpaque(false);
    panel.setOpaque(false);

    // http://www.icongalore.com/ XP Style Icons - Windows Application Icon, Software XP Icons
    nicon = new ImageIcon(getClass().getResource("wi0063-16.png"));
    sicon =
        new ImageIcon(
            p.createImage(
                new FilteredImageSource(nicon.getImage().getSource(), new SelectedImageFilter())));

    iconLabel = new JLabel(nicon);
    iconLabel.setBorder(BorderFactory.createEmptyBorder());

    p.add(iconLabel, BorderLayout.WEST);
    p.add(textLabel);
    panel.add(p, BorderLayout.WEST);

    Dimension d = iconLabel.getPreferredSize();
    dim.setSize(d);
    table.setRowHeight(d.height);
  }
コード例 #13
0
 /** Method executed before persist operation. */
 @PrePersist
 public final void beforePersist() {
   if (Objects.isNull(creationDate)) {
     creationDate = new Date();
   } else {
     updateDate = new Date();
   }
 }
コード例 #14
0
 public void parameterStillNullable(Object a) {
   Object x = checkForNullMethod();
   if (Objects.isNull(x)) {
     log("was null");
   } else {
     x.toString(); // Compliant: x was checked for non null
   }
 }
コード例 #15
0
 private <E> void printPath(
     BinaryTreeNode<E> node, Map<BinaryTreeNode<E>, BinaryTreeNode<E>> childParentMap) {
   System.out.print("\nPath for leaf : " + node.getData() + " :: ");
   while (!Objects.isNull(node)) {
     System.out.print(node.getData() + " => ");
     node = childParentMap.get(node);
   }
 }
コード例 #16
0
ファイル: OfficialDao.java プロジェクト: jimmor/sampler
 public Set<Official> getOfficials(final Government government) {
   if (Objects.isNull(government)) {
     return Collections.emptySet();
   }
   return Utils.<Official>uncheckedCast(
           getBaseCriteria().add(Restrictions.eq("government", government)).list())
       .stream()
       .collect(Collectors.<Official>toSet());
 }
コード例 #17
0
 public StreamedContent getChanges() {
   StreamedContent result = null;
   if (Objects.isNull(logToSave)) {
     LOGGER.error("Cannot download changes file! No data available!");
   } else {
     result = getFile(String.format("%s.%s", "changes", getFileExt()), logToSave.getChangeLog());
   }
   return result;
 }
 @Override
 public Object getPreviousValue() {
   // Calendar cal = Calendar.getInstance();
   // cal.setTime(value.getTime());
   // cal.add(calendarField, -1);
   // Date prev = cal.getTime();
   ChronoLocalDateTime<?> prev = value.minus(1, temporalUnit);
   return Objects.isNull(start) || start.compareTo(prev) <= 0 ? prev : null;
 }
 @Override
 public Object getNextValue() {
   // Calendar cal = Calendar.getInstance();
   // cal.setTime(value.getTime());
   // cal.add(calendarField, 1);
   // Date next = cal.getTime();
   ChronoLocalDateTime<?> next = value.plus(1, temporalUnit);
   return Objects.isNull(end) || end.compareTo(next) >= 0 ? next : null;
 }
コード例 #20
0
ファイル: GraphicTester.java プロジェクト: nroduit/Weasis
 @SuppressWarnings("unchecked")
 public Class<E> getGraphicClass() {
   if (Objects.isNull(clazz)) {
     clazz =
         (Class<E>)
             ((ParameterizedType) this.getClass().getGenericSuperclass())
                 .getActualTypeArguments()[0];
   }
   return clazz;
 }
コード例 #21
0
 @Override
 public String getName() {
   String name;
   if (Objects.isNull(device)) {
     name = "Error.";
   } else {
     name = device.getName();
   }
   return name;
 }
コード例 #22
0
  /**
   * Makes a disjoint union with another graph. They must share the same bottom and top elements.
   *
   * @param otherGraph other graph to make the union
   */
  public void disjointUnion(IntegerHierarchicalGraph otherGraph) {
    Objects.requireNonNull(otherGraph);
    if (getBottomElement().equals(otherGraph.getBottomElement())
        && getTopElement().equals(otherGraph.getTopElement())) {
      Set<Integer> set = new HashSet<>();
      set.addAll(getElements());
      set.remove(getBottomElement());
      set.remove(getTopElement());
      set.retainAll(otherGraph.getElements());

      if (!set.isEmpty()) {
        throw new IllegalArgumentException("Graphs are not disjoint.");
      }

      Set<Integer> otherSet = new HashSet<>();
      otherSet.addAll(otherGraph.getElements());
      otherSet.forEach(
          elem -> {
            if (Objects.isNull(this.children.get(elem))) {
              this.children.put(elem, new HashSet<>());
            }
            this.children.get(elem).addAll(otherGraph.getChildren(elem));

            if (Objects.isNull(this.parents.get(elem))) {
              this.parents.put(elem, new HashSet<>());
            }
            this.parents.get(elem).addAll(otherGraph.getParents(elem));

            if (Objects.isNull(this.equivalents.get(elem))) {
              this.equivalents.put(elem, new HashSet<>());
            }
            if (Objects.isNull(this.representative.get(elem))) {
              this.representative.put(elem, elem);
            }
            otherGraph.getEquivalents(elem).forEach(otherElem -> makeEquivalent(elem, otherElem));
          });

    } else {
      throw new IllegalArgumentException(
          "Both graphs have different bottom element or different top element.");
    }
  }
コード例 #23
0
 public StreamedContent getTransportFile() {
   StreamedContent result = null;
   if (Objects.isNull(logToSave)) {
     LOGGER.error("Cannot download transport file! No item selected!");
   } else {
     result =
         getFile(
             String.format("%s.%s", logToSave.getMessageName(), getFileExt()),
             logToSave.getTransportForm());
   }
   return result;
 }
コード例 #24
0
ファイル: DLock.java プロジェクト: aHumbleCoder/DLock
  public void release() throws DLockException {
    if (Objects.isNull(lockPath)) {
      return;
    }

    try {
      zookeeper.deleteLockNode(lockPath);
      lockPath = null;
    } catch (InterruptedException | KeeperException e) {
      throw new DLockException("failed to release the lock", e);
    }
  }
コード例 #25
0
  @Override
  public void send(ResultMessage resultMessage) {
    if (resultMessage.getChannelType() == ChannelType.NONE) return;
    TelegramInterfaceContext ic = (TelegramInterfaceContext) resultMessage.getIc();
    for (Message msg : resultMessage.getMessages()) {
      OutputMessageHandler outputMessageHandler = handlers.get(msg.getMessageCode());
      if (Objects.isNull(outputMessageHandler)) outputMessageHandler = defaultOutputMessageHandler;
      outputMessageHandler.execute(msg, resultMessage.getChannelType(), ic);
    }

    //        sendMessage(msg, resultMessage.getChannelType(), ic);
  }
コード例 #26
0
  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {

    if (Objects.isNull(value)) return false;

    CommonPrincipal commonPrincipal = UserUtils.getCommonPrincipal();

    if (!UserUtils.isJakdukUser()) return true;

    UserOnPasswordUpdate user = userService.findUserOnPasswordUpdateById(commonPrincipal.getId());
    String oldPassword = user.getPassword();

    return encoder.matches(value, oldPassword);
  }
コード例 #27
0
 protected void fireEditingCanceled() {
   // Guaranteed to return a non-null array
   Object[] listeners = listenerList.getListenerList();
   // Process the listeners last to first, notifying
   // those that are interested in this event
   for (int i = listeners.length - 2; i >= 0; i -= 2) {
     if (listeners[i] == CellEditorListener.class) {
       // Lazily create the event:
       if (Objects.isNull(changeEvent)) {
         changeEvent = new ChangeEvent(this);
       }
       ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent);
     }
   }
 }
コード例 #28
0
  @ApiOperation(
      value = "로그인 중인 내 프로필",
      produces = "application/json",
      response = AuthUserProfile.class)
  @RequestMapping(value = "/auth/user", method = RequestMethod.GET)
  public AuthUserProfile getMyProfile() {

    AuthUserProfile authUserProfile = commonService.getAuthUserProfile();

    if (Objects.isNull(authUserProfile))
      throw new NoSuchElementException(
          commonService.getResourceBundleMessage(
              "messages.common", "common.exception.no.such.element"));

    return authUserProfile;
  }
コード例 #29
0
  @Override
  public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) {
    LocalDate[] times = getQueryDates(conversionQuery);
    if (Objects.isNull(times)) {
      return super.getExchangeRate(conversionQuery);
    }

    for (YearMonth yearMonth : Stream.of(times).map(YearMonth::from).collect(Collectors.toSet())) {

      if (!cachedHistoric.contains(yearMonth)) {
        Map<IMFHistoricalType, InputStream> resources =
            IMFRemoteSearch.INSTANCE.getResources(yearMonth);
        loadFromRemote(resources);
        cachedHistoric.add(yearMonth);
      }
    }
    return super.getExchangeRate(conversionQuery);
  }
 public SpinnerLocalDateTimeModel(
     ChronoLocalDateTime<?> value,
     Comparable<ChronoLocalDateTime<?>> start,
     Comparable<ChronoLocalDateTime<?>> end,
     TemporalUnit temporalUnit) {
   super();
   if (Objects.isNull(value)) {
     throw new IllegalArgumentException("value is null");
   }
   if (Objects.nonNull(start) && start.compareTo(value) >= 0
       || Objects.nonNull(end) && end.compareTo(value) <= 0) {
     throw new IllegalArgumentException("(start <= value <= end) is false");
   }
   this.value = value;
   this.start = start;
   this.end = end;
   this.temporalUnit = temporalUnit;
 }