I would like to use CognitiveJ (GitHub from CognitiveJ) but all I get is:
Status:401; Body: {"error":{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}}
Here is the Code:
public static String lic1 = "xxx";
public static String lic2 = "xxx";
public static void main(String[] args) throws IOException {
new Bildkontrolle();
}
public Bildkontrolle() throws IOException {
File imageFile = new File("E:\\DSC00306.jpg");
new FaceRecognicion(lic1, lic2, imageFile);
}
And here the second class:
public FaceRecognicion(String lic1, String lic2, File imageFile) throws IOException {
BufferedImage bufImage = ImageIO.read(imageFile);
InputStream inpStream = new FileInputStream(imageFile);
FaceScenarios faceScenarios = new FaceScenarios(lic1,
lic1);
ImageOverlayBuilder imageOverlayBuilder = ImageOverlayBuilder.builder(bufImage);
imageOverlayBuilder.outlineFacesOnImage(faceScenarios.findFaces(inpStream), RectangleType.FULL,
CognitiveJColourPalette.STRAWBERRY).launchViewer();
}
Does anyone have an examplecode where I can look up how to use the API.
I stuck at the point where to send the Request.
Related
I am attempting to run a simple HTTP server that I will send a request to with JSON string in the body and I need to extract data from it. I'm new to Java and having a difficulty doing so. Ive searched online and most of the examples dont work for me, so there must be something im doing wrong.
public class shareManagerServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
HttpContext context = server.createContext("/shareWithUser");
context.setHandler(shareManagerServer::handleshareWithUserRequest);
server.start();
}
private static void handleshareWithUserRequest(HttpExchange exchange) throws IOException {
if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
Headers requestHeaders = exchange.getRequestHeaders();
// Request body
String body = utils.readString(exchange.getRequestBody());
}
}
}
Based on this, how would I get this to an object that I can access the JSON information with? For testing im sending this curl:
curl -X POST -d "{'age':26,'email':'norman#futurestud.io','isDeveloper':true,'name':'Norman'}" localhost:8500/shareWithUser
Edit:
From my utils:
public class utils {
public static String readString(InputStream inputStream) throws IOException {
ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int n; 0 < (n = inputStream.read(buf));) {
into.write(buf, 0, n);
}
into.close();
return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
}
}
First you can create class with having all the properties
public class Person {
private int age;
private String email;
private boolean isDeveloper;
private String name;
//getters and setters
}
Now it is pretty string forward by using Gson
String body = utils.readString(exchange.getRequestBody());
Gson gson = new Gson();
Person person = gson.fromJson(body, Person.class);
Here is the code to read a PDF with iText5, and it works :
public class CreateTOC {
public static final String SRC = "file.pdf";
class FontRenderFilter extends RenderFilter {
public boolean allowText(TextRenderInfo renderInfo) {
String font = renderInfo.getFont().getPostscriptFontName();
return font.endsWith("Bold") || font.endsWith("Oblique");
}
}
public static void main(String[] args) throws IOException, DocumentException {
new CreateTOC().parse(SRC);
}
public void parse(String filename) throws IOException {
PdfReader reader = new PdfReader(filename);
Rectangle rect = new Rectangle(1000, 1000);
RenderFilter regionFilter = new RegionTextRenderFilter(rect);
FontRenderFilter fontFilter = new FontRenderFilter();
TextExtractionStrategy strategy = new FilteredTextRenderListener(
new LocationTextExtractionStrategy(), regionFilter, fontFilter);
System.out.println(PdfTextExtractor.getTextFromPage(reader, 56, strategy));
reader.close();
}
}
Can someone help me to do it working in iText7 ? There are problems with the Rectangle and the TextExtractionStrategy (it's not the same constructor as iText5)
Edit : RenderFilter isn't available in iText7...
I am referring below Github link,
https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/storage/json-api/src/main/java/StorageSample.java
Code Snippet
public static void uploadFile(String bucketName, String targetPath, String filePath) throws Exception {
Storage storage = getStorage();
StorageObject object = new StorageObject();
object.setBucket(bucketName);
File file = new File(filePath);
InputStream stream = new FileInputStream(file);
try {
// String contentType =
// URLConnection.guessContentTypeFromStream(stream);
InputStreamContent content = new InputStreamContent("image/jpeg", stream);
Storage.Objects.Insert insert = storage.objects().insert(bucketName, null, content);
insert.setName(targetPath + file.getName());
insert.execute();
} finally {
stream.close();
}
}
public static void uploadFile(String name, String targetPath, String contentType, File file, String bucketName)
throws IOException, GeneralSecurityException, Exception {
InputStreamContent contentStream = new InputStreamContent(contentType, new FileInputStream(file));
contentStream.setLength(file.length());
StorageObject objectMetadata = new StorageObject().setName(targetPath + name)
.setAcl(Arrays.asList(new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
Storage client = getStorage();
Storage.Objects.Insert insertRequest = client.objects().insert(bucketName, objectMetadata, contentStream);
insertRequest.execute();
}
private static Storage getStorage() throws Exception {
if (storage == null) {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
// Collection<String> scopes = StorageScopes.all();
Credential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory).setServiceAccountId(getProperties().getProperty(ACCOUNT_ID_PROPERTY))
.setServiceAccountPrivateKeyFromP12File(
new File(getProperties().getProperty(PRIVATE_KEY_PATH_PROPERTY)))
.setServiceAccountScopes(scopes).build();
storage = new Storage.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(getProperties().getProperty(APPLICATION_NAME_PROPERTY)).build();
}
return storage;
}
public static void main(String[] args) throws Exception {
// CloudStorage.createBucket("my-bucket3/good");
CloudStorage.uploadFile("my-static", "temp/",
"/Users/rupanjan/Downloads/15676285_10158033346085311_1317913818452680683_o.jpg");
CloudStorage.uploadFile("15676285_10158033346085311_1317913818452680683_o.jpg", "temp/", "image/jpeg",
new File("/Users/rupanjan/Downloads/15676285_10158033346085311_1317913818452680683_o.jpg"),
"my-static");
// CloudStorage.downloadFile("my-bucket", "some-file.jpg",
// "/var/downloads");
List<String> buckets = CloudStorage.listBuckets();
System.out.println(buckets.size());
}
The issue I am facing,
I am able to upload the file successfully, but whenever, I click on that "Public Link", it downloads automatically. My intention was to share it for all user with read access.
N.B. If I am uploading the file manually from browser, I am able to open the file in browser, but when I upload it programically, it downloads everytime I click on "Public Link"
Please correct me if I am missing anything!!
It sounds like you know the name of the bucket and the object, and that the objects are all publicly readable, and that you want a URL that you can share that will allow others to read the object.
There is no need to use the "public link" functionality in the console for this. Public URLs can be constructed programmatically. They follow this pattern:
https://storage.googleapis.com/bucket_name/object_name
This question is based on this question.
With provided comments, i had written three different tests to validate properly set content-types.
#Test
public void testGetImageJpg_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_JPG);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.jpg").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_JPEG))
.andExpect(content().bytes(expectedBytes));
}
#Test
public void testGetImagePng_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_PNG);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.png").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_PNG))
.andExpect(content().bytes(expectedBytes));
}
#Test
public void testGetImageGif_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_GIF);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.gif").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_GIF))
.andExpect(content().bytes(expectedBytes));
}
This is my controller, where all tests succeed:
#RequestMapping(value="/getImage/{id}/{path}", produces = {"image/png","image/jpeg","image/gif"})
#ResponseBody
byte[] getImage(#PathVariable("id") String id,
#PathVariable("path") String path) throws ImageNotFoundException {
File imageFile = service.getImage(id, path);
InputStream in;
try {
in = new FileInputStream(imageFile);
return IOUtils.toByteArray(in);
} catch (IOException e) {
throw new ImageNotFoundException();
}
}
But when I change the order of produces value to
produces = {"image/jpeg","image/png","image/gif"}
The test for png is failing:
java.lang.AssertionError: Content type expected:<image/png> but was:<image/jpeg>
Im little confused, that changing the order of produces values leads to different results.
Does anyone observed this, is it a bug or did I miss something ?
My code is:
public class RemotePlay {
static final String USER_NAME = "bwisniewski";
static final String PASSWORD = "xxx";
static final String NETWORK_FOLDER = "smb://192.168.1.141/ADMIN$/";
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
String fileContent = "This is a test File";
new RemotePlay().copyFiles(fileContent, "testFile1.txt");
}
public boolean copyFiles(String fileContent, String fileName) {
boolean successful = false;
try{
String user = USER_NAME + ":" + PASSWORD;
System.out.println("User: "+user);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = NETWORK_FOLDER + fileName;
System.out.println("Path: "+path);
SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
sfos.write(fileContent.getBytes());
successful = true;
System.out.println("Successful "+successful);
}
catch(Exception e) {
successful = false;
e.printStackTrace();
}
return successful;
}}
How can I change it to send exe file to ADMIN$ share. I prefer to use this method because I have to authenticate to remote pc. If you got better ideas to copy file to ADMIN$ share I am looking forward to hear about it.
Thanks.
sfos.write(fileContent.getBytes());
if your data is text, then why not to use PrintWriter to write down your file
public static void main(String [] args) throws Exception { // temporary
File fileOne = new File("testfile1.txt");
PrintWriter writer = new PrintWriter(fileOne);
// write down data
writer.println("This is a test File");
// free resources
writer.flush();
writer.close();
}
and about the extension, you can use any extension you want while creating the file, it will still hold the data, and can be opened if you renamed it to the correct extension on the hard drive
if you named your file testfile.exe it will still hold your data, but when you double click it it wont work until you rename it to testfile.txt (or it will work if the extension is compatible with the data in the file)