Looking to Parse the following code (Apache CLI 1.4), but it doesn't get into the if loop - jdeveloper

I have the following code in JDeveloper and I am trying to parse the output but can't seem to figure it out.
package project1;
import org.apache.commons.cli.*;
public class cmdParser
{
public static void main(String[] args)
{
try
{
Options options = new Options();
options.addOption("t", false, "display current time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("t"))
{
String optionT=cmd.getOptionValue("t");
System.out.println("Option t" + optionT);
}
else
{
System.out.println("Can't get the option");
}
}
catch(ParseException exp)
{
System.out.println("Error:" + exp.getMessage());
}
}
}
Output:
Click to enlarge the image

How do you get the option if you don't pass such an option...
Not sure how it is done in JDeveloper but from command line:
java cmdParser -t "my test option"
further more, you should use options.addOption("t", true, "display current time"); if you want to pass a value to the option. If the 2nd parameter is false, this option would just be a flag.

Related

How to paste the text copied in clipboard through Selenium and Java on MacOS

I want to paste some text in one of the textbox in MACOS. I am trying below code. But Control + v and Command + v both are not working. I have also seen that this is known issue, but not sure if it is resolved or not.
https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5919
The code is as below.
public void copyToClipbord(String copyTo)
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection str = new StringSelection(copyTo);
clipboard.setContents(str, null );
}
// And paste into required input/testfield/testarea field object
public void pasteText(WebElement element, String value)
{
copyToClipbord(value);
element.click();
//new Actions( driver ).contextClick( element ).sendKeys( "P" ).sendKeys("\n").perform();
element.sendKeys(Keys.CONTROL, "V");
}
I have also tried context click, that also does not work. I have validated that copyToClipboard function is working properly. Please suggest me, if there are any work around to this.
Thanks,
Umang
You have to select paste option in pop up which open after right and then click on paste option.
You can write code like this.
new Actions(driver ).contextClick(element).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).
sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
For me Paste option is present at 5th position. So I have written sendKeys(Keys.ARROW_DOWN) 5 times. You can write this as per your requirement.
I hope this will work for you.
As you have mentioned copyToClipboard() function is working properly moving forward to send the character sequence through sendKeys() you can use the following solution:
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
copyToClipbord(value);
String data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
element.sendKeys(data);
public String copyFromClipboard() {
boolean found = false
String data = ''
int count = 0
while (found == false) {
count++
try {
WebDriver driver = DriverFactory.getWebDriver()
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
data = ((Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor)) as String)
if (!(data.contains('https'))) {
found = false
} else {
println((('Found the data in the ' + count) + ' try: ') + data)
return data
found = true
break
}
}
catch (UnsupportedFlavorException e) {
println(e)
}
catch (IOException e) {
println(e)
}
}
}

How to send enter as an input in console application

I want to create a console application and want to send command prompt commands
but I dont know how to send enter in it
Module Module1
Sub Main()
Console.ForegroundColor = ConsoleColor.Green
Console.Write("tree")
End Sub
End Module
If you don't use Enter as the termination of input. How do you alert the console that you finish your input?
Suppose that you press X to terminate the input.
You can use do while loop runs to listen what you press (including the Enter to break line) until you press X. Something like:
public static string CustomReadline()
{
string s = "";
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
if (keyinfo.Key == ConsoleKey.Enter)
{
Console.WriteLine();
}
s += keyinfo.KeyChar.ToString();
}
while (keyinfo.Key != ConsoleKey.X);
return s;
}
and you call the method to receive the input
static void Main(string[] args)
{
var s = CustomReadline();
}

java 8 - some error with compiling lambda function

public class GrammarValidityTest {
private String[] dataPaths = new String[] {"data/", "freebase/", "tables/", "regex/"};
#Test(groups = {"grammar"})
public void readGrammars() {
try {
List<String> successes = new ArrayList<>(), failures = new ArrayList<>();
for (String dataPath : dataPaths) {
// Files.walk(Paths.get(dataPath)).forEach(filePath -> {
try {
if (filePath.toString().toLowerCase().endsWith(".grammar")) {
Grammar test = new Grammar();
LogInfo.logs("Reading grammar file: %s", filePath.toString());
test.read(filePath.toString());
LogInfo.logs("Finished reading", filePath.toString());
successes.add(filePath.toString());
}
}
catch (Exception ex) {
failures.add(filePath.toString());
}
});
}
LogInfo.begin_track("Following grammar tests passed:");
for (String path : successes)
LogInfo.logs("%s", path);
LogInfo.end_track();
LogInfo.begin_track("Following grammar tests failed:");
for (String path : failures)
LogInfo.logs("%s", path);
LogInfo.end_track();
assertEquals(0, failures.size());
}
catch (Exception ex) {
LogInfo.logs(ex.toString());
}
}
}
The line beginning with // is the one that brings up the error -"illegal start of expression" starting at the '>' sign.
I do not program much in java. I just downloaded a code from somewhere that is quite popular and supposed to run but I got this error. Any help/fixes/explanation would be appreciated.
Run javac -version and verify that you are actually using the compiler from JDK8, it's possible that even if your java points to the 1.8 releaase, your javac has a different version.
If you are using Eclipse, remember to set the source type for your project to 1.8.
Edit:
Since you are using ant, verify that your JAVA_HOME environment variable points to your jdk1.8 directory.

keyboard vs menu conflict on Java 7, Mac OS

How can I get a Java 7 application to have its menu bar at the top of the screen (on a Mac) and also have correctly working keyboard shortcuts?
I have a Java application with a Swing user interface. Many menus have keyboard equivalents, which are essential.
There is very little that is system-dependent, but on Mac OS X the menu bar should appear at the top of the screen instead of on each window, so I set apple.laf.useScreenMenuBar.
This works fine on Java 6, but on Java 7 (out last week!) compiling and running the same code causes the keyboard shortcuts to carry out their menu actions twice. For example, in the attached code, Command ⌘ + O opens two file dialogues instead of one. (The other keyboard shortcuts also act twice, but you sometimes have to move windows to see that they did.)
The keyboard problem goes away if I don't set apple.laf.useScreenMenuBar, and that's what I'll do if I have to, but my Mac users will be displeased. I'd really like to have the menu bar in the right place and the keyboard shortcuts working.
System: Mac OS 10.7.3 (Lion) on a late-2010 MacBook Pro
Java 7:
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b21)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b21, mixed mode)
Java 6:
java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b04-415-11M3635)
Java HotSpot(TM) 64-Bit Server VM (build 20.6-b01-415, mixed mode)
Where I've looked:
A discussion of why apple.laf.useScreenMenuBar should be gotten rid of
-- I'm all for it, but it doesn't seem to have happened.
A discussion about not using mrj.version to detect that you're on a Mac
-- not directly relevant, but sounded promising.
My apologies for the length of the attached code (148 lines), but my Swing coding is very old-fashioned. It should compile and run from the command line without any special flags or settings.
import javax.swing.*;
import java.awt.Toolkit;
import java.awt.*;
import java.awt.event.*;
/**
* Shows that using the single screen-top menu bar on a Mac with Java 7
* causes keyboard shortcuts to act twice.
*
* To see the problem(on a Mac -- running OS X 10.7.3 in my case):
* 1) compile on either Java 6 or Java 7
* 2) run on Java 7
* 3) give the command-O shortcut
* You will see two file dialogues.
*
* -- J. Clarke, May 2012
*/
public class MenuBug {
private static void go(String[] args) {
// Comment out the following line to fix the problem;
// leave it active to see the problem.
// It doesn't help to ...
// ... put the line into a static block.
// ... put the line right after the setLookAndFeel call.
// ... put the line before after the setLookAndFeel call.
System.setProperty("apple.laf.useScreenMenuBar", "true");
MainWindow mainWindow = new MainWindow();
}
public static void main(final String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,
e + " while loading look and feel",
"MenuBug error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
go(args);
}
});
}
}
class MainWindow extends JFrame {
MainWindow() {
super ("Main Window");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener (new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
JMenuBar menuBar = createMenuBar();
setJMenuBar(menuBar);
pack();
setSize(350,300);
setVisible(true);
}
private JMenuBar createMenuBar() {
JMenuBar mBar = new JMenuBar();
JMenu menu = new JMenu("File");
String[] menuItemNames = new String[] {"New", "Open...", "Other"};
for (int i = 0; i < menuItemNames.length; i++) {
String miName = menuItemNames[i];
JMenuItem mi = new JMenuItem(miName);
mi.setActionCommand(miName);
linkMenuItemToAction(mi);
menu.add(mi);
}
mBar.add(menu);
return mBar;
}
/**
* Create an Action for menuItem, and make sure the action and the menu
* item know about each other; where appropriate, add keyboard equivalents.
* #param menuItem The menu item to be linked to an action.
*/
private void linkMenuItemToAction(JMenuItem menuItem) {
final int META_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
Action a = null;
String miName = menuItem.getActionCommand();
if (miName.equals ("New")) {
a = new NewAction();
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
META_MASK));
}
else if (miName.equals ("Open...")) {
a = new OpenAction();
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
META_MASK));
}
else if (miName.equals ("Other")) {
a = new OtherAction();
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
META_MASK));
}
menuItem.setEnabled(a.isEnabled());
menuItem.addActionListener(a);
}
private class NewAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
new MainWindow();
}
}
private void makeDialog() {
String dialogTitle = "Please choose a file to open";
FileDialog fileDialog = new FileDialog(this, dialogTitle,
FileDialog.LOAD);
fileDialog.setVisible(true);
String fileName = fileDialog.getFile();
}
private class OpenAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
makeDialog();
}
}
private class OtherAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"an example message",
"not really an error", JOptionPane.ERROR_MESSAGE);
}
}
}
I'm answering my own question -- sort of. As noted in the comments to the original, the trouble goes away with Java 1.7u10.
It looks like that this problem still exist but now it can be reproduced with fn + backSpace (delete) on mac with 1.7_21.
I used the same example as above just added text field. Select part of text in textfield and press delete (fn+backspace)
Change KeyStroke to "DELETE" in linkMenuItemToAction method
else if (miName.equals ("Other"))
{
a = new OtherAction();
menuItem.setAccelerator(KeyStroke.getKeyStroke("DELETE"));
}
and add this:
JTextField textField = new JTextField(10);
textField.setText("Long long long long long long long text");
add(textField, BorderLayout.PAGE_START);
to MainWindow constructor.

How to create a Mathematica Notebook in Java?

I am looking for the prototypical 'Hello World' program that creates a Mathematica Notebook file.
I have this working program.
package graphica;
import com.wolfram.jlink.*;
/**
*
* #author Nilo
*/
public class MathematicaTester {
public static void main(String[] args) {
KernelLink ml = null;
String jLinkDir = "C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\SystemFiles\\Links\\JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir);
try {
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\MathKernel.exe'");
ml.discardAnswer();
String expr = "Sum[k^2,{k,1,11}]";
ml.evaluate(expr);
ml.waitForAnswer();
String x = ml.getString();
System.out.println("Result = " + x);
} catch (MathLinkException e) {
System.out.println("Fatal error opening link: " +
e.getMessage());
return;
}
}
}
When I run this I get the following -expected- output.
run:
Result = 506
BUILD SUCCESSFUL (total time: 2 seconds)
QUESTION:
I want to change this program so that a Mathematica Notebook is created. The program will ( eventually ) add line after line of mma command strings. It would be nice if a Mathematica frontend is started at the same time and that the mma code is evaluated by request from the Java program. Essential is the creation of a Notebook that can be opened later by the mma front-end.
A method for creating a formatted notebook file is shown here:
How to create a notebook with a properly formatted expression
You can box format your Mathematica code (mathCommand) using a kernel call, e.g.
String mathCommand = "Plot[Sin[x], {x, 0, 6}]";
mathCommand = "FullForm[ToBoxes[Defer[" + mathCommand + "]]]";
MathKernel kernel = new MathKernel();
kernel.Compute(mathCommand);
mathCommand = kernel.Result.ToString();
Then encapsulate it like so, and save it with .nb extension.
Notebook[{Cell[BoxData[
... ( inserted box-formatted output ) ...
], "Input"]
},
WindowSize->{615, 750},
WindowMargins->{{328, Automatic}, {Automatic, 76}},
StyleDefinitions->"Default.nb"
]
Mathematica notebooks are plaintext files with structures like
Notebook[{Cell[],Cell[]}]
You can work out the required structure by viewing them with a text editor. Assuming you can get Java to create a text file, save it with a .nb file name ending, and invoke the command-line version of Mathematica, then what you want should be doable. You will probably want to set the input cells to initialization type.
It took some research but I managed to answer the question myself.
package graphica;
import com.wolfram.jlink.*;
/**
*
* #author Nilo
*/
public class MathematicaTester {
public static void main(String[] args) {
KernelLink ml = null;
String jLinkDir = "C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\ \SystemFiles\\Links\\JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir);
try {
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\MathKernel.exe'");
//test-1
ml.discardAnswer();
String expr = "Sum[k,{k,1,11}]";
ml.evaluate(expr);
ml.waitForAnswer();
String x = ml.getString();
System.out.println("Result = " + x);
//test-2
expr = "UsingFrontEnd[nb=NotebookPut[Notebook[{Cell[\"Graphics3D[Cuboid[]]\", \"Input\"]}]]]";
System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
expr = "UsingFrontEnd[NotebookSave[nb,\"TERRANOVA1\"]]";
System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
} catch (MathLinkException e) {
System.out.println("Fatal error opening link: " +
e.getMessage());
return;
}
}
}

Resources