how do I extract attachments from integrity PTC items using Java API - mks-integrity

I'm trying to extract attachments from integrity PTC items that are on a linux server from my Windows PC but it keeps giving me errors. The exact same command worked in command line
IntegrationPoint integrationPoint =
IntegrationPointFactory.getInstance().createIntegrationPoint(
hostName,
port,
APIVersion.API_4_16);
System.out.println("Start download Attachment");
// Start the Integrity client.
integrationPoint.setAutoStartIntegrityClient(true);
// Connect to the Integrity server.
Session session = integrationPoint.createSession(username, password);
Command command = new Command(Command.IM, "extractattachments");
command.addOption(new Option("issue", itemID));
command.addOption(new Option("field", "Text Attachments"));
command.addSelection(attachment);
Response response = session.createCmdRunner().execute(command);
I'm getting an error that says
Error encountered trying to get the next name: File paths must be rooted in /export/home/ptc/Integrity/ILMServer11.0/data/tmp: Current file is /export/home/ptc/Integrity/ILMServer11.0/bin/C:\Workspace\document/bear.jpg
Anytime I add cwd to the command it just appends whatever I put after the /bin/ It says it's a InvalidCommandSelectionException and a CommandException

You're missing the outputFile option on the extractattachments command.
This code worked the way I expected it to ...
IntegrationPointFactory ipfact = IntegrationPointFactory.getInstance();
IntegrationPoint ip = ipfact.createIntegrationPoint(hostname, port, APIVersion.API_4_16);
Session session = ip.createNamedSession("test", APIVersion.API_4_16, user, passwd);
CmdRunner cr = session.createCmdRunner();
Command cmd = new Command(Command.IM, "extractattachments");
cmd.addSelection(attachmentName);
cmd.addOption(new Option("issue", issueid));
cmd.addOption(new FileOption("outputFile", "d:/data/" + attachmentName));
cr.execute(cmd);
cr.release();
ip.release();

Related

When importing a NetCDF into Geoserver Data Store a non obvious error occurs

I've a brand new install of Geoserver 2.22 on Ubuntu 22.04 and installation was smooth. I've added the official NetCDF plugin by unzipping the contents to the WEB-INF/lib/ folder, and it shows up as a type in the data store. Great!
I have a selection of NEtCDFs that can be loaded successfully elsewhere (QGIS, ArcGIS Pro, Python via Xarray), however, when I attempt to create a new data store, choose NetCDF and select the .nc files, I get the following error message:
There was an error trying to connect to store AFDRS_FSE_curing. Do you want to save it anyway?
Original exception error:
Failed to create reader from file:efs/temp_surface.nc and hints Hints: FORCE_LONGITUDE_FIRST_AXIS_ORDER = true EXECUTOR_SERVICE = java.util.concurrent.ThreadPoolExecutor#1242674b[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0] FILTER_FACTORY = FilterFactoryImpl STYLE_FACTORY = StyleFactoryImpl FEATURE_FACTORY = org.geotools.feature.LenientFeatureFactoryImpl#6bfaa0a6 FORCE_AXIS_ORDER_HONORING = http GRID_COVERAGE_FACTORY = GridCoverageFactory TILE_ENCODING = null REPOSITORY = org.geoserver.catalog.CatalogRepository#3ef5cfc5 LENIENT_DATUM_SHIFT = true COMPARISON_TOLERANCE = 1.0E-8
What am I missing here? That error message doesn't seem to be highlighting somethign obviously as an error...
The NetCDFs are located in: /usr/share/geoserver/data_dir/data

How do I make uCanAccess use Samba authentication, with special characters in username or password?

TL;DR: What Database.FileFormat constant should I use for an MS Access 2000-2003 database, when creating the Database object?
I have built a SAMBA test application using jCIFS. It allows me to create/overwrite files if given the correct authentication credentials, regardless of on which PC in the domain I use it.
I also have an application that uses uCanAccess/jackcess to connect to an MDB on a network share. However (from what I understand), it uses the credentials of the logged-in user, a number of whom have read-only access. Only system/network administrators have write permission.
The database in question is not password-protected. (I don't need to enter a password when opening it.)
My intention is to have the app ask for the administrator's Samba credentials before it writes to the DB, using those in the uCanAccess connection, so that it doesn't throw a java.nio.channels.NonWritableChannelException, as per the below stack trace:
java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:747)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:310)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:247)
at com.healthmarketscience.jackcess.impl.TableImpl.writeDataPage(TableImpl.java:1980)
at com.healthmarketscience.jackcess.impl.TableImpl.addRows(TableImpl.java:2229)
at com.healthmarketscience.jackcess.impl.TableImpl.addRow(TableImpl.java:2067)
at net.ucanaccess.converters.UcanaccessTable.addRow(UcanaccessTable.java:44)
at net.ucanaccess.commands.InsertCommand.insertRow(InsertCommand.java:101)
at net.ucanaccess.commands.InsertCommand.persist(InsertCommand.java:148)
at net.ucanaccess.jdbc.UcanaccessConnection.flushIO(UcanaccessConnection.java:315)
at net.ucanaccess.jdbc.UcanaccessConnection.commit(UcanaccessConnection.java:205)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:217)
at net.ucanaccess.jdbc.Execute.execute(Execute.java:46)
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.execute(UcanaccessPreparedStatement.java:228)
at myapp.db.Digger.addTransaction(Digger.java:993)
at myapp.tasks.TransactionRunnable.run(TransactionRunnable.java:42)
at java.lang.Thread.run(Thread.java:745)
Update: I have tried using the smbFileChannel class by Gord Thompson and J. T. Alhborn, shown here. My code, based off the main class shown in that answer, looks like this:
// Ask the user for login credentials and the path to the database
String smbURL = (chosenDir.endsWith("/") ? chosenDir : chosenDir + '/')
+ dbName;
System.out.println("DB Path to use for URL: " + smbURL);
URL u = new URL(smbURL);
try (
// construct the SMB DB URL
SmbFileChannel sfc = new SmbFileChannel(smbURL);
Database db = new DatabaseBuilder().setChannel(sfc)
.setFileFormat(Database.FileFormat.GENERIC_JET4).create();
) {
// Model the table
Table tbl = new TableBuilder("Transactions")
.addColumn(new ColumnBuilder("TransactionID", DataType.LONG).setAutoNumber(true))
.addColumn(new ColumnBuilder("ControllerID", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("ReaderID", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("Event", DataType.LONG).setAutoNumber(false))
.addColumn(new ColumnBuilder("Timestamp", DataType.SHORT_DATE_TIME).setAutoNumber(false))
.addColumn(new ColumnBuilder("Number", DataType.LONG).setAutoNumber(false))
.addIndex(new IndexBuilder(IndexBuilder.PRIMARY_KEY_NAME).addColumns("TransactionID").setPrimaryKey())
.toTable(db);
// Add the row
Map<String, Object> values = new HashMap<>();
values.put("ControllerID", cid);
values.put("ReaderID", rid);
values.put("Event", evtNum);
values.put("Timestamp", ts); // Long; must be converted to DataType.SHORT_DATE_TIME
values.put("Number", accNum);
tbl.addRowFromMap(values);
} catch (IOException IOEx) {
System.err.println(
"Failed to write record to Transactions table in database: "
+ IOEx.getMessage()
);
IOEx.printStackTrace(System.err);
} catch (Exception ex) {
System.err.println(
'[' + ex.getClass().getSimpleName() + "]: Failed to write record to "
+ "Transactions table in database: " + ex.getMessage()
);
ex.printStackTrace(System.err);
}
Executing the above code results in the following output:
DB Path to use for URL: smb://machine.vpnName/Storage/me/dbs/DBName.mdb
Failed to write record to Transactions table in database: Logon failure: account currently disabled.
jcifs.smb.SmbAuthException: Logon failure: account currently disabled.
at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:546)
at jcifs.smb.SmbTransport.send(SmbTransport.java:663)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:390)
at jcifs.smb.SmbSession.send(SmbSession.java:218)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:176)
at jcifs.smb.SmbFile.doConnect(SmbFile.java:911)
at jcifs.smb.SmbFile.connect(SmbFile.java:957)
at jcifs.smb.SmbFile.connect0(SmbFile.java:880)
at jcifs.smb.SmbFile.open0(SmbFile.java:975)
at jcifs.smb.SmbFile.open(SmbFile.java:1009)
at jcifs.smb.SmbRandomAccessFile.<init>(SmbRandomAccessFile.java:57)
at jcifs.smb.SmbRandomAccessFile.<init>(SmbRandomAccessFile.java:42)
at samba.SmbFileChannel.<init>(SmbFileChannel.java:30)
at samba.SambaLanWriteTest.writeTest(SambaLanWriteTest.java:130)
at samba.SambaLanWriteTest.main(SambaLanWriteTest.java:181)
I have write access to a test copy of the database file in question when using Windows File Explorer. I am choosing that one when prompted.
Update 2: I realised that I neglected to add my username and password to the smb:// URL, as Thompson's example shows. I changed to code to this:
String smbCred = "smb://" + auth.getUsername() + ":" + auth.getPassword() + "#",
fixer = chosenDir.replace("\\", "/").replace("smb://", smbCred),
smbURL = fixer + dbName;
System.out.println("DB Path to use for URL: " + smbURL);
// URL u = new URL(smbURL);
The next problem I had was that my password contains special illegal characters (such as '#', ':', ';', '=' and '?'). I escaped these by using java.net.URLEncoder.encode() on auth.getUsername() and auth.getPassword() so the code doesn't throw a MalformedURLException when creating the SmbChannel. However, the next exception I encountered is as follows:
Failed to write record to Transactions table in database: File format GENERIC_JET4 [VERSION_4] does not support file creation for null
java.io.IOException: File format GENERIC_JET4 [VERSION_4] does not support file creation for null
at com.healthmarketscience.jackcess.impl.DatabaseImpl.create(DatabaseImpl.java:444)
What Database.FileFormat constant should I use for an MS Access 2000-2003 database, when creating the Database object?
It turns out that I needed to use Database.FileFormat.V2000.
After that, it was all plain sailing (although I still need to work out how to get the Long timestamp to convert correctly).

sqlcmd runs fine and cmd line but will not produce output as a exec cmd step in a SQL Agent job

I am pulling my hair out and have tried every posting suggest.
I have a tsql script called C:\DBAReports\testsql.sql. If I go to a command logged prompt on my server, and run: sqlcmd -S localhost -i C:\DBAReports\testsql.sql -o C:\DBAReports\testout.txt
But if I create an new agent job with 1 step of type Operating system (CmdExec) to run as a SQL Server Agent Service Account, On Success Quit the job reporting success and on Failure Quit the job reporting failure. with the owner my same admin windows login as when I run the cmd prompt, right click on the agent job and start at step 1, I get the job succeeded (Job was invoked by my windows login), and the Step 1 is Executed as user is-sql "The step did not generate any output. Process Exit Code 0. The step was successful".
But it doesn't write the output file.
Any ideas?
The reason I want to do this is I am getting periodic Error: 18057, Severity: 20, State: 2 Failed to set up execution content in my sql server log. What I hope to do is kick off this job when this occurs to try and find out what are the SPIDs, status, SQL running, etc and write it to an output file.
My testsql.sql script contains.
SELECT
SPID = er.session_id
,STATUS = ses.STATUS
,[Login] = ses.login_name
,Host = ses.host_name
,BlkBy = er.blocking_session_id
,DBName = DB_Name(er.database_id)
,CommandType = er.command
,SQLStatement = st.text
,ObjectName = OBJECT_NAME(st.objectid)
,ElapsedMS = er.total_elapsed_time
,CPUTime = er.cpu_time
,IOReads = er.logical_reads + er.reads
,IOWrites = er.writes
,LastWaitType = er.last_wait_type
,StartTime = er.start_time
,Protocol = con.net_transport
,ConnectionWrites = con.num_writes
,ConnectionReads = con.num_reads
,ClientAddress = con.client_net_address
,Authentication = con.auth_scheme
FROM sys.dm_exec_requests er
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
Thanks in advance for any help. I have tried so many suggestions, and either get syntax errors on the command, and when I don't get any syntax error on the sqlcmd, it just generates no output.
An alternate way - try modifying the job step as Type: T-SQL script and the command as:
EXEC master..xp_CMDShell 'C:\Work\temp\test3.bat'
Please replace the bat file path with yours.

connecting the setInputStream and setOutputStream of the JSch to jTextField's

I am new to java and i need help.
I use the jsch libraries to create a SHH connection to a remote linux machine. In the next code, given from a tutorial of the JSCH creator, you can see it is implemented shell communication, it is a direct communication from a cmd window. You enter a command from the cmd window and you get aback the results in the cmd window.
String user = "username";
String host = "hostname";
session session=jsch.getSession(user, host, 22);
String passwd = JOptionPane.showInputDialog("Enter password");
session.setPassword(passwd);
Channel channel=session.openChannel("shell");
session.connect();
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
How i can connect the next two lines to jTextField1 and jTextField2. To give an example i want to sen the command from the jTextField1 and to get the results from the jTextField2.
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
Thank you in advanced
Instead of System.in you can give your desired stream .For example
String ls = "ls \n"; // here i am passing a string to stream, you can pass as you desire
InputStream in = new ByteArrayInputStream(ls.getBytes("UTF-8"));
channel2.setInputStream(in);//you passed the string as input
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(out);
channel2.setOutputStream(ps);
String result = out.toString();//here we get output to a string which you can add to your file.
This is one option There may be better ways.

Java Runtime Exec on Windows Fails with Unicode in Arguments

I want to launch a browser and load a web page using Java's Runtime exec. The exact call looks like this:
String[] explorer = {"C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE",
"-noframemerging",
"C:\\ ... path containing unicode chars ... \\Main.html"};
Runtime.getRuntime().exec(explorer);
In my case, the path contains "\u65E5\u672C\u8A9E", the characters 日本語.
Apparently it's a java bug:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4947220
My question is: is there a viable workaround that can be done solely using Java? It appears that it is possible to write a JNI library for this, but I'd like to avoid that if possible. I have tried URI-encoding the path as ascii and writing the commands to a batch file, without success.
At the mentioned Java bug page you will find a workaround that is reported to work using ProcessBuilder and wrapping the parameters in environment variables. Here is the source code from Parag Thakur:
String[] cmd = new String[]{"yourcmd.exe", "Japanese CLI argument: \ufeff\u30cb\u30e5\u30fc\u30b9"};
Map<String, String> newEnv = new HashMap<String, String>();
newEnv.putAll(System.getenv());
String[] i18n = new String[cmd.length + 2];
i18n[0] = "cmd";
i18n[1] = "/C";
i18n[2] = cmd[0];
for (int counter = 1; counter < cmd.length; counter++)
{
String envName = "JENV_" + counter;
i18n[counter + 2] = "%" + envName + "%";
newEnv.put(envName, cmd[counter]);
}
cmd = i18n;
ProcessBuilder pb = new ProcessBuilder(cmd);
Map<String, String> env = pb.environment();
env.putAll(newEnv);
final Process p = pb.start();
Create a .bat/.sh file. Write your commands to that file and execute it. Make sure that you have changed the code page to unicode in case of windows(chcp 65001).
For example to execute the below command in windows:
String[] command ={"C:\\aconex\\学校\\mysql\\bin\\mysql", "-esource", "大村箕島a\\data.sql"};
Create a temp file called temp.bat and execute with the Runtime.getRuntime().exec
temp.bat
chcp 65001
C:\aconex\学校\mysql\bin\mysql -esource 大村箕島a\data.sql
These are the two solutions I considered, each of which are more or less workarounds:
Create a temp html redirect file which will redirect the browser to the proper page.
Note that IE will expect unencoded unicode for local files, while other browsers may accept only uri-encoded file paths
Use the short filename for the windows file. It won't contain unicode characters.
We've been using a JNI to start processes from Java for years. Neither Runtime.exec or ProcessBuilder will work, and it seems unlikely that they will fix this, given how long it's been already.
However, you should be able to work around the issue by using the input stream, a socket, or environment variables to pass parameters. If you don't have direct control over the executable, you'll have to make a wrapper.
You could use JNA. With version 3.3.0 or later call CreateProcess:
WinBase.PROCESS_INFORMATION.ByReference processInfo =
new WinBase.PROCESS_INFORMATION.ByReference();
WinBase.STARTUPINFO startupInfo = new WinBase.STARTUPINFO();
String command = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE " +
"-noframemerging \"C:\\\u65E5\u672C\u8A9E\\Main.html\"";
if (!Kernel32.INSTANCE.CreateProcess(
null, // Application name, not needed if supplied in command line
command, // Command line
null, // Process security attributes
null, // Thread security attributes
true, // Inherit handles
0, // Creation flags
null, // Environment
null, // Directory
startupInfo,
processInfo))
{
throw new IllegalStateException("Error creating process. Last error: " +
Kernel32.INSTANCE.GetLastError());
}
// The CreateProcess documentation indicates that it is very important to
// close the returned handles
Kernel32.INSTANCE.CloseHandle(processInfo.hThread);
Kernel32.INSTANCE.CloseHandle(processInfo.hProcess);
long pid = processInfo.dwProcessId.longValue();
Redirecting output from the child process is a bit harder but not impossible.
I think you can use Apache Commons Exec library or ProcessBuilder to give a try;)

Resources