How do I retrieve a Mac OS setting using Java? - java

Mac OS has a setting that allows users to define when scroll bars should be visible (automatically, when scrolling, always).
Is there a way to find out the current setting using Java?

For me, running on macOS 10.14.6, the setting (when not set to "automatic") can be found in the current user's global preferences ~/Library/Preferences/.GlobalPreferences.plist. This file has content such as:
{
AKDeviceUnlockState = :false;
AKLastIDMSEnvironment = 0;
AppleActionOnDoubleClick = "Maximize";
AppleAntiAliasingThreshold = 4;
AppleInterfaceStyle = "Dark";
AppleLanguages = ( "en-US" );
AppleLanguagesDidMigrate = "10.14.6";
AppleLocale = "en_US";
AppleMiniaturizeOnDoubleClick = :false;
AppleShowScrollBars = "Always";
...
}
I'm not 100% sure if this covers all possible scenarios, but you could start by parsing this file, finding the AppleShowScrollBars value and using that to drive your desired functionality.
There's a handy library called dd-plist that allows you to use the following code:
try {
final File preferences = new File("~/Library/Preferences/.GlobalPreferences.plist");
final NSDictionary root = (NSDictionary) PropertyListParser.parse(preferences);
final String scrollbars = root.get("AppleShowScrollBars").toString();
System.out.println(scrollbars);
} catch (Exception e) {
// Handle errors
System.out.println();
}

Related

Netbeans module development - How to modify opened file

I am writing my own Netbeans plugin to edit opened files. I have managed to get some information about currently active file using
TopComponent activeTC = TopComponent.getRegistry().getActivated();
FileObject fo = activeTC.getLookup().lookup(FileObject.class);
io.getOut().println(fo.getNameExt());
io.getOut().println(fo.canWrite());
io.getOut().println(fo.asText());
But I have no idea how to modify this file. Can someone help me with this?
And second question, how to get text selection ranges? I want to run my command only on selected text.
For modifying the file you could use the NetBeans org.openide.filesystems.FileUtil.toFile() and then the regular Java stuff to read and write files and for getting the selected text of the current editor window you would have to do something like:
Node[] arr = activeTC.getActivatedNodes();
for (int j = 0; j < arr.length; j++) {
EditorCookie ec = (EditorCookie) arr[j].getCookie(EditorCookie.class);
if (ec != null) {
JEditorPane[] panes = ec.getOpenedPanes();
if (panes != null) {
// USE panes
}
}
}
For more code examples see also here
After several hours of research I found out that:
The code I posted in Question can be used to obtain basic information about active file.
To get caret position or get selection range you can do:
JTextComponent editor = EditorRegistry.lastFocusedComponent();
io.getOut().println("Caret pos: "+ editor.getCaretPosition());
io.getOut().println("Selection start: "+ editor.getSelectionStart());
io.getOut().println("Selection end: "+ editor.getSelectionEnd());
To modify content of active file (in a way that the modification can be undo by Ctrl+z) you may use this code:
final StyledDocument doc = context.openDocument();
NbDocument.runAtomicAsUser(doc, new Runnable() {
public void run() {
try {
doc.insertString(ofset, "New text.", SimpleAttributeSet.EMPTY);
} catch (Exception e) {
}
}
});

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);
}
}
}
}

Jacob Export Outlook Contact Pictures (Java, Jacob)

Good Morning,
I’am using Jacob 1.17 o read all my Outlook Contact Pictures and save them to an File. The Procedure works pretty fine for the first 199 Contatcs. After that the Dispatch.call fails and terminates with the following Exception:
Exception in thread "main" com.jacob.com.ComFailException: Invoke of: SaveAsFile
Source: Microsoft Outlook
Description: Cannot save the attachment. Cannot create file: ContactPicture.jpg.
Right-click the folder you want to create the file in, and then click Properties on
the shortcut menu to check your permissions for the folder.
at com.jacob.com.Dispatch.invokev(Native Method)
at com.jacob.com.Dispatch.invokev(Dispatch.java:625)
at com.jacob.com.Dispatch.callN(Dispatch.java:453)
at com.jacob.com.Dispatch.call(Dispatch.java:541)
at outlookStuff.ManageContactsOutlook.tmpTest(ManageContactsOutlook.java:217)
at mainPackage.Main.main(Main.java:32)
I’m really not sure way. I tested a different set of Contacts – same Error. Set all Objects to null to make shore that the Garbage Collector is involved but it doesn’t help.
The piece of Code which makes the trouble:
public void tmpTest(int intOutlookFolder, String strWorkingDir) {
Dispatch dipNamespace = this.axc.getProperty("Session").toDispatch();
Dispatch dipContactsFolder = Dispatch.call(dipNamespace, "GetDefaultFolder", (Object) new Integer(intOutlookFolder)).toDispatch();
Dispatch dipContactItems = Dispatch.get(dipContactsFolder, "items").toDispatch();
#SuppressWarnings("deprecation")
int count = Dispatch.call(dipContactItems, "Count").toInt();
for (int i=1; i<=count; i++) {
Dispatch dipContact;
dipContact = Dispatch.call(dipContactItems, "Item", new Integer(i)).toDispatch();
String strEntryID = Dispatch.get(dipContact, "EntryID").toString().trim();
//For Testing
Status.printStatusToConsole("Outlook Contact "+strEntryID+" loaded");
byte[] byteContactPicture = null;
String strPathToTmpPicture = null;
Dispatch dipAttachments = Dispatch.get(dipContact, "Attachments").toDispatch();
#SuppressWarnings("deprecation")
int countAttachements = Dispatch.call((Dispatch) dipAttachments, "Count").toInt();
for (int j=1; j<=countAttachements; j++) {
Dispatch currentAttachement;
currentAttachement = Dispatch.call(dipAttachments, "Item", new Integer(j)).toDispatch();
if (Dispatch.get(currentAttachement, "FileName").toString().equals("ContactPicture.jpg")) {
strPathToTmpPicture = strWorkingDir+strEntryID+".jpg";
//The Crashing Part
Dispatch.call(currentAttachement, "SaveAsFile", strPathToTmpPicture);
File tmpFile = new File(strPathToTmpPicture);
if (tmpFile.exists()) {
try {
byteContactPicture = org.apache.commons.io.FileUtils.readFileToByteArray(tmpFile);
} catch (IOException e) {
e.printStackTrace();
}
}
currentAttachement = null;
tmpFile = null;
}
currentAttachement = null;
}
dipAttachments = null;
}
dipContactItems = null;
dipContactsFolder = null;
dipNamespace = null;
}
May someone has an idea?
Thanks
Aviation

How to execute the Windows 'printto' verb using Java?

In the past I have used the 'printto' verb to print PDFs from with a .Net application. It looked something like this:
ProcessStartInfo psi = new ProcessStartInfo(file);
psi.Verb = "printto"; // print to given printer
psi.Arguments = "LPT1";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.ErrorDialog = true;
Process.Start(psi);
How can I do this from a Java application? Or is there an alternative approach? Note that the target platform will always be Windows.
Please try this.
public void print() {
//The desktop api can help calling native applications in windows
Desktop desktop = Desktop.getDesktop();
try {
desktop.print(new File("yourFile.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
Please Note : This is the easy fix. You can also use java's Print API to achieve the same thing

Get GPS data from an image Java code

I would like to get the metadata from an image file in my local system using Java code
In the attached image you can see the desired data which i would like to pull from java code.
I wrote the below code and do not seem pull the data mentioned in the "Details" tab. The below code's output is and this is not what I look for.
Started ..
Format name: javax_imageio_jpeg_image_1.0
Format name: javax_imageio_1.0
Please give me your ideas. Thanks
try {
ImageInputStream inStream = ImageIO.createImageInputStream(new File("D:\\codeTest\\arun.jpg"));
Iterator<ImageReader> imgItr = ImageIO.getImageReaders(inStream);
while (imgItr.hasNext()) {
ImageReader reader = imgItr.next();
reader.setInput(inStream, true);
IIOMetadata metadata = reader.getImageMetadata(0);
String[] names = metadata.getMetadataFormatNames();
int length = names.length;
for (int i = 0; i < length; i++) {
System.out.println( "Format name: " + names[ i ] );
}
}
} catch (IOException e) {
e.printStackTrace();
}
There's no easy way to do it with the Java Core API. You'd have to parse the image's metadata tree, and interpret the proper EXIF tags. Instead, you can pick up the required code from an existing library with EXIF-parsing capabilities, and use it in yours. For example, I have used the Image class of javaxt, which provides a very useful method to extract GPS metadata from an image. It is as simple as:
javaxt.io.Image image = new javaxt.io.Image("D:\\codeTest\\arun.jpg");
double[] gps = image.getGPSCoordinate();
Plus, javaxt.io.Image has no external dependencies, so you can just use that particular class if you don't want to add a dependency on the entire library.
I suggest you read the EXIF header of the image and then parse the tags for finding the GPS information. In Java there is a great library (called metadata-extractor) for extracting and parsing the EXIF header. Please see the getting started for this library here.
Once you do the first 2 steps in the tutorial, look for the tags starting with [GPS] ([GPS] GPS Longitude, [GPS] GPS Latitude, ...).
Based on #dan-d answer, here is my code (kotlin)
private fun readGps(file: String): Optional<GeoLocation> {
// Read all metadata from the image
// Read all metadata from the image
val metadata: Metadata = ImageMetadataReader.readMetadata(File(file))
// See whether it has GPS data
val gpsDirectories = metadata.getDirectoriesOfType(
GpsDirectory::class.java)
for (gpsDirectory in gpsDirectories) {
// Try to read out the location, making sure it's non-zero
val geoLocation = gpsDirectory.geoLocation
if (geoLocation != null && !geoLocation.isZero) {
return Optional.of(geoLocation)
}
}
return Optional.empty()
}

Categories

Resources