Skip to content

Instantly share code, notes, and snippets.

@gazhikaba
Last active April 12, 2018 08:09
Show Gist options
  • Select an option

  • Save gazhikaba/e32efb589e7d4ab5dd9757f4b71d3735 to your computer and use it in GitHub Desktop.

Select an option

Save gazhikaba/e32efb589e7d4ab5dd9757f4b71d3735 to your computer and use it in GitHub Desktop.
Note of JAVA
  1. Get system environment: System.getenv(String).
  2. Object <-> file.
  3. Access class varible by name.
  4. Comm.java Commom class. * print methods * Read file line(word) by line(word) to list with java.util.Scanner.
protected static JSONObject getObjectFromFile() throws Exception {
JSONObject json = null;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:/temp/json.obj"));
json = (JSONObject) ois.readObject();
ois.close();
json.keySet();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// execute
return json;
}
If your object's class (or any of its superclasses) implements interface java.io.Serilizable, you can easily serialize this object and store it in a file. Let's say you have an object:
MyClass myObj = new MyClass();
Just open 'Display' view in Eclipse (Window -> Show view -> Other... -> Debug/Display) and type:
java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(new java.io.FileOutputStream("/path/to/your/file"));
oos.writeObject(myObj);
oos.close();
Select this code and press Ctrl+i - Eclipse will execute code, so myObj will be stored in the file (in this case, "/path/to/your/file"). Use canonical names of classes from java.io package in a Display view, because this package may be not imported in the class whis is currently being executed.
Later, you can restore this object (say, in a test class):
import java.io.*;
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/path/to/your/file"));
MyClass myObj = (MyClass) ois.readObject();
ois.close();
Of course, you should wrap this in usual try/catch/finally stuff to avoid resorce leaks.
Unfortunately, this won't work if MyClass doesn't implement java.io.Serializable interface.
class Workaround extends ObjectInputStream {
String className;
public Workaround(InputStream in, Class<?> cls) throws IOException {
super(in);
this.className = cls.getName();
}
@Override
protected ObjectStreamClass readClassDescriptor() throws IOException,
ClassNotFoundException {
ObjectStreamClass cd = super.readClassDescriptor();
try {
Field f = cd.getClass().getDeclaredField("name");
f.setAccessible(true);
f.set(cd, className);
} catch (Exception e) {
throw new RuntimeException(e);
}
return cd;
}
}
Now I can write an instance of Test1 and read it as an instance of Test2
class Test1 implements Serializable {
private static final long serialVersionUID = 1L;
int i;
}
class Test2 implements Serializable {
private static final long serialVersionUID = 1L;
int i;
}
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("1"));
Test1 test1 = new Test1();
oos.writeObject(test1);
oos.close();
Workaround x = new Workaround(new FileInputStream("1"), Test2.class);
Test2 test2 = (Test2)x.readObject();
Field f = cd.getClass().getDeclaredField("name");
f.setAccessible(true);
f.set(cd, className);
package common;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.dom4j.Document;
import org.dom4j.io.DOMReader;
import org.xml.sax.InputSource;
public class Comm {
// Example of processor
// Function<SomeClass,Object>processor=(element)->
// {
// return element.getName();
// };
public static String getContent(String url) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response;
HttpGet httpGet = new HttpGet(url);
response = httpclient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(entity.getContent()))) {
return buffer.lines().collect(Collectors.joining("\n"));
}
} finally {
response.close();
}
}
public static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
DOMReader reader = new DOMReader();
Document document = reader.read(doc);
return document;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
# access is not allowed due to restriction set by the accessExternalDTD property.
javax.xml.accessExternalSchema = all
Struts1.3.5のMaskValidatorでまとめてたけど、改めてまとめてみた。よく使いそうなものだけを選抜。正規表現無敵説を感じる。
チェックはEclipseのQuickRExを使っている。
Windpowsについている文字コード表をもとに調べた。文字コードはUnicode。
【半角英字】^[a-zA-Z]+$
abcdefghijklmnopqrstuvwxyz
【半角数字】^[0-9]+$
0-9
【半角記号】^[ -/:-@\[-\`\{-\~]+$
半角空白!”#$%&’()*+-.,/:;<=>?@[\]^_`{|}~
【半角英数字】^[a-zA-Z0-9]+$
abcdefghijklmnopqrstuvwxyz0123456789
【半角英数字記号】^[a-zA-Z0-9 -/:-@\[-\`\{-\~]+$
abcdefghijklmnopqrstuvwxyz0123456789半角空白!”#$%&’()*+-.,/:;<=>?@[\]^_`{|}~
【半角カタカナ】^[。-゚+]+$
ー。「」、・ヲァィゥェォャュョッタアイウエオカキクケコサシスセソミチツテトナニヌネノハヒフヘホマムメモヤユヨラリルレロワン゙゚
【ひらがな】^[ぁ-ゞ]+$
あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわをんぁぃぅぇぉっゃゅょがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽゑヴ繧輔v繧吶z゛゜ゝゞ
【カタカナ】^[ァ-ヶ]+$
ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ
【漢字】^[一-龠]*$
【全角文字】^[^ -~。-゚]+$
半角以外としているのがポイント。
【桁数を指定(1桁から5桁)】^[a-zA-Z0-9]{5,10}$
【5桁以上の繰り返し】^[a-zA-Z0-9]{5,}$
【5桁以下の繰り返し】^[a-zA-Z0-9]{1,5}$
【定数(trueもしくはfalse)】^true$|^false$
// http://www.oracle.com/technetwork/articles/vasiliev-oracle-jdbc-090470.html
/*
*A simple example illustrating aUCP JDBC connection in action
*/
import java.sql.*;
import oracle.ucp.jdbc.PoolDataSourceFactory;
import oracle.ucp.jdbc.PoolDataSource;
public class UcpConnection {
public static void main(String args[]) throws SQLException {
try
{
//Creating a pool-enabled data source
PoolDataSource pds = PoolDataSourceFactory.getPoolDataSource();
//Setting connection properties of the data source
pds.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");
pds.setURL("jdbc:oracle:thin:@//localhost:1521/XE");
pds.setUser("hr");
pds.setPassword("hr");
//Setting pool properties
pds.setInitialPoolSize(5);
pds.setMinPoolSize(5);
pds.setMaxPoolSize(10);
//Borrowing a connection from the pool
Connection conn = pds.getConnection();
System.out.println("\nConnection borrowed from the pool");
//Checking the number of available and borrowed connections
int avlConnCount = pds.getAvailableConnectionsCount();
System.out.println("\nAvailable connections: " + avlConnCount);
int brwConnCount = pds.getBorrowedConnectionsCount();
System.out.println("\nBorrowed connections: " + brwConnCount);
//Working with the connection
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select user from dual");
while(rs.next())
System.out.println("\nConnected as: "+rs.getString(1));
rs.close();
//Returning the connection to the pool
conn.close();
conn=null;
System.out.println("\nConnection returned to the pool");
//Checking the number of available and borrowed connections again
avlConnCount = pds.getAvailableConnectionsCount();
System.out.println("\nAvailable connections: " + avlConnCount);
brwConnCount = pds.getBorrowedConnectionsCount();
System.out.println("\nBorrowed connections: " + brwConnCount);
}
catch(SQLException e)
{
System.out.println("\nAn SQL exception occurred : " + e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment