Cannot read chinese characters in an excel file - spring-boot

I have developed a java application that will read an excel file containing chinese characters and convert it to multiple CSV files. The file is as below:
public class SplitterBean {
public static final Logger LOGGER = LoggerFactory.getLogger(SplitterBean.class);
public List<Map<String, String>> splitBody(XSSFWorkbook workbook) {
LOGGER.info("Inside SplitterBean, splitting: " + workbook.getNumberOfSheets());
Map<String, String> sheetMap = null;
List<Map<String, String>> sheetList = new ArrayList<Map<String,String>>();
int numberOfSheets = workbook.getNumberOfSheets();
XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
for (int i = 0; i < numberOfSheets; i++) {
StringBuilder sb = new StringBuilder();
sheetMap = new HashMap<String, String>();
XSSFSheet sheet = workbook.getSheetAt(i);
String sheetName = sheet.getSheetName();
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = null;
LOGGER.info("Cell type is: " + cell.getCellType());
switch (cell.getCellType()) {
case NUMERIC:
cellValue = Double.toString(cell.getNumericCellValue());
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
case BLANK:
cellValue = "";
break;
case FORMULA:
LOGGER.info("Reached formula cell, cell type is: " + cell.getCellType().toString());
switch (cell.getCellType()) {
case NUMERIC:
cellValue = Double.toString(cell.getNumericCellValue());
break;
case STRING:
cellValue = cell.getStringCellValue();
break;
case BLANK:
cellValue = "";
break;
default:
cellValue = "";
break;
}
default:
cellValue = "";
break;
}
sb.append(cellValue).append(",");
}
sb.append("\n");
}
sheetMap.put(sheetName, sb.toString());
sheetList.add(sheetMap);
}
return sheetList;
}
}
We are deploying our project as war file in Wildfly 17.0.1.FINAL. But when the CSV file is generated, the chinese characters are getting distorted. I guess this is due to server encoding which I need to change to UTF-8. Can anyone suggest me how to change server encoding in Wildfly 17.0.1.FINAL or how this issue can be solved?

Related

No appropriate font found using MigraDoc to create a PDF on Xamarin Forms

I'm trying to create a pdf using MigraDoc. Here's a list of the libraries that I'm using:
MigraDoc.DocumentObjectModel
MigraDoc.DocumentObjectModel.Tables
MigraDoc.Rendering
It throws me an error on printer.RenderDocument(). Code below
private async Task SavePDF()
{
filePath = emulatorFolderPath + "/Signed/" + _reportInformationViewModel.SelectedClient.Username + "-" + DateTime.Now.ToString("dd_MM_yyyy HH-mm") + ".pdf";
MigraDocRendering.PdfDocumentRenderer printer = new MigraDocRendering.PdfDocumentRenderer
{
Document = document
};
printer.RenderDocument();
printer.PdfDocument.Save(filePath);
}
PS: I don't need to use a private font.
I've resolved by implementing IFontResolver
I've added a folder Fonts that contains Open-Sans font.
I've created a folder Helpers that contains a class called GenericFontResolver:
public class GenericFontResolver : IFontResolver
{
public string DefaultFontName => "OpenSans";
public byte[] GetFont(string faceName)
{
if (faceName.Contains(DefaultFontName))
{
var assembly = typeof(ReportPreviewAndSignatureViewModel).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"PDFDemo.Fonts.{faceName}.ttf");
using (var reader = new StreamReader(stream))
{
var bytes = default(byte[]);
using (var ms = new MemoryStream())
{
reader.BaseStream.CopyTo(ms);
bytes = ms.ToArray();
}
return bytes;
}
}
else
return GetFont(DefaultFontName);
}
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
var fontName = string.Empty;
switch (familyName)
{
case "Open Sans":
case "OpenSans":
fontName = "OpenSans";
if (isBold && isItalic)
fontName = $"{fontName}-BoldItalic";
else if (isBold)
fontName = $"{fontName}-Bold";
else if (isItalic)
fontName = $"{fontName}-Italic";
else
fontName = $"{fontName}-Regular";
return new FontResolverInfo(fontName);
default:
break;
}
return null;
}
}
Then, on the constructor of the class that needs the font I've added:
GlobalFontSettings.FontResolver = new GenericFontResolver();
Then, when I'm creating the table you must add:
Style style = document.Styles["Normal"];
style.Font.Name = "OpenSans";

I have created container successfully but failed to upload an image/pdf to my blob container using Rest API

I am using PUT Blob Rest API for uploading img/pdf- PUT Blob reference. But it is showing- Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature error (403 response code).
Below are the string to sign:
"PUT\n\n\n41676\n\nimage/png\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:Wed, 17 Feb 2021 10:24:02 GMT\nx-ms-version:2020-02-10\n/acc_name/container_name/12362_50800_13_s_1.png"
Below are the header details:
{ "x-ms-blob-type" : "BlockBlob" , "x-ms-date" : "Wed, 17 Feb 2021 10:24:02 GMT" , "x-ms-version" : "2020-02-10" , "Authorization" : "SharedKey acc_name:XXXQsR728D7aqyJzFi/HXk+qT9rpjYbplUG9KXXXX" , "Content-Type" : "image/png" , "Content-Length" : "41676"}
Below are the URL details:
https://acc_name.blob.core.windows.net/container_name/12362_50800_13_s_1.png
private BasicDBObject createAzureBlob(String storageAPIVersion, String storageAccURL, String storageAccName, String storageAcckey, String storageAccConString,
String containerName, BasicDBObject clientReqObj, File outputfile) throws Exception
{
log.info("Entry createAzureBlob in the GenericServicesDeligator");
BasicDBObject clientResponse = null;
String date = clientReqObj.remove(Constants.F_CREATED_DATE).toString();
String filePath = clientReqObj.remove(Constants.F_PATH).toString();
String contentLength = clientReqObj.remove("Content-Length").toString();
String contentType = clientReqObj.remove("Content-Type").toString();
String hostMethod = "PUT";
StringBuilder authorization = new StringBuilder("SharedKey ").append(storageAccName).append(":").append("sharedKeySign");
StringBuilder canonicalizedResource = new StringBuilder("/").append(storageAccName).append("/").append(containerName).append("/").append(filePath);
BasicDBObject clientReqHeader = new BasicDBObject();
// Host URL
String hostName = clientReqHeader.size()>0l?new StringBuilder("/").append(filePath).append(prepareHostInfo(clientReqHeader)).toString():new StringBuilder("/").
append(filePath).toString();
String hostURL = new StringBuilder(storageAccURL).append("/").append(containerName).append(hostName).toString().trim();
// canonicalizedResource should always be in alphabetical order
canonicalizedResource.append(prepareCanonicalizedResource(clientReqHeader));
//canonicalizedHeader should always be in alphabetical order and include only that begin with x-ms-
clientReqHeader.clear();
clientReqHeader.put("x-ms-blob-type", "BlockBlob");
clientReqHeader.put("x-ms-date", date);
clientReqHeader.put("x-ms-version", storageAPIVersion);
String canonicalizedHeader = prepareCanonicalizedHeader(clientReqHeader);
// string to sign
String stringToSign = prepareStringToSign(hostMethod, contentLength, contentType, canonicalizedHeader, canonicalizedResource.toString());
// encode the string by using the HMAC-SHA256 algorithm over the UTF-8-encoded signature string
String signature = encodeSharedKeySignature(stringToSign, storageAcckey);
clientReqHeader.put("Authorization", authorization.toString().replace("sharedKeySign", signature));
clientReqHeader.put("Content-Length", contentLength);
clientReqHeader.put("Content-Type", contentType);
clientResponse = sendAzureClientRequest(hostMethod, hostURL, clientReqHeader, clientReqObj, outputfile);
log.info("Exit createAzureBlob in the GenericServicesDeligator");
return clientResponse;
}
private String prepareHostInfo(BasicDBObject hostNameObject) throws Exception
{
StringBuilder hostName = new StringBuilder();
for(String key: hostNameObject.keySet())
{
if(hostName.length() == 0l)
hostName.append("?").append(key).append("=").append(hostNameObject.get(key));
else
hostName.append("&").append(key).append("=").append(hostNameObject.get(key));
}
return hostName.toString().trim();
}
private String prepareCanonicalizedResource(BasicDBObject hostNameObject) throws Exception
{
StringBuilder canonicalizedResource = new StringBuilder();
Map<String, String> canonicalizedMap = new TreeMap<String, String>();
canonicalizedMap.putAll(hostNameObject.toMap());
for(String key: canonicalizedMap.keySet())
{
canonicalizedResource.append("\n").append(key).append(":").append(canonicalizedMap.get(key));
}
return canonicalizedResource.toString();
}
private String prepareCanonicalizedHeader(BasicDBObject hostNameObject) throws Exception
{
StringBuilder canonicalizedHeader = new StringBuilder();
Map<String, String> canonicalizedMap = new TreeMap<String, String>();
canonicalizedMap.putAll(hostNameObject.toMap());
for(String key: canonicalizedMap.keySet())
{
canonicalizedHeader.append(key).append(":").append(canonicalizedMap.get(key).toString().trim()).append("\n");
}
return canonicalizedHeader.toString();
}
private String prepareStringToSign(String hostMethod, String contentLength, String contentType, String canonicalizedHeader, String canonicalizedResource)
{
String input = "";
input = new StringBuilder(hostMethod).append("\n").
append("\n"). // Content-Encoding + "\n" +
append("\n"). // Content-Language + "\n" +
append(contentLength!=null?contentLength:"").append("\n").
append("\n"). // Content-MD5 + "\n" +
append(contentType!=null?contentType:"").append("\n").
append("\n"). // Date
append("\n"). // If-Modified-Since + "\n" +
append("\n"). // If-Match + "\n" +
append("\n"). // If-None-Match + "\n" +
append("\n"). // If-Unmodified-Since + "\n" +
append("\n"). // Range + "\n" +
append(canonicalizedHeader).
append(canonicalizedResource).toString().trim();
return input;
}
public String getUTCDate(Date date) throws Exception
{
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return (sdf.format(date) + " GMT").trim();
}
public static String getFileContentType(String fileType)
{
String contentType = "";
switch (fileType)
{
case "pdf":
contentType = "application/pdf";
break;
case "txt":
contentType = "text/plain";
break;
case "bmp":
contentType = "image/bmp";
break;
case "gif":
contentType = "image/gif";
break;
case "png":
contentType = "image/png";
break;
case "jpg":
contentType = "image/jpeg";
break;
case "jpeg":
contentType = "image/jpeg";
break;
case "xls":
contentType = "application/vnd.ms-excel";
break;
case "xlsx":
contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
case "csv":
contentType = "text/csv";
break;
case "html":
contentType = "text/html";
break;
case "xml":
contentType = "text/xml";
break;
case "zip":
contentType = "application/zip";
break;
default:
contentType = "application/octet-stream";
break;
}
return contentType.trim();
}
private String encodeSharedKeySignature(String inputVal, String storageAcckey) throws Exception
{
SecretKeySpec secretkey = new SecretKeySpec(new BASE64Decoder().decodeBuffer(storageAcckey), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretkey);
String hash = Base64.encodeAsString(mac.doFinal(inputVal.getBytes("UTF-8")));
return hash.trim();
}
Kindly share the solution so i would upload a image/pdf.
Thanks in advance
In the private BasicDBObject createAzureBlob() method, in the following section:
//encode the string by using the HMAC-SHA256 algorithm over the UTF-8-encoded signature string
String signature = encodeSharedKeySignature(stringToSign, storageAcckey);
clientReqHeader.put("Authorization", authorization.toString().replace("sharedKeySign", storageAcckey));
clientReqHeader.put("Content-Length", contentLength);
clientReqHeader.put("Content-Type", contentType);
You should use the signature instead of storageAcckey for Authorization header, so please change this line of code
clientReqHeader.put("Authorization", authorization.toString().replace("sharedKeySign", storageAcckey));
to
clientReqHeader.put("Authorization", authorization.toString().replace("sharedKeySign", signature));

Got Null result from Oracle even though the real result are decimal value

I am new to Oracle in Visual Studio,
I used Oracle.ManagedDataAccess as my reference,
The case is whenever I tried to retrieve decimal value from arithmetic in Oracle query, Its always return null
e.g
SELECT 26/3 FROM DUAL < ---- This code return null in my visual studio but has a value in TOAD.
Did I do it wrong ?
Here is my code to retrieve the value
List<object[]> result = new List<object[]>();
OracleDataReader data;
string constr = ConfigurationManager.ConnectionStrings["OraConnection"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
string query = QueryString;
using (OracleCommand cmd = new OracleCommand(query))
{
cmd.Connection = con;
con.Open();
data = cmd.ExecuteReader();
try
{
if (data.HasRows)
{
while (data.Read())
{
object[] itemData = new object[data.FieldCount];
//Dictionary<string, string> itemData = new Dictionary<string, string>();
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
if (typeof(string) == type)
{
itemData[i] = data.GetString(i);
}
if (typeof(DateTime) == type)
{
itemData[i] = data.GetDateTime(i);
}
if (typeof(int) == type)
{
itemData[i] = data.GetInt32(i);
}
if (typeof(decimal) == type)
{
itemData[i] = data.GetDecimal(i);
}
if (typeof(bool) == type)
{
itemData[i] = data.GetBoolean(i);
}
if (typeof(TimeSpan) == type)
{
itemData[i] = data.GetTimeSpan(i);
}
if (typeof(Single) == type)
{
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
}
}
result.Add(itemData);
}
}
else
{
Console.WriteLine("Rows not found.");
}
}
finally
{
data.Close();
}
con.Close();
}
}
return result;
UPDATED : It got null just for division which has decimal value. Addition, Substraction, multiplication has no issue
It seems your data type doesn't match any of your if expressions. As there is no default branch, itemData[i] remains null. I suggest something like the following to find the gap:
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
switch(type)
{
case typeof(string):
itemData[i] = data.GetString(i);
break;
case typeof(DateTime):
itemData[i] = data.GetDateTime(i);
break;
case typeof(int):
itemData[i] = data.GetInt32(i);
break;
case typeof(decimal):
itemData[i] = data.GetDecimal(i);
break;
case typeof(bool):
itemData[i] = data.GetBoolean(i);
break;
case typeof(TimeSpan):
itemData[i] = data.GetTimeSpan(i);
break;
case typeof(Single):
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
break;
default:
MessageBox.Show("Unknown type " + type.Name);
break;
}
}
So, I got an advice to edit the oracle query
From (e.g.)
SELECT 26/7 FROM DUAL
TO
SELECT TO_CHAR(26/7) FROM DUAL
And yes it works
But still, I don't know why

Problem two query db2 sqlserver is not print output

This is the correct example, which does not work:
If the LANGUAGE column is the same as the LANGUAGE COLUMN and the NLS_CLASS_NAME column is the same as the KEYWORD COLUMN
Given that they are true, if you noticed the language string I turned it into lowercase and I cut the string so that it becomes "en", since it was first ENG
You must print the language list, keyword is translation
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
//Traduzione in Db2 a SqlServer
public void getTraduzione() throws Exception {
List<DizioPt> listDizio = new ArrayList<DizioPt>();
List<ClassHdrNls> listHdr = new ArrayList<ClassHdrNls>();
String className = "";
String language = "";
String nlsClassName = "";
String lingua = "";
String keyword = "";
String traduzione = "";
Database database = new Database();
// Db2
Connection dbConnectionDb2 = null;
Statement statementDb2 = null;
// SqlServer
Connection dbConnectionSqlServer = null;
Statement statementSqlServer = null;
// Query Db2
String queryDb2 = "select * from THERA.CLASS_HDR_NLS WHERE
THERA.CLASS_HDR_NLS.LANGUAGE='en'";
// Query SqlServer
String querySqlServer = "select * from DIZIOPT WHERE
DIZIOPT.LINGUA='ENG'";
try {
// Connessione --> SqlServer
dbConnectionSqlServer = database.getConnectionSqlServer();
statementSqlServer = dbConnectionSqlServer.createStatement();
// Connessione -->Db2
dbConnectionDb2 = database.getConnectionDb2();
statementDb2 = dbConnectionDb2.createStatement();
// Risultato SqlServer
ResultSet rsSqlServer = statementSqlServer.executeQuery(querySqlServer);
// Risultato Db2
ResultSet rsDb2 = statementDb2.executeQuery(queryDb2);
while (rsSqlServer.next() && rsDb2.next()) {
ClassHdrNls classHdrNls = new ClassHdrNls();
className = rsDb2.getString("CLASS_NAME");
classHdrNls.setClassName(className);
language = rsDb2.getString("LANGUAGE");
classHdrNls.setLanguage(language);
nlsClassName = rsDb2.getString("NLS_CLASS_NAME");
classHdrNls.setNlsClassName(nlsClassName);
listHdr.add(classHdrNls);
DizioPt diziopt = new DizioPt();
lingua = rsSqlServer.getString("LINGUA");
diziopt.setLingua(lingua);
keyword = rsSqlServer.getString("KEYWORD");
diziopt.setKeyword(keyword);
traduzione = rsSqlServer.getString("TRADUZIONE");
diziopt.setTraduzione(traduzione);
listDizio.add(diziopt);
for (int i = 0; i < listHdr.size(); i++) {
for (int j = 0; j < listDizio.size(); j++) {
if (listHdr.get(i).getNlsClassName().equalsIgnoreCase(listDizio.get(j).getKeyword())
&& listHdr.get(i).getLanguage()
.equalsIgnoreCase(listDizio.get(j).getLingua().toLowerCase().substring(0, 2))) {
System.out.println("Class name: " + listHdr.get(i).getClassName());
System.out.println("Lingua: " + listHdr.get(i).getLanguage());
System.out.println("Testo: " + listHdr.get(i).getNlsClassName());
System.out.println("Traduzione: " + listDizio.get(j).getTraduzione());
}
}
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statementDb2 != null && statementSqlServer != null) {
statementDb2.close();
statementSqlServer.close();
}
if (dbConnectionDb2 != null && dbConnectionSqlServer != null) {
dbConnectionDb2.close();
dbConnectionSqlServer.close();
}
}
}

NPOI does not evaluate 3d formula

I'm using NPOI to read data from Excel 2003 files. These files contains formulas like this SUM('1:2'!$C$17). NPOI recognized such formulas like SUM('1'!$C$17) (w/o sheet 2) and evaluate invalid result.
I'm using a regular code from NPOI examples, like
foreach (var row in docRows)
{
sb.AppendFormat("{0}\t", SomeCode);
rowCounter += 1;
sb.AppendFormat("{0}\t", rowCounter);
foreach (var col in docColumns)
{
ICell cell = sheet.GetRow(row).GetCell(col);
sb.AppendFormat("{0}\t", GetExcelCellValue(cell));
}
sb.AppendLine();
}
private string GetExcelCellValue(ICell cell)
{
string cellValue = string.Empty;
IFormulaEvaluator evaluator = _hssfworkbook.GetCreationHelper().CreateFormulaEvaluator();
evaluator.Evaluate(cell);
switch (evaluator.EvaluateInCell(cell).CellType)
{
case CellType.BLANK:
cellValue = string.Empty;
break;
case CellType.BOOLEAN:
cellValue = string.Empty;
break;
case CellType.NUMERIC:
cellValue = Convert.ToString(cell.NumericCellValue); //This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number.
break;
case CellType.STRING:
throw new ArgumentNullException();
cellValue = cell.StringCellValue;
break;
case CellType.ERROR:
cellValue = string.Empty;
break;
case CellType.FORMULA:
break;
}
return cellValue;
}
I have just encountered this problem and I solved it by
switch (cell.CellType)
{
case CellType.Blank:
cellValue = "";
break;
case CellType.Boolean:
cellValue = cell.BooleanCellValue.ToString();
break;
case CellType.Formula:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.Numeric:
cellValue = cell.NumericCellValue.ToString();
break;
case CellType.String:
cellValue = cell.StringCellValue;
break;
}

Resources