Exemple #1
0
  /**
   * Gets the content of the article, and creates the final section for the generated report (html)
   *
   * @param aLink
   * @return
   */
  public static String getArticleContent(String aLink, ArticleBodyParser parser) {
    Document doc = null;
    String htmltext = "";
    if (Objects.nonNull(aLink) && !aLink.isEmpty()) {
      try {
        doc =
            Jsoup.connect(aLink)
                .header("Accept-Encoding", "gzip, deflate")
                .userAgent(userAgent)
                .timeout(6000)
                .followRedirects(true)
                .maxBodySize(0)
                .get();
      } catch (IOException e) {
        LOGGER.log(
            Level.WARNING, "Error connecting, while fetching the article with link " + aLink);
      }
      if (doc != null) {
        Element title = doc.getElementsByTag("title").first();
        Element mainArticle = parser.parseArticleFromDoc(doc);
        if (Objects.nonNull(title) && Objects.nonNull(mainArticle)) {
          htmltext =
              HtmlContentWriterUtil.generateArticleHtml(
                  title.html(), aLink, Jsoup.clean(mainArticle.html(), Whitelist.basic()));

        } else {
          LOGGER.warning("We could not fetch the title and main body for link: " + aLink);
        }
      }
    }
    return htmltext;
  }
Exemple #2
0
  default void notNull(HttpServerRequest request, String... args) {
    Objects.nonNull(request);
    Objects.nonNull(args);

    for (String arg : args) {
      if (request.getParam(arg) == null) throw new RestValidationError();
    }
  }
  private static int testNonNull() {
    int errors = 0;

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

    return errors;
  }
 // Overridden for performance reasons. ---->
 @Override
 public boolean isOpaque() {
   Color back = getBackground();
   Component p = getParent();
   if (Objects.nonNull(p)) {
     p = p.getParent();
   } // p should now be the JTable.
   boolean colorMatch =
       Objects.nonNull(back)
           && Objects.nonNull(p)
           && back.equals(p.getBackground())
           && p.isOpaque();
   return !colorMatch && super.isOpaque();
 }
Exemple #5
0
  /** Gets the error, nicely formatted */
  protected String getLocationString(final SAXParseException e) {
    final StringBuffer sb = new StringBuffer(256);
    String systemId = e.getSystemId();

    if (Objects.nonNull(systemId)) {
      final int index = systemId.lastIndexOf('/');

      if (index != -1) {
        systemId = systemId.substring(index + 1);
      }

      sb.append(systemId);
      sb.append(':');
    }

    sb.append("line ");
    sb.append(e.getLineNumber());
    sb.append(":col ");
    sb.append(e.getColumnNumber());
    sb.append(':');
    sb.append(e.getMessage());

    // e.printStackTrace();

    return sb.toString();
  } // getLocationString()
 @Override
 public void removeDomain(final String name) {
   Objects.nonNull(name);
   if (!cache.isExist(name)) {
     throw new RuntimeException("Can't perform operation, the domain is not existing.");
   }
   cache.remove(name);
 }
 @Override
 public Optional<DomainDefinition> getDomain(final String name) {
   Objects.nonNull(name);
   if (!cache.isExist(name)) {
     return Optional.empty();
   }
   return Optional.of(cache.get(name));
 }
 @Override
 public List<ServiceSpiDefault> getDomainServiceSpi(final String name) {
   Objects.nonNull(name);
   if (!cache.isExist(name)) {
     return Collections.emptyList();
   }
   return cache.get(name).getServices();
 }
 public void parameterNoLongerNullable(Object a) {
   Object x = checkForNullMethod();
   if (Objects.nonNull(x)) {
     x.toString(); // Compliant: x was checked for non null
   } else {
     x.logNull(); // Noncompliant {{NullPointerException might be thrown as 'x' is nullable here}}
   }
 }
 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;
 }
 @Override
 public void updateUI() {
   if (Objects.nonNull(cbml)) {
     JList<?> list = getList();
     if (Objects.nonNull(list)) {
       list.removeMouseListener(cbml);
       list.removeMouseMotionListener(cbml);
     }
   }
   super.updateUI();
   setRenderer(new ButtonsRenderer<E>(this));
   JList<?> list = getList();
   if (Objects.nonNull(list)) {
     cbml = new CellButtonsMouseListener();
     list.addMouseListener(cbml);
     list.addMouseMotionListener(cbml);
   }
 }
Exemple #12
0
  @Override
  public void processPacket(final Player c, int packetType, int packetSize) {
    c.walkingToItem = false;
    c.pItemY = c.getInStream().readSignedWordBigEndian();
    c.pItemId = c.getInStream().readUnsignedWord();
    c.pItemX = c.getInStream().readSignedWordBigEndian();
    if (Math.abs(c.getX() - c.pItemX) > 25 || Math.abs(c.getY() - c.pItemY) > 25) {
      c.resetWalkingQueue();
      return;
    }
    DuelSession duelSession =
        (DuelSession)
            Server.getMultiplayerSessionListener()
                .getMultiplayerSession(c, MultiplayerSessionType.DUEL);
    if (Objects.nonNull(duelSession)
        && duelSession.getStage().getStage() > MultiplayerSessionStage.REQUEST
        && duelSession.getStage().getStage() < MultiplayerSessionStage.FURTHER_INTERACTION) {
      c.sendMessage("Your actions have declined the duel.");
      duelSession.getOther(c).sendMessage("The challenger has declined the duel.");
      duelSession.finish(MultiplayerSessionFinalizeType.WITHDRAW_ITEMS);
      return;
    }
    if (c.getInterfaceEvent().isActive()) {
      c.sendMessage("Please finish what you're doing.");
      return;
    }
    if (c.getPA().viewingOtherBank) {
      c.getPA().resetOtherBank();
    }
    c.getCombat().resetPlayerAttack();
    if (c.getX() == c.pItemX && c.getY() == c.pItemY) {
      Server.itemHandler.removeGroundItem(c, c.pItemId, c.pItemX, c.pItemY, c.heightLevel, true);
    } else {
      c.walkingToItem = true;
      CycleEventHandler.getSingleton()
          .addEvent(
              c,
              new CycleEvent() {
                @Override
                public void execute(CycleEventContainer container) {
                  if (!c.walkingToItem) container.stop();
                  if (c.getX() == c.pItemX && c.getY() == c.pItemY) {
                    Server.itemHandler.removeGroundItem(
                        c, c.pItemId, c.pItemX, c.pItemY, c.heightLevel, true);
                    container.stop();
                  }
                }

                @Override
                public void stop() {
                  c.walkingToItem = false;
                }
              },
              1);
    }
  }
 /**
  * returns the bookmarks where the title contains the given string. The search must be case
  * insensitive.
  *
  * @param s the substring to search
  * @return the found bookmarks
  */
 @Override
 public Collection<Bookmark> getBookmarksWithSearch(String s) {
   final String titleToSearch = Objects.requireNonNull(s).toLowerCase();
   return bookmarks
       .values()
       .stream()
       .filter(bookmark -> Objects.nonNull(bookmark.getTitle()))
       .filter(bookmark -> bookmark.getTitle().toLowerCase().contains(titleToSearch))
       .collect(Collectors.toList());
 }
 @Override
 public void show(Component c, int x, int y) {
   if (c instanceof JTextComponent) {
     JTextComponent textArea = (JTextComponent) c;
     boolean flg = Objects.nonNull(textArea.getSelectedText());
     cutAction.setEnabled(flg);
     copyAction.setEnabled(flg);
     deleteAction.setEnabled(flg);
     super.show(c, x, y);
   }
 }
 @Override
 public void mousePressed(MouseEvent e) {
   JList list = (JList) e.getComponent();
   Point pt = e.getPoint();
   int index = list.locationToIndex(pt);
   if (index >= 0) {
     JButton button = getButton(list, pt, index);
     if (Objects.nonNull(button)) {
       listRepaint(list, list.getCellBounds(index, index));
     }
   }
 }
 @Override
 public void mouseMoved(MouseEvent e) {
   JList list = (JList) e.getComponent();
   Point pt = e.getPoint();
   int index = list.locationToIndex(pt);
   if (!list.getCellBounds(index, index).contains(pt)) {
     if (prevIndex >= 0) {
       Rectangle r = list.getCellBounds(prevIndex, prevIndex);
       listRepaint(list, r);
     }
     index = -1;
     prevButton = null;
     return;
   }
   if (index >= 0) {
     JButton button = getButton(list, pt, index);
     ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer();
     if (Objects.nonNull(button)) {
       renderer.rolloverIndex = index;
       if (!button.equals(prevButton)) {
         Rectangle r = list.getCellBounds(prevIndex, index);
         listRepaint(list, r);
       }
     } else {
       renderer.rolloverIndex = -1;
       Rectangle r = null;
       if (prevIndex == index) {
         if (prevIndex >= 0 && Objects.nonNull(prevButton)) {
           r = list.getCellBounds(prevIndex, prevIndex);
         }
       } else {
         r = list.getCellBounds(index, index);
       }
       listRepaint(list, r);
       prevIndex = -1;
     }
     prevButton = button;
   }
   prevIndex = index;
 }
 @Override
 public int read(final byte[] b) throws IOException {
   Objects.nonNull(b);
   int result = 0;
   while (result > -1 && result < b.length) {
     int c = read();
     if (c == -1) {
       return result == 0 ? -1 : result;
     }
     b[result++] = (byte) c;
   }
   return result;
 }
 @Override
 public void mousePressed(MouseEvent e) {
   // JList list = (JList) e.getComponent();
   Point pt = e.getPoint();
   int index = list.locationToIndex(pt);
   if (index >= 0) {
     JButton button = getButton(list, pt, index);
     if (Objects.nonNull(button)) {
       ButtonsRenderer renderer = (ButtonsRenderer) list.getCellRenderer();
       renderer.pressedIndex = index;
       renderer.button = button;
       listRepaint(list, list.getCellBounds(index, index));
     }
   }
 }
 @Override
 public void paintIcon(Component c, Graphics g, int x, int y) {
   Graphics2D g2 = (Graphics2D) g.create();
   g2.setPaint(Objects.nonNull(c) ? c.getBackground() : Color.WHITE);
   g2.fillRect(x, y, getIconWidth(), getIconHeight());
   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
   g2.setColor(ELLIPSE_COLOR);
   g2.translate(x, y);
   int size = list.size();
   for (int i = 0; i < size; i++) {
     float alpha = isRunning ? (i + 1) / (float) size : .5f;
     g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
     g2.fill(list.get(i));
   }
   // g2.translate(-x, -y);
   g2.dispose();
 }
  @Override
  public MonthIndicator getLastMonthIndicator() {
    Page<MonthIndicator> page =
        repository.findAll(new PageRequest(0, 1, Sort.Direction.DESC, "dateTime"));

    MonthIndicator monthIndicator;
    if (Objects.nonNull(page)) {
      monthIndicator = page.iterator().next();

      log.debug("Found Last Month Indicator: {}", monthIndicator);
      return monthIndicator;
    }

    log.error("Could not found Last Month Indicator in DB");

    return null;
  }
 @Override
 public int read(final byte[] b, final int off, final int len) throws IOException {
   Objects.nonNull(b);
   if (off < 0 || len < 0 || len > b.length - off) {
     throw new IndexOutOfBoundsException();
   } else if (len == 0) {
     return 0;
   }
   int result = 0;
   while (result > -1 && result < len) {
     int c = read();
     if (c == -1) {
       return result == 0 ? -1 : result;
     }
     b[off + result++] = (byte) c;
   }
   return result;
 }
  @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;
  }
Exemple #23
0
 public void initializeTabChangeListener(TabPane tabPane) {
   ReadOnlyObjectProperty<Tab> itemProperty = tabPane.getSelectionModel().selectedItemProperty();
   itemProperty.addListener(
       (observable, oldValue, selectedTab) -> {
         if (Objects.isNull(selectedTab)) return;
         threadService.runActionLater(
             () -> {
               EditorPane editorPane = ((MyTab) selectedTab).getEditorPane();
               if (Objects.nonNull(editorPane)) {
                 try {
                   editorPane.rerender();
                   editorPane.focus();
                 } catch (Exception e) {
                   logger.error("Problem occured after changing tab {}", selectedTab, e);
                 }
               }
             });
       });
 }
  @RequestMapping(value = ERROR_PATH)
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request, Locale locale) {
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    Map<String, Object> body = errorAttributes.getErrorAttributes(requestAttributes, true);

    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
    if (Objects.nonNull(body.get("status"))) {
      try {
        status = HttpStatus.valueOf((Integer) body.get("status"));
      } catch (Exception ignore) {
      }
    }

    String message =
        messageSource.getMessage("error." + status, null, ERROR_DEFAULT_MESSAGE, locale);
    if (StringUtils.hasText(message)) {
      body.put("message", message);
    }

    return ResponseEntity.status(status).body(body);
  }
  @Subscribe
  public void listen(SharedEntryNotPresentEvent event) {
    BasePanel panel = jabRefFrame.getCurrentBasePanel();
    EntryEditor entryEditor = panel.getCurrentEditor();

    panel
        .getUndoManager()
        .addEdit(new UndoableRemoveEntry(panel.getDatabase(), event.getBibEntry(), panel));

    if (Objects.nonNull(entryEditor) && (entryEditor.getEntry() == event.getBibEntry())) {
      JOptionPane.showMessageDialog(
          jabRefFrame,
          Localization.lang(
                  "The BibEntry you currently work on has been deleted on the shared side.")
              + "\n"
              + Localization.lang("You can restore the entry using the \"Undo\" operation."),
          Localization.lang("Shared entry is no longer present"),
          JOptionPane.INFORMATION_MESSAGE);

      SwingUtilities.invokeLater(() -> panel.hideBottomComponent());
    }
  }
 @Override
 public Component getListCellRendererComponent(
     JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
   label.setText(Objects.toString(value, ""));
   this.index = index;
   if (isSelected) {
     setBackground(list.getSelectionBackground());
     label.setForeground(list.getSelectionForeground());
   } else {
     setBackground(index % 2 == 0 ? EVEN_COLOR : list.getBackground());
     label.setForeground(list.getForeground());
   }
   resetButtonStatus();
   if (Objects.nonNull(button)) {
     if (index == pressedIndex) {
       button.getModel().setSelected(true);
       button.getModel().setArmed(true);
       button.getModel().setPressed(true);
     } else if (index == rolloverIndex) {
       button.getModel().setRollover(true);
     }
   }
   return this;
 }
Exemple #27
0
  @Override
  public void postProcess(IOTMessage ioTMessage) {

    switch (ioTMessage.getMessageType()) {
      case ConnectAcknowledgeMessage.MESSAGE_TYPE:
        ConnectAcknowledgeMessage conMessage = (ConnectAcknowledgeMessage) ioTMessage;

        /** Use the connection acknowledgement message to store session id for persistance. */
        Channel channel = getChannel(ioTMessage.getConnectionId());
        if (Objects.nonNull(channel)) {

          if (MqttConnectReturnCode.CONNECTION_ACCEPTED.equals(conMessage.getReturnCode())) {

            channel.attr(ServerImpl.REQUEST_SESSION_ID).set(ioTMessage.getSessionId());
          } else {
            closeClient(ioTMessage.getConnectionId());
          }
        }

        break;
      default:
        super.postProcess(ioTMessage);
    }
  }
Exemple #28
0
 /**
  * 指定されたT2型の要素を持つ新しいUnion2を返す.
  *
  * @param value
  * @return 新しいUnion2
  * @exception NullPointerException valueがnullの場合
  */
 public static <T1, T2> Union2<T1, T2> of2(T2 value) {
   Objects.nonNull(value);
   return new Union2<T1, T2>(new Member2<>(value));
 }
Exemple #29
0
  private Pair<TableSchema, Function<MappingMetaData, Optional<TypeToken<?>>>> estimateSchema(
      final TableSchema providedSchema) {
    final Map<String, MappingMetaData> providedData =
        providedSchema
            .getEntries()
            .stream()
            .distinct()
            .collect(Collectors.toMap(MappingMetaData::getName, metaData -> metaData));

    final List<MappingMetaData> metaDataList = new ArrayList<>(providedSchema.getEntries().size());
    final Map<MappingMetaData, TypeToken<?>> types = new HashMap<>();

    try (final ResultSet result = database.get().execute("SHOW COLUMNS FROM " + tableName)) {
      while (result.next()) {
        final String name = result.getString("Field");
        final boolean isPrimaryKey = result.getString("Key").equals("PRI");

        final String defaultValue;
        {
          final String cache = result.getString("Default");
          if (cache == null || "null".equals(cache)) defaultValue = "";
          else defaultValue = cache;
        }

        final TypeToken<?> type = getJavaTypeOf(result.getString("Type"), isPrimaryKey);

        final MappingMetaData finalMetaData;

        final MappingMetaData data = providedData.get(name);
        if (Objects.nonNull(data)) {
          // Complete info
          finalMetaData =
              new AbstractMappingMetaData() {
                @Override
                public String getName() {
                  return data.getName();
                }

                @Override
                public String getTarget() {
                  return data.getTarget();
                }

                @Override
                public String getDescription() {
                  return data.getDescription();
                }

                @Override
                public String getCategory() {
                  return data.getCategory();
                };

                @Override
                public String getDefaultValue() {
                  return data.getDefaultValue().isEmpty() ? defaultValue : data.getDefaultValue();
                };

                @Override
                public int getIndex() {
                  return data.getIndex();
                }

                @Override
                public boolean isKey() {
                  return data.isKey() ? true : isPrimaryKey;
                }

                @Override
                public String getAlias() {
                  return data.getAlias();
                }
              };
        } else if (providedSchema.getPolicy().hasPermissionToAddColumns()) {
          // Add column
          finalMetaData =
              new AbstractMappingMetaData() {
                @Override
                public String getName() {
                  return name;
                }

                @Override
                public String getDescription() {
                  return "Auto completed";
                }

                @Override
                public String getDefaultValue() {
                  return defaultValue;
                };

                @Override
                public boolean isKey() {
                  return isPrimaryKey;
                }
              };
        } else continue;

        metaDataList.add(finalMetaData);
        types.put(finalMetaData, type);
      }
    } catch (final Throwable t) {
      throw new DatabaseConnectionException(t);
    }

    // Get Fields of the table
    return new Pair<>(
        new TableSchema() {
          private final List<MappingMetaData> entries = Collections.unmodifiableList(metaDataList);

          @Override
          public SchemaPolicy getPolicy() {
            return providedSchema.getPolicy();
          }

          @Override
          public String getStructure() {
            return providedSchema.getStructure();
          }

          @Override
          public String getName() {
            return providedSchema.getName();
          }

          @Override
          public ClientStorageFormat getFormat() {
            return providedSchema.getFormat();
          }

          @Override
          public List<MappingMetaData> getEntries() {
            return entries;
          }
        },
        m -> Optional.ofNullable(types.get(m)));
  }
 private static void listRepaint(JList list, Rectangle rect) {
   if (Objects.nonNull(rect)) {
     list.repaint(rect);
   }
 }