Can't run XML parser Jackson on Android - java

Can't run XML parser Jackson on Android
import android.content.Context;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
in onCreate(){
ObjectMapper xmlMapper = new XmlMapper();
Channel root = xmlMapper.readValue(stringXML, Channel.class);
}
#JacksonXmlRootElement(localName = "channel")
public static class Channel {
public List<Item> channel;
}
public static class Item {
#JacksonXmlProperty(localName = "item")
public String item;
}
Error is :
java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/xml/stream/XMLInputFactory;
Caused by: java.lang.ClassNotFoundException: Didn't find class "javax.xml.stream.XMLInputFactory" on path: DexPathList

Old question but...
Android doesn't have the javax.xml.stream package, which is required for most libraries involving XML.
To add this yourself, add this dependency to your build.gradle file:
compile group: 'javax.xml.stream', name: 'stax-api', version: '1.0-2'
This is the latest release as of writing this comment. You can check here for updated versions.

You didn't setup Jackson for Android correctly. Look at this page Using jackson-dataformat-xml on android. There are good description how to do it.

Related

How to use extensions in OpenTelemetry java

I am trying to extend OpenTelemetry java agent and I don't see any indication it is trying to load my jar.
I am running the following cmd:
java -javaagent:../src/main/resources/opentelemetry-javaagent.jar -Dotel.javaagent.configuration-file=../src/main/resources/agent-prp.properties -jar simple-service-1.0-SNAPSHOT-jar-with-dependencies.jar
my config file is (the attributes are working):
otel.javaagent.extensions=/Users/foo/source/simple-service/src/main/resources/span-processor-1.0-SNAPSHOT.jar
otel.resource.attributes=service.name=foooBarr
my extension is:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.trace.ReadWriteSpan;
import io.opentelemetry.sdk.trace.ReadableSpan;
import io.opentelemetry.sdk.trace.SpanProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class FooSpanProcessor implements SpanProcessor {
private static final ObjectMapper objMapper = new ObjectMapper();
private static final Logger log = LoggerFactory.getLogger(FooSpanProcessor.class);
#Override
public void onStart(Context parentContext, ReadWriteSpan span) {
log.error("fffffffffff");
span.setAttribute("fooToken", FooProperties.INSTANCE.fooToken);
span.setAttribute("service.name", FooProperties.INSTANCE.serviceName);
span.setAttribute("runtime", FooProperties.INSTANCE.javaVersion);
span.setAttribute("tracerVersion", "0.0.1");
span.setAttribute("framework", FooProperties.INSTANCE.frameWork);
span.setAttribute("envs", FooProperties.INSTANCE.environment);
span.setAttribute("metaData", FooProperties.INSTANCE.metadata);
}
#Override
public boolean isStartRequired() {
return true;
}
#Override
public void onEnd(ReadableSpan span) {
}
....
I don't see any indication that my extension is loaded, I don't see any of my parameters on the produced spans. can any body help me?
"otel.javaagent.extensions" is not supported in the config file. add it with -D.
add the span processor to a config call implementing sdkTracerProviderConfigurer

What is the difference between java.lang.String vs String (Java)

I'm fairly new to java but have been studying it for quite a bit. I am currently learning Spring Boot with MyBatis and am getting this frustrating compilation error. I am trying to implement this Hash Service and during this process, I am trying to catch and log any errors. The problem is when I try and use the logger that I import from mybatis to log the error I get the compilation error
required type java.lang.String
Provided: String
I was previously under the impression that these two classes were the same but I'm guessing the String class isn't the same as the java.lang.String class? Or is there something else going on? Here is the actual code for you to look at. Could someone help me?
import org.apache.tomcat.util.codec.binary.Base64;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.lang.String;
#Component
public class HashedService {
private Logger logger = LoggerFactory.getLogger(HashedService.class);
public String getHashedValue(String data, String salt) {
byte[] hashedValue = null;
KeySpec spec = new PBEKeySpec(data.toCharArray(), salt.getBytes(), 5000, 128);
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
hashedValue = factory.generateSecret(spec).getEncoded();
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
java.lang.String error = e.getMessage();
logger.error(error);
}
return Base64.encodeBase64String(hashedValue);
}
}
EDIT
I am using intellij
I used
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
// https://mvnrepository.com/artifact/org.mybatis/mybatis-spring
compile group: 'org.mybatis', name: 'mybatis-spring', version: '2.0.5'
And I found that method error from org.mybatis.logging.Logger looks like this:
public void error(Supplier<String> s) {
log.error(s.get());
}
I think you shouldn't use the logger from MyBatis.
You can try to replace:
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
with:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

SyncResponse which jar is needed to create the device

import java.util.Collections;
import java.util.Map;
import javax.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import com.google.actions.api.smarthome.DisconnectRequest;
import com.google.actions.api.smarthome.ExecuteRequest;
import com.google.actions.api.smarthome.ExecuteResponse;
import com.google.actions.api.smarthome.QueryRequest;
import com.google.actions.api.smarthome.QueryResponse;
import com.google.actions.api.smarthome.SmartHomeApp;
import com.google.actions.api.smarthome.SyncRequest;
import com.google.actions.api.smarthome.SyncResponse;
import com.google.actions.api.smarthome.SyncResponse.Payload;
public class GoogleDeviceSync extends SmartHomeApp {
#NotNull
#Override
public SyncResponse onSync(#NotNull SyncRequest syncRequest, #Nullable Map<?, ?> map) {
Payload payload = new Payload();
payload.setAgentUserId("1836.15267389");
payload.setDevices(
new Device[] {
new Device.Builder()
.setId("123")
.setType("action.devices.types.OUTLET")
.addTrait("action.devices.traits.OnOff")
.setName(
Collections.singletonList("My Outlet 1234"),
"Night light",
Collections.singletonList("Wall plug"))
.setWillReportState(true)
.setDeviceInfo("lights-out-inc", "hs1234", "3.2", "11.4")
.setCustomData(
new JSONObject()
.put("fooValue", 74)
.put("barValue", true)
.put("bazValue", "foo"))
.build(),
new Device.Builder()
.setId("456")
.setType("action.devices.types.LIGHT")
.addTrait("action.devices.traits.OnOff")
.addTrait("action.devices.traits.Brightness")
.addTrait("action.devices.traits.ColorTemperature")
.addTrait("action.devices.traits.ColorSpectrum")
.setName(
Collections.singletonList("Lights Out Inc. bulb A19 color hyperglow"),
"Lamp",
Collections.singletonList("Reading lamp"))
.setWillReportState(true)
.setDeviceInfo("Lights Out Inc.", "hg11", "1.2", "5.4")
.setCustomData(
new JSONObject()
.put("fooValue", 12)
.put("barValue", false)
.put("bazValue", "bar"))
.build(),
});
return new SyncResponse(syncRequest.getRequestId(), payload);
}
}
Which jar is payload.setDevices(new Device[]) and Device introduced from?
From the https://developers.google.com/assistant/smarthome/develop/process-intents document, there is only code, and the introduction of jar is not shown. So which jar does'device' need to introduce
Adding dependencies (jars)
The dependency (the jar) that needs to be added in the gradle.build should be:
implementation 'com.google.actions:actions-on-google:1.8.0'
The specific version will depend on your configuration and environment.
You can see a full example gradle.build. In the same folder there are also other configuration examples.
Importing Classes
I also add some information on where the Payload and Device classes are.
Payload is nested inside SyncResponse and Device is nested inside Payload.
Payload is imported with the following import statement:
import com.google.actions.api.smarthome.SyncResponse.Payload
Device can be imported with the following import statement:
import com.google.actions.api.smarthome.SyncResponse.Payload.Device
Creating Objects
To create a new Payload from the Payload in the SyncResponse:
new SyncResponse.Payload()
And you can try to create a Device from its builder:
SyncResponse.Payload.Device.Builder deviceBuilder = new syncResponse.Payload.Device.Builder()
See this example for usage of the 'Payload' and 'Device'.

cannot find symbol import com.user.userCom

Trying to create native module for react-native. I have all the dependencies needed and I followed the instructions user com mobile sdk installation
in project/android/build.gradle
allprojects {
repositories {
…
maven {
url 'https://android-sdk.user.com'
}
}
}
in project/android/app/build.gradle
dependencies {
implementation 'com.user:android-sdk:1.0.0'
}
then i created file in project/app/src/main/java/com/my_app/UserComModule.java
package com.my_app;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
import com.user.UserCom;
public class UserComModule extends ReactContextBaseJavaModule {
private static ReactApplicationContext reactContext;
#Override
public void onCreate() {
super.onCreate();
new UserCom.Builder(
this,
"api_secret", //your api secret key generated in User.com webpanel details
"https://<your_app_subdomain>.user.com"
)
.trackAllActivities(true) // false by default
.openLinksInChromeCustomTabs(true) // true by default
.setCustomTabsBuilder(getCustomTabsBuilder())
.build();
}
}
When i run i get: cannot find symbol import com.user.UserCom;
You're importing UserCom, and that module is not availabe, as you've mentioned you had created the file UserComModule in that directory, either create UserCom class or delete this line from UserComModule
import com.user.UserCom;

import com.amazonaws.services.dynamodbv2.document.DynamoDB; the document part of the import cannot be resolved

I tried to update my dynamodb using aws but I am not able to create a dynamodb object or a table object as the import com.amazonaws.services.dynamodbv2.**document**.* does not register document but it reads all the other imports:
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ListTablesResult;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.TableDescription;
Below is the full class I am using:
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.model.UpdateItemRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.TableCollection;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.TableCollection;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ListTablesResult;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.TableDescription;
public class LoadingPage extends AppCompatActivity {
static AmazonDynamoDBClient dynamoDB;
LocationManager locationmanager;
private TrackGPS gps;
double longitude;
double latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_page);
gps = new TrackGPS(LoadingPage.this);
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
new ProfileCredentialsProvider()));
Table table = dynamoDB.getTable("ProductCatalog");
Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#A", "Authors");
expressionAttributeNames.put("#P", "Price");
expressionAttributeNames.put("#I", "ISBN");
Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1",
new HashSet<String>(Arrays.asList("Author YY","Author ZZ")));
expressionAttributeValues.put(":val2", 1); //Price
UpdateItemOutcome outcome = table.updateItem(
"Id", // key attribute name
101, // key attribute value
"add #A :val1 set #P = #P - :val2 remove #I",
expressionAttributeNames,
expressionAttributeValues);
I had a similar problem and what I've learned is that the availability of, and/or source repositories for, packages can change over time.Therefore, if an import cannot be resolved, the following procedure may help.
Identify the package that supplies the dependency.
Locate a source for the package.
Configure the source with Gradle or Maven.
For my answer, I verified your desired imports against com.amazonaws:DynamoDBLocal:1.11.477 under Kotlin.
From the artifact page at MVNRepository, I selected View All.
This led me to a repository source with the following URL:
https://repository.mulesoft.org/nexus/content/repositories/public/com/amazonaws/DynamoDBLocal/1.11.477/
Since I was using Kotlin, I added the corresponding repository data to repositories in my build.gradle.kts for Gradle.
// Local DynamoDB.
repositories {
maven(url = "https://repository.mulesoft.org/nexus/content/repositories/public")
}
dependencies {
implementation ("com.amazonaws:DynamoDBLocal:1.11.477")
}
These imports, for the non-local case, can also be satisfied from the package at:
http://central.maven.org/maven2/com/amazonaws/aws-java-sdk-dynamodb/1.11.564/
Therefore, the following entries also work:
// Remote DynamoDB.
repositories {
mavenCentral()
}
dependencies {
implementation("com.amazonaws:aws-java-sdk-dynamodb:1.11.564")
}
After configuring my project for either the local or remote versions, I was able to verify that all of your imports that include "document" were available.
I'm assuming you probably tried this already, but it worked for me so I'm going to mention it anyway: I made sure that the AWS SDK for Java library had been added and then I refreshed the project. Now all is working!
I closed my project down and reopened it many times with no success, but refreshing the project did the trick. Good luck.

Categories

Resources