org.joda.time.format.ISODateTimeFormat Java Examples

The following examples show how to use org.joda.time.format.ISODateTimeFormat. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VectorOutput.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTimestamp(boolean isNull) throws IOException {
  TimeStampMilliWriter ts = writer.timeStampMilli();
  if(!isNull){
    switch (parser.getCurrentToken()) {
    case VALUE_NUMBER_INT:
      LocalDateTime dt = new LocalDateTime(parser.getLongValue(), org.joda.time.DateTimeZone.UTC);
      ts.writeTimeStampMilli(com.dremio.common.util.DateTimes.toMillis(dt));
      break;
    case VALUE_STRING:
      DateTimeFormatter f = ISODateTimeFormat.dateTime();
      ts.writeTimeStampMilli(com.dremio.common.util.DateTimes.toMillis(LocalDateTime.parse(parser.getValueAsString(), f)));
      break;
    default:
      throw UserException.unsupportedError()
          .message(parser.getCurrentToken().toString())
          .build(LOG);
    }
  }
}
 
Example #2
Source File: Partial.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets a formatter suitable for the fields in this partial.
 * <p>
 * If there is no appropriate ISO format, null is returned.
 * This method may return a formatter that does not display all the
 * fields of the partial. This might occur when you have overlapping
 * fields, such as dayOfWeek and dayOfMonth.
 *
 * @return a formatter suitable for the fields in this partial, null
 *  if none is suitable
 */
public DateTimeFormatter getFormatter() {
    DateTimeFormatter[] f = iFormatter;
    if (f == null) {
        if (size() == 0) {
            return null;
        }
        f = new DateTimeFormatter[2];
        try {
            List<DateTimeFieldType> list = new ArrayList<DateTimeFieldType>(Arrays.asList(iTypes));
            f[0] = ISODateTimeFormat.forFields(list, true, false);
            if (list.size() == 0) {
                f[1] = f[0];
            }
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        iFormatter = f;
    }
    return f[0];
}
 
Example #3
Source File: ElasticsearchSpewer.java    From datashare with GNU Affero General Public License v3.0 6 votes vote down vote up
Map<String, Object> getDocumentMap(TikaDocument document) throws IOException {
    Map<String, Object> jsonDocument = new HashMap<>();

    jsonDocument.put(esCfg.docTypeField, ES_DOCUMENT_TYPE);
    jsonDocument.put(esCfg.indexJoinField, new HashMap<String, String>() {{
        put("name", "Document");
    }});
    jsonDocument.put("path", document.getPath().toString());
    jsonDocument.put("dirname", ofNullable(document.getPath().getParent()).orElse(get("")).toString());
    jsonDocument.put("status", "INDEXED");
    jsonDocument.put("nerTags", new HashSet<>());
    jsonDocument.put("tags", new HashSet<>());
    jsonDocument.put("extractionDate", ISODateTimeFormat.dateTime().print(new Date().getTime()));
    jsonDocument.put("metadata", getMetadata(document));
    jsonDocument.put("contentType", ofNullable(document.getMetadata().get(CONTENT_TYPE)).orElse(DEFAULT_VALUE_UNKNOWN).split(";")[0]);
    jsonDocument.put("contentLength", valueOf(ofNullable(document.getMetadata().get(CONTENT_LENGTH)).orElse("-1")));
    jsonDocument.put("contentEncoding", ofNullable(document.getMetadata().get(CONTENT_ENCODING)).orElse(DEFAULT_VALUE_UNKNOWN));

    String content = toString(document.getReader()).trim();
    jsonDocument.put("language", languageGuesser.guess(content));
    jsonDocument.put(ES_CONTENT_FIELD, content);
    return jsonDocument;
}
 
Example #4
Source File: UnboundedWrite.java    From components with Apache License 2.0 6 votes vote down vote up
@ProcessElement
public void processElement(ProcessContext c) throws Exception {
    KV<Instant, Iterable<KV<K, V>>> kv = c.element();

    // Create a writer on the sink and use it brutally to write all records to one file.
    Sink.Writer<KV<K, V>, ?> writer = sink.createWriteOperation().createWriter(c.getPipelineOptions());
    writer.open(UUID.randomUUID().toString());
    for (KV<K, V> v : kv.getValue())
        writer.write(v);

    // Use the write result to move the file to the expected output name.
    Object writeResult = writer.close();
    if (writer instanceof ConfigurableHDFSFileSink.HDFSWriter) {
        String attemptResultName = String.valueOf(writeResult);
        String timeslice = ISODateTimeFormat.basicDateTime().print(kv.getKey().getMillis());
        String resultName = "output-" + timeslice + "-" + timeslice + "-00001-of-00001";

        ((ConfigurableHDFSFileSink.HDFSWriter) writer).commitManually(attemptResultName, resultName);
    }
}
 
Example #5
Source File: TimeUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getDateTimeWithTimezoneConversion(Date dateToConvert) {
    if (dateToConvert == null) {
        return null;
    }
    DateTime dt = new DateTime(dateToConvert);
    DateTimeFormatter fmt = ISODateTimeFormat.yearMonthDay();
    DateTimeFormatter fmtTime = ISODateTimeFormat.hourMinuteSecond();

    // If the client browser is in a different timezone than server, need to modify date
    if (m_client_timezone !=null && m_server_timezone!=null && !m_client_timezone.hasSameRules(m_server_timezone)) {
      DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(m_client_timezone);
      fmt = fmt.withZone(dateTimeZone);
      fmtTime = fmtTime.withZone(dateTimeZone);
    }
    return dt.toString(fmt) + " " + dt.toString(fmtTime);
}
 
Example #6
Source File: KuduTableProperties.java    From presto with Apache License 2.0 6 votes vote down vote up
private static long toUnixTimeMicros(Object obj, Type type, String name)
{
    if (Number.class.isAssignableFrom(obj.getClass())) {
        return ((Number) obj).longValue();
    }
    else if (obj instanceof String) {
        String s = (String) obj;
        s = s.trim().replace(' ', 'T');
        long millis = ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC).parseMillis(s);
        return millis * 1000;
    }
    else {
        handleInvalidValue(name, type, obj);
        return 0;
    }
}
 
Example #7
Source File: Time_18_GJChronology_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets a debugging toString.
 * 
 * @return a debugging string
 */
public String toString() {
    StringBuffer sb = new StringBuffer(60);
    sb.append("GJChronology");
    sb.append('[');
    sb.append(getZone().getID());
    
    if (iCutoverMillis != DEFAULT_CUTOVER.getMillis()) {
        sb.append(",cutover=");
        DateTimeFormatter printer;
        if (withUTC().dayOfYear().remainder(iCutoverMillis) == 0) {
            printer = ISODateTimeFormat.date();
        } else {
            printer = ISODateTimeFormat.dateTime();
        }
        printer.withChronology(withUTC()).printTo(sb, iCutoverMillis);
    }
    
    if (getMinimumDaysInFirstWeek() != 4) {
        sb.append(",mdfw=");
        sb.append(getMinimumDaysInFirstWeek());
    }
    sb.append(']');
    
    return sb.toString();
}
 
Example #8
Source File: EventActivityBuilder.java    From BotServiceStressToolkit with MIT License 6 votes vote down vote up
public static Event build(JsonObject channeldata, String name, Member from,
		Member recipient, String channelId, String serviceUrl, String conversationId) {
	Event event = new Event();
	event.setType(Event.EVENT_TYPE);
	event.setChanneldata(channeldata);
	event.setName(name);
	event.setFrom(from);

	event.setTimestamp(
			ISODateTimeFormat.dateHourMinuteSecondMillis().withZoneUTC().print(System.currentTimeMillis()));
	event.setTimestamp(ISODateTimeFormat.dateHourMinuteSecondMillis().withZone(DateTimeZone.forOffsetHours(-3))
			.print(System.currentTimeMillis()));

	event.setRecipient(recipient);
	event.setConversation(new Conversation(conversationId));
	event.setServiceUrl(serviceUrl);
	event.setChannelId(channelId);
	
	setActivityProperties(event);
	
	return event;
}
 
Example #9
Source File: Time_2_Partial_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets a formatter suitable for the fields in this partial.
 * <p>
 * If there is no appropriate ISO format, null is returned.
 * This method may return a formatter that does not display all the
 * fields of the partial. This might occur when you have overlapping
 * fields, such as dayOfWeek and dayOfMonth.
 *
 * @return a formatter suitable for the fields in this partial, null
 *  if none is suitable
 */
public DateTimeFormatter getFormatter() {
    DateTimeFormatter[] f = iFormatter;
    if (f == null) {
        if (size() == 0) {
            return null;
        }
        f = new DateTimeFormatter[2];
        try {
            List<DateTimeFieldType> list = new ArrayList<DateTimeFieldType>(Arrays.asList(iTypes));
            f[0] = ISODateTimeFormat.forFields(list, true, false);
            if (list.size() == 0) {
                f[1] = f[0];
            }
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        iFormatter = f;
    }
    return f[0];
}
 
Example #10
Source File: Nopol2017_0090_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets a formatter suitable for the fields in this partial.
 * <p>
 * If there is no appropriate ISO format, null is returned.
 * This method may return a formatter that does not display all the
 * fields of the partial. This might occur when you have overlapping
 * fields, such as dayOfWeek and dayOfMonth.
 *
 * @return a formatter suitable for the fields in this partial, null
 *  if none is suitable
 */
public DateTimeFormatter getFormatter() {
    DateTimeFormatter[] f = iFormatter;
    if (f == null) {
        if (size() == 0) {
            return null;
        }
        f = new DateTimeFormatter[2];
        try {
            List<DateTimeFieldType> list = new ArrayList<DateTimeFieldType>(Arrays.asList(iTypes));
            f[0] = ISODateTimeFormat.forFields(list, true, false);
            if (list.size() == 0) {
                f[1] = f[0];
            }
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        iFormatter = f;
    }
    return f[0];
}
 
Example #11
Source File: patch1-Time-4-Nopol2017_patch1-Time-4-Nopol2017_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets a formatter suitable for the fields in this partial.
 * <p>
 * If there is no appropriate ISO format, null is returned.
 * This method may return a formatter that does not display all the
 * fields of the partial. This might occur when you have overlapping
 * fields, such as dayOfWeek and dayOfMonth.
 *
 * @return a formatter suitable for the fields in this partial, null
 *  if none is suitable
 */
public DateTimeFormatter getFormatter() {
    DateTimeFormatter[] f = iFormatter;
    if (f == null) {
        if (size() == 0) {
            return null;
        }
        f = new DateTimeFormatter[2];
        try {
            List<DateTimeFieldType> list = new ArrayList<DateTimeFieldType>(Arrays.asList(iTypes));
            f[0] = ISODateTimeFormat.forFields(list, true, false);
            if (list.size() == 0) {
                f[1] = f[0];
            }
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        iFormatter = f;
    }
    return f[0];
}
 
Example #12
Source File: FmtDateTimeTest.java    From super-csv with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	formatter = ISODateTimeFormat.dateTime();
	processor1 = new FmtDateTime();
	processor2 = new FmtDateTime(formatter);
	processor3 = new FmtDateTime(DATE_TIME_FORMAT);
	processor4 = new FmtDateTime(DATE_TIME_FORMAT, Locale.ENGLISH);
	processorChain1 = new FmtDateTime(new IdentityTransform());
	processorChain2 = new FmtDateTime(formatter, new IdentityTransform());
	processorChain3 = new FmtDateTime(DATE_TIME_FORMAT,
			new IdentityTransform());
	processorChain4 = new FmtDateTime(DATE_TIME_FORMAT, Locale.ENGLISH,
			new IdentityTransform());
	processors = Arrays.asList(processor1, processor2, processor3,
			processor4, processorChain1, processorChain2, processorChain3,
			processorChain4);
}
 
Example #13
Source File: Time_4_Partial_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Gets a formatter suitable for the fields in this partial.
 * <p>
 * If there is no appropriate ISO format, null is returned.
 * This method may return a formatter that does not display all the
 * fields of the partial. This might occur when you have overlapping
 * fields, such as dayOfWeek and dayOfMonth.
 *
 * @return a formatter suitable for the fields in this partial, null
 *  if none is suitable
 */
public DateTimeFormatter getFormatter() {
    DateTimeFormatter[] f = iFormatter;
    if (f == null) {
        if (size() == 0) {
            return null;
        }
        f = new DateTimeFormatter[2];
        try {
            List<DateTimeFieldType> list = new ArrayList<DateTimeFieldType>(Arrays.asList(iTypes));
            f[0] = ISODateTimeFormat.forFields(list, true, false);
            if (list.size() == 0) {
                f[1] = f[0];
            }
        } catch (IllegalArgumentException ex) {
            // ignore
        }
        iFormatter = f;
    }
    return f[0];
}
 
Example #14
Source File: StorageAdminAPI.java    From chipster with MIT License 5 votes vote down vote up
public void onChipsterMessage(ChipsterMessage msg) {
	ParameterMessage resultMessage = (ParameterMessage) msg;

	String usernamesString =  resultMessage.getNamedParameter(ParameterMessage.PARAMETER_USERNAME_LIST);
	String namesString = resultMessage.getNamedParameter(ParameterMessage.PARAMETER_SESSION_NAME_LIST);
	String sizesString = resultMessage.getNamedParameter(ParameterMessage.PARAMETER_SIZE_LIST);
	String datesString = resultMessage.getNamedParameter(ParameterMessage.PARAMETER_DATE_LIST);
	String idsString = resultMessage.getNamedParameter(ParameterMessage.PARAMETER_SESSION_UUID_LIST);
	String quotaString = resultMessage.getNamedParameter(ParameterMessage.PARAMETER_QUOTA);
	String quotaWarningString = resultMessage.getNamedParameter(ParameterMessage.PARAMETER_QUOTA_WARNING);
	String storageUsageString = resultMessage.getNamedParameter(ParameterMessage.PARAMETER_SIZE);
	
	String[] usernames = Strings.splitUnlessEmpty(usernamesString, "\t");
	String[] names = Strings.splitUnlessEmpty(namesString, "\t");
	String[] sizes = Strings.splitUnlessEmpty(sizesString, "\t");
	String[] dates = Strings.splitUnlessEmpty(datesString, "\t");
	String[] ids = Strings.splitUnlessEmpty(idsString, "\t");
	
	DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime();
	entries = new LinkedList<StorageEntry>();
	for (int i = 0; i < names.length; i++) {

		StorageEntry entry = new StorageEntry();
		entry.setDate(dateTimeFormatter.parseDateTime(dates[i]).toDate());
		entry.setUsername(usernames[i]);
		entry.setSize(Long.parseLong(sizes[i]));
		entry.setName(names[i]);
		entry.setID(ids[i]);
		entries.add(entry);
	}
	
	quota = Long.parseLong(quotaString);
	quotaWarning = Long.parseLong(quotaWarningString);
	storageUsage = Long.parseLong(storageUsageString);

	latch.countDown();
}
 
Example #15
Source File: LocalOnlineApplication.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public String startProcess(String name, String owner, DateTime date, DateTime creationDate,
        OnlineWorkflowStartParameters start, OnlineWorkflowParameters params, DateTime[] basecases, int numThreads)
                throws Exception {
    Objects.requireNonNull(date);
    Objects.requireNonNull(creationDate);
    Objects.requireNonNull(params);
    Objects.requireNonNull(basecases);
    config = OnlineConfig.load();
    OnlineDb onlineDb = config.getOnlineDbFactoryClass().newInstance().create();
    String processId = DateTimeFormat.forPattern("yyyyMMddHHmmSSS").print(new DateTime());
    LOGGER.info("Starting process: " + processId);
    OnlineProcess proc = new OnlineProcess(processId, name, owner, params.getCaseType().toString(), date, creationDate);

    ExecutorService taskExecutor = Executors.newFixedThreadPool(numThreads);
    List<Callable<Void>> tasks = new ArrayList<>(numThreads);

    for (DateTime basecase : basecases) {
        tasks.add(new Callable() {
            @Override
            public Object call() throws Exception {
                OnlineWorkflowParameters pars = new OnlineWorkflowParameters(basecase, params.getStates(), params.getHistoInterval(), params.getOfflineWorkflowId(), params.getTimeHorizon(), params.getFeAnalysisId(), params.getRulesPurityThreshold(), params.storeStates(), params.analyseBasecase(), params.validation(), params.getSecurityIndexes(), params.getCaseType(), params.getCountries(), params.isMergeOptimized(), params.getLimitReduction(), params.isHandleViolationsInN(), params.getConstraintMargin());
                String workflowId = startWorkflow(start, pars);
                org.joda.time.format.DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                String basecaseString = fmt.print(basecase);
                proc.addWorkflow(basecaseString, workflowId);
                return workflowId;
            } });

    }
    taskExecutor.invokeAll(tasks);
    taskExecutor.shutdown();

    onlineDb.storeProcess(proc);
    LOGGER.info("End of process: " + processId);
    return processId;
}
 
Example #16
Source File: ParseLocalDateTest.java    From super-csv with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	formatter = ISODateTimeFormat.localDateParser();
	processor1 = new ParseLocalDate();
	processor2 = new ParseLocalDate(formatter);
	processorChain1 = new ParseLocalDate(new IdentityTransform());
	processorChain2 = new ParseLocalDate(formatter, new IdentityTransform());
	processors = Arrays.asList(processor1, processor2, processorChain1,
			processorChain2);
}
 
Example #17
Source File: DateTimeDeserializer.java    From chronos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public DateTime deserialize(JsonParser p, DeserializationContext ctxt)
  throws IOException, JsonProcessingException {
  String dt = p.getText();
  return ISODateTimeFormat.dateTimeParser()
          .parseDateTime(dt).withZone(DateTimeZone.UTC);
}
 
Example #18
Source File: GitLabManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public static java.util.Date convertStringToDate(String isoDate) {
	
	isoDate = isoDate.replaceAll("\"", "");
	DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
	DateTime date = parser.parseDateTime(isoDate);
	return date.toDate();
}
 
Example #19
Source File: StringColumnInstantMapper.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
public String toNonNullValue(Instant value) {

    String formatted = ISODateTimeFormat.dateTime().print(value);
    if (formatted.endsWith(".000Z")) {
        formatted = formatted.substring(0, formatted.length() - 5) + "Z";
    }
    return formatted;
}
 
Example #20
Source File: Times.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
public static DateTime decodeDateTime(String string) {
    if (Strings.isNullOrEmpty(string)) {
        return null;
    }
    if (string.contains("+") || Pattern.matches("-\\d", string) || string.contains(Z) || string.contains("z")) {
        return ISODateTimeFormat.dateOptionalTimeParser().withOffsetParsed().parseDateTime(string);
    } else {
        return ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC).parseDateTime(string);
    }
}
 
Example #21
Source File: DateTimeUtil.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
private static DateTimeFormatter getDataTimeFormater() {
  if (DATE_TIME_FORMATER == null) {
    DATE_TIME_FORMATER = ISODateTimeFormat.dateTimeParser().withZone(JVM_DEFAULT_DATE_TIME_ZONE);
  }

  return DATE_TIME_FORMATER;
}
 
Example #22
Source File: GitLabComment.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private static java.util.Date convertStringToDate(String isoDate) {
	
	isoDate = isoDate.replaceAll("\"", "");
	DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
	DateTime date = parser.parseDateTime(isoDate);
	return date.toDate();
}
 
Example #23
Source File: MonthDay.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Output the month-day in ISO8601 format (--MM-dd).
 *
 * @return ISO8601 time formatted string.
 */
@ToString
public String toString() {
    List<DateTimeFieldType> fields = new ArrayList<DateTimeFieldType>();
    fields.add(DateTimeFieldType.monthOfYear());
    fields.add(DateTimeFieldType.dayOfMonth());
    return ISODateTimeFormat.forFields(fields, true, true).print(this);
}
 
Example #24
Source File: TestJodaTime.java    From jdit with MIT License 5 votes vote down vote up
@Test
public void testDateTimeParameter() {
    DateTime dateTime = ISODateTimeFormat.date().withZoneUTC().parseDateTime("1991-04-01");
    List<Player> players = playerDao.getPlayersBornAfter(dateTime);
    assertThat(players)
            .hasSize(3)
            .extracting(p -> p.birthDate)
            .allSatisfy(d -> d.after(dateTime.toDate()));
}
 
Example #25
Source File: IotHubClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
public QueryEndpointDailyMqttUsageResponse queryEndpointDailyMqttUsage(QueryEndpointDailyMqttUsageRequest request) {
    checkNotNull(request.getEndpointName(), "endpointName should not be null");
    checkNotNull(request.getStart(), "start should not be null");
    checkNotNull(request.getEnd(), "end should not be null");
    InternalRequest internalRequest = createRequest(request, HttpMethodName.POST, ENDPOINT,
            request.getEndpointName(), USAGE_QUERY);
    internalRequest.addParameter(START, ISODateTimeFormat.date().print(request.getStart()));
    internalRequest.addParameter(END, ISODateTimeFormat.date().print(request.getEnd()));
    return this.invokeHttpClient(internalRequest, QueryEndpointDailyMqttUsageResponse.class);
}
 
Example #26
Source File: DerbyMetadataServer.java    From chipster with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<String>[] getStorageUsageOfSessions(String username) throws SQLException {
	
	PreparedStatement ps = connection.prepareStatement(SQL_LIST_STORAGE_USAGE_OF_SESSIONS);
	ps.setString(1, username);
	ResultSet rs = ps.executeQuery();
	
	LinkedList<String> usernames = new LinkedList<String>();
	LinkedList<String> sessions = new LinkedList<String>();
	LinkedList<String> sizes = new LinkedList<String>();
	LinkedList<String> dates = new LinkedList<String>();
	LinkedList<String> ids = new LinkedList<String>();

	
	DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTime();
	
	while (rs.next()) {
		String user = rs.getString("username");
		String session = rs.getString("name");
		String size = rs.getString("size");
		String id = rs.getString("uuid");
		DateTime date = new DateTime(rs.getTimestamp("date"));
		usernames.add(user);
		sessions.add(session);
		sizes.add(size);
		ids.add(id);
		dates.add(dateTimeFormatter.print(date));
	}

	return new List[] { usernames, sessions, sizes, dates, ids };
}
 
Example #27
Source File: AssertionMarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void marshallAttributes(XMLObject samlElement, Element domElement) throws MarshallingException {

    Assertion assertion = (Assertion) samlElement;

    if (assertion.getID() != null) {
        domElement.setAttributeNS(null, Assertion.ID_ATTRIB_NAME, assertion.getID());
        if (assertion.getMinorVersion() != 0) {
            domElement.setIdAttributeNS(null, Assertion.ID_ATTRIB_NAME, true);
        }
    }

    if (assertion.getIssuer() != null) {
        domElement.setAttributeNS(null, Assertion.ISSUER_ATTRIB_NAME, assertion.getIssuer());
    }

    if (assertion.getIssueInstant() != null) {
        String date = ISODateTimeFormat.dateTime().print(assertion.getIssueInstant());
        domElement.setAttributeNS(null, Assertion.ISSUEINSTANT_ATTRIB_NAME, date);
    }

    domElement.setAttributeNS(null, Assertion.MAJORVERSION_ATTRIB_NAME, "1");
    if (assertion.getMinorVersion() == 0) {
        domElement.setAttributeNS(null, Assertion.MINORVERSION_ATTRIB_NAME, "0");
    } else {
        domElement.setAttributeNS(null, Assertion.MINORVERSION_ATTRIB_NAME, "1");
    }
}
 
Example #28
Source File: SoapTransportCommandProcessorTest.java    From cougar with Apache License 2.0 5 votes vote down vote up
/**
 * Tests List and Date parameters in and out
 * @throws Exception
 */
@Test
public void testProcess_ListDate() throws Exception {
	// Set up the input
	when(request.getInputStream()).thenReturn(
			new TestServletInputStream(buildSoapMessage(null, listOpIn, null, null)));
       when(request.getScheme()).thenReturn("http");

	// Resolve the input command
	soapCommandProcessor.process(command);
	assertEquals(1, ev.getInvokedCount());

	DateTimeFormatter xmlFormat = ISODateTimeFormat.dateTimeParser();

	// Assert that we resolved the expected arguments
	Object[] args = ev.getArgs();
	assertNotNull(args);
	assertEquals(1, args.length);
	List<Date> listArg = (List<Date>)args[0];
	assertEquals(2, listArg.size());
	assertEquals(xmlFormat.parseDateTime("248556211-09-30T12:12:53.297+01:00").toDate(), listArg.get(0));
	assertEquals(xmlFormat.parseDateTime("248556211-09-30T12:12:53.297Z").toDate(), listArg.get(1));

	// Assert that the expected result is sent
	assertNotNull(ev.getObserver());
	List<Date> response = new ArrayList<Date>();
	response.add(xmlFormat.parseDateTime("248556211-09-30T12:12:53.297+01:00").toDate());
	response.add(xmlFormat.parseDateTime("248556211-09-30T12:12:53.297Z").toDate());

	ev.getObserver().onResult(new ExecutionResult(response));
	assertEquals(CommandStatus.Complete, command.getStatus());
	assertSoapyEquals(buildSoapMessage(null, listOpOut, null, null), testOut.getOutput());
       verify(logger).logAccess(eq(command), isA(ExecutionContext.class), anyLong(), anyLong(),
                                           any(MediaType.class), any(MediaType.class), any(ResponseCode.class));

       verifyTracerCalls(listOpKey);
}
 
Example #29
Source File: JSON.java    From java with Apache License 2.0 5 votes vote down vote up
@Override
public void write(JsonWriter out, Date date) throws IOException {
    if (date == null) {
        out.nullValue();
    } else {
        String value;
        if (dateFormat != null) {
            value = dateFormat.format(date);
        } else {
            value = ISODateTimeFormat.basicDateTime().print(date.getTime());
        }
        out.value(value);
    }
}
 
Example #30
Source File: AmforeasUtils.java    From amforeas with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check if a string has the ISO date time format. Uses the ISODateTimeFormat.dateTime() from JodaTime
 * and returns a DateTime instance. The correct format is yyyy-MM-ddTHH:mm:ss.SSSZ
 * @param arg the string to check
 * @return a DateTime instance if the string is in the correct ISO format.
 */
public static DateTime isDateTime (final String arg) {
    if (arg == null)
        return null;
    DateTimeFormatter f = ISODateTimeFormat.dateTime();
    DateTime ret = null;
    try {
        ret = f.parseDateTime(arg);
    } catch (IllegalArgumentException e) {
        l.debug("{} is not a valid ISO DateTime", arg);
    }
    return ret;
}