I use this code to access weather data from yahoo and everything just work fine.
Somehow this stops working getting a "Bad request" from yahoo...
"Please provide valid credentials. OAuth oauth_problem="OST_OAUTH_PARAMETER_ABSENT_ERROR", realm="yahooapis.com"
"
I try to understood what happed and i think that has to do with the oAuth from yahoo but i don't know how to use it and the documentation from yahoo sucks...
code below..
mForcastTown.Add(MainForm.ExtraFE_IdHttp.Get('http://weather.yahooapis.com/forecastrss?w='+ mAdd_Town[mTonwNum].mWoeID +'&u='+ mAdd_Town[mTonwNum].mDegree);
Thank you...
UPDATE...
I found this below and when run in the browser i get the xml i need but when i run it to the
IdHttp.get('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid=55903793%20and%20u=%27c%27&format=xml')
i get unknown version found...
What is this...
Thank you...
I had the same problem for Java, maybe this will direct you to something.
In this link there is a sample java code:
// Copyright 2019 Oath Inc. Licensed under the terms of the zLib license see https://opensource.org/licenses/Zlib for terms.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Random;
import java.util.Collections;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.URI;
/**
*
* <pre>
* % java --version
* % java 11.0.1 2018-10-16 LTS
*
* % javac WeatherYdnJava.java && java -ea WeatherYdnJava
* </pre>
*
*/
public class WeatherYdnJava {
public static void main(String[] args) throws Exception {
final String appId = "test-app-id";
final String consumerKey = "your-consumer-key";
final String consumerSecret = "your-consumer-secret";
final String url = "https://weather-ydn-yql.media.yahoo.com/forecastrss";
long timestamp = new Date().getTime() / 1000;
byte[] nonce = new byte[32];
Random rand = new Random();
rand.nextBytes(nonce);
String oauthNonce = new String(nonce).replaceAll("\\W", "");
List<String> parameters = new ArrayList<>();
parameters.add("oauth_consumer_key=" + consumerKey);
parameters.add("oauth_nonce=" + oauthNonce);
parameters.add("oauth_signature_method=HMAC-SHA1");
parameters.add("oauth_timestamp=" + timestamp);
parameters.add("oauth_version=1.0");
// Make sure value is encoded
parameters.add("location=" + URLEncoder.encode("sunnyvale,ca", "UTF-8"));
parameters.add("format=json");
Collections.sort(parameters);
StringBuffer parametersList = new StringBuffer();
for (int i = 0; i < parameters.size(); i++) {
parametersList.append(((i > 0) ? "&" : "") + parameters.get(i));
}
String signatureString = "GET&" +
URLEncoder.encode(url, "UTF-8") + "&" +
URLEncoder.encode(parametersList.toString(), "UTF-8");
String signature = null;
try {
SecretKeySpec signingKey = new SecretKeySpec((consumerSecret + "&").getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHMAC = mac.doFinal(signatureString.getBytes());
Encoder encoder = Base64.getEncoder();
signature = encoder.encodeToString(rawHMAC);
} catch (Exception e) {
System.err.println("Unable to append signature");
System.exit(0);
}
String authorizationLine = "OAuth " +
"oauth_consumer_key=\"" + consumerKey + "\", " +
"oauth_nonce=\"" + oauthNonce + "\", " +
"oauth_timestamp=\"" + timestamp + "\", " +
"oauth_signature_method=\"HMAC-SHA1\", " +
"oauth_signature=\"" + signature + "\", " +
"oauth_version=\"1.0\"";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url + "?location=sunnyvale,ca&format=json"))
.header("Authorization", authorizationLine)
.header("X-Yahoo-App-Id", appId)
.header("Content-Type", "application/json")
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.body());
}
}
The problem with this code is where the oauthNonce generated with random bytes. Here, the error is caused by the unrecognized chars. Because for any random byte there can be any char that your system doesn't recognize and can't process because it converts it into a string.
I replace the whole part with this:
String oauthNonce = RandomStringUtils.random(10, true, true);
It worked like a charm. I currently don't have any errors now and able to get the response. I hope this helps.
Related
When using remote-webdriver instance of BrowserStack, only when ran in Jenkins, the failed screenshot is not attached to the report. please help. folder structure is ExtentReport\Screenshots
I tried Extent Report: Not able to see the screenshots on other machine
this but it's not resolve the issue.
public void onTestFailure(ITestResult result) {
testMap.get().fail(result.getThrowable());
//add screenshot for failed test.
WebDriver driver= WebDriverFactory.getDriver();
//experimental to get screenshot
driver = new Augmenter().augment(driver);
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String destination = System.getProperty("user.dir") + "/ExtentReport/" + "/Screenshots/" + result.getMethod().getMethodName() + dateName + ".png";
File finalDestination = new File(destination);
try {
FileUtils.copyFile(source, finalDestination);
} catch (IOException e) {
e.printStackTrace();
}
testMap.get().addScreenCaptureFromPath(destination,result.getMethod().getMethodName());
}
Different operating systems use different characters as file and path separators. When our application has to run on multiple platforms, we need to handle these correctly.
To handle this issue Java provide File.separator.
So, instead of
String destination = System.getProperty("user.dir") + "/ExtentReport/" + "/Screenshots/" + result.getMethod().getMethodName() + dateName + ".png";
Try this:
String destination = System.getProperty("user.dir") + File.separator + "ExtentReport" + File.separator +"Screenshots" + File.separator + result.getMethod().getMethodName() + dateName + ".png";
To use it you will have to add this import
import java.io.File;
Based on the answer of ravi creed,
HTML : Unable to view the base64 image in html report
String base64Screenshot ="data:image/png;base64," + ((TakesScreenshot) Objects.requireNonNull(driver)).getScreenshotAs(OutputType.BASE64);
testMap.get().addScreenCaptureFromBase64String(base64Screenshot).getModel().getMedia().get(0);
I managed to solve this using above code.Once click on base64 img, it opens the actual screenshot.
I am trying to request a token to the Here API with Rest service java in order to obtain OAuth 2.0 Token Credentials. I am blocked in the request level and constantly having the same error but according to the documentation I don't do anything wrong.
Here is the necessary code in REST Java to make the request.
The below code i tried.
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class here {
private static final String HMAC_SHA256 = "HmacSHA256";
private static final String ENC = "UTF-8";
private static Base64 base64 = new Base64();
private static String key = "MyKeyID"; // here.access.key.id from credential file
private static String secret = "MySecretKey" //here.access.key.secret
public static void main(String[] args) {
HttpClient httpClient = new DefaultHttpClient();
long value = (System.currentTimeMillis() / 1000);
int unique = (int) (Math.random() * 100000000);
// These params should ordered in key
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("grant_type", "client_credentials"));
qparams.add(new BasicNameValuePair("oauth_consumer_key", "MY_KEY_ID"));
qparams.add(new BasicNameValuePair("oauth_nonce", ""
+ unique));
qparams.add(new BasicNameValuePair("oauth_signature_method",
"HMAC-SHA256"));
qparams.add(new BasicNameValuePair("oauth_timestamp", ""
+ value));
qparams.add(new BasicNameValuePair("oauth_version", "1.0"));
System.err.println("query param->>>");
// creating authentication signature
String signature = getSignature(URLEncoder.encode(
"https://account.api.here.com/oauth2/token", ENC),
URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));
// comibining the params
String authHeader = "OAuth oauth_consumer_key=MY_KEY,"
+"oauth_nonce="+unique+","
+"oauth_signature="+signature+","
+"oauth_signature_method=HMAC-SHA256,"
+"oauth_timestamp="+value+","
+"oauth_version=1.0";
HttpPost httpPost = new HttpPost("https://account.api.here.com/oauth2/token");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
String grant_type = "client_credentials";
StringEntity input = new StringEntity("grant_type=" + grant_type);
httpPost.setEntity(input);
// output the response content.
System.out.println("Token and Token Secrect:");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int len;
byte[] tmp = new byte[2048];
try {
while ((len = instream.read(tmp)) != -1) {
System.out.println(new String(tmp, 0, len, ENC));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static String getSignature(String url, String params) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
StringBuilder base = new StringBuilder();
base.append("POST&");
base.append(url);
base.append("&");
base.append(params);
System.out.println("Stirng for oauth_signature generation:" + base);
// yea, don't ask me why, it is needed to append a "&" to the end of
// secret key.
byte[] keyBytes = (secret + "&").getBytes(ENC);
SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA256);
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(key);
// encode it, base64 it, change it to string and return.
return new String(base64.encode(mac.doFinal(base.toString().getBytes(
ENC))), ENC).trim();
}}
And this is the error that I keep getting :
{"errorId":"ERROR-27b88f02-5d76-40ea-81d5-de6e70cf8464","httpStatus":401,"errorCode":401205,"message":"Unsupported signature method in the header. Require HMAC-SHA256","error":"invalid_request","error_description":"errorCode: '401205'. Unsupported signature method in the header. Require HMAC-SHA256"}
According to the documentation, https://developer.here.com/documentation/authentication/dev_guide/topics/using-aaa-javasdk-or-3rd-party-libraries.html
I develop the code based on the above api documentation but iam not getting the result.
Does anyone know how to fix this issue?
I tried this code
HttpClient httpClient = HttpClientBuilder.create().build();
String headers = "grant_type=client_credentials"+"&oauth_consumer_key=mykey"+"&oauth_nonce=uniquevalue"+"&oauth_signature_method=HMAC-SHA256"+"&oauth_timestamp=timestamp"+"&oauth_version=1.0";
String combine = "POST"+"\n&"+URLEncoder.encode("https://account.api.here.com/oauth2/token", StandardCharsets.UTF_8.toString())+"\n&"+URLEncoder.encode(headers, StandardCharsets.UTF_8.toString());
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(("mysecretkey &").getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
String signature = Base64.encodeBase64String(sha256_HMAC.doFinal(combine.getBytes()));
String authHeader = "OAuth "
+ "oauth_consumer_key=\"X1E2a0ElfkaHx7aezqN5Hg-1234\","
+"oauth_nonce=\"uniquevalue\","
+"oauth_signature=\""+signature+"\","
+"oauth_signature_method=\"HMAC-SHA256\","
+"oauth_timestamp=\"timestamp\","
+"oauth_version=\"1.0\"";
HttpPost httpPost = new HttpPost("https://account.api.here.com/oauth2/token");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.addHeader("Host", "account.api.here.com");
httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
StringEntity input = new StringEntity("grant_type=" + "client_credentials");
httpPost.setEntity(input);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
Its showing one more error like errorCode: '401202'. Invalid Client Authorization header, expecting signed request format. Please give some suggestion how to request a toke ?
Can you try to modify your code as-
// creating authentication signature
String signature = getSignature(URLEncoder.encode(
"https://account.api.here.com/oauth2/token", ENC),
URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));
// comibining the params
String authHeader = "OAuth oauth_consumer_key=MY_KEY,"
+"oauth_nonce="+unique+","
+"oauth_signature="+URLEncoder.encode(signature,"UTF-8")+","
+"oauth_signature_method=HMAC-SHA256,"
+"oauth_timestamp="+value+","
+"oauth_version=1.0";
I tried your solution and got the same error. There is some problem with the generated signature. I found this official Here Java SDK, which has classes to generate signature and Authorization Header.
https://github.com/heremaps/here-aaa-java-sdk/blob/acf6c7a982070f0b311c1741ce4887938b60df5b/here-oauth-client/src/main/java/com/here/account/auth/SignatureCalculator.java#L101
Hope this helps !
I'm trying to test some procedure I have made with the code given by Neo4j for testing procedure. However my procedure is based on the results from the random walk algorithm which I have to call through 'algo.randomWalk.stream()'.
To do so, I'm instantiating a Neo4j test server. However it doesn't recognize the algo.randomWalk.stream(), because I think it doesn't have the algorithm package in its plugins.
This is the code I'm working on
package example;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Rule;
import org.junit.Test;
import org.neo4j.driver.v1.*;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import static org.neo4j.driver.v1.Values.parameters;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import org.neo4j.harness.junit.Neo4jRule;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
import static org.neo4j.driver.v1.Values.parameters;
public class ScoringTest {
// This rule starts a Neo4j instance for us
#Rule
public Neo4jRule neo4j = new Neo4jRule()
// This is the Procedure we want to test
.withProcedure( Scoring.class );
//org.neo4j.server.thirdparty_jaxrs_classes=org.neo4j.examples.server.unmanaged=/examples/unmanaged
#Test
public void shouldAllowReturningTheLastValue() throws Throwable
{
// This is in a try-block, to make sure we close the driver after the test
try( Driver driver = GraphDatabase
.driver( neo4j.boltURI() , Config.build().withEncryptionLevel( Config.EncryptionLevel.NONE ).toConfig() ) )
{
System.out.println(neo4j.boltURI().toString());
// Given
neo4j.withExtension(neo4j.boltURI().toString(), "..\\graph-algorithms-algo-3.5.4.0.jar");
Session session = driver.session();
String PATH = "..\\data\\data.json";
File JSON_SOURCE = new File(PATH);
List<HashMap<String,Object>> mss = new ObjectMapper().readValue(JSON_SOURCE, List.class);
session.run("UNWIND {bulk} as row " +
"CREATE (n:Users) " +
"SET n += row.properties", parameters("bulk", mss ));
for(int k = 0; k<9; k++) {
PATH = "..\\data\\"+k+".json";
mss = new ObjectMapper().readValue(JSON_SOURCE, List.class);
JSON_SOURCE = new File(PATH);
session.run("UNWIND {bulk} as row " +
"MATCH (from:Users), (to:Clips) " +
"WHERE ID(from) = toInt(row.from) AND ID(to) = toInt(row.to._key) " +
"CREATE (from)-[rel:hasClipped]->(to) " +
"SET rel += row.properties ", parameters("bulk", mss ));
}
// When
Value result = session.run( "MATCH (n:Clips) WHERE ID(n) = 1038 " +
"CALL algo.randomWalk.stream(ID(n), 2, 1) " +
"YIELD nodeIds " +
"UNWIND nodeIds as nodeId " +
"MATCH (l:Clips)-[r:hasClipped]-(q:Users) " +
"WHERE (ID(l) = nodeId) AND (ID(q) in nodeIds) " +
"WITH collect({relation:r,Clip:l,User:q}) as res " +
"RETURN res").single().get("res");
System.out.println(result);
// Then
assertThat( result, equalTo( 0L ) );
}
}
}
The exact error that I get is : org.neo4j.driver.v1.exceptions.ClientException: There is no procedure with the name algo.randomWalk.stream registered for this database instance. Please ensure you've spelled the procedure name correctly and that the procedure is properly deployed.
Thanks for your time and your future answers,
Syndorik
So I found out a solution for this issue.
There's an option for Neo4jRule object that allows you to change the path to the plugin directory.
For instance, I've just added this config to Neo4jRule and then could call the graphalgo library :
public Neo4jRule neo4j = new Neo4jRule()
// This is the Procedure we want to test
.withProcedure( Scoring.class )
.withConfig(GraphDatabaseSettings.plugin_dir, "PATH_TO_PLUGIN_DIR")
.withConfig(GraphDatabaseSettings.procedure_unrestricted, "algo.*" );
I need to help with command "Ant clean all". I will try build one application of SAP Hybris, but, one class return de errors in to lines:
BOLDWEIGHT_BOLD cannot be resolved or is not a field
method with error:
#Override
public HSSFWorkbook createMDDExportFile(final List<JnJProductModel> products, final String fileName)
{
final String METHOD_NAME = "createMDDExportFile()";
LOGGER.info("JnJGTProductService" + Logging.HYPHEN + METHOD_NAME + Logging.HYPHEN + "Start of the method");
catalogVersionService.setSessionCatalogVersion(Jnjb2bCoreConstants.MDD_CATALOG_ID, Jnjb2bCoreConstants.ONLINE);
final String sheetName = "MDD_Products_Sheet_0";
final HSSFWorkbook excelWorkBook = new HSSFWorkbook();
final HSSFFont font = excelWorkBook.createFont();
ERROR=> font.setBoldweight(Font.BOLDWEIGHT_BOLD);
final HSSFCellStyle style = excelWorkBook.createCellStyle();
style.setFont(font);
final HSSFSheet sheet = excelWorkBook.createSheet(sheetName);
sheet.autoSizeColumn(0);
final HSSFRow downloadDateHeader = sheet.createRow(0);
downloadDateHeader.createCell(0).setCellValue("Download date");
downloadDateHeader.getCell(0).setCellStyle(style);
final String currentTime = new Date().toString();
downloadDateHeader.createCell(1).setCellValue(currentTime);
/*
* final HSSFRow globalAccounHeader = sheet.createRow(1);
* globalAccounHeader.createCell(0).setCellValue("Global Account Name");
* globalAccounHeader.getCell(0).setCellStyle(style);
* globalAccounHeader.createCell(1).setCellValue(currentAccount);
*/
try
{
final String filepath = Config.getParameter(Jnjb2bCoreConstants.EXPORT_EMAIL_ATTACHMENT_PATH_KEY) + File.separator
+ fileName;
createMDDExcelFile(products, sheet, excelWorkBook, style, filepath);
final File file = new File(filepath);
createMedia(file);
}
catch (final Exception exception)
{
LOGGER.error("There was an error while trying to create the excel file for the catalog export", exception);
}
LOGGER.info("JnJGTProductService" + Logging.HYPHEN + METHOD_NAME + Logging.HYPHEN + "End of the method");
return excelWorkBook;
}
Your maven version having issue with the one Font interface you are accessing. You imported the wrong path of Font interface.
Check your Font interface contains BOLDWEIGHT_BOLD attribute or not ?
I have my Font interface at org.apache.poi.ss.usermodel.Font location.
hi i'm making program that record video with audio by javacv but i got some error. any suggestion?
lib version : jdk 1.8 javacv 0.8 opencv 2.4.9
Exception in thread "main" org.bytedeco.javacv.FrameGrabber$Exception: avformat_open_input() error -2: Could not open input "output.mp4". (Has setFormat() been called?)
at org.bytedeco.javacv.FFmpegFrameGrabber.startUnsafe(FFmpegFrameGrabber.java:362)
at org.bytedeco.javacv.FFmpegFrameGrabber.start(FFmpegFrameGrabber.java:312)
at com.unomic.securobot.javacv.main(javacv.java:14)
my code
FFmpegFrameGrabber grabber1 = new FFmpegFrameGrabber("output.mp4");
FFmpegFrameGrabber grabber2 = new FFmpegFrameGrabber("test.mp3");
grabber1.setFormat("mp4");
grabber1.start();
grabber2.start();
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("outputFinal.mp4",
grabber1.getImageWidth(), grabber1.getImageHeight(),
grabber2.getAudioChannels());
recorder.setFrameRate(grabber1.getFrameRate());
recorder.setSampleFormat(grabber2.getSampleFormat());
recorder.setSampleRate(grabber2.getSampleRate());
recorder.start();
Frame frame1;
Frame frame2 = null;
while ((frame1 = grabber1.grabFrame()) != null ||
(frame2 = grabber2.grabFrame()) != null) {
recorder.record(frame1);
recorder.record(frame2);
}
recorder.stop();
grabber1.stop();
grabber2.stop();
}
I was trying to get thumbnails from a videos using the framegrabber. I was getting the same error but then I just tried giving the full path of the files and voila it worked. Previously, I was using a relative path which was not working. When I gave the full path it started working.
package com.tape.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.OpenCVFrameGrabber;
public class VideoThumbTaker {
protected String ffmpegApp;
public VideoThumbTaker(String ffmpegApp)
{
this.ffmpegApp = ffmpegApp;
}
public void getThumb(String videoFilename, String thumbFilename, int width, int height,int hour, int min, float sec)
throws IOException, InterruptedException
{
ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y", "-i", videoFilename, "-vframes", "1",
"-ss", hour + ":" + min + ":" + sec, "-f", "mjpeg", "-s", width + "*" + height, "-an", thumbFilename);
Process process = processBuilder.start();
InputStream stderr = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null);
process.waitFor();
}
public static void main(String[] args) throws Exception, IOException
{
//Both case work
FFmpegFrameGrabber g = new FFmpegFrameGrabber("C:\\JavaEE\\New Project\\tape\\src\\main\\webapp\\web-resources\\videos\\vid.mp4");
g.setFormat("mp4");
g.start();
for (int i = 0 ; i < 50 ; i++) {
ImageIO.write(g.grab().getBufferedImage(), "png", new File("C:\\JavaEE\\New Project\\tape\\src\\main\\webapp\\web-resources\\thumbnails\\video-frame-" + System.currentTimeMillis() + ".png"));
}
g.stop();
}
}