Java Code Examples for com.helger.commons.string.StringParser

The following examples show how to use com.helger.commons.string.StringParser. These examples are extracted from open source projects. 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 Project: ph-commons   Source File: EqualsHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNullSafeEquals () throws MalformedURLException
{
  _test ("s1", "s2");
  _test (StringParser.parseBigDecimal ("12562136756"), StringParser.parseBigDecimal ("67673455"));
  _test (Double.valueOf (3.1234d), Double.valueOf (23.456d));
  _test (Float.valueOf (3.1234f), Float.valueOf (23.456f));
  _test (new URL ("http://www.helger.com"), new URL ("http://www.google.com"));
  _test (new boolean [] { true }, new boolean [] { false });
  _test (new byte [] { 1 }, new byte [] { 2 });
  _test (new char [] { 'a' }, new char [] { 'b' });
  _test (new double [] { 2.1 }, new double [] { 2 });
  _test (new float [] { 2.1f }, new float [] { 1.9f });
  _test (new int [] { 5 }, new int [] { 6 });
  _test (new long [] { 7 }, new long [] { 8 });
  _test (new short [] { -9 }, new short [] { -10 });

  final String s1 = "s1";
  final String s2 = "S1";
  assertTrue (EqualsHelper.equalsIgnoreCase (s1, s1));
  assertTrue (EqualsHelper.equalsIgnoreCase (s1, s2));
  assertTrue (EqualsHelper.equalsIgnoreCase (s2, s1));
  assertFalse (EqualsHelper.equalsIgnoreCase (s1, null));
  assertFalse (EqualsHelper.equalsIgnoreCase (null, s2));
  assertTrue (EqualsHelper.equalsIgnoreCase (null, null));
}
 
Example 2
Source Project: ph-commons   Source File: LocaleParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParseBigDecimal ()
{
  final BigDecimal aBD1M = StringParser.parseBigDecimal ("1000000");
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1.000.000", L_DE, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1,000,000", L_EN, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (aBD1M, LocaleParser.parseBigDecimal ("1,000,000", (DecimalFormat) NumberFormat.getInstance (L_EN)));
  assertEquals (new BigDecimal ("1234567.8901"),
                LocaleParser.parseBigDecimal ("1.234.567,8901", L_DE, CGlobal.BIGDEC_MINUS_ONE));
  assertEquals (CGlobal.BIGDEC_MINUS_ONE,
                LocaleParser.parseBigDecimal ("... und denken", L_EN, CGlobal.BIGDEC_MINUS_ONE));
  final ChoiceFormat aCF = new ChoiceFormat ("-1#negative|0#zero|1.0#one");
  assertEquals (BigDecimal.valueOf (0.0), LocaleParser.parseBigDecimal ("zero", aCF, CGlobal.BIGDEC_MINUS_ONE));

  try
  {
    LocaleParser.parseBigDecimal ("0", (DecimalFormat) null);
    fail ();
  }
  catch (final NullPointerException ex)
  {}
}
 
Example 3
Source Project: ph-commons   Source File: MapperIteratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetIteratorWithConversion ()
{
  final Iterator <Integer> it = new MapperIterator <> (CollectionHelper.newList ("100", "-25"),
                                                       StringParser::parseIntObj);
  assertNotNull (it);
  assertTrue (it.hasNext ());
  assertEquals (Integer.valueOf (100), it.next ());
  assertTrue (it.hasNext ());
  assertEquals (Integer.valueOf (-25), it.next ());
  assertFalse (it.hasNext ());

  try
  {
    it.next ();
    fail ();
  }
  catch (final NoSuchElementException ex)
  {}

  it.remove ();
}
 
Example 4
Source Project: ph-css   Source File: CSSNumberHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the passed string value with unit into a structured
 * {@link CSSSimpleValueWithUnit}. Example: parsing <code>5px</code> will
 * result in the numeric value <code>5</code> and the unit
 * <code>ECSSUnit.PX</code>. The special value "0" is returned with the unit
 * "px".
 *
 * @param sCSSValue
 *        The value to be parsed. May be <code>null</code> and is trimmed
 *        inside this method.
 * @param bWithPerc
 *        <code>true</code> to include the percentage unit, <code>false</code>
 *        to exclude the percentage unit.
 * @return <code>null</code> if the passed value could not be converted to
 *         value and unit.
 */
@Nullable
public static CSSSimpleValueWithUnit getValueWithUnit (@Nullable final String sCSSValue, final boolean bWithPerc)
{
  String sRealValue = StringHelper.trim (sCSSValue);
  if (StringHelper.hasText (sRealValue))
  {
    // Special case for 0!
    if (sRealValue.equals ("0"))
      return new CSSSimpleValueWithUnit (BigDecimal.ZERO, ECSSUnit.PX);

    final ECSSUnit eUnit = bWithPerc ? getMatchingUnitInclPercentage (sRealValue)
                                     : getMatchingUnitExclPercentage (sRealValue);
    if (eUnit != null)
    {
      // Cut the unit off
      sRealValue = sRealValue.substring (0, sRealValue.length () - eUnit.getName ().length ()).trim ();
      final BigDecimal aValue = StringParser.parseBigDecimal (sRealValue);
      if (aValue != null)
        return new CSSSimpleValueWithUnit (aValue, eUnit);
    }
  }
  return null;
}
 
Example 5
Source Project: ph-commons   Source File: ColorMicroTypeConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public Color convertToNative (@Nonnull final IMicroElement aElement)
{
  final int nRed = StringParser.parseInt (aElement.getAttributeValue (ATTR_RED), 0);
  final int nGreen = StringParser.parseInt (aElement.getAttributeValue (ATTR_GREEN), 0);
  final int nBlue = StringParser.parseInt (aElement.getAttributeValue (ATTR_BLUE), 0);
  final int nAlpha = StringParser.parseInt (aElement.getAttributeValue (ATTR_ALPHA), 0xff);
  return new Color (nRed, nGreen, nBlue, nAlpha);
}
 
Example 6
Source Project: ph-commons   Source File: HomoglyphBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Consumes the supplied Reader and uses it to construct a populated Homoglyph
 * object.
 *
 * @param aReader
 *        a Reader object that provides access to homoglyph data (see the
 *        bundled char_codes.txt file for an example of the required format)
 * @return a Homoglyph object populated using the data returned by the Reader
 *         object
 * @throws IOException
 *         if the specified Reader cannot be read
 */
@Nonnull
public static Homoglyph build (@Nonnull @WillClose final Reader aReader) throws IOException
{
  ValueEnforcer.notNull (aReader, "reader");
  try (final NonBlockingBufferedReader aBR = new NonBlockingBufferedReader (aReader))
  {
    final ICommonsList <IntSet> aList = new CommonsArrayList <> ();
    String sLine;
    while ((sLine = aBR.readLine ()) != null)
    {
      sLine = sLine.trim ();
      if (sLine.length () == 0 || sLine.charAt (0) == '#')
        continue;

      final IntSet aSet = new IntSet (sLine.length () / 3);
      for (final String sCharCode : StringHelper.getExploded (',', sLine))
      {
        final int nVal = StringParser.parseInt (sCharCode, 16, -1);
        if (nVal >= 0)
          aSet.add (nVal);
      }
      aList.add (aSet);
    }

    return new Homoglyph (aList);
  }
}
 
Example 7
Source Project: ph-commons   Source File: Version.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@ReturnsMutableCopy
private static String [] _extSplit (@Nonnull final String s)
{
  final String [] aDotParts = StringHelper.getExplodedArray ('.', s, 2);
  if (aDotParts.length == 2)
  {
    // Dots always take precedence
    return aDotParts;
  }

  if (StringParser.isInt (aDotParts[0]))
  {
    // If it is numeric, use the dot parts anyway (e.g. for "5" or "-1")
    return aDotParts;
  }

  final String [] aDashParts = StringHelper.getExplodedArray ('-', s, 2);
  if (aDashParts.length == 1)
  {
    // Neither dot nor dash present
    return aDotParts;
  }

  // More matches for dash split! (e.g. "0-RC1")
  return aDashParts;
}
 
Example 8
Source Project: ph-commons   Source File: EqualsHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEquals_BigDecimal ()
{
  final BigDecimal bd1 = StringParser.parseBigDecimal ("5.5");
  final BigDecimal bd2 = StringParser.parseBigDecimal ("5.49999");
  CommonsAssert.assertEquals (bd1, bd1);
  CommonsAssert.assertEquals (bd1, StringParser.parseBigDecimal ("5.5000"));
  CommonsAssert.assertEquals (bd1, StringParser.parseBigDecimal ("5.50000000000000000"));
  CommonsAssert.assertNotEquals (bd1, bd2);
}
 
Example 9
Source Project: ph-css   Source File: CSSPropertyCustomizerOpacity.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public ICSSValue createSpecialValue (@Nonnull final ICSSProperty aProperty,
                                     @Nonnull @Nonempty final String sValue,
                                     final boolean bIsImportant)
{
  final double dValue = StringParser.parseDouble (sValue, Double.NaN);
  if (!Double.isNaN (dValue))
  {
    final int nPerc = (int) (dValue * 100);
    return new CSSValueList (ECSSProperty.OPACITY,
                             new ICSSProperty [] { new CSSPropertyFree (ECSSProperty.FILTER,
                                                                        ECSSVendorPrefix.MICROSOFT),
                                                   new CSSPropertyFree (ECSSProperty.FILTER),
                                                   aProperty.getClone (ECSSVendorPrefix.MOZILLA),
                                                   aProperty.getClone (ECSSVendorPrefix.WEBKIT),
                                                   aProperty },
                             new String [] { "\"progid:DXImageTransform.Microsoft.Alpha(Opacity=" +
                                             nPerc +
                                             ")\"",
                                             "alpha(opacity=" + nPerc + ")",
                                             sValue,
                                             sValue,
                                             sValue },
                             bIsImportant);
  }
  return null;
}
 
Example 10
Source Project: ph-commons   Source File: SettingsPersistenceJsonTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testViceVersaConversion () throws UnsupportedEncodingException
{
  // Name is important!
  final ISettings aSrc = new Settings ("anonymous");
  aSrc.putIn ("field1a", BigInteger.valueOf (1234));
  aSrc.putIn ("field1b", BigInteger.valueOf (-23423424));
  aSrc.putIn ("field2a", BigDecimal.valueOf (12.34));
  aSrc.putIn ("field2b", BigDecimal.valueOf (-2342.334599424));
  aSrc.putIn ("field3a", "My wonderbra string\n(incl newline)");
  aSrc.putIn ("field3b", "");
  aSrc.putIn ("field9a", Boolean.TRUE);
  aSrc.putIn ("field9b", StringParser.parseByteObj ("5"));
  aSrc.putIn ("field9c", Character.valueOf ('ä'));
  aSrc.putIn ("fieldxa", PDTFactory.getCurrentLocalDate ());
  aSrc.putIn ("fieldxb", PDTFactory.getCurrentLocalTime ());
  aSrc.putIn ("fieldxc", PDTFactory.getCurrentLocalDateTime ());
  aSrc.putIn ("fieldxd", PDTFactory.getCurrentZonedDateTime ());
  aSrc.putIn ("fieldxe", Duration.ofHours (5));
  aSrc.putIn ("fieldxf", Period.ofDays (3));
  aSrc.putIn ("fieldxg", "Any byte ärräy".getBytes (StandardCharsets.UTF_8.name ()));

  // null value
  aSrc.putIn ("fieldnull", null);

  final SettingsPersistenceJson aSPP = new SettingsPersistenceJson ();
  final String sSrc = aSPP.writeSettings (aSrc);
  assertNotNull (sSrc);

  // The created object is different, because now all values are String typed!
  final ISettings aDst1 = aSPP.readSettings (sSrc);
  assertNotNull (aDst1);

  // Reading the String typed version again should result in the same object
  final ISettings aDst2 = aSPP.readSettings (aSPP.writeSettings (aDst1));
  assertNotNull (aDst2);

  if (false)
  {
    // Differs because of different types
    assertEquals (aDst1, aDst2);
  }

  assertNotNull (aDst2.getAsLocalDate ("fieldxa"));
  assertNotNull (aDst2.getAsLocalTime ("fieldxb"));
  assertNotNull (aDst2.getAsLocalDateTime ("fieldxc"));
  assertNotNull (aDst2.getConvertedValue ("fieldxd", ZonedDateTime.class));
  assertNotNull (aDst2.getConvertedValue ("fieldxe", Duration.class));
  assertNotNull (aDst2.getConvertedValue ("fieldxf", Period.class));
}
 
Example 11
@Test
public void testViceVersaConversion () throws UnsupportedEncodingException
{
  // Name is important!
  final ISettings aSrc = new Settings ("anonymous");
  aSrc.putIn ("field1a", BigInteger.valueOf (1234));
  aSrc.putIn ("field1b", BigInteger.valueOf (-23423424));
  aSrc.putIn ("field2a", BigDecimal.valueOf (12.34));
  aSrc.putIn ("field2b", BigDecimal.valueOf (-2342.334599424));
  aSrc.putIn ("field3a", "My wonderbra string\n(incl newline)");
  aSrc.putIn ("field3b", "");
  aSrc.putIn ("field9a", Boolean.TRUE);
  aSrc.putIn ("field9b", StringParser.parseByteObj ("5"));
  aSrc.putIn ("field9c", Character.valueOf ('ä'));
  aSrc.putIn ("fieldxa", PDTFactory.getCurrentLocalDate ());
  aSrc.putIn ("fieldxb", PDTFactory.getCurrentLocalTime ());
  aSrc.putIn ("fieldxc", PDTFactory.getCurrentLocalDateTime ());
  aSrc.putIn ("fieldxd", PDTFactory.getCurrentZonedDateTime ());
  aSrc.putIn ("fieldxe", Duration.ofHours (5));
  aSrc.putIn ("fieldxf", Period.ofDays (3));
  aSrc.putIn ("fieldxg", "Any byte ärräy".getBytes (StandardCharsets.UTF_8.name ()));

  // null value
  aSrc.putIn ("fieldnull", null);

  final SettingsPersistenceProperties aSPP = new SettingsPersistenceProperties ();
  final String sSrc = aSPP.writeSettings (aSrc);
  assertNotNull (sSrc);

  // The created object is different, because now all values are String typed!
  final ISettings aDst1 = aSPP.readSettings (sSrc);
  assertNotNull (aDst1);

  // Reading the String typed version again should result in the same object
  final ISettings aDst2 = aSPP.readSettings (aSPP.writeSettings (aDst1));
  assertNotNull (aDst2);
  assertEquals (aDst1, aDst2);

  assertNotNull (aDst2.getAsLocalDate ("fieldxa"));
  assertNotNull (aDst2.getAsLocalTime ("fieldxb"));
  assertNotNull (aDst2.getAsLocalDateTime ("fieldxc"));
  assertNotNull (aDst2.getConvertedValue ("fieldxd", ZonedDateTime.class));
  assertNotNull (aDst2.getConvertedValue ("fieldxe", Duration.class));
  assertNotNull (aDst2.getConvertedValue ("fieldxf", Period.class));
}
 
Example 12
@Test
public void testConversionWithTypes () throws UnsupportedEncodingException
{
  final Settings aSrc = new Settings ("myName");
  aSrc.putIn ("field1a", BigInteger.valueOf (1234));
  aSrc.putIn ("field1b", BigInteger.valueOf (-23423424));
  aSrc.putIn ("field2a", BigDecimal.valueOf (12.34));
  aSrc.putIn ("field2b", BigDecimal.valueOf (-2342.334599424));
  aSrc.putIn ("field3a", "My wonderbra string\n(incl newline)");
  aSrc.putIn ("field3b", "");
  aSrc.putIn ("field9a", Boolean.TRUE);
  aSrc.putIn ("field9b", StringParser.parseByteObj ("5"));
  aSrc.putIn ("field9c", Character.valueOf ('ä'));
  aSrc.putIn ("fieldxa", PDTFactory.getCurrentLocalDate ());
  aSrc.putIn ("fieldxb", PDTFactory.getCurrentLocalTime ());
  aSrc.putIn ("fieldxc", PDTFactory.getCurrentLocalDateTime ());
  aSrc.putIn ("fieldxd", PDTFactory.getCurrentZonedDateTime ());
  aSrc.putIn ("fieldxe", Duration.ofHours (5));
  aSrc.putIn ("fieldxf", Period.ofDays (3));
  aSrc.putIn ("fieldxg", "Any byte ärräy".getBytes (StandardCharsets.UTF_8.name ()));

  final Settings aNestedSettings = new Settings ("nestedSettings");
  aNestedSettings.putIn ("a", "b");
  aNestedSettings.putIn ("c", "d");
  aNestedSettings.putIn ("e", Clock.systemDefaultZone ().millis ());
  aSrc.putIn ("fieldxh", aNestedSettings);

  // null value
  aSrc.putIn ("fieldnull", null);

  // To XML
  final IMicroElement eSrcElement = MicroTypeConverter.convertToMicroElement (aSrc, "root");
  assertNotNull (eSrcElement);
  if (false)
    LOGGER.info (MicroWriter.getNodeAsString (eSrcElement));

  // From XML
  final ISettings aDst = MicroTypeConverter.convertToNative (eSrcElement, Settings.class);
  assertNotNull (aDst);

  // No longer true, because now all values are String
  if (false)
  {
    assertEquals (aSrc, aDst);

    // Compare list
    assertEquals (BigInteger.valueOf (1234), aDst.getValue ("field1a"));
  }
  else
  {
    assertEquals ("1234", aDst.getValue ("field1a"));
  }

  final ISettings aDst2 = new Settings (aDst.getName ());
  aDst2.putAllIn (aDst);
  assertEquals (aDst, aDst2);
  assertTrue (aDst2.putIn ("field3b", "doch was").isChanged ());
  assertFalse (aDst.equals (aDst2));
}
 
Example 13
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default boolean getAttributeValueAsBool (@Nullable final String sAttrName, final boolean bDefault)
{
  return StringParser.parseBool (getAttributeValue (sAttrName), bDefault);
}
 
Example 14
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default boolean getAttributeValueAsBool (@Nullable final String sNamespaceURI,
                                         @Nullable final String sAttrName,
                                         final boolean bDefault)
{
  return StringParser.parseBool (getAttributeValue (sNamespaceURI, sAttrName), bDefault);
}
 
Example 15
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default boolean getAttributeValueAsBool (@Nullable final IMicroQName aAttrName, final boolean bDefault)
{
  return StringParser.parseBool (getAttributeValue (aAttrName), bDefault);
}
 
Example 16
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default double getAttributeValueAsDouble (@Nullable final String sAttrName, final double dDefault)
{
  return StringParser.parseDouble (getAttributeValue (sAttrName), dDefault);
}
 
Example 17
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default double getAttributeValueAsDouble (@Nullable final String sNamespaceURI,
                                          @Nullable final String sAttrName,
                                          final double dDefault)
{
  return StringParser.parseDouble (getAttributeValue (sNamespaceURI, sAttrName), dDefault);
}
 
Example 18
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default double getAttributeValueAsDouble (@Nullable final IMicroQName aAttrName, final double dDefault)
{
  return StringParser.parseDouble (getAttributeValue (aAttrName), dDefault);
}
 
Example 19
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default float getAttributeValueAsFloat (@Nullable final String sAttrName, final float fDefault)
{
  return StringParser.parseFloat (getAttributeValue (sAttrName), fDefault);
}
 
Example 20
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default float getAttributeValueAsFloat (@Nullable final String sNamespaceURI,
                                        @Nullable final String sAttrName,
                                        final float fDefault)
{
  return StringParser.parseFloat (getAttributeValue (sNamespaceURI, sAttrName), fDefault);
}
 
Example 21
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default float getAttributeValueAsFloat (@Nullable final IMicroQName aAttrName, final float fDefault)
{
  return StringParser.parseFloat (getAttributeValue (aAttrName), fDefault);
}
 
Example 22
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default int getAttributeValueAsInt (@Nullable final String sAttrName, final int nDefault)
{
  return StringParser.parseInt (getAttributeValue (sAttrName), nDefault);
}
 
Example 23
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default int getAttributeValueAsInt (@Nullable final String sNamespaceURI,
                                    @Nullable final String sAttrName,
                                    final int nDefault)
{
  return StringParser.parseInt (getAttributeValue (sNamespaceURI, sAttrName), nDefault);
}
 
Example 24
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default int getAttributeValueAsInt (@Nullable final IMicroQName aAttrName, final int nDefault)
{
  return StringParser.parseInt (getAttributeValue (aAttrName), nDefault);
}
 
Example 25
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default long getAttributeValueAsLong (@Nullable final String sAttrName, final long nDefault)
{
  return StringParser.parseLong (getAttributeValue (sAttrName), nDefault);
}
 
Example 26
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default long getAttributeValueAsLong (@Nullable final String sNamespaceURI,
                                      @Nullable final String sAttrName,
                                      final long nDefault)
{
  return StringParser.parseLong (getAttributeValue (sNamespaceURI, sAttrName), nDefault);
}
 
Example 27
Source Project: ph-commons   Source File: IMicroAttributeContainer.java    License: Apache License 2.0 4 votes vote down vote up
default long getAttributeValueAsLong (@Nullable final IMicroQName aAttrName, final long nDefault)
{
  return StringParser.parseLong (getAttributeValue (aAttrName), nDefault);
}
 
Example 28
Source Project: ph-commons   Source File: FileIntIDFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
@MustBeLocked (ELockType.WRITE)
protected final int readAndUpdateIDCounter (@Nonnegative final int nReserveCount)
{
  // Read the old content
  final String sContent = SimpleFileIO.getFileAsString (m_aFile, CHARSET_TO_USE);
  final int nRead = sContent != null ? StringParser.parseInt (sContent.trim (), 0) : 0;

  // Write the new content to the new file
  // This will fail, if the disk is full
  SimpleFileIO.writeFile (m_aNewFile, Integer.toString (nRead + nReserveCount), CHARSET_TO_USE);

  FileIOError aIOError;
  boolean bRenamedToPrev = false;
  if (m_aFile.exists ())
  {
    // Rename the existing file to the prev file
    aIOError = FileOperationManager.INSTANCE.renameFile (m_aFile, m_aPrevFile);
    bRenamedToPrev = true;
  }
  else
    aIOError = new FileIOError (EFileIOOperation.RENAME_FILE, EFileIOErrorCode.NO_ERROR);
  if (aIOError.isSuccess ())
  {
    // Rename the new file to the destination file
    aIOError = FileOperationManager.INSTANCE.renameFile (m_aNewFile, m_aFile);
    if (aIOError.isSuccess ())
    {
      // Finally delete the prev file (may not be existing for fresh
      // instances)
      aIOError = FileOperationManager.INSTANCE.deleteFileIfExisting (m_aPrevFile);
    }
    else
    {
      // 2nd rename failed
      // -> Revert original rename to stay as consistent as possible
      if (bRenamedToPrev)
        FileOperationManager.INSTANCE.renameFile (m_aPrevFile, m_aFile);
    }
  }
  if (aIOError.isFailure ())
    throw new IllegalStateException ("Error on rename(existing-old)/rename(new-existing)/delete(old): " + aIOError);

  return nRead;
}
 
Example 29
Source Project: ph-commons   Source File: FileLongIDFactory.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected final long readAndUpdateIDCounter (@Nonnegative final int nReserveCount)
{
  final String sContent = SimpleFileIO.getFileAsString (m_aFile, CHARSET_TO_USE);
  final long nRead = sContent != null ? StringParser.parseLong (sContent.trim (), 0) : 0;

  // Write the new content to the new file
  // This will fail, if the disk is full
  SimpleFileIO.writeFile (m_aNewFile, Long.toString (nRead + nReserveCount), CHARSET_TO_USE);

  FileIOError aIOError;
  boolean bRenamedToPrev = false;
  if (m_aFile.exists ())
  {
    // Rename the existing file to the prev file
    aIOError = FileOperationManager.INSTANCE.renameFile (m_aFile, m_aPrevFile);
    bRenamedToPrev = true;
  }
  else
    aIOError = new FileIOError (EFileIOOperation.RENAME_FILE, EFileIOErrorCode.NO_ERROR);
  if (aIOError.isSuccess ())
  {
    // Rename the new file to the destination file
    aIOError = FileOperationManager.INSTANCE.renameFile (m_aNewFile, m_aFile);
    if (aIOError.isSuccess ())
    {
      // Finally delete the prev file (may not be existing for fresh
      // instances)
      aIOError = FileOperationManager.INSTANCE.deleteFileIfExisting (m_aPrevFile);
    }
    else
    {
      // 2nd rename failed
      // -> Revert original rename to stay as consistent as possible
      if (bRenamedToPrev)
        FileOperationManager.INSTANCE.renameFile (m_aPrevFile, m_aFile);
    }
  }
  if (aIOError.isFailure ())
    throw new IllegalStateException ("Error on rename(existing-old)/rename(new-existing)/delete(old): " + aIOError);

  return nRead;
}
 
Example 30
Source Project: ph-schematron   Source File: PSReader.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Read a &lt;pattern&gt; element
 *
 * @param ePattern
 *        The source micro element. Never <code>null</code>.
 * @return The created domain object. May not be <code>null</code>.
 */
@Nonnull
public PSPattern readPatternFromXML (@Nonnull final IMicroElement ePattern)
{
  final PSPattern ret = new PSPattern ();

  final PSRichGroup aRichGroup = new PSRichGroup ();
  ePattern.forAllAttributes ( (sNS, sAttrName, sVal) -> {
    final String sAttrValue = _getAttributeValue (sVal);
    if (sAttrName.equals (CSchematronXML.ATTR_ABSTRACT))
      ret.setAbstract (StringParser.parseBool (sAttrValue));
    else
      if (sAttrName.equals (CSchematronXML.ATTR_ID))
        ret.setID (sAttrValue);
      else
        if (sAttrName.equals (CSchematronXML.ATTR_IS_A))
          ret.setIsA (sAttrValue);
        else
          if (PSRichGroup.isRichAttribute (sAttrName))
            _handleRichGroup (sAttrName, sAttrValue, aRichGroup);
          else
            ret.addForeignAttribute (sAttrName, sAttrValue);
  });
  ret.setRich (aRichGroup);

  ePattern.forAllChildElements (ePatternChild -> {
    if (isValidSchematronNS (ePatternChild.getNamespaceURI ()))
    {
      if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_INCLUDE))
        ret.addInclude (readIncludeFromXML (ePatternChild));
      else
        if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_TITLE))
          ret.setTitle (readTitleFromXML (ePatternChild));
        else
          if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_P))
            ret.addP (readPFromXML (ePatternChild));
          else
            if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_LET))
              ret.addLet (readLetFromXML (ePatternChild));
            else
              if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_RULE))
                ret.addRule (readRuleFromXML (ePatternChild));
              else
                if (ePatternChild.getLocalName ().equals (CSchematronXML.ELEMENT_PARAM))
                  ret.addParam (readParamFromXML (ePatternChild));
                else
                  _warn (ret,
                         "Unsupported Schematron element '" +
                              ePatternChild.getLocalName () +
                              "' in " +
                              ret.toString ());
    }
    else
      ret.addForeignElement (ePatternChild.getClone ());
  });
  return ret;
}