Hi I want to know how I can use Optional in java SE 8 in the function below.
public URL getAuthenticatedURL() throws MalformedURLException {
if (log != null){
log.writeINFOToLog("Fetching authentication URL...");
}
else{
Log.initLog();
log.writeINFOToLog("Fetching authentication URL...");
}
try{
String url = String.format("%s://%s%s?username=%s&password=%s",getProtocol(), getHost(), getPath(), getUsername(), getPassword());
URL returnURL = new URL(url);
return returnURL;
}
catch (MalformedURLException ex){
log.writeExceptionToLog(ex);
return null;
}
}
I want to be able to handle the scenario where values involved in constructing the URL is null or empty.
After some research, I think its best that I avoid nulls, since it does not make much sense to have a null.
Here is my code snippet of the same function once I have used Optional<URL>
public Optional<URL> getAuthenticatedURL() throws MalformedURLException {
if (log != null){
log.writeINFOToLog("Fetching authentication URL...");
}
else{
Log.initLog();
log.writeINFOToLog("Fetching authentication URL...");
}
String url = String.format("%s://%s%s?username=%s&password=%s",getProtocol(), getHost(), getPath(), getUsername(), getPassword());
return Optional.ofNullable(new URL(url));
}
So when I call the function the code will be something like this.
if(getAuthenticatedURL.isPresent()){
URL val = getAuthenticatedURL.get();
}
I think it is more reasonable to use Supplier than Optional, because getAuthenticatedURL() has no argument and generates an Object(URL).
It looks like:
Supplier<URL> supplier = () -> {
...
try {
return new URL(...);
} catch (MalformedURLException e) {
return null;
}
};
URL url = supplier.get();
Related
I am new to OpenTelemetry word. I have created spans for my services separately, but when i am try to combine spans of two different services, using context propogation, I am not able to do it successfully.
I have used following code:
// at client side:
public static void sendContext(String resource) {
TextMapSetter<HttpURLConnection> setter =
new TextMapSetter<HttpURLConnection>() {
#Override
public void set(HttpURLConnection carrier, String key, String value) {
carrier.setRequestProperty(key, value);
}
};
HttpURLConnection transportLayer = null;
String urlString = "http://127.0.0.1:8080" + resource;
try {
URL url = new URL(urlString);
transportLayer = (HttpURLConnection) url.openConnection();
} catch (MalformedURLException ex) {
System.out.println(ex.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
GlobalOpenTelemetry.getPropagators()
.getTextMapPropagator()
.inject(Context.current(), transportLayer, setter);
}
// at server side:
public static Context getContext(HttpServletRequest request) {
TextMapGetter<HttpServletRequest> getter =
new TextMapGetter<HttpServletRequest>() {
#Override
public String get(HttpServletRequest carrier, String key) {
Enumeration<String> headerNames = carrier.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println("headerNames.nextElement(): " + headerName);
if (headerName.equals(key)) {
String headerValue = request.getHeader(headerName);
System.out.println("headerValue): " + headerValue);
return headerValue;
}
}
}
return null;
}
#Override
public Iterable<String> keys(HttpServletRequest carrier) {
Set<String> set = new HashSet<String>();
Enumeration<String> headerNames = carrier.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
set.add(headerNames.nextElement());
}
}
return set;
}
};
Context extractedContext =
GlobalOpenTelemetry.getPropagators()
.getTextMapPropagator()
.extract(Context.current(), request, getter);
At server, i am not able to get parent span.
Kindly help on this.
You can refer to OpenTelemetry main documentation from here. It contains the context propagation part but I used HttpHeader type getter as the TextMapGetter with the same functionality which shows in the doc and instead of using
Scope scope = extractedContext.makeCurrent()
as the scope to create a child span, better to use directly without the scope,
tracer.spanBuilder(spanName).setParent(extractedContext)
Because sometimes the automated way to propagate the parent span on the current thread does not work fine.
In Java How can we verify that i given String is a JWT Token without using Signature?
I am using
try {
return (new JwtConsumerBuilder()).setVerificationKey(SECRET_KEY).build().processToClaims(token);
} catch (InvalidJwtException var4) {
throw new IOException("Failed to parse");
}
This works fine but I want to verify this without SECRET_KEY.
I Just want to verify whether it is a JWT token or not.
Here is an example to check the structure of the JWT. You only need to add the validations of the data that the JWT should carry
boolean isJWT(String jwt) {
String[] jwtSplitted = jwt.split("\\.");
if (jwtSplitted.length != 3) // The JWT is composed of three parts
return false;
try {
String jsonFirstPart = new String(Base64.getDecoder().decode(jwtSplitted[0]));
JSONObject firstPart = new JSONObject(jsonFirstPart); // The first part of the JWT is a JSON
if (!firstPart.has("alg")) // The first part has the attribute "alg"
return false;
String jsonSecondPart = new String(Base64.getDecoder().decode(jwtSplitted[1]));
JSONObject secondPart = new JSONObject(jsonSecondPart); // The first part of the JWT is a JSON
//Put the validations you think are necessary for the data the JWT should take to validate
}catch (JSONException err){
return false;
}
return true;
}
You can decode JWT from base64 and check necessarily field. Or simply check token, why you want verify it, It's not faster then simpy check it.
Try this one.
public static JSONObject getPayload(String jwt) {
try {
Base64.Decoder dec = Base64.getDecoder();
final String payload = jwt.split(SecurityConstants.SPLIT_SLASH)[PAYLOAD];
final byte[] sectionDecoded = dec.decode(payload);
final String jwtSection = new String(sectionDecoded, SecurityConstants.CODE_PAGE);
return new JSONObject(jwtSection);
} catch (final UnsupportedEncodingException e) {
throw new InvalidParameterException(e.getMessage());
} catch (final Exception e) {
throw new InvalidParameterException(SecurityConstants.ERROR_IN_PARSING_JSON);
}
}
Next You need to get from jwt body this part which is important for You eg.
JSONObject body = JWTUtils.getPayload(token);
String username = body.getString("username");
I am trying to do a simple script that will convert any possible HTML link into HTTP URL, such as
http://example.com //example.com /index.html ./index.html index.html
I already tried function that I found in another answer:
public static Integer isAbsoluteURL (String url) throws java.net.MalformedURLException {
final URL baseHTTP = new URL("http://example.com");
final URL baseFILE = new URL("file:///");
if (url.length() > 0) {
if (url.substring(0, 1) == "/") {
return 0;
}
}
URL frelative;
URL hrelative;
try {
frelative = new URL(baseFILE, url);
hrelative = new URL(baseHTTP, url);
} catch (MalformedURLException e) {
System.out.println("MalformedURLException found");
return 3;
}
if (frelative.equals(hrelative)) {
return 0;
} else {
return 1;
}
}
I want to get absolute links, but the code don't work for ./, //(without http[s]).
Thanks.
I'd prefer to use spring's UriComponentBuilder which will take care about everything:
https://www.baeldung.com/spring-uricomponentsbuilder
I am very new to the GC platform and am trying to create an API in Java with two methods: one which returns a list of all of the files in a specific bucket and another which retrieves a specified file from that bucket. The goal is to be able to iterate the file list in order to download every file from the bucket. Essentially, I am wanting to mirror the contents of the bucket on an Android device, so the API will be called from a generated client library in an Android app.
My getFileList() method returns a ListResult object. How do I extract a list of files from this?
#ApiMethod(name = "getFileList", path = "getFileList", httpMethod = ApiMethod.HttpMethod.GET)
public ListResult getFileList(#Named("bucketName") String bucketName) {
GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
ListResult result = null;
try {
result = gcsService.list(bucketName, ListOptions.DEFAULT);
return result;
} catch (IOException e) {
return null; // Handle this properly.
}
}
Also, I am struggling to determine what the return type of my getFile() API method should be. I can’t use a byte array since return types cannot be simple types as I understand it. This is where I am with it:
#ApiMethod(name = "getFile", path = "getFile", httpMethod = ApiMethod.HttpMethod.GET)
public byte[] getFile(#Named("bucketName") String bucketName, ListItem file) {
GcsService gcsService = GcsServiceFactory.createGcsService();
GcsFilename gcsFilename = new GcsFilename(bucketName, file.getName());
ByteBuffer byteBuffer;
try {
int fileSize = (int) gcsService.getMetadata(gcsFilename).getLength();
byteBuffer = ByteBuffer.allocate(fileSize);
GcsInputChannel gcsInputChannel = gcsService.openReadChannel(gcsFilename, 0);
gcsInputChannel.read(byteBuffer);
return byteBuffer.array();
} catch (IOException e) {
return null; // Handle this properly.
}
}
I am lost in the Google documentation for this stuff and am concerned that I am coming at it from completely the wrong direction since all I am trying to do is securely download a bunch of files!
I can't give you a complete solution because, this is code I wrote for my company, but I can show you some basics. I use the google-cloud-java API.
First you need to create an API key and download this in JSON format. More details can be found here.
I have - amongst other - these two fields in my class:
protected final Object storageInitLock = new Object();
protected Storage storage;
First you will need a method to initialize a com.google.cloud.storage.Storage object, something like (set your project-id and path to json api key):
protected final Storage getStorage() {
synchronized (storageInitLock) {
if (null == storage) {
try {
storage = StorageOptions.newBuilder()
.setProjectId(PROJECTID)
.setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(pathToJsonKey)))
.build()
.getService();
} catch (IOException e) {
throw new MyCustomException("Error reading auth file " + pathToJsonKey, e);
} catch (StorageException e) {
throw new MyCustomException("Error initializing storage", e);
}
}
return storage;
}
}
to get all entries you could use something like:
protected final Iterator<Blob> getAllEntries() {
try {
return getStorage().list(bucketName).iterateAll();
} catch (StorageException e) {
throw new MyCustomException("error retrieving entries", e);
}
}
list files in a directory:
public final Optional<Page<Blob>> listFilesInDirectory(#NotNull String directory) {
try {
return Optional.ofNullable(getStorage().list(getBucketName(), Storage.BlobListOption.currentDirectory(),
Storage.BlobListOption.prefix(directory)));
} catch (Exception e) {
return Optional.empty();
}
}
get info about a file:
public final Optional<Blob> getFileInfo(#NotNull String bucketFilename) {
try {
return Optional.ofNullable(getStorage().get(BlobId.of(getBucketName(), bucketFilename)));
} catch (Exception e) {
return Optional.empty();
}
}
adding a file:
public final void addFile(#NotNull String localFilename, #NotNull String bucketFilename,
#Nullable ContentType contentType) {
final BlobInfo.Builder builder = BlobInfo.newBuilder(BlobId.of(bucketName, bucketFilename));
if (null != contentType) {
builder.setContentType(contentType.getsValue());
}
final BlobInfo blobInfo = builder.build();
try (final RandomAccessFile raf = new RandomAccessFile(localFilename, "r");
final FileChannel channel = raf.getChannel();
final WriteChannel writer = getStorage().writer(blobInfo)) {
writer.write(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()));
} catch (Exception e) {
throw new MyCustomException(MessageFormat.format("Error storing {0} to {1}", localFilename,
bucketFilename), e);
}
}
I hope these code snippets and the referenced documentation will get you going, actulally it's not too hard.
I am using java.net.CookieManager & java.net.CookieHandler to track cookies. I need to remove one but keep all others. The problem is that the List return from the using cookieManger.getCookieStore().getCookies() is unmodifiable and therefore throws an exception when I attempt to remove the cookie.
Here is the code regarding cookies:
public HttpProxy(String host, String port) {
cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
//other irrelevant code
}
private CookieManager cookieManager;
public void deleteGameCookie() {
CookieStore cookieStore = cookieManager.getCookieStore();
List<HttpCookie> cookieList = cookieStore.getCookies();
HttpCookie temp = null;
// iterate HttpCookie object
for (HttpCookie cookie : cookieList) {
try {
String name = URLDecoder.decode(cookie.getName().replace("+", "%2B"), "UTF-8").replace("%2B", "+");
if(name.equals("catan.game")) {
System.out.println("catan.game cookie found");
temp = cookie;
}
} catch (UnsupportedEncodingException e) {
//System.out.println("Error decoding cookie... bummer...");
e.printStackTrace();
}
}
cookieList.remove(temp);
}
Is there a way around this or a better way to do this?
I found a similar question about unmodifiable collections here but it hasn't been answered. Thanks for your help!
you probably want to use one of the remove methods on cookie store not try and work with the list directly. see:
http://docs.oracle.com/javase/7/docs/api/java/net/CookieStore.html
Here is a code that should do the trick:
public void deleteGameCookie() {
CookieStore cookieStore = cookieManager.getCookieStore();
List<HttpCookie> cookiesToRemove = new ArrayList<>();
for (HttpCookie cookie : cookieStore.getCookies()) {
try {
String name = URLDecoder.decode(cookie.getName().replace("+", "%2B"), "UTF-8").replace("%2B", "+");
if (name.equals("catan.game")) {
cookiesToRemove.add(cookie);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
for (HttpCookie cookie : cookiesToRemove) {
cookieStore.remove(null, cookie);
}
}
The code should also handle situation where no cookie was found and when there is more than one cookie matching your criteria.