netbeans makefile java execution - java

Here I have attached the source code and make file of it.
I use netbeans. How should I build my project to execute this java code in netbeans. please help me with detailed steps. I am new to netbeans and java.
I use netbeans 8.0.2 for windows 10 64 bit OS.
Source code:
package net.sourceforge.jpcap.tutorial.example15;
import net.sourceforge.jpcap.capture.*;
import net.sourceforge.jpcap.net.*;
/*
* This example utilizes the endCapture() feature.
*/
public class Example15 {
private static final int INFINITE = -1;
private static final int PACKET_COUNT = INFINITE;
// BPF filter for capturing any packet
private static final String FILTER = "";
private PacketCapture m_pcap;
private String m_device;
public Example15() throws Exception {
// Step 1: Instantiate Capturing Engine
m_pcap = new PacketCapture();
// Step 2: Check for devices
m_device = m_pcap.findDevice();
// Step 3: Open Device for Capturing (requires root)
m_pcap.open(m_device, true);
// Step 4: Add a BPF Filter (see tcpdump documentation)
m_pcap.setFilter(FILTER, true);
// Step 5: Register a Listener for Raw Packets
m_pcap.addRawPacketListener(new RawPacketHandler(m_pcap));
// Step 6: Capture Data (max. PACKET_COUNT packets)
m_pcap.capture(PACKET_COUNT);
}
public static void main(String[] args) {
try {
Example15 example = new Example15();
} catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
class RawPacketHandler implements RawPacketListener
{
private static int m_counter = 0;
private PacketCapture m_pcap = null;
public RawPacketHandler(PacketCapture pcap) {
m_counter = 0;
m_pcap = pcap;
}
public synchronized void rawPacketArrived(RawPacket data) {
m_counter++;
System.out.println("Packet " + m_counter + "\n" + data + "\n");
if(condition())
m_pcap.endCapture();
}
private boolean condition() {
return (m_counter == 5) ? true : false;
}
}
make file:
# $Id: makefile,v 1.1 2002/07/10 23:05:26 pcharles Exp $
#
# package net.sourceforge.jpcap.tutorial.example15
#
PKG = net.sourceforge.jpcap.tutorial.example15
PKG_DIR = $(subst .,/, $(PKG))
REL = ../../../../..
include ${MAKE_HOME}/os.makefile
include ${MAKE_HOME}/rules.makefile
JAVA = \
Example15
JAVA_SOURCE = $(addsuffix .java, $(JAVA))
JAVA_CLASSES = $(addsuffix .class, $(JAVA))
all: $(JAVA_CLASSES)
include ${MAKE_HOME}/targets.makefile
include ${MAKE_HOME}/depend.makefile

Netbeans uses Makefiles for C++ code but not for Java code. It is easy to get this code to build but there is no need for the Makefile.
File -> New Project
Select Category Java on the left and "Java Application with Existing Sources" (with this option the project and sources will be in different directories) on the right.
Click Next
Change the Project name and/or directory to create the project in.
Add the original source directory in the dialog.
Click Finish to Create the project.
Within netbeans you can now use the Run-> Build Project to build it.
If you really have to have a Makefile just make one that just runs the Netbeans project( which is actually an ant project).
eg.
build:
ant jar

Related

java class getResource can't find icons listed in jar file

I am really stumped. I'm just an old C X11/Motif programmer trying to write a little Java program. After a week of reading the Oracle Java Documentation, as well as the
Stack Overflow answers related to getResource, I still can not figure out how to retrieve the path to the icon files in my jar file.
My icons are contained within the jar file for my application. I wish to access them using the relative position within jar file. I am assuming the best way to do this is through the getResource method.
The core part of my code for my program called Fŭd (pronounced food - like the cat spells it in the comic strip "Get Fuzzy") is as follows:
package localhost.system1;
imports not shown for brevity.
public class Fud extends JPanel
implements FocusListener, ActionListener, ItemListener
{
private static final long serialVersionUID = 1L;
static Food data = null;
static int prev = 0;
static int next = 1;
static int plus = 2;
static int minus = 3;
public static void main(String args[]) throws Exception
{
LocalDate now = LocalDate.now();
int dateDifference = 0;
// load in the existing data
data = new Food(programName);
data.loadFood(programName);
// test to see if data is up to date. Add days if not
dateDifference = Math.abs((int)ChronoUnit.DAYS.between(now, data.day[0].date));
if ( dateDifference != 0)
{
data.adjustToToday(dateDifference, programName);
}
/////////////////////////////////////////////////
// create the GUI and switch running over to it.
/////////////////////////////////////////////////
Fud fud = new Fud();
Class<? extends Fud> fudClass = fud.getClass();
String className = fudClass.getName();
System.out.println("fudClass getname returns " + className);
URL testURL = fudClass.getResource("prev.png");
System.out.println("fudClass getResource returned " + testURL);
// Create GUI and turn the control over to it
javax.swing.SwingUtilities.invokeLater
(new Runnable()
{
public void run()
{
URL[] iconURL = new URL[4];
iconURL[prev] = Fud.class.getResource("prev.png");
iconURL[next] = Fud.class.getResource("next.png");
iconURL[plus] = Fud.class.getResource("plus.png");
iconURL[minus] = Fud.class.getResource("minus.png");
createAndShowGUI(fud, iconURL);
}
}
);
} // end of main
.
.
.
Rest of methods and subroutines needed
.
.
.
}
When run, the code returns the following results:
fudClass getname returns localhost.system1.Fud
fudClass getResource returned null
This has me quite frustrated. No matter what I try (and I have tried a number of things) the result remains the same. I keep getting NULL for a response from the getResource method. When I query the jar file with jar -tf Fud.jar I get the following:
jar tf Fud.jar
META-INF/MANIFEST.MF
localhost/
localhost/system1/
localhost/system1/Day.class
localhost/system1/Food.class
localhost/system1/Fud$1.class
localhost/system1/Fud$2.class
localhost/system1/Fud$3.class
localhost/system1/Fud$4.class
localhost/system1/Fud$5.class
localhost/system1/Fud$6.class
localhost/system1/Fud$7.class
localhost/system1/Fud.class
minus.png
next.png
plus.png
prev.png
So the icons are in the Jar file. Can anyone tell me what I am doing wrong? In Eclipse, my project explorer looks like:eclipse Project Explorer
I added the Image directory to my project Java build in eclipse as follows: Eclipse Java Build
I built the program using Eclipse Version: 2021-12 (4.22.0) Build id: 20211202-1639. Furthermore, I am using Java 17.0.1 2021-10-19 LTS on Windows 11 Pro build 22000.434.
You have to add a slash in front of the resource:
Fud.class.getResource("/prev.png");
otherwise java searching in the same folder as the class is located,
so it will search in localhost/system1

How to call cplex .mod and .data from Java

I have an optimization problem modelled and written in IBM ILOG CPLEX Optimization Studio. I want to call .mod and .dat from Java. I found some example to do it. However, I got some error.
My code is shown below. I also added all cplex and opl library
package cplexJava;
import ilog.concert.*;
import ilog.cplex.*;
import ilog.opl.*;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
model();
}
public static void model() {
int status = 127;
IloOplFactory.setDebugMode(true);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler();
IloOplModelSource modelSource = oplF.createOplModelSource("D:/Cplex project/Example_2/Example_2.mod");
IloOplSettings settings = oplF.createOplSettings(errHandler);
IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings);
IloCplex cplex = oplF.createCplex();
cplex.setOut(null);
IloOplModel opl = oplF.createOplModel(def, cplex);
IloOplDataSource dataSource = oplF.createOplDataSource("D:/Cplex project/Example_2/Example_2.dat");
opl.addDataSource(dataSource);
opl.generate();
if (cplex.solve())
{
System.out.println("OBJECTIVE: " + opl.getCplex().getObjValue());
opl.postProcess();
opl.printSolution(System.out);
}
else
{
System.out.println("No solution!");
}
oplF.end();
status = 0;
System.exit(status);
}
}
In my code, the errors came from from oplF.createCplex() and cplex.solve(). When I tried to run it, this is the error I got.
I could not figure out why I got the errors from oplF.createCplex() and cplex.solve() although I already added the cplex and opl library
Actually your IDE tells you what the problem is: There are possible IloExceptions thrown and you do not handle them. You need to either surround your code with a try catch block, or your main-method should have a "throws IloException" in the signature:
package cplexJava;
import ilog.concert.*;
import ilog.cplex.*;
import ilog.opl.*;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
model();
}
public static void model() {
int status = 127;
try {
IloOplFactory.setDebugMode(true);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler();
IloOplModelSource modelSource = oplF.createOplModelSource("D:/Cplex project/Example_2/Example_2.mod");
IloOplSettings settings = oplF.createOplSettings(errHandler);
IloOplModelDefinition def = oplF.createOplModelDefinition(modelSource,settings);
IloCplex cplex = oplF.createCplex();
cplex.setOut(null);
IloOplModel opl = oplF.createOplModel(def, cplex);
IloOplDataSource dataSource = oplF.createOplDataSource("D:/Cplex project/Example_2/Example_2.dat");
opl.addDataSource(dataSource);
opl.generate();
if (cplex.solve())
{
System.out.println("OBJECTIVE: " + opl.getCplex().getObjValue());
opl.postProcess();
opl.printSolution(System.out);
}
else
{
System.out.println("No solution!");
}
oplF.end();
} catch (IloException ilx) {
// log error message or something like that
}
status = 0;
System.exit(status);
}
}
And please use class names with upper case first letter and package names with all lower case.
For the OPL Java API, you should only need oplall.jar.
SETUP
On my x86-64 Linux machine with Eclipse 3.6, this is done, like so (hopefully it's similar for you):
Right click on your Java Project and select Properties
Select "Java Build Path" on the left and the Libraries tab on the right
Click on the "Add External JARs..." button and select COS_INSTALL_DIR/opl/lib/oplall.jar (where COS_INSTALL_DIR is the location where you installed CPLEX Optimization Studio)
Click OK
One more thing to do is make sure that your LD_LIBRARY_PATH environment variable is set to COS_INSTALL_DIR/opl/bin/x86-64_linux. (NOTE: On Windows, I think you should set the PATH environment variable instead.) You can set this in Eclipse, like so:
Select "Run > Run Configurations..." in the menu
On the left, select your java application
On the right, select the Environment tab and click on the "New..." button
Enter LD_LIBRARY_PATH in the Name field (try PATH on Windows)
Enter COS_INSTALL_DIR/opl/bin/x86-64_linux in the Value field (again, where COS_INSTALL_DIR is the location where you installed CPLEX Optimization Studio)
Click OK
FIX COMPILER ERRORS
Once you have that set up, you'll probably notice that you are still getting compiler errors (the little red squiggle lines indicate this). Hover your mouse over the those and you'll be presented with a list of quick fixes: 1) add throws declaration; 2) Surround with try/catch. Pick one of those to fix the issue. After all of the red squiggly lines are gone you should be able to run your program.
If you're not familiar with fixing compiler errors in Eclipse, maybe this Eclipse tutorial with help. Sometimes you have to select "Project > Clean" to force a recompile.
I also faced the the same problem.
After some trial and error I realized that the correct name is DYLD_LIBRARY_PATH for macos.
Referral link

Unable to retrieve JaCoCo coverage from exec file via Java API

We have JaCoCo for coverage. Some tests spawn a new java process for which I add the jacocoagent arguments and I get the expected jacoco.exec. Each file has a different path.
i.e. -javaagent:path/jacoco.jar=destfile=path/to/output.exec
I merge those and generate a report in which they correctly show as covered from those external processes.
Later I try to use the merged.exec using the Java API but I can't get coverage on those methods to perform some internal calculations.
In some cases I found that there might be multiple class coverage records for certain line (I assume depending on how many times that particular line was executed) so I use the following methods to get the best coverage out of those:
private List<IClassCoverage> getJacocoCoverageData(ExecutionDataStore
execDataStore,
String classFile) throws IOException
{
List<IClassCoverage> result = new ArrayList<>();
logger.debug("Processing coverage for class: " + classFile);
final CoverageBuilder coverageBuilder = new CoverageBuilder();
final Analyzer analyzer = new Analyzer(execDataStore, coverageBuilder);
File file = new File(this.workspaceRoot, classFile);
logger.debug("Analyzing coverage in: " + file);
if (file.exists())
{
try (FileInputStream fis = new FileInputStream(file))
{
analyzer.analyzeClass(fis, file.getAbsolutePath());
}
Iterator<IClassCoverage> it = coverageBuilder.getClasses().iterator();
while (it.hasNext())
{
result.add(it.next());
}
}
return result;
}
private IClassCoverage getBestCoverage(List<IClassCoverage> coverage,
int workingCopyLine)
{
IClassCoverage coverageData = null;
for (IClassCoverage cc : coverage)
{
ILine temp = cc.getLine(workingCopyLine);
if (coverageData == null
|| temp.getStatus()
> coverageData.getLine(workingCopyLine).getStatus())
{
coverageData = cc;
}
}
return coverageData;
}
Somehow I only find not covered coverage data. Both the reports and the methods above look at the same merged.exec file.
This turned out to be something completely unrelated to the JaCoCo file. The code above worked fine.

How to check in a file into TFS using Java SDK

I am planning to integrate the TFS with another application using websevice.
I am new to TFS.so I downloaded the TFS Java SDK 2010.I have been writing s sample program to checkin file into TFS. but not successful. On internet also not much helpful post for Java side SDK samples.
Below is the code I have written:-
public static void main(String[] args) {
// TODO Auto-generated method stub
TFSTeamProjectCollection tpc = SnippetSettings.connectToTFS(); //got the connection to TFS
VersionControlClient vcc = tpc.getVersionControlClient();
//WorkspaceInfo wi = Workstation.Current.GetLocalWorkspaceInfo(Environment.CurrentDirectory);
//vcc.get
String[] paths =new String[1];
paths[0]="D:\\Tools\testfile.txt"; //wants to checkin this local file
Workspace ws = vcc.createWorkspace(null,"Testworkspacename3", null, "","Testcomment",null, null); // this is workspace created at path local C:\ProgramData\Microsoft Team Foundation Local Workspaces
int item = ws.pendAdd(paths, true, null, LockLevel.NONE, GetOptions.GET_ALL, PendChangesOptions.GET_LATEST_ON_CHECKOUT); // this line gives me 0 count. so this is problematic . 0 means nothing is being added.
PendingSet pd = ws.getPendingChanges();
PendingChange[] pendingChanges = pd.getPendingChanges();
ws.checkIn(pendingChanges, "samashti comment");
Project project = tpc.getWorkItemClient().getProjects().get(SnippetSettings.PROJECT_NAME);
System.out.println();
Please help here...what is the wrong here. Can some one provide me correct working sample for new file checkin and existing file checkin using JAVA.
Just refer these steps below:
Connect to team project collection
Get version control client
Create a new workspace
Add file to workspace
Get pending changes
Check in pending changes
Below are some links about TFS SDK for JAVA for your reference:
https://github.com/gocd/gocd/blob/master/tfs-impl/src/com/thoughtworks/go/tfssdk/TfsSDKCommand.java
https://github.com/jenkinsci/tfs-plugin/blob/master/src/main/java/hudson/plugins/tfs/commands/NewWorkspaceCommand.java
Please see the code snippet for creating and mapping workspace as per TFS-SDK-14.0.3
public static Workspace createAndMapWorkspace(final TFSTeamProjectCollection tpc) {
final String workspaceName = "SampleVCWorkspace" + System.currentTimeMillis(); //$NON-NLS-1$
Workspace workspace = null;
// Get the workspace
workspace = tpc.getVersionControlClient().tryGetWorkspace(ConsoleSettings.MAPPING_LOCAL_PATH);
// Create and map the workspace if it does not exist
if (workspace == null) {
workspace = tpc.getVersionControlClient().createWorkspace(
null,
workspaceName,
"Sample workspace comment", //$NON-NLS-1$
WorkspaceLocation.SERVER,
null,
WorkspacePermissionProfile.getPrivateProfile());
// Map the workspace
final WorkingFolder workingFolder = new WorkingFolder(
ConsoleSettings.MAPPING_SERVER_PATH,
LocalPath.canonicalize(ConsoleSettings.MAPPING_LOCAL_PATH));
workspace.createWorkingFolder(workingFolder);
}
System.out.println("Workspace '" + workspaceName + "' now exists and is mapped"); //$NON-NLS-1$ //$NON-NLS-2$
return workspace;
}

How to edit a microsoft window spacing from a java application?

i'm trying to implement steganography's word shifting coding protocol on a microsoft word report using java application. Basicly, it uses an existing report and edit it's spacing to put some secret data. If it's wider, then its 1 bit data. And if it's narrower, then it's 0 bit data. So i wonder what kind of library should i have to start constructing this java app or if java doesn't support this kind of comunication with ms-word what kind language of programming should i use, thank you for your time.
I would recommend using C# and the Microsoft.Office.Interop.Word. You can use the free Visual Studio Community version (https://www.visualstudio.com/products/visual-studio-community-vs), create a console application and add a reference for the interop namespace (in project explorer, right click on references, add reference: COM->Microsoft Word 16.0 Object Library).
Simple example:
namespace WordShiftingExample
{
class Program
{
private static int[] getSpaces(string text)
{
System.Collections.ArrayList list = new System.Collections.ArrayList();
int index = 0;
while (index != text.LastIndexOf(" "))
{
index = text.IndexOf(" ", index + 1);
list.Add(index);
}
return list.ToArray(typeof(int)) as int[];
}
static void Main(string[] args)
{
try
{
Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
winword.ShowAnimation = false;
winword.Visible = false;
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
float zero = 0.1F;
float one = 0.15F;
document.Content.Text = "This is a test document.";
//set word-spacing for first two spaces
int[] spaces = getSpaces(document.Content.Text);
document.Range(spaces[0], spaces[0]+1).Font.Spacing=zero;
document.Range(spaces[1], spaces[1]+1).Font.Spacing = one;
//read word-spacing for first two spaces
System.Diagnostics.Debug.WriteLine(document.Range(spaces[0], spaces[0]+1).Font.Spacing); // prints 0.1
System.Diagnostics.Debug.WriteLine(document.Range(spaces[1], spaces[1]+1).Font.Spacing); // prints 0.15
//Save the document
object filename = System.Environment.GetEnvironmentVariable("USERPROFILE")+"\\temp1.docx";
document.SaveAs2(ref filename);
document.Close(ref missing, ref missing, ref missing);
document = null;
winword.Quit(ref missing, ref missing, ref missing);
winword = null;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
}
}
}

Categories

Resources