List of usage examples for java.time.format DateTimeFormatter ofPattern
public static DateTimeFormatter ofPattern(String pattern)
From source file:controller.UpdateEC.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww .j a v a 2 s .c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); ExtenuatingCircumstance ec = new ExtenuatingCircumstance(); if (ServletFileUpload.isMultipartContent(request)) { try { String fname = StringUtils.EMPTY; String title = StringUtils.EMPTY; String desciption = StringUtils.EMPTY; String status = StringUtils.EMPTY; int id = 0; List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); ArrayList<FileItem> files = new ArrayList<>(); for (FileItem item : multiparts) { if (item.isFormField()) { if (item.getFieldName().equals("id")) { id = Integer.parseInt(item.getString()); System.out.println("id: " + id); } if (item.getFieldName().equals("title")) { title = item.getString(); } if (item.getFieldName().equals("description")) { desciption = item.getString(); } if (item.getFieldName().equals("status")) { status = item.getString(); System.out.println("status: " + status); } } else { if (StringUtils.isNotEmpty(item.getName())) { files.add(item); } } } HttpSession session = request.getSession(false); Account studentAccount = (Account) session.getAttribute("account"); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); LocalDateTime now = LocalDateTime.now(); // insert EC ec.setId(id); ec.setTitle(title); ec.setDescription(desciption); ec.setProcess_status(status); //ec.setSubmitted_date(now.toString()); ec.setAccount(studentAccount.getId()); new ExtenuatingCircumstanceDAO().updateEC(ec, "student"); //insert additional evident evidence if (files.size() > 0) { insertedEvidence(files, now, ec, studentAccount); } request.setAttribute("resultMsg", "updated"); request.getRequestDispatcher("AddNewECResult.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } }
From source file:org.codelibs.fess.service.ClickLogService.java
public void exportCsv(final Writer writer) { final CsvConfig cfg = new CsvConfig(',', '"', '"'); cfg.setEscapeDisabled(false);//from w w w . ja v a 2s . co m cfg.setQuoteDisabled(false); final CsvWriter csvWriter = new CsvWriter(writer, cfg); try { final List<String> list = new ArrayList<String>(); list.add("SearchId"); list.add("URL"); list.add("RequestedTime"); list.add("QueryRequestedTime"); list.add("UserSessionId"); csvWriter.writeValues(list); final DateTimeFormatter formatter = DateTimeFormatter .ofPattern(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND); clickLogBhv.selectCursor(cb -> { cb.setupSelect_SearchLog(); cb.specify().specifySearchLog().columnUserSessionId(); cb.specify().specifySearchLog().columnRequestedTime(); }, new EntityRowHandler<ClickLog>() { @Override public void handle(final ClickLog entity) { final List<String> list = new ArrayList<String>(); addToList(list, entity.getSearchId()); addToList(list, entity.getUrl()); addToList(list, entity.getRequestedTime()); entity.getSearchLog().ifPresent(searchLog -> { addToList(list, searchLog.getRequestedTime()); addToList(list, searchLog.getUserSessionId()); }); try { csvWriter.writeValues(list); } catch (final IOException e) { log.warn("Failed to write a search log: " + entity, e); } } private void addToList(final List<String> list, final Object value) { if (value == null) { list.add(StringUtil.EMPTY); } else if (value instanceof LocalDateTime) { list.add(((LocalDateTime) value).format(formatter)); } else { list.add(value.toString()); } } }); csvWriter.flush(); } catch (final IOException e) { log.warn("Failed to write a search log.", e); } }
From source file:org.cloud.mblog.utils.FileUtil.java
private static String getDateTypeFileName(LocalDateTime date, String suffix) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FILE_UPLOAD_SUB_IMG_DIR_FMT); return date.format(formatter) + "." + suffix; }
From source file:RequestStat.java
private String getDateFromInstant(long start) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd " + "HH:mm:ss") .withZone(ZoneId.systemDefault()); return formatter.format(Instant.ofEpochMilli(start)); }
From source file:org.primeframework.mvc.parameter.convert.converters.ZonedDateTimeConverter.java
protected String objectToString(Object value, Type convertFrom, Map<String, String> attributes, String expression) throws ConversionException, ConverterStateException { String format = attributes.get("dateTimeFormat"); if (format == null) { throw new ConverterStateException("You must provide the dateTimeFormat dynamic attribute for " + "the form fields [" + expression + "] that maps to DateTime properties in the action. " + "If you are using a text field it will look like this: [@jc.text _dateTimeFormat=\"MM/dd/yyyy hh:mm:ss aa Z\"]\n\n" + "NOTE: The format must include the time and a timezone. Otherwise, it will be unparseable"); }/*from ww w.ja va 2 s .c om*/ return ((ZonedDateTime) value).format(DateTimeFormatter.ofPattern(format)); }
From source file:com.intuit.wasabi.api.pagination.filters.FilterUtil.java
/** * Parses a UI date of the format {@code M/d/yZ} (See {@link DateTimeFormatter}) as it is allowed to be * entered in advanced search fields in the UI. Throws a {@link PaginationException} on failure, notifying the user. * * @param dateString the string as received from the UI * @param timeZoneOffset the user's timezone offset * @return a parsed date/*ww w . j a v a 2s. c o m*/ */ public static OffsetDateTime parseUIDate(String dateString, String timeZoneOffset) { try { TemporalAccessor tempAccessor = DateTimeFormatter.ofPattern("M/d/yyyyZ") .parse(dateString + timeZoneOffset); return OffsetDateTime.of(java.time.LocalDate.from(tempAccessor), LocalTime.MIDNIGHT, ZoneOffset.UTC); } catch (DateTimeParseException parseException) { throw new PaginationException( ErrorCode.FILTER_KEY_UNPROCESSABLE, "Wrong format: Can not parse date (" + dateString + ") , must be of " + "format MM/dd/yyyy , e.g. 05/23/2014 or 4/7/2013", parseException); } }
From source file:squash.booking.lambdas.core.PageManagerTest.java
@Before public void beforeTest() throws Exception { fakeCurrentDate = LocalDate.of(2015, 10, 6); fakeCurrentDateString = fakeCurrentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); validDates = new ArrayList<>(); validDates.add(fakeCurrentDateString); validDates.add(fakeCurrentDate.plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); pageManager = new squash.booking.lambdas.core.PageManagerTest.TestPageManager(); pageManager.setCurrentLocalDate(fakeCurrentDate); activeLifecycleState = Optional .of(new ImmutablePair<LifecycleState, Optional<String>>(LifecycleState.ACTIVE, Optional.empty())); mockery = new Mockery(); // Set up mock context mockContext = mockery.mock(Context.class); mockery.checking(new Expectations() { {//from w w w . j a va 2 s.com ignoring(mockContext); } }); // Set up mock logger mockLogger = mockery.mock(LambdaLogger.class); mockery.checking(new Expectations() { { ignoring(mockLogger); } }); // Set up mock booking manager mockBookingManager = mockery.mock(IBookingManager.class); mockery.checking(new Expectations() { { ignoring(mockBookingManager); } }); // Set up mock lifecycle manager mockLifecycleManager = mockery.mock(ILifecycleManager.class); mockery.checking(new Expectations() { { // Some page manager methods query for lifecycle state - return ACTIVE // state by default. allowing(mockLifecycleManager).getLifecycleState(); will(returnValue(activeLifecycleState.get())); ignoring(mockLifecycleManager); } }); websiteBucketName = "websiteBucketName"; pageManager.setS3WebsiteBucketName(websiteBucketName); // Use a single booking for most of the tests court = 5; courtSpan = 1; slot = 12; slotSpan = 1; name = "D.Playerd/F.Playerf"; booking = new Booking(court, courtSpan, slot, slotSpan, name); bookings = new ArrayList<>(); bookings.add(booking); revvingSuffix = "revvingSuffix"; apiGatewayBaseUrl = "apiGatewayBaseUrl"; adminSnsTopicArn = "adminSnsTopicArn"; pageManager.setAdminSnsTopicArn(adminSnsTopicArn); }
From source file:com.blackducksoftware.integration.hub.detect.workflow.project.ProjectNameVersionDecider.java
public NameVersion decideProjectNameVersion(String preferredDetectTools, final List<DetectToolProjectInfo> detectToolProjectInfo) throws DetectUserFriendlyException { Optional<String> decidedProjectName = Optional.empty(); Optional<String> decidedProjectVersion = Optional.empty(); if (StringUtils.isNotBlank(projectVersionOptions.overrideProjectName)) { decidedProjectName = Optional.of(projectVersionOptions.overrideProjectName); }/*from w w w . j a v a 2s . c o m*/ if (StringUtils.isNotBlank(projectVersionOptions.overrideProjectVersionName)) { decidedProjectVersion = Optional.of(projectVersionOptions.overrideProjectVersionName); } Optional<DetectToolProjectInfo> chosenTool = decideToolProjectInfo(preferredDetectTools, detectToolProjectInfo); if (chosenTool.isPresent()) { if (!decidedProjectName.isPresent()) { String suggestedName = chosenTool.get().getSuggestedNameVersion().getName(); if (StringUtils.isNotBlank(suggestedName)) { decidedProjectName = Optional.of(suggestedName); } } if (!decidedProjectVersion.isPresent()) { String suggestedVersion = chosenTool.get().getSuggestedNameVersion().getVersion(); if (StringUtils.isNotBlank(suggestedVersion)) { decidedProjectVersion = Optional.of(suggestedVersion); } } } if (!decidedProjectName.isPresent()) { logger.info("A project name could not be decided. Using the name of the source path."); decidedProjectName = Optional.of(projectVersionOptions.sourcePathName); } if (!decidedProjectVersion.isPresent()) { if ("timestamp".equals(projectVersionOptions.defaultProjectVersionScheme)) { logger.info("A project version name could not be decided. Using the current timestamp."); final String timeformat = projectVersionOptions.defaultProjectVersionFormat; final String timeString = DateTimeFormatter.ofPattern(timeformat).withZone(ZoneOffset.UTC) .format(Instant.now().atZone(ZoneOffset.UTC)); decidedProjectVersion = Optional.of(timeString); } else { logger.info("A project version name could not be decided. Using the default version text."); decidedProjectVersion = Optional.of(projectVersionOptions.defaultProjectVersionText); } } return new NameVersion(decidedProjectName.get(), decidedProjectVersion.get()); }
From source file:org.primeframework.mvc.parameter.convert.converters.ZonedDateTimeConverter.java
private ZonedDateTime toDateTime(String value, String format) { try {/*from w ww . j a va 2 s .c o m*/ return ZonedDateTime.parse(value, DateTimeFormatter.ofPattern(format)); } catch (DateTimeParseException e) { throw new ConversionException("Invalid date [" + value + "] for format [" + format + "]", e); } }
From source file:org.teknux.dropbitz.controller.UploadController.java
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML }) @Authenticated//from w ww . j a va 2 s .com public Response uploadFile(@FormDataParam("file") final InputStream inputStream, @FormDataParam("file") final FormDataContentDisposition formDataContentDisposition, @FormDataParam("name") final String name, @FormDataParam("email") final String email, @FormDataParam("fallback") final Boolean fallback) { String fileName = null; try { fileName = new String(formDataContentDisposition.getFileName().getBytes(CHARSET_ISO_8859_1), CHARSET_UTF8); } catch (UnsupportedEncodingException e) { logger.warn("Can not translate file name charset", e); fileName = formDataContentDisposition.getFileName(); } ; logger.trace("Checking email"); if (!email.isEmpty()) { //validate email if (!EmailValidator.getInstance().isValid(email)) { return getResponse(fallback, Status.INTERNAL_SERVER_ERROR, fileName, i18n(I18nKey.DROP_FILE_EMAIL_ERROR)); } } String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT)); String destFileName = date + (name.isEmpty() ? "" : "-" + name) + "-" + fileName; try { if (formDataContentDisposition.getFileName().isEmpty()) { return getResponse(fallback, Status.BAD_REQUEST, fileName, i18n(I18nKey.DROP_FILE_MISSING)); } Configuration config = getServiceManager().getService(IConfigurationService.class).getConfiguration(); java.nio.file.Path outputPath = FileSystems.getDefault() .getPath(config.getDirectory().getAbsolutePath(), destFileName); //Checks destination directory if (!FileUtil.isChildOfDirectory(outputPath.toFile(), config.getDirectory())) { return getResponse(fallback, Status.FORBIDDEN, fileName, i18n(I18nKey.DROP_FILE_MISSING)); } Files.copy(inputStream, outputPath); long fileSize = outputPath.toFile().length(); sendEmail(true, name, fileName, destFileName, fileSize, email); } catch (IOException e) { logger.error("Can not copy file", e); sendEmail(false, name, fileName, null, 0L, email); return getResponse(fallback, Status.INTERNAL_SERVER_ERROR, fileName, i18n(I18nKey.DROP_FILE_ERROR)); } return getResponse(fallback, Status.OK, fileName, null); }