Convert Clob to String - java

How can I get String out of Clob. I did google it, but
myClob.getSubString(0, (int) info.length()));
is the only thing I get. Console says:
java.sql.SQLException: Invalid argument(s) in call at
oracle.sql.CLOB.getSubString(CLOB.java:278) at
ru.tenet.es09.dao.CompanyDAOImpl.get(CompanyDAOImpl.java:72) at
ru.tenet.es09.dao.CompanyDAOImpl.getList(CompanyDAOImpl.java:132) at
ru.tenet.es09.dao.AddressDAOImpl.getList(AddressDAOImpl.java:59) at
ru.tenet.es09.Test.main(Test.java:11)
It points on getSubString() method. What is wrong?

Assuming you're using standard JDBC, once you have a ResultSet object you should be able to call ResultSet#getString("clob_field_name") to retrieve your CLOB data.

I know I'm late to this party!. Here is the one liner i used from hibernate library. If hibernate is already integrated to project then we can use annotations to convert clob to java String. In my case i had custom result transformer which read data from multiple tables after costly join. In the resultSetTransformer the below line does the job.
ClobType.INSTANCE.toString((Clob) tuple[2])
// org.hibernate.type.ClobType

this my way (sorry my english)
res = ps.executeQuery();
try {
while (res.next()) {
System.out.println(res.getClob(1));//confirm data
sRet = res.getString(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ps.close();
}

Converting String to CLOB
SOobject.setLongStringField( new SerialClob(entityString.toCharArray()));//Converting String to CLOB
Convert Clob to String
public String getLongStringField() {
Reader reader = null;
BufferedReader bufferedReader = null;
try {
reader = longStringField.getCharacterStream();
bufferedReader = new BufferedReader(reader);
return IOUtils.toString(bufferedReader);
} catch (Exception e) {
throw new RuntimeException("Error while reading String from CLOB", e);
} finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(bufferedReader);
}
}

I have created a java method which can create string from a CLOB object:
public String clobToString(Clob data) {
StringBuilder sb = new StringBuilder();
try {
Reader reader = data.getCharacterStream();
BufferedReader br = new BufferedReader(reader);
String line;
while(null != (line = br.readLine())) {
sb.append(line);
}
br.close();
} catch (SQLException e) {
// handle this exception
} catch (IOException e) {
// handle this exception
}
return sb.toString();
}

Related

How do I test currency exchange method with API?

I have problem with testing my method for currency exchange from API. I have no idea how to do testings to this method as I can't predict what currency rates are at the moment, they are changing every second. My teacher told me that I have to do another method that testing my first one and then Mock something. Please guys help.
public class CurrencyService {
private static HttpURLConnection conn;
private Pattern currencyPattern;
public double exchange(String currencyFrom, String currencyTo, double amount) {
currencyPattern = Pattern.compile("[A-Z]{3}");
if (!currencyPattern.matcher(currencyFrom).matches() || !currencyPattern.matcher(currencyTo).matches()) {
throw new BadPatternForCurrency("Currency FROM and TO must be for example: Dollar USD, euro EUR etc.");
}
if (amount < 0) {
throw new NoMinusValuesInAmountException("Amonut must be more than 0!");
}
DecimalFormat df = new DecimalFormat("##.##");
String adres = "https://api.apilayer.com/exchangerates_data/";
BufferedReader reader;
String line;
StringBuilder responseContent = new StringBuilder();
try {
URL url = new URL(adres + "convert?to=" + currencyTo.toUpperCase() + "&from=" + currencyFrom.toUpperCase() + "&amount=" + amount);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", "tSaLWidFRzgzO2mGNfFgVEIr2cqeWCUY");
int status = conn.getResponseCode();
if (status != 200) {
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject obj = new JSONObject(responseContent.toString());
double result = obj.getDouble("result");
return result;
}
}
To elaborate on #tgdavies comment:
You should better move everything starting with:
BufferedReader reader; into a separate class, for example, ExchangeApiClient and provide that class into your CurrencyService via a constructor. That ExchangeApiClient should return a string, so everything left to your service is to create a call exchangeApiClient.getResponse().
This way you will be able to unit-test your currency service.
The question remains how to test your ExchangeApiClient - that can also be done. You must create a HttpConnectionFactory and pass that factory via a constructor to your ExchangeApiClient. You should also make it non-static. Then you can pass a mock connection, which returns mock inputStream, you can here more about that here
If you want to read something about mocking I recommend a book "Practical Unit Testing with JUnit and Mockito".

GC overhead limit exceeded while read from CSV file

I am using below piece of code for reading the 150MB CSV file and getting GC error
Same code which was causing the problem
public List<String[]> readCsvFile(String ipFilePath) {
logger.info("Start executing readCsvFile method !!! on file " + ipFilePath);
CSVReader csvReader = null;
List<String[]> allRecrods = null;
Reader reader = null;
try {
reader = Files.newBufferedReader(Paths.get(ipFilePath));
csvReader = new CSVReader(reader);
allRecrods = csvReader.readAll();
} catch (Exception e) {
logger.error("Error in CsvFileReader !!!");
e.printStackTrace();
logger.error("Exception : ", e);
} finally {
try {
reader.close();
csvReader.close();
} catch (IOException e) {
logger.error("Error while closing fileReader/csvFileParser !!!");
e.printStackTrace();
logger.error("IOException : ", e);
}
}
return allRecrods;
}
I am getting error on the method : csvReader.readAll() as mentioned above.
I am not sure what is the problem which the code, and how to solve this, as the same code is working fine with 20-30 MB files.
The simplest solution is to increase heap size with flag "-Xmx" for example:
"-Xmx1024m". First you should use some heap size monitoring tool to see if the usage is expected.
You should not read all the lines but instead process the file line by line and size won't matter and is way more memory efficient.
Example from here: http://www.baeldung.com/java-read-lines-large-file
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
// System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
Edit: Also if you are looking for a framework I can recommend Spring Batch https://projects.spring.io/spring-batch/

Setting value of an attribute when uploading file to database

I have a .csv file "Salesman" that will be uploaded to the sqlite database. This file contains details about a Salesman.
A sample row for Salesman:
-----------
|code|name|
-----------
|0001|Jon|
-----------
|0002|Stu|
DDL for Salesman:
CREATE TABLE salesman (
code INTEGER NOT NULL,
name TEXT NOT NULL,
isSelected INTEGER NOT NULL,
PRIMARY KEY (
code
)
);
The attribute isSelected acts as a tag stating that the Salesman has been selected, thus cannot be chosen again.
This is my code for getting Salesman details from .CSV file:
public static ArrayList<Salesman> getSalesmanFromFile(String filePath){
ArrayList<Salesman> salesmanList= new ArrayList<Salesman>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
String[] strSalesman = null;
try {
while ((line=br.readLine()) != null){
strSalesman = line.split(",");
salesmanList.add(new Salesman(Integer.parseInt(strSalesman[0]), strSalesman[1]));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
String status = "Error"; //- Please review file selected. Make sure that format is followed.";
}
return salesmanList;
}
My question is, how can I set the third attribute isSelected in the method to 0 (not selected)? Since .csv file doesn't contain the tagging attribute, I'm thinking of placing it in the method above (which will be used at the start of the whole program).
I'm thinking of creating a variable within the method int isSelected = 0 but I don't know how to incorporate it with the BufferedReader. Something like:
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
String[] strSalesman = null;
//int isSelected = 0;
try {
while ((line=br.readLine()) != null){
strSalesman = line.split(",");
salesmanList.add(new Salesman(Integer.parseInt(strSalesman[0]), strSalesman[1], isSelected?));
}
} catch (IOException ex) {
ex.printStackTrace();
}
Any help would be appreciated!

How get android cpu model name?

I want to learn my phone cpu model name and I tryed to use /proc/cpuinfo and a lot of code but I failed. Can anyone help me?
Run
$ adb shell cat /proc/cpuinfo
Here is my code
public static String getCpuName() {
try {
FileReader fr = new FileReader("/proc/cpuinfo");
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
br.close();
String[] array = text.split(":\\s+", 2);
if (array.length >= 2) {
return array[1];
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
What about your code?

cannot read arabic text from url in java

I've a web service that prints the following text.
[{"packid":"p101","title":"صفته 1","description":"شسیب: 1\r\nثق س: 50","linkfuntext":"funtext","linkshortstory":"short","linkfunpic":"pic","linkringtone":"ring","linkfungif":"gif","linkwallpaper":"wall","price":"500","buyid":"pack.fun.1","buyed":""},{"packid":"p102","title":"بسته صدا","description":" متن ها: 50\r\nصداها: 120\r\nتصاویر: 100\r\nتصاویر متحرک: 50\r\nداستان کوتاه: 20","linkfuntext":"","linkshortstory":"","linkfunpic":"","linkringtone":"","linkfungif":"","linkwallpaper":"","price":"1200","buyid":"fun.pack.2","buyed":""}]
When I try to read it in java I receive it in the following format
[{"packid":"p101","title":"صفته 1","description":"شسیب: 1\r\nثق س: 50","linkfuntext":"funtext","linkshortstory":"short","linkfunpic":"pic","linkringtone":"ring","linkfungif":"gif","linkwallpaper":"wall","price":"500","buyid":"pack.fun.1","buyed":""},{"packid":"p102","title":"بسته صدا","description":" متن ها: 50\r\nصداها: 120\r\nتصاویر: 100\r\nتصاویر متحرک: 50\r\nداستان کوتاه: 20","linkfuntext":"","linkshortstory":"","linkfunpic":"","linkringtone":"","linkfungif":"","linkwallpaper":"","price":"1200","buyid":"fun.pack.2","buyed":""}]
I've tried changing the character set to UTF-8 as well as ISO-8859-6 but still no luck. When I print the text on console it is printed correctly which means there is no issue in character set of eclipse or console. Also I've tried changing the character set of string that is storing the text, but same issue.
String serverOutput = new String(TEXT_FROM_SERVER.getBytes(), "UTF-8");
Here is my code that gets output from web service
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String serverOutput = convertStreamToString(is);
private String convertStreamToString(InputStream is) {
Reader rd = null;
BufferedReader reader = null;
try {
rd = new InputStreamReader(is,"UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
reader = new BufferedReader(rd);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Any kind of help will be greatly appreciated. Thanks
you need to unescape those HTML characters, and you can do so with a method from Apache Commons Lang called unescapeHtml. More info here.
Example:
String afterDecoding = StringEscapeUtils.unescapeHtml(beforeDecoding);

Categories

Resources