Java Code Examples for java.text.ParseException#getErrorOffset()

The following examples show how to use java.text.ParseException#getErrorOffset() . 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: ValueMetaBase.java    From hop with Apache License 2.0 6 votes vote down vote up
public synchronized Date convertStringToDate( String string ) throws HopValueException {
  string = Const.trimToType( string, getTrimType() ); // see if trimming needs
  // to be performed before
  // conversion

  if ( Utils.isEmpty( string ) ) {
    return null;
  }

  try {
    ParsePosition pp = new ParsePosition( 0 );
    Date result = getDateFormat( TYPE_DATE ).parse( string, pp );
    if ( pp.getErrorIndex() >= 0 ) {
      // error happen
      throw new ParseException( string, pp.getErrorIndex() );
    }
    // some chars can be after pp.getIndex(). That means, not full value was parsed. For example, for value
    // "25-03-1918 11:54" and format "dd-MM-yyyy", value will be "25-03-1918 00:00" without any exception.
    // If there are only spaces after pp.getIndex() - that means full values was parsed
    return result;
  } catch ( ParseException e ) {
    String dateFormat = ( getDateFormat() != null ) ? getDateFormat().toPattern() : "null";
    throw new HopValueException( toString() + " : couldn't convert string [" + string
      + "] to a date using format [" + dateFormat + "] on offset location " + e.getErrorOffset(), e );
  }
}
 
Example 2
Source File: DateUtil.java    From wasindoor with Apache License 2.0 6 votes vote down vote up
/**
 * This method converts a String to a date using the datePattern
 * 
 * @param strDate
 *            the date to convert (in format MM/dd/yyyy)
 * @return a date object
 * 
 * @throws ParseException
 */
public static Date convertStringToDate(String strDate)
		throws ParseException {
	Date aDate = null;

	try {

		aDate = convertStringToDate(getDatePattern(), strDate);
	} catch (ParseException pe) {

		pe.printStackTrace();
		throw new ParseException(pe.getMessage(), pe.getErrorOffset());
	}

	return aDate;
}
 
Example 3
Source File: ValueMetaBase.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
protected synchronized Date convertStringToDate( String string ) throws KettleValueException {
  string = Const.trimToType( string, getTrimType() ); // see if trimming needs
  // to be performed before
  // conversion

  if ( Utils.isEmpty( string ) ) {
    return null;
  }

  try {
    ParsePosition pp = new ParsePosition( 0 );
    Date result = getDateFormat( TYPE_DATE ).parse( string, pp );
    if ( pp.getErrorIndex() >= 0 ) {
      // error happen
      throw new ParseException( string, pp.getErrorIndex() );
    }
    // some chars can be after pp.getIndex(). That means, not full value was parsed. For example, for value
    // "25-03-1918 11:54" and format "dd-MM-yyyy", value will be "25-03-1918 00:00" without any exception.
    // If there are only spaces after pp.getIndex() - that means full values was parsed
    return result;
  } catch ( ParseException e ) {
    String dateFormat = ( getDateFormat() != null ) ? getDateFormat().toPattern() : "null";
    throw new KettleValueException( toString() + " : couldn't convert string [" + string
        + "] to a date using format [" + dateFormat + "] on offset location " + e.getErrorOffset(), e );
  }
}
 
Example 4
Source File: EventQueryServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Parses the string to create a date object
 */
private Date getDateFromString(String dateString) throws ParseException {

	try {
		Date date = df.parse(dateString);
		return date;
	} catch (ParseException e) {
		log.warn("Date format should be yyyy-MM-dd HH:mm:ss");
		throw new ParseException("Date format should be yyyy-MM-dd HH:mm:ss",e.getErrorOffset());
	}

}
 
Example 5
Source File: ManifestHeaderValue.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
public static void writeParseException(PrintStream out, String source, ParseException e) {
    out.println(e.getMessage());
    out.print("   " + source + "\n   ");
    for (int i = 0; i < e.getErrorOffset(); i++) {
        out.print(' ');
    }
    out.println('^');
}
 
Example 6
Source File: EventQueryServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Parses the string to create a date object
 */
private Date getDateFromString(String dateString) throws ParseException {

	try {
		Date date = df.parse(dateString);
		return date;
	} catch (ParseException e) {
		log.warn("Date format should be yyyy-MM-dd HH:mm:ss");
		throw new ParseException("Date format should be yyyy-MM-dd HH:mm:ss",e.getErrorOffset());
	}

}
 
Example 7
Source File: Launcher.java    From bluima with Apache License 2.0 5 votes vote down vote up
/**
 * Parse this pipeline and run it
 * 
 * @return true if no error during processing
 * @throws ParseException
 */
public static void runPipeline(File scriptFile, List<String> cliArgs)
        throws IOException, UIMAException, ParseException {
    if (!scriptFile.exists()) {
        throw new IOException("Script file does not exist ("
                + scriptFile.getAbsolutePath() + ")");
    }

    LOG.info("Parsing pipeline script at '{}'",
            scriptFile.getAbsolutePath() + " \n with CLI parameters: "
                    + join(cliArgs, ", "));
    Pipeline pipeline = null;
    try {
        pipeline = PipelineScriptParser.parse(scriptFile, cliArgs);
    } catch (ParseException e) {
        throw new ParseException("\nERROR parsing '" + scriptFile.getName()
                + "'\n" + e.getMessage()
                + "\n(see the README.txt for the pipeline script format)",
                e.getErrorOffset());
    }

    LOG.info("Successfully parsed pipeline script, now starting pipeline...");
    LOG.info("*************************************************************");
    pipeline.run();
    // will be printed if no exception.
    // used in pipeline tests, do not change
    System.out.println(OK_MESSAGE);
}
 
Example 8
Source File: ExpressionBuilder.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Validates the current script.
 * 
 * @return <code>true</code> if no error was found, <code>false</code>
 *         otherwise.
 */
protected boolean validateScript( )
{
	if ( sourceViewer == null )
	{
		return false;
	}

	String errorMessage = null;

	try
	{
		new ScriptValidator( sourceViewer ).validate( true, true );
		setMessage( Messages.getString( "ExpressionBuilder.Script.NoError" ), IMessageProvider.INFORMATION ); //$NON-NLS-1$
		return true;
	}
	catch ( ParseException e )
	{
		int offset = e.getErrorOffset( );
		int row = sourceViewer.getTextWidget( ).getLineAtOffset( offset ) + 1;
		int column = offset
				- sourceViewer.getTextWidget( ).getOffsetAtLine( row - 1 )
				+ 1;

		errorMessage = Messages.getFormattedString( "ExpressionBuilder.Script.Error", new Object[]{Integer.toString( row ), Integer.toString( column ), e.getLocalizedMessage( )} ); //$NON-NLS-1$
		return false;
	}
	finally
	{
		setErrorMessage( errorMessage );
	}
}
 
Example 9
Source File: Rabbitify.java    From bluima with Apache License 2.0 4 votes vote down vote up
/**
 * @param scriptFile
 *            script file, separated with {@link Rabbitify#BEGIN_RABBITIFY}
 *            and {@link Rabbitify#END_RABBITIFY}
 * @param replacementVars
 *            see {@link PipelineScriptParser#parse()}
 * 
 * @param mode
 *            either sender (the first part of the pipeline), slave (the
 *            middle part of a pipeline) or receiver (the last part of a
 *            pipeline)
 * @param runId
 *            gets used to name the rabbit queues, use 'test' for testing
 * @param timeout
 *            how long to wait (in seconds) before the reader exits the
 *            queue
 */
public static void run(File scriptFile, String[] replacementVars,
        Mode mode, String runId, int timeout) throws IOException,
        ParseException, UIMAException {
    LOG.info("Rabbitifying pipeline script at '{}'",
            scriptFile.getAbsolutePath() + " \n with CLI parameters: "
                    + join(replacementVars, ", "));

    // SPLITTING PIPELINE
    final String pipelineLines = asText(scriptFile);
    checkArgument(pipelineLines.length() > 2);
    // in 3 parts
    final List<String> masterSender, slave, masterReceiver;
    String[] split1 = pipelineLines.split(BEGIN_RABBITIFY);
    checkEquals(2, split1.length);
    masterSender = list(split1[0].split("\n"));
    String[] split2 = split1[1].split(END_RABBITIFY);
    checkEquals(2, split1.length);
    slave = list(split2[0].split("\n"));
    masterReceiver = list(split2[1].split("\n"));

    // preparing script lines
    List<String> lines = list();
    if (mode.equals(sender)) {// MASTER_SENDER PIPELINE

        lines = masterSender;

        // add Rabbit writer
        lines.add("");
        lines.add("ae: " + RabbitWriter.class.getName());
        lines.add(" " + PARAM_QUEUE + ": "
                + getMasterToSlaveQueue(runId + ""));

        lines.add("ae: StatsAnnotatorPlus");
        lines.add(" printEvery__java: 1000");

    } else if (mode.equals(Mode.slave)) { // SLAVE PIPELINE

        // add Rabbit reader
        lines.add("cr: " + RabbitReader.class.getName());
        lines.add(" " + PARAM_QUEUE + ": "
                + getMasterToSlaveQueue(runId + ""));
        lines.add(" " + PARAM_TIMEOUT + "__java: " + timeout);

        lines.add("");
        lines.addAll(slave);
        lines.add("");

        // add Rabbit writer
        lines.add("ae: " + RabbitWriter.class.getName());
        lines.add(" " + PARAM_QUEUE + ": "
                + getSlaveToMasterQueue(runId + ""));

    } else if (mode.equals(receiver)) {// MASTER_RECEIVER PIPELINE

        // add Rabbit reader
        lines.add("cr: " + RabbitReader.class.getName());
        lines.add(" " + PARAM_QUEUE + ": "
                + getSlaveToMasterQueue(runId + ""));
        lines.add(" " + PARAM_TIMEOUT + "__java: " + timeout);

        lines.add("");
        lines.add("threads: 1");
        lines.add("");
        lines.addAll(masterReceiver);
    }

    // RUN PIPELINE
    try {
        LOG.info("Starting Rabbit " + mode);
        Pipeline p = PipelineScriptParser.parse(lines,
                scriptFile.getParent(), list(replacementVars));
        p.run();

    } catch (ParseException e) {
        throw new ParseException("\nERROR parsing " + mode + "\n"
                + e.getMessage()
                + "\n(see the README.txt for the pipeline script format)",
                e.getErrorOffset());
    }
    System.out.println(Launcher.OK_MESSAGE);
}
 
Example 10
Source File: ScriptValidator.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Validates the current script, and selects the error if the specified falg
 * is <code>true</code>.
 * 
 * @param isFunctionBody
 *            <code>true</code> if a function body is validated,
 *            <code>false</code> otherwise.
 * @param isErrorSelected
 *            <code>true</code> if error will be selected after
 *            validating, <code>false</code> otherwise.
 * @throws ParseException
 *             if an syntax error is found.
 */
public void validate( boolean isFunctionBody, boolean isErrorSelected )
		throws ParseException
{
	if ( scriptViewer == null )
	{
		return;
	}

	clearAnnotations( );

	StyledText textField = scriptViewer.getTextWidget( );

	if ( textField == null || !textField.isEnabled( ) )
	{
		return;
	}

	String functionTag = "function(){"; //$NON-NLS-1$
	IDocument document = scriptViewer.getDocument( );
	String text = document == null ? null : scriptViewer.getDocument( )
			.get( );

	String script = text;

	if ( isFunctionBody )
	{
		script = functionTag + script + "\n}"; //$NON-NLS-1$
	}

	try
	{
		validateScript( script );
	}
	catch ( ParseException e )
	{
		int offset = e.getErrorOffset( );

		if ( isFunctionBody )
		{
			offset -= functionTag.length( );
			while ( offset >= text.length( ) )
			{
				offset--;
			}
		}

		String errorMessage = e.getLocalizedMessage( );
		Position position = getErrorPosition( text, offset );

		if ( position != null )
		{
			IAnnotationModel annotationModel = scriptViewer.getAnnotationModel( );

			if ( annotationModel != null )
			{
				annotationModel.addAnnotation( new Annotation( IReportGraphicConstants.ANNOTATION_ERROR,
						true,
						errorMessage ),
						position );
			}
			if ( isErrorSelected )
			{
				if ( scriptViewer instanceof SourceViewer )
				{
					( (SourceViewer) scriptViewer ).setSelection( new TextSelection( position.getOffset( ),
							position.getLength( ) ) );
				}
				scriptViewer.revealRange( position.getOffset( ),
						position.getLength( ) );
			}
		}
		throw new ParseException( e.getLocalizedMessage( ), position.offset );
	}
}
 
Example 11
Source File: MappingReader.java    From openccg with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Starts reading from the next mapping group.
 * @return The next {@link MappingGroup} found by reading from the underlying reader.
 * @throws IOException If a {@link ParseException} is encountered when calling
 * {@link MappingFormat#parseMapping(String)} based on the underlying input, or if one is thrown by the
 * underlying reader. An IOException is also thrown if the number of mappings in the
 * {@linkplain MappingGroup#getLength() current group} could not be read. 
 */
public MappingGroup nextGroup() throws IOException {
	checkMappingCount();
	mappingCount = 0;
	
	MappingGroup previous = (currentGroup == null) ? null : currentGroup;
	int newCount = mappingQueue.size();
	
	currentGroup = (newCount == 0)
		? null : new MappingGroup(mappingQueue.peek().phraseNumber, newCount);
	
	boolean eog = false;
	
	while(!eog) {
		StringBuilder sb = new StringBuilder();
		
		int i;
		while((i = in.read()) != -1) {
			char c = (char)i;
			
			if(skipLF) {
				skipLF = false;
				if(c == '\n') {
					continue;
				}
			}
			
			if(c == '\r') {
				skipLF = true;
			}
			
			if(format.encodingScheme.isMappingDelimiter(c)) {
				break;
			}
			else if(format.encodingScheme.isGroupDelimiter(c)) {
				eog = true;
				break;
			}
			else {
				sb.append(c); 
			}
		}
		
		if(sb.length() == 0) {
			break; // for EOF and end of group
		}
		
		Mapping a = null;
		try {
			a = format.parseMapping(sb.toString());
		}
		catch(ParseException pe) {
			throw new IOException(((currentGroup == null) ? ""
					: "group " + currentGroup.phraseNumber + ": ") + "problem formatting mapping "
					+ sb.toString() + " at offset " + pe.getErrorOffset() + ": " + pe.getMessage(), pe);
		}
		
		// if the format allows null IDs, use previous's running counter
		if(currentGroup == null) {
			Integer I = (a.phraseNumber == null)
				? (previous == null) ? format.encodingScheme.getPhraseNumberBase().start
						: previous.phraseNumber + 1
				: a.phraseNumber;
			
			currentGroup = new MappingGroup(I, 0);
		}
		
		if(a.phraseNumber == null) {
			// have to copy because phraseNumber is immutable (and final)
			a = a.copyWithPhraseNumber(currentGroup.phraseNumber);
		}
		
		if(!currentGroup.phraseNumber.equals(a.phraseNumber)) {
			eog = true;
		}
		else {
			newCount++; // only increment if should be read
		}			
		
		if(!mappingQueue.offer(a)) { // save for next read
			throw new IOException("unable to read mapping");
		}
	}
	
	if(currentGroup != null) {
		currentGroup.length = newCount;
	}
	
	return (currentGroup == null || currentGroup.length == 0) ? null : currentGroup;
}