Beispiel #1
0
  public Optional<String> toImageBlock(Image image) {

    if (!current.currentPath().isPresent()) asciiDocController.saveDoc();

    Path currentPath = current.currentPath().map(Path::getParent).get();
    IOHelper.createDirectories(currentPath.resolve("images"));

    List<String> buffer = new LinkedList<>();
    DateTimeFormatter dateTimeFormatter =
        DateTimeFormatter.ofPattern(asciiDocController.getClipboardImageFilePattern());
    Path path = Paths.get(dateTimeFormatter.format(LocalDateTime.now()));

    Path targetImage = currentPath.resolve("images").resolve(path.getFileName());

    try {
      BufferedImage fromFXImage = SwingFXUtils.fromFXImage(image, null);
      ImageIO.write(fromFXImage, "png", targetImage.toFile());

    } catch (Exception e) {
      logger.error("Problem occured while saving clipboard image {}", targetImage);
    }

    buffer.add(String.format("image::images/%s[]", path.getFileName()));

    if (buffer.size() > 0) return Optional.of(String.join("\n", buffer));

    return Optional.empty();
  }
public class DateComparisonUsingLocalDate {

  LocalDate now = LocalDate.now();
  String beginningOfMonth =
      now.withDayOfMonth(1).format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  String today = now.format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  String yesterday = now.minusDays(1).format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
  SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

  void checkIfSameDay() throws Exception {
    String startDateStr = "03/03/2011";
    String endDateStr = "03/03/2011";
    Date endDate = formatter.parse(endDateStr);

    boolean isSameDay;
    isSameDay =
        DateUtils.isSameDay(formatter.parse(beginningOfMonth), formatter.parse(startDateStr));
    System.out.println("==1==" + isSameDay);
    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), endDate);
    System.out.println("==2==" + isSameDay);

    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), formatter.parse(startDateStr));
    System.out.println("==3==" + isSameDay);
    isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), endDate);
    System.out.println("==4==" + isSameDay);
  }
}
  /**
   * RFC 2616 allows three different date-formats:
   *
   * <ul>
   *   <li>RFC 1123
   *   <li>RFC 1036
   *   <li>ASCI-Time
   * </ul>
   *
   * @param headerValue value transmitted from client
   * @return the parsed DateTime
   * @see <a href= "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3">RFC 2616</a>
   */
  private LocalDateTime convertIfModifiedSinceToDate(String headerValue) {

    LocalDateTime time = null;
    try {
      time = LocalDateTime.parse(headerValue, DateTimeFormatter.RFC_1123_DATE_TIME);
    } catch (DateTimeParseException e) {
      logger.trace("could not parse date with RFC-1123. Will try RFC-1036 format...");
    }

    if (time == null) {
      try {
        final String PATTERN_RFC1036 = "EEE, dd-MMM-yy HH:mm:ss zzz";
        time = LocalDateTime.parse(headerValue, DateTimeFormatter.ofPattern(PATTERN_RFC1036));
      } catch (DateTimeParseException e) {
        logger.trace("could not parse date with RFC-1036. Will try ASCITIME format...");
      }
    }

    if (time == null) {
      try {
        final String PATTERN_ASCITIME = "EEE MMM d HH:mm:ss yyyy";
        time = LocalDateTime.parse(headerValue, DateTimeFormatter.ofPattern(PATTERN_ASCITIME));
      } catch (DateTimeParseException e) {
        logger.trace("could not parse date with ASCITIME.");
      }
    }

    if (time == null) {
      logger.error("Could not parse given if-modified-since header with value '{}'", headerValue);
    }
    return time;
  }
Beispiel #4
0
 @Override
 public boolean handleMessage(final Message event) {
   final String message = event.getValue().toLowerCase();
   final Channel channel = event.getChannel();
   if (message.startsWith("info ")) {
     final String key = message.substring("info ".length());
     final Factoid factoid = dao.getFactoid(key);
     if (factoid != null) {
       DateTimeFormatter formatter = DateTimeFormatter.ofPattern(INFO_DATE_FORMAT);
       LocalDateTime updated = factoid.getUpdated();
       String formatted = formatter.format(updated);
       getBot()
           .postMessageToChannel(
               event,
               Sofia.factoidInfo(
                   key,
                   factoid.getLocked() ? "*" : "",
                   factoid.getUserName(),
                   formatted,
                   factoid.getValue()));
     } else {
       getBot().postMessageToChannel(event, Sofia.factoidUnknown(key));
     }
     return true;
   }
   return false;
 }
Beispiel #5
0
  public static void main(String[] args) {
    LocalDate hoje = LocalDate.now();
    System.out.println(hoje);

    LocalDate olimpiadasRio = LocalDate.of(2016, Month.JUNE, 5);
    System.out.println(olimpiadasRio);

    int dias = olimpiadasRio.getDayOfYear() - hoje.getDayOfYear();
    System.out.println(dias + " dias para as Olímpiadas no Rio!");

    Period periodo = Period.between(hoje, olimpiadasRio);
    System.out.println(periodo.getMonths() + " meses e " + periodo.getDays() + " dias.");

    DateTimeFormatter formatador = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    String valorFormatado = olimpiadasRio.format(formatador);
    System.out.println(valorFormatado);

    System.out.println(" --- Medida de tempo ---");

    DateTimeFormatter formatadorComHoras = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss");
    LocalDateTime agora = LocalDateTime.now();
    System.out.println(agora);
    System.out.println(agora.format(formatadorComHoras));

    LocalTime intervalo = LocalTime.of(12, 30);
    System.out.println(intervalo);
  }
  public void setCheckin(Checkin checkin) {
    this.checkin = checkin;
    if (checkin == null) {
      this.jLabelCode.setText("<html>Kodi: <b>?");
      this.jLabelDate.setText("<html>Data: <b>?");
      this.jLabelTime.setText("<html>Ora: <b>?");
      this.jLabel1.setText("<html>Furnitori<b>?");
      this.jLabelTotValue.setText("<html>Tot.: <>?");
      this.items = new ArrayList();
    } else {
      this.jLabelCode.setText("<html>Kodi: <b>" + checkin.getCode());
      this.jLabelDate.setText(
          "<html>Data: <b>"
              + checkin.getEmissionTime().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")));
      this.jLabelTime.setText(
          "<html>Ora: <b>"
              + checkin.getEmissionTime().format(DateTimeFormatter.ofPattern("HH.mm.ss")));
      this.jLabel1.setText("<html>Furnitori: <b>" + checkin.getSupplier());
      this.jLabelTotValue.setText("<html>Tot.: " + checkin.getValue());
      this.items = checkin.getItems();
    }

    DecimalFormat df = new DecimalFormat();
    df.applyPattern("#,##0.0#");
    String[] header = {"Kodi", "Emertimi", "Marka", "Tipi", "Sasia", "Cmimi", "Vlera"};
    Object[][] data = new Object[this.items.size()][header.length];
    for (int r = 0; r < this.items.size(); r++) {
      data[r][0] = this.items.get(r).getCode();
      data[r][1] = this.items.get(r).getName();
      data[r][2] = this.items.get(r).getBrand();
      data[r][3] = this.items.get(r).getType();
      data[r][4] = this.items.get(r).getQuantity();
      data[r][5] = this.items.get(r).getValue();
      data[r][6] = this.items.get(r).getValue() * this.items.get(r).getQuantity();
    }
    DefaultTableModel dtm =
        new DefaultTableModel(data, header) {
          @Override
          public boolean isCellEditable(int r, int c) {
            return false;
          }

          @Override
          public Class getColumnClass(int columnIndex) {
            Class[] types =
                new Class[] {
                  java.lang.String.class,
                  java.lang.String.class,
                  java.lang.String.class,
                  java.lang.String.class,
                  java.lang.Integer.class,
                  java.lang.Float.class,
                  java.lang.Float.class
                };
            return types[columnIndex];
          }
        };
    this.jTableItems.setModel(dtm);
  }
 private void isoDate() {
   // 建格式器
   DateTimeFormatter d = DateTimeFormatter.ISO_DATE;
   // 创建对象
   LocalDate ld = LocalDate.now();
   System.out.println(ld);
   String str = d.format(ld);
   System.out.println(str);
 }
Beispiel #8
0
 public Exam(String name, String day, String hour, String color) {
   this.name = name;
   this.day = day;
   time =
       LocalTime.parse(hour, DateTimeFormatter.ofPattern("HH.mm"))
           .atDate(LocalDate.parse(day, DateTimeFormatter.ofPattern("dd/MM/yy")));
   this.color = color; // don't blame me they're all static methods ^^^		
   this.hour = hour;
 }
Beispiel #9
0
  public static void main(String[] args) {

    LocalDate jetzt = LocalDate.now();
    DateTimeFormatter myformatter = DateTimeFormatter.ofPattern("EEEE, d. MMM yyyy");
    System.out.println("Heute ist " + myformatter.format(jetzt) + ".");
    System.out.println("ein weiteres Bespiel.....");
    java.util.Random r = new java.util.Random();
    int x = r.nextInt(1000);
    System.out.println("eine Zufallszahl: " + x);
  }
 @Override
 public String toString() {
   return "["
       + "checkoutdate:"
       + checkoutDate.format(DateTimeFormatter.ofPattern(Constant.DATE_PATTERN))
       + ", dueDate: "
       + dueDate.format(DateTimeFormatter.ofPattern(Constant.DATE_PATTERN))
       + ", publication: "
       + copy
       + "]";
 }
 @Override
 protected String toString(LocalDateTime value) {
   DateTimeFormatter formatter = getDateTimeFormatter();
   if (formatter != null) {
     try {
       return formatter.format(value);
     } catch (Exception e) {
       CommonUtils.ignoreException(e);
     }
   }
   return super.toString(value);
 }
 private FilterBuilder[] makeFilters(ZonedDateTime currentDate) {
   List<FilterBuilder> builders = new ArrayList<>();
   boolean minRange = down(TimeUnit.HOURS, currentDate).isBefore(config.getFrom());
   boolean maxRange = up(TimeUnit.HOURS, currentDate).isAfter(config.getTo());
   if (minRange || maxRange) {
     RangeFilterBuilder rangeFilterBuilder = FilterBuilders.rangeFilter("received_at");
     if (minRange)
       rangeFilterBuilder = rangeFilterBuilder.gte(DATE_FORMAT.format(config.getFrom()));
     if (maxRange) rangeFilterBuilder = rangeFilterBuilder.lte(DATE_FORMAT.format(config.getTo()));
     builders.add(rangeFilterBuilder);
   }
   return builders.toArray(new FilterBuilder[builders.size()]);
 }
  @Test
  public void testCreateHtml() throws Exception {
    List<Transaction> result =
        new CsvImporter()
            .importCsv(new FileInputStream("src/test/resources/transactions_example6.csv"), null);

    LocalDate beginPeriod =
        LocalDate.parse("04-02-2016", DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    LocalDate endPeriod = LocalDate.parse("05-03-2016", DateTimeFormatter.ofPattern("dd-MM-yyyy"));
    /*ByteArrayInputStream bStream = new HtmlGenerator().createHtml(result, "134567890", beginPeriod, endPeriod);
    try (OutputStream os = new FileOutputStream("src/test/resources/testHtmlGenerator.html")) {
        IOUtils.copy(bStream, os);
    }*/

  }
Beispiel #14
0
  static void f3() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss");
    LocalDateTime dateTime = LocalDateTime.now();
    String string = formatter.format(dateTime);
    System.out.println(string);

    DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyyMMdd-HH:mm:ss");
    LocalDateTime dateTime1 = LocalDateTime.parse("20160124-15:03:59", formatter1);
    System.out.println(dateTime1);

    // LocalDateTime dt1 = LocalDateTime.of(2016, Month.JANUARY, 10, 20, 30);
    // LocalDateTime dt2 = LocalDateTime.of(date, time);
    // LocalDateTime dt3 = date.atTime(20, 30);
    // LocalDateTime dt4 = date.atTime(time);
  }
@ServerEndpoint("/clock")
public class WebSocketClock {
  static ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();

  private static Set<Session> allSessions;

  DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

  @OnOpen
  public void showTime(Session session) {
    allSessions = session.getOpenSessions();

    // start the scheduler on the very first connection
    // to call sendTimeToAll every second
    if (allSessions.size() == 0) {
      timer.scheduleAtFixedRate(() -> sendTimeToAll(session), 0, 5, TimeUnit.SECONDS);
    }
  }

  private void sendTimeToAll(Session session) {
    allSessions = session.getOpenSessions();
    for (Session sess : allSessions) {
      try {
        sess.getBasicRemote().sendText("Local time: " + LocalTime.now().format(timeFormatter));
      } catch (IOException ioe) {
        System.out.println(ioe.getMessage());
      }
    }
  }
}
Beispiel #16
0
 /**
  * Converts a String in the format of the defined {@link DateUtil#DATE_PATTERN} to a {@link
  * LocalDate} object.
  *
  * <p>Returns null if the String could not be converted.
  *
  * @param dateString the date as String
  * @return the date object or null if it could not be converted
  */
 public static LocalDate parse(String dateString) {
   try {
     return DATE_FORMATTER.parse(dateString, LocalDate::from);
   } catch (DateTimeParseException e) {
     return null;
   }
 }
  private void setNextRepetitionDate(LocalDate nextRepetitionDate) {
    String formattedNextRepetitionDate =
        nextRepetitionDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy"));

    nextRepetitionDateTextField.setText(formattedNextRepetitionDate);
    setNextRepetitionDateForeground(nextRepetitionDate);
  }
  /**
   * Map a ComputerDTo to a Computer.
   *
   * @param dto the ComputerDTO to map
   * @return the dto as a computer
   */
  public Computer toComputer(ComputerDto dto) {

    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, Locale.getDefault()));
    LocalDate introduced = null;
    LocalDate discontinued = null;

    if (null != dto.getIntroduced() && !dto.getIntroduced().isEmpty()) {
      introduced = LocalDate.parse(dto.getIntroduced(), formatter);
    }
    if (null != dto.getDiscontinued() && !dto.getDiscontinued().isEmpty()) {
      discontinued = LocalDate.parse(dto.getDiscontinued(), formatter);
    }
    Company company = null;
    if (dto.getCompanyId() != 0) {
      company = new Company(dto.getCompanyId(), dto.getCompanyName());
    }

    return new Computer.ComputerBuilder(dto.getName())
        .id(dto.getId())
        .company(company)
        .introduced(introduced)
        .discontinued(discontinued)
        .build();
  }
  /**
   * Map a list of Computer to a list of ComputerDTO.
   *
   * @param computers the computers to map
   * @return the computers as dto
   */
  public List<ComputerDto> listFromModel(List<Computer> computers) {
    DateTimeFormatter formatter =
        DateTimeFormatter.ofPattern(
            messageSource.getMessage("app.formatDate", null, LocaleContextHolder.getLocale()));
    List<ComputerDto> computersDto = new ArrayList<ComputerDto>();

    for (Computer computer : computers) {
      String introduced = null;
      String discontinued = null;
      long companyId = 0;
      String companyName = null;
      if (null != computer.getIntroduced()) {
        introduced = computer.getIntroduced().format(formatter);
      }
      if (null != computer.getDiscontinued()) {
        discontinued = computer.getDiscontinued().format(formatter);
      }
      if (null != computer.getCompany()) {
        companyId = computer.getCompany().getId();
        companyName = computer.getCompany().getName();
      }

      computersDto.add(
          new ComputerDto.ComputerDtoBuilder(computer.getName())
              .id(computer.getId())
              .companyId(companyId)
              .companyName(companyName)
              .introduced(introduced)
              .discontinued(discontinued)
              .build());
    }
    return computersDto;
  }
Beispiel #20
0
@Controller
public class ActivityService implements ApplicationListener<SessionDisconnectEvent> {

  private static final Logger log = LoggerFactory.getLogger(ActivityService.class);

  private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

  @Inject SimpMessageSendingOperations messagingTemplate;

  @SubscribeMapping("/topic/activity")
  @SendTo("/topic/tracker")
  public ActivityDTO sendActivity(
      @Payload ActivityDTO activityDTO,
      StompHeaderAccessor stompHeaderAccessor,
      Principal principal) {
    activityDTO.setUserLogin(SecurityUtils.getCurrentUserLogin());
    activityDTO.setUserLogin(principal.getName());
    activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
    activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
    Instant instant = Instant.ofEpochMilli(Calendar.getInstance().getTimeInMillis());
    activityDTO.setTime(
        dateTimeFormatter.format(ZonedDateTime.ofInstant(instant, ZoneOffset.systemDefault())));
    log.debug("Sending user tracking data {}", activityDTO);
    return activityDTO;
  }

  @Override
  public void onApplicationEvent(SessionDisconnectEvent event) {
    ActivityDTO activityDTO = new ActivityDTO();
    activityDTO.setSessionId(event.getSessionId());
    activityDTO.setPage("logout");
    messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
  }
}
Beispiel #21
0
/** Created by zhangb on 22/9/2015. */
public class DateTimeTest {

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

  public static void main(String[] args) {
    DateTimeTest test = new DateTimeTest();

    test.localDateTimeTest();

    test.localDateTest();
  }

  public void localDateTimeTest() {
    LocalDateTime currentTime = LocalDateTime.now();

    System.out.println(currentTime);

    System.out.println(currentTime.format(formatter));
  }

  public void localDateTest() {
    LocalDate localDate = LocalDate.now();
    System.out.println(localDate);
  }
}
Beispiel #22
0
  @Override
  public void insertString(int offs, String val, AttributeSet attr) throws BadLocationException {
    if (val.length() == 0) super.insertString(offs, val, attr);

    if (val.length() == 1) {

      int numChars = 1;
      if (offs < getLength() - 1) {
        String nextChar = getText(offs + 1, 1);
        if (nextChar.equals("-")) {
          numChars = 2;
          val = val + "-";
        }
      }

      String testString =
          getText(0, offs) + val + getText(offs + numChars, getLength() - (offs + numChars));

      try {
        dateFormatter.parse(testString);
      } catch (Exception e) {
        //				LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        return;
      }

      super.remove(offs, numChars);
      super.insertString(offs, val, attr);

    } else if (val.matches(testRegex)) {
      super.remove(0, getLength());
      super.insertString(getLength(), val, attr);
    }
  }
Beispiel #23
0
  private static void executeJob(String jobId) {
    long execID = 0;
    // ジョブの開始時はXML読み込みなど同時実行されるとおかしくなる処理があるので、ジョブID単位で同期化しておく。
    JobOperator jobOperator = BatchRuntime.getJobOperator();
    synchronized (jobId) {
      Properties props = new Properties();
      props.setProperty(
          "date", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
      execID = jobOperator.start(jobId, props);
      System.out.println("job stated id:" + execID);
    }
    JobExecution jobExec = null;
    // ジョブが終了するまでポーリング
    while (true) {
      jobExec = jobOperator.getJobExecution(execID);

      if (jobExec.getEndTime() != null) {
        break;
      }

      try {
        Thread.sleep(1000L);
      } catch (InterruptedException ex) {
      }
    }
    System.out.println("JOB END:Status is " + jobExec.getExitStatus());
  }
 @Override
 public QuoteResponse getQuote(
     String sender,
     String fromAddress,
     String fromzipcode,
     String fromcity,
     String receiver,
     String toAddress,
     String tozipcode,
     String tocity,
     double height,
     double width,
     double depth,
     double weight,
     String pickupDate) {
   Parcel parcel = new Parcel("parcel_", StatusParcel.UNKNOWN, width, height, depth, weight);
   parcel.idParcel += parcel.dimension.getVolume();
   LocalDateTime date =
       LocalDateTime.parse(pickupDate, DateTimeFormatter.ofPattern("uuuu-MM-dd'_'HH:mm"));
   Quote q =
       new Quote(
           "idquote1234",
           new Company(sender),
           new Address(fromAddress, fromzipcode, fromcity),
           new Company(receiver),
           new Address(toAddress, tozipcode, tocity),
           parcel,
           date);
   q.setIdQuote("idQuote_" + q.getParcel().idParcel);
   daoContractors.addQuote(q);
   return q.calculateQuote();
 }
 private void handleBirthDateChange() {
   String bdateStr = view.bDateFld.getText();
   if (bdateStr == null || bdateStr.trim().equals("")) {
     model.setBirthDate(null);
     view.syncBirthDate();
   } else {
     try {
       DateTimeFormatter formatter = DateTimeFormatter.ofPattern(view.dateFormat);
       LocalDate bdate = LocalDate.parse(bdateStr, formatter);
       List<String> errorList = new ArrayList<>();
       if (model.isValidBirthDate(bdate, errorList)) {
         model.setBirthDate(bdate);
         view.syncAgeCategory();
       } else {
         this.showError(errorList);
         view.syncBirthDate();
       }
     } catch (DateTimeParseException e) {
       // Birth date is not in the specified date format
       List<String> errorList = new ArrayList<>();
       errorList.add("Birth date must be in the " + view.dateFormat.toLowerCase() + " format.");
       this.showError(errorList);
       // Refresh the view
       view.syncBirthDate();
     }
   }
 }
Beispiel #26
0
public class DateSerializer extends Serializer<LocalDate> {

  private static final String STR = "uuuu-MM-dd";
  private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern(STR);

  public static final PgType PGTYPE =
      new PgType.Builder().name("date").oid(1082).arrayId(1182).build();

  public static final DateSerializer instance = new DateSerializer();

  private DateSerializer() {
    super(LocalDate.class);
  }

  public LocalDate fromString(final String str) {
    return LocalDate.parse(str, DATE);
  }

  public LocalDate read(final Stream stream, final int size) {
    return isNull(size) ? null : fromString(str(stream, size, ASCII_ENCODING));
  }

  public int length(final LocalDate d) {
    // yyyy-mm-dd -> 10
    return (d == null) ? NULL_LENGTH : 10;
  }

  public void write(final Stream stream, final LocalDate val) {
    stream.putString(val.format(DATE));
  }
}
Beispiel #27
0
  /** Renders this TransferFile as wikitext for Commons. */
  private String gen() {
    String t = sumSection + licSection;

    t = t.replaceAll("(?s)\\<!\\-\\-.*?\\-\\-\\>", ""); // strip comments
    t = t.replaceAll("(?i)\\n?\\[\\[(Category:).*?\\]\\]", ""); // categories don't transfer well.
    t = t.replaceAll("(?<=\\[\\[)(.+?\\]\\])", "w:$1"); // add enwp prefix to links
    t = t.replaceAll("(?i)\\[\\[(w::|w:w:)", "[[w:"); // Remove any double colons in interwiki links

    // Generate Upload Log Section
    t +=
        "\n== {{Original upload log}} ==\n"
            + String.format(
                "{{Original description page|en.wikipedia|%s}}%n", FString.enc(enwp.nss(wpFN)))
            + "{| class=\"wikitable\"\n! {{int:filehist-datetime}} !! {{int:filehist-dimensions}} !! {{int:filehist-user}} "
            + "!! {{int:filehist-comment}}\n|-\n";

    for (ImageInfo ii : imgInfoL)
      t +=
          String.format(
              uLFmt,
              dtf.format(LocalDateTime.ofInstant(ii.timestamp, ZoneOffset.UTC)),
              ii.dimensions.x,
              ii.dimensions.y,
              ii.user,
              ii.user,
              ii.summary.replace("\n", " "));
    t += "|}\n\n{{Subst:Unc}}";

    if (mtc.useTrackingCat) t += "\n[[Category:Uploaded with MTC!]]";

    return t;
  }
Beispiel #28
0
  public Post(String mensagem, String data) throws SystemException {
    this.valida = new Valida();
    if (!valida.conteudoPost(mensagem)) {
      throw new PostException("Conteudo do post nao pode ser nulo ou vazio.");
    }

    if (separaMensagem(mensagem, "#").length() >= MAXIMO_CARACTERES) {
      throw new PostException(
          "Nao eh possivel criar o post. O limite maximo da mensagem sao 200 caracteres.");
    }

    if (mensagem.contains("#")) {
      String hashtagErro = valida.hashtags(mensagem);
      if (hashtagErro != null) {
        throw new PostException(
            "Nao eh possivel criar o post. As hashtags devem comecar com '#'."
                + " Erro na hashtag: '"
                + hashtagErro
                + "'.");
      }
    }
    formatador = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    this.pops = 0;
    this.mensagem = separaMensagem(mensagem, ("#"));
    this.data = LocalDate.parse(data.substring(0, data.indexOf(" ")), formatador);
    this.hora = LocalTime.parse(data.substring(data.indexOf(" ") + 1));
    this.hashtags = separaHashtags(mensagem);
    this.curtidas = 0;
    adicionaMidia(mensagem);
  }
@Configuration
public class JacksonConfiguration {

  public static final DateTimeFormatter ISO_FIXED_FORMAT =
      DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("Z"));

  public static final DateTimeFormatter ISO_DATE_OPTIONAL_TIME =
      new DateTimeFormatterBuilder()
          .append(DateTimeFormatter.ISO_LOCAL_DATE)
          .optionalStart()
          .appendLiteral('T')
          .append(DateTimeFormatter.ISO_TIME)
          .toFormatter();

  @Autowired private Jackson2ObjectMapperBuilder builder;

  // To be replaced by a Jackson2ObjectMapperBuilderCustomizer in Spring-boot 1.4
  @PostConstruct
  public void postConstruct() {
    this.builder.serializers(new ZonedDateTimeSerializer(ISO_FIXED_FORMAT));
    // Will not be needed anymore with SB 1.4 (Jackson > 2.7.1)
    this.builder.deserializerByType(
        LocalDate.class, new LocalDateDeserializer(ISO_DATE_OPTIONAL_TIME));
  }

  @Bean
  public ObjectMapper jacksonObjectMapper() {
    return this.builder.createXmlMapper(false).build();
  }
}
 @Override
 protected LocalDateTime fromString(String text) {
   DateTimeFormatter dateTimeFormatter = getDateTimeFormatter();
   if (dateTimeFormatter != null) {
     try {
       TemporalAccessor parse = dateTimeFormatter.parse(text);
       try {
         return LocalDateTime.from(parse);
       } catch (DateTimeException e) {
         CommonUtils.ignoreException(e);
       }
     } catch (DateTimeParseException e) {
       CommonUtils.ignoreException(e);
     }
   }
   return super.fromString(text);
 }