Social Icons

.

суббота, 22 мая 2010 г.

J2EE деструктор

Задача

Требуется понять, что J2EE приложение выгружается, обновляется или еще каким-то способом уничтожается. Понимание такое требуется для освобождения занятых ресурсов (например, глушения прослушивания TCP порта)

Сканирование директорий из JAVA

Задача: необходимо просканировать директорию на предмет наличия в ней определенных файлов и что-то сделать с ними. Например, переименовать.

воскресенье, 9 мая 2010 г.

JSE: Перепаковка даты из строки в строку

 


//szFormatFrom="yyyy-MM-dd", а szFormatTo="dd.MM.yyyy"
public static String repackDate(String szValue, String szFormatFrom, String szFormatTo, String szDefault  ){
 SimpleDateFormat szInput = new SimpleDateFormat(szFormatFrom);
 SimpleDateFormat szOutput = new SimpleDateFormat(szFormatTo);
 try {
  Date theDate = szInput.parse( szValue );
  return szOutput.format(theDate);
 } catch (Exception e) {
  System.out.println("ParseException is " + e.getMessage() ) ;
 }
 return szDefault;
}
 
public static String currentDate(String szFormat){
 SimpleDateFormat sdf = new SimpleDateFormat( szFormat );
 return sdf.format( Calendar.getInstance().getTime() );  
} 



JSE: XML to String

 

public static String toPlaneXml( Document theDocument ) throws TransformerException{
 DOMSource  theSource = new DOMSource (theDocument);
 StringWriter writer = new StringWriter();
 StreamResult result = new StreamResult(writer);
 TransformerFactory tf = TransformerFactory.newInstance();
 Transformer transformer = tf.newTransformer();
 transformer.transform(theSource, result);
 return writer.toString();
}


 

суббота, 8 мая 2010 г.

JSE: Выравнивание строки

 

public static String padingLeft(String szText, int nLength, char ch){
 return pading(szText, nLength, ch, true);
}
public static String padingRight(String szText, int nLength, char ch){
 return pading(szText, nLength, ch, false);
}
public static String pading(String szText, int nLength, char ch, boolean bLeft) {
 if(szText == null) szText = szEmptyString;
 if(szText.length() >= nLength) return szText;
 String szPadding = String.format("%" + ( nLength - szText.length() ) + "s", "").replace(" ", String.valueOf(ch) );
 return bLeft?(szPadding + szText):(szText+szPadding);
} 


JSE: String to XML

 


public static Document parseXml(String szMessage){
 Document theDocument = null;
 try{
  DocumentBuilderFactory theFactory = DocumentBuilderFactory.newInstance();
  theFactory.setValidating(false);
  theFactory.setNamespaceAware(false);
  DocumentBuilder theBuilder = theFactory.newDocumentBuilder();

  ByteArrayInputStream theStream = new ByteArrayInputStream( szMessage.getBytes() );
  theDocument = theBuilder.parse(theStream);

  if( theDocument == null) throw new Exception("theDocument == null");
  if( theDocument.getDocumentElement() == null) throw new Exception("theDocument.getDocumentElement() == null");
 }
 catch(Exception ex){
  System.out.println("Can't transform message to XML document. " + ex.getMessage() );
  theDocument = null;
 }
 
 return theDocument;
}


 

JSE: статичный Map в классе

 

...
import java.util.Collections;
...

public class SSomeAlias
{
 private static final Map theList;

 static {
  Map theTemplate = new HashMap();
  theTemplate.put(ESomeField.ACCOUNT, "Счет");
  theTemplate.put(ESomeField.REQUISITES, "Реквизиты счета");
  theTemplate.put(ESomeField.IDENTIFIER, "Плательщик");
  theList = Collections.unmodifiableMap( theTemplate );
 }

  public static String decode(String szField){ 
  return decode( ESomeField.decode(szField) ); 
 }

 public static String decode(ESomeField theField){ 
  return theList.containsKey(theField)?theList.get(theField):theField.type(); 
 }
}



вторник, 4 мая 2010 г.

JSE: Представить набор строк перечислением (enum)


 


public enum ESomeField 
{
 ACCOUNT("account"),
 REQUISITES("requisites"),
 IDENTIFIER("identifier"),
 
 UNKNOWN("Unknown");
 
 private String szType;
 public String type() { return this.szType; }
 
 private ESomeField(String szType) { this.szType = szType; }
 
 static public ESomeField decode(String szType) {
  if( szType != null && szTyle.) ){
   for ( ESomeField theType: ESomeField.values() ) {
    if (theType.type().equals(szType)) return theType;
   }
  }
  return UNKNOWN;
 }
}


понедельник, 3 мая 2010 г.

JSE: Прочитать файл в строку

 
 
   public static String readFileAsString( String szFileName, String szEncoder ) throws Exception {   
        InputStream theInputStream = new BufferedInputStream( new FileInputStream( szFileName ) );   
        byte[] theData = new byte[theInputStream.available()];   
        theInputStream.read(data);   
        theInputStream.close();   
        return new String(theData, szEncoder);   
   }


 

Так говорил Учитель:

У хорошо написанной программы есть свой собственный рай, у плохо написанной — свой собственный ад.

Russian Developer

Взгляд его светел, усилия праведны, старания бесплодны, дело безнадежно ...