Eclipse Plugin change Language programmatically - eclipse

I am trying to change the language of my RCP plugin programmatically. I had no luck so far. The Approach below is not working for me. After restart the language does not change. I populate a Menu dynamically with listet Translation files in a specific folder. The method LanguageSelectedListener.widgetSelected when a MenuItem is selected. Tried this with an exported product and also running from eclipse.
private void setMenuLanguages(Menu menu){
File dir = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + language_directory);
String[] dirList = dir.list();
String currentLocale = System.getProperty("user.language");
Locale current = new Locale(currentLocale, "", "");
Locale[] locales = new Locale[dirList.length];
LanguageSelectedListener listener = new LanguageSelectedListener();
for(int i=0; i<dirList.length; i++){
String file = dirList[i].split(".properties")[0];
String locShort;
if(file.equals("messages"))locShort = "en"; //default english
else locShort = file.split("_")[1];
locales[i] = new Locale(locShort);
MenuItem menuItem = new MenuItem(menu, SWT.RADIO, i);
menuItem.setText(locales[i].getDisplayName());
menuItem.setData("locale", locales[i]);
menuItem.addSelectionListener(listener);
if(locales[i].getLanguage().equals(current.getLanguage()))
menuItem.setSelection(true);
}
return;
}
private class LanguageSelectedListener extends SelectionAdapter{
#Override
public void widgetSelected(SelectionEvent e) {
MenuItem item = (MenuItem) e.widget;
if(!item.getSelection() || !MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Info", "Programm wird neu gestartet. Möchten Sie fortfahren?")){
item.setSelection(false);
return;
}
Locale locale = (Locale) item.getData("locale");
StringBuffer arguments = new StringBuffer();
arguments.append("${eclipse.vm}\n"); //$NON-NLS-1$
arguments.append("-nl\n").append(locale.getLanguage()).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
System.setProperty("eclipse.exitcode", Integer.toString(IApplication.EXIT_RELAUNCH)); //$NON-NLS-1$
System.getProperties().setProperty(IApplicationContext.EXIT_DATA_PROPERTY, arguments.toString());
PlatformUI.getWorkbench().restart();
}
}
so I implemented the hacky solution by manipulating the ini file of the product (not the config.ini file). Works pretty well for me.
String installLoc = Platform.getInstallLocation().getURL().getPath();
String oldIniLocation = installLoc + "decoder.ini";
String content = null;
File oldIni = null;
try {
oldIni = new File(oldIniLocation);
content = FileUtils.readFileToString(oldIni, "UTF-8");
} catch (IOException e1) {
throw new RuntimeException("reading from file failed!", e1);
}
Locale locale = (Locale) item.getData("locale");
if(content.contains("-nl")){
content = content.replaceFirst("-nl\r\n..", "-nl\r\n" + locale.getLanguage());
}
else{
StringBuilder newContent = new StringBuilder("-nl\r\n" + locale.getLanguage() +"\r\n");
content = newContent.append(content).toString();
}
File newIni = new File(installLoc + "rename.ini");
try {
FileUtils.writeStringToFile(newIni, content, "UTF-8");
} catch (IOException e1) {
throw new RuntimeException("writing to file failed!", e1);
}
oldIni.delete();
//renaming newIni by moving it
oldIni = new File(installLoc + "decoder.ini");
try {
FileUtils.moveFile(newIni, oldIni);
} catch (IOException e1) {
throw new RuntimeException("renaming/moving file failed!", e1);
}
System.setProperty("eclipse.exitcode", Integer.toString(IApplication.EXIT_RESTART)); //$NON-NLS-1$
PlatformUI.getWorkbench().restart();

Related

Android 8 - FileProvider Uri opens a blank screen

I have the following code and it's only working on Android 7 and below. Android 8 only shows a blank file, I opened the pdf manually and works fine.
I have the following code and this is the repo:
private static final String SHARED_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID + ".myfileprovider";
private static final String PDF_FOLDER = "pdf";
Bitmap bitmap = myCanvasView.getBitmap();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
document.finishPage(page);
// write the document content
File file = null;
try {
file = createFile();
document.writeTo(new FileOutputStream(file));
} catch (IOException e) {
e.printStackTrace();
showToast("Something wrong: " + e.toString());
}
// close the document
document.close();
Uri uri = getUriFrom(file);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
Where:
#NonNull
private Uri getUriFrom(File file){
if(Build.VERSION.SDK_INT >= 26) {
return FileProvider.getUriForFile(getApplicationContext(), SHARED_PROVIDER_AUTHORITY, file);
}
else{
return Uri.fromFile(file);
}
}
#NonNull
private File createFile() throws IOException {
if(Build.VERSION.SDK_INT >= 26){
final File sharedFolder = new File(getFilesDir(), PDF_FOLDER);
sharedFolder.mkdirs();
final File sharedFile = File.createTempFile(getFilename(), ".pdf", sharedFolder);
sharedFile.createNewFile();
return sharedFile;
}
else{
return new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ getFilename());
}
}
I found a solution for you. Just add flag Intent.FLAG_GRANT_READ_URI_PERMISSION to your intent:
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri,"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
I just tested it with your repo on Pixel 2 XL with Android 8.1 and got rid of this issue:
And got things working:
Hope this could help you! :)

Issue in converting HTML to PDF containing <pre> tag with Flying Saucer and ITEXT

I am using Flying Saucer library to convert html to pdf. It is working fine with the all the HTML files.
But for some HTML files which include some tags in pre tag, generated PDF file has tags displayed.
If I remove pre tags then the formatting of data is lost.
My code is
org.w3c.dom.Document document = null;
try {
Document doc = Jsoup.parse(new File(htmlFile), "UTF-8", "");
Whitelist wl = new RelaxedPlusDataBase64Images();
Cleaner cleaner = new Cleaner(wl);
doc = cleaner.clean(doc);
Tidy tidy = new Tidy();
tidy.setShowWarnings(false);
tidy.setXmlTags(false);
tidy.setInputEncoding("UTF-8");
tidy.setOutputEncoding("UTF-8");
tidy.setPrintBodyOnly(true);
tidy.setXHTML(true);
tidy.setMakeClean(true);
tidy.setAsciiChars(true);
if (doc.select("pre").html().contains("</")) {
doc.select("pre").unwrap();
}
Reader reader = new StringReader(doc.html());
document = (tidy.parseDOM(reader, null));
Element element = (Element) document.getElementsByTagName("head").item(0);
element.getParentNode().removeChild(element);
NodeList elements = document.getElementsByTagName("img");
for (int i = 0; i < elements.getLength(); i++) {
String value = elements.item(i).getAttributes().getNamedItem("src").getNodeValue();
if (value != null && value.startsWith("cid:") && value.contains("#")) {
value = value.substring(value.indexOf("cid:") + 4, value.indexOf("#"));
elements.item(i).getAttributes().getNamedItem("src").setNodeValue(value);
System.out.println(value);
}
}
document.normalize();
System.out.println(getNiceLyFormattedXMLDocument(document));
} catch (Exception e) {
System.out.println(e);
}
Method to create PDF is :
try {
org.w3c.dom.Document doc = CleanHtml.cleanNTidyHTML("b.html");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.setPDFVersion(new Character('7'));
String outputFile = "test.pdf";
OutputStream os = new FileOutputStream(outputFile);
renderer.layout();
renderer.createPDF(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
By using itext XMLWorker :
try {
org.w3c.dom.Document doc = CleanHtml.cleanNTidyHTML("a.html");
String k = CleanHtml.getNiceLyFormattedXMLDocument(doc);
OutputStream file = new FileOutputStream(new File("test.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
ByteArrayInputStream is = new ByteArrayInputStream(k.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
public static String getNiceLyFormattedXMLDocument(org.w3c.dom.Document doc) throws IOException, TransformerException {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
// transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
Writer stringWriter = new StringWriter();
StreamResult streamResult = new StreamResult(stringWriter);
transformer.transform(new DOMSource(doc), streamResult);
String result = stringWriter.toString();
return result;
}

iText rotation creates pdf which displays out of memory exception

Following is a code snippet creating a pdf file where pages could be rotated in the resulting file. This works fine for most pdf files. But one particualr pdf file of version 1.6 the page is already rotated by 180, on applying further rotation to it e.g. 90 degress and saving the file causes it to get corrupted. Infact even if you don't rotate the file and simply write it out to another file using iText the file the resulting pdf is corrupted and displays an out of memory exception when opened in Adobe reader.
Why would that happen? Am I missing some sort of compression in the file.
private String createPdfFileWithoutForms(final EditStateData[] editStateData, final String directory)
throws EditingException {
Long startTime = System.currentTimeMillis();
File pdfFileToReturn = new File(directory + File.separator + UidGenerator.generate() + ".pdf");
com.lowagie.text.Document document = null;
FileOutputStream outputStream = null;
PdfCopy pdfCopy = null;
PdfReader reader = null;
PdfDictionary pageDict = null;
int rotationAngle = 0;
Map<Integer, Integer> rotationQuadrants = null;
try {
document = new com.lowagie.text.Document();
outputStream = new FileOutputStream(pdfFileToReturn);
pdfCopy = new PdfCopy(document, outputStream);
pdfCopy.setFullCompression();
pdfCopy.setCompressionLevel(9);
document.open();
for (EditStateData state : editStateData) {
try {
reader = new PdfReader(state.getFileName());
reader.selectPages(state.getPages());
rotationQuadrants = state.getRotationQuadrants();
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
// Rotation quadrant key is the source page number
if (rotationQuadrants.containsKey(state.getPages().get(i - 1))) {
rotationAngle = reader.getPageRotation(i);
pageDict = reader.getPageN(i);
pageDict.put(PdfName.ROTATE,
new PdfNumber((rotationAngle
+ rotationQuadrants.get(state.getPages().get(i - 1))) % 360));
}
document.setPageSize(reader.getPageSizeWithRotation(i));
document.newPage();
// import the page from source pdf
PdfImportedPage page = pdfCopy.getImportedPage(reader, i);
// add the page to the destination pdf
pdfCopy.addPage(page);
}
} catch (final IOException e) {
LOGGER.error(e.getMessage(), e);
throw new EditingException(e.getMessage(), e);
} finally {
if (reader != null) {
reader.close();
}
}
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new EditingException(e.getMessage(), e);
} finally {
if (document != null) {
document.close();
}
if (pdfCopy != null) {
pdfCopy.close();
}
IoUtils.closeQuietly(outputStream);
}
LOGGER.debug("Combining " + editStateData.length + " pdf files took "
+ ((System.currentTimeMillis() - startTime) / 1000) + " msecs");
return pdfFileToReturn.getAbsolutePath();
}

How do I convert text files to .arff format(weka)

Please advise me How do I convert text files to .arff format(weka)
because i wan to do data clustering for 1000 txt file.
regards
There are some converters implemented in WEKA, just find the right format or make little changes to your data (using awk, sed...).
Here is the API pages related to this topic: http://weka.sourceforge.net/doc.stable/weka/core/converters/package-summary.html
For exapmle here is how to convert from CSV to ARFF:
java weka.core.converters.CSVLoader filename.csv > filename.arff
Here is the code you can use
package text.Classification;
import java.io.*;
import weka.core.*;
public class TextDirectoryToArff {
public Instances createDataset(String directoryPath) throws Exception {
FastVector atts;
FastVector attVals;
atts = new FastVector();
atts.addElement(new Attribute("contents", (FastVector) null));
String[] s = { "class1", "class2", "class3" };
attVals = new FastVector();
for (String p : s)
attVals.addElement(p);
atts.addElement(new Attribute("class", attVals));
Instances data = new Instances("MyRelation", atts, 0);
System.out.println(data);
InputStreamReader is = null;
File dir = new File(directoryPath);
String[] files = dir.list();
for (int i = 0; i < files.length; i++) {
if (files[i].endsWith(".txt")) {
double[] newInst = new double[2];
File txt = new File(directoryPath + File.separator + files[i]);
is = new InputStreamReader(new FileInputStream(txt));
StringBuffer txtStr = new StringBuffer();
int c;
while ((c = is.read()) != -1) {
txtStr.append((char) c);
}
newInst[0] = data.attribute(0).addStringValue(txtStr.toString());
int j=i%(s.length-1);
newInst[1] = attVals.indexOf(s[j]);
data.add(new Instance(1.0, newInst));
}
}
return data;
}
public static void main(String[] args) {
TextDirectoryToArff tdta = new TextDirectoryToArff();
try {
Instances dataset = tdta.createDataset("/home/asadul/Desktop/Downloads/text_example/class5");
PrintWriter fileWriter = new PrintWriter("/home/asadul/Desktop/Downloads/text_example/abc.arff", "UTF-8");
fileWriter.println(dataset);
fileWriter.close();
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}

Android reading text fie from sdcsrd and store it in ArrayList

I need help on this one, I am trying to read a text file stored in sdcard and store the result in an ArrayList for subsequent usage, but the code is crashing.
public class Mytextreader extends Activity {
final ArrayList> dataList = new ArrayList>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadData();
String text = "";
for (int i = 0; i < dataList.size(); i++) {
text = text + dataList.get(i).get("name") + ":"
+ dataList.get(i).get("image") + ":"
+ dataList.get(i).get("price") + ":"
+ dataList.get(i).get("barcode") + "\n";
}
TextView txv = (TextView) findViewById(R.id.textView01);
txv.setText(text);
}
private void loadData() {
File sdcardDir = Environment.getExternalStorageDirectory();
String sdcard = sdcardDir.getAbsolutePath();
File file = new File(sdcard + "/Downloads/data/data.txt");
// For each entry the following lines are repeated
HashMap<String, String> hmap = new HashMap<String, String>();
String text = "", line = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text = text + line + "\n";
}
br.close();
} catch (IOException e) {
Log.d("File Read test: Error= ", e.getMessage());
}
while (true) {
line = text.substring(0, text.indexOf('\n'));
text = text.substring(text.indexOf('\n') + 1);
hmap.put("name", line.substring(0, line.indexOf(';')));
line = line.substring(line.indexOf(';') + 1);
// Toast.makeText(this, line, Toast.LENGTH_LONG).show();
hmap.put("image", line.substring(0, line.indexOf(';')));
line = line.substring(line.indexOf(';') + 1);
// Toast.makeText(this, line, Toast.LENGTH_LONG).show();
hmap.put("price", line.substring(0, line.indexOf(';')));
line = line.substring(line.indexOf(';') + 1);
// Toast.makeText(this, line, Toast.LENGTH_LONG).show();
hmap.put("barcode", line);
dataList.add(hmap);
hmap.clear();
if (text.length() == 0)
break;
}
}
}
Ok fixed, the text file has an empty line, removed that line and the code is ok now