Printing to console removes hyperlinks created already - eclipse

I was trying to create a feature to create hyperlinks in the console while the information is added.
While debugging, I noticed that the first hyperlink is succesfully created, but when the next line is printed to console, the hyperlink dissapears.
The code which I use to create the hyperlinks is:
String hyperLinkText = "test";
myConsole.printToConsole(test);
String myFile = new File("D:/Test/testFile.txt");
URI location = myFile.toURI();
IFile[] files = project.getWorkspace().getRoot().findFilesForLocationURI(location);
HyperlinkInformation hyperlinkInformation = new HyperlinkInformation(myConsole, myConsole.getDocument().get().length(), hyperLinkText.length());
FileHyperlink fileHyperlink = new FileHyperlink(hyperlinkInformation,
files[0], 1);
try {
hyperlinkInformation.getConsole().addHyperlink(fileHyperlink,
fileHyperlink.getOffset(), fileHyperlink.getLength());
} catch (BadLocationException e) {
//
}
The function addHyperlink:
public void addHyperlink(IHyperlink hyperlink, int offset, int length) throws BadLocationException {
IDocument document = getDocument();
ConsoleHyperlinkPosition hyperlinkPosition = new ConsoleHyperlinkPosition(hyperlink, offset, length);
try {
document.addPosition(ConsoleHyperlinkPosition.HYPER_LINK_CATEGORY, hyperlinkPosition);
fConsoleManager.refresh(this);
} catch (BadPositionCategoryException e) {
ConsolePlugin.log(e);
}
}
Is this the normal behaviour or am I missing something?

Related

Generating a coruppted PDF file from a visual force page

I am trying to generate a PDF file attachment in an after update trigger and below is the trigger handler method but the file sent is corrupted.
public static void sendEOB(List<Claim_Payment__c> newList,Map<Id, Claim_Payment__c> oldMap){
for(Claim_Payment__c claimPayment : newList){
if (claimPayment.Status__c == 'Pending'){
String sfUrl = URL.getSalesforceBaseUrl().getHost();
String myURL = 'https://'+sfUrl+'/apex/ClaimPayments?Id='+ claimPayment.Id;
PageReference pdf = new PageReference(myURL);
// the contents of the report in pdf form
Blob body;
try {
body = pdf.getContent();
} catch (VisualforceException e) {
body = Blob.valueOf('PDF Get Failed');
}
Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
attach.setContentType('application/pdf');
attach.setFileName('Payment_Statement.pdf');
attach.setInline(false);
attach.Body = body;
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setUseSignature(false);
mail.setToAddresses(new String[] {'whatever#gmail.com' });
mail.setSubject('Payment Statement');
mail.setHtmlBody('Important Statement Attachment!');
mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });
// Send the email
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}
Update :
Using #future(callout=true) & getContentAsPDF() now i get this error message FATAL_ERROR Internal Salesforce.com Error on executing body = pdf.getContent();
public static void sendEOB(List<Claim_Payment__c> newList,Map<Id, Claim_Payment__c> oldMap){
for(Claim_Payment__c claimPayment : newList){
if (claimPayment.Status__c == 'Pending'){
String sfUrl = URL.getSalesforceBaseUrl().getHost();
String myURL = 'https://'+sfUrl+'/apex/ClaimPayments?Id='+ claimPayment.Id;
sendPDFEmail.sendPDF(myURL);
}
}
}
Public class sendPDFEmail{
#future(callout=true)
public static void sendPDF(String myURL){
PageReference pdf = new PageReference(myURL);
// the contents of the report in pdf form
Blob body;
body = pdf.getContentAsPDF();
// Rest of the implementation goes below
}
}
What errors (if any) you see in debug log? From what I remember you might need #future(callout=true) or other asynchronous processing (Queueable etc) because calling getContent counts as callout. And shouldn't that be getContentAsPdf? or is the page already set to renderas="pdf"?
If you download the file - what size it is, couple bytes or bigger? That try-catch is swallowing the actual error message, you don't even show it as System.debug(e); Remove the try-catch and check in the debbug what exactly it explodes on.

(log) File watching with citrus-framework

Is there a way and/or what are best practices to watch log files from the System Under Test?
My requirement is to validate presence/absence of log entries according known patterns produced by the SUT.
Thank you very much!
Well, I don't think there is a Citrus tool specifically designed for that. But I think that is a really good idea. You could open an issue and ask for this feature.
Meanwhile, here is a solution that we have used in one of our projects to check if the applicaiton log contained specific strings that were generated by our test.
sleep(2000),
echo("Searching the log..."),
new AbstractTestAction() {
#Override
public void doExecute(TestContext context) {
try {
String logfile = FileUtils.getFileContentAsString(Paths.get("target", "my-super-service.log").toAbsolutePath().normalize());
if (!logfile.contains("ExpectedException: ... | Details: BOOM!.")) {
throw new RuntimeException("Missing exceptions in log");
}
} catch (IOException e) {
throw new RuntimeException("Unable to get log");
}
}
}
OR you can replace that simple contains with a more elegant solution:
String grepResult = grepForLine(LOGFILE_PATH, ".*: SupermanMissingException.*");
if (grepResult == null) {
throw new RuntimeException("Expected error log entry not found");
}
The function goes over each line searching for a match to the regex supplied.
public String grepForLine(Path path, String regex) {
Pattern regexp = Pattern.compile(regex);
Matcher matcher = regexp.matcher("");
String msg = null;
try (
BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset());
LineNumberReader lineReader = new LineNumberReader(reader)
) {
String line;
while ((line = lineReader.readLine()) != null) {
matcher.reset(line); //reset the input
if (matcher.find()) {
msg = "Line " + lineReader.getLineNumber() + " contains the error log: " + line;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return msg;
}

GWT-RPC method returns empty list on success

I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;

How to indicate a file has changed after modifying it using IFile

I've been able to successfully update the contents of a file via a popup menu extension I've created underneath the Source menu that comes up when right-clicking on a file.
I'd like to indicate that the file has been changed and needs to be saved. Right now, the file contents change and save automatically. I thought the IFile.touch method would cause the file to be in a state where it needed to be saved but I'm not seeing that happen.
Here's my code...
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
IEditorInput input = editorPart.getEditorInput();
InputStream is = null;
if (input instanceof FileEditorInput) {
IFile file = ((FileEditorInput) input).getFile();
try {
is = file.getContents();
String originalContents = convertStreamToString(is);
String newContents = originalContents + "testing changing the contents...";
InputStream newInput = new ByteArrayInputStream(newContents.getBytes());
file.setContents(newInput, false, true, null);
file.touch(null);
} catch (CoreException e) {
MessageDialog.openError(
window.getShell(),
"Generate Builder Error",
"An Exception has been thrown when interacting with file " + file.getName() +
": " + e.getMessage());
}
}
return null;
}
If you want the file's contents marked as needing to be saved, you need to be interacting with the in-memory representation you want to prompt as needing to be saved--the editor from which you're getting the input.
Based on help from nitind and this post - Replace selected code from eclipse editor thru plugin comand - I was able to update the text editor and the file shows up as modified. The key was to work with the ITextEditor and IDocumentProvider instead of a FileEditor.
Here's the updated code...
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
if (editorPart instanceof ITextEditor ) {
ITextEditor editor = (ITextEditor)editorPart;
IDocumentProvider prov = editor.getDocumentProvider();
IDocument doc = prov.getDocument( editor.getEditorInput() );
String className = getClassName(doc.get());
ISelection sel = editor.getSelectionProvider().getSelection();
if (sel instanceof TextSelection ) {
TextSelection textSel = (TextSelection)sel;
String newText = generateBuilderText(className, textSel.getText());
try {
doc.replace(textSel.getOffset(), textSel.getLength(), newText);
} catch (Exception e) {
MessageDialog.openError(
window.getShell(),
"Generate Builder Error",
"An Exception has been thrown when attempting to replace "
+ "text in editor " + editor.getTitle() +
": " + e.getMessage());
}
}
}
return null;
}

Excel Export in MVC for IE not allowing to open multiple windows

Here is our ExcelExport action that inherits from ActionResult:
public class ExcelResult<Model> : ActionResult
{
string _fileName;
string _viewPath;
Model _model;
ControllerContext _context;
public ExcelResult(ControllerContext context, string viewPath, string fileName, Model model)
{
this._context = context;
this._fileName = fileName;
this._viewPath = viewPath;
this._model = model;
}
protected string RenderViewToString()
{
if (!_viewPath.EndsWith(".aspx"))
{
return _viewPath;
}
using (var writer = new StringWriter())
{
var view = new WebFormView(_context, _viewPath);
var vdd = new ViewDataDictionary<Model>(_model);
var viewCxt = new ViewContext(_context, view, vdd, new TempDataDictionary(), writer);
viewCxt.View.Render(viewCxt, writer);
return writer.ToString();
}
}
void WriteFile(string content)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachment;filename=\"" + _fileName + "\"");
context.Response.Charset = "";
//context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/ms-excel";
context.Response.Write(RemoveImages(content));
context.Response.End();
}
public override void ExecuteResult(ControllerContext context)
{
string content = this.RenderViewToString();
this.WriteFile(content);
}
public static string RemoveImages(string html)
{
StringBuilder retval = new StringBuilder();
using (StringReader reader = new StringReader(html))
{
string line = string.Empty;
do
{
line = reader.ReadLine();
if (line != null)
{
if (!line.StartsWith("<img"))
{
retval.Append(line);
}
}
} while (line != null);
}
return retval.ToString();
}
}
The export works fine, but in IE only (works in FF), if you export, and choose to open the file instead of save it, and then click export again right away, it tries to open another file with the same name and therefore Excel won't let you until you close your working document.
In FF however, the name just adds an integer that increments by 1 each time you click export.
What do I have to do to achieve the same functionality in IE?
I faced the same problem and out of the box you cant do anything because that's the way IE and Excel handle this. You are also not able to identify that a file of the same name is already opened. But you can use either JavaScript or the user session to identify that the user has already loaded the export within a timespan and and change the file name on server side for this download. That worked for me after 2 days of searching and mailing.