I'm trying to import PAC file from URL and change Wifi proxy settings programmatically. I searched and found that it`s possible with:
ProxyInfo.buildPacProxy(Uri.parse("someurl")
Before asking this question I checked here and also all of this. The problem that I face is when I implement some of these solutions everything compiles well without exceptions, but when I check there are no proxy settings updated.
This is my last code, but once again without success:
public void setWifiProxySettings5()
{
//get the current wifi configuration
WifiManager manager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiConfiguration config = GetCurrentWifiConfiguration(manager);
if(null == config)
return;
try
{
//linkProperties is no longer in WifiConfiguration
Class proxyInfoClass = Class.forName("android.net.ProxyInfo");
Class[] setHttpProxyParams = new Class[1];
setHttpProxyParams[0] = proxyInfoClass;
Class wifiConfigClass = Class.forName("android.net.wifi.WifiConfiguration");
Method setHttpProxy = wifiConfigClass.getDeclaredMethod("setHttpProxy", setHttpProxyParams);
setHttpProxy.setAccessible(true);
Class proxySettingsClass = Class.forName("android.net.IpConfiguration$ProxySettings");
Class[] setProxySettingsParams = new Class[1];
setProxySettingsParams[0] = proxySettingsClass;
Method setProxySettings = wifiConfigClass.getDeclaredMethod("setProxySettings", setProxySettingsParams);
setProxySettings.setAccessible(true);
ProxyInfo pacInfo = ProxyInfo.buildPacProxy(Uri.parse("http://localhost/pac"));
//pass the new object to setHttpProxy
Object[] params_SetHttpProxy = new Object[1];
params_SetHttpProxy[0] = pacInfo;
setHttpProxy.invoke(config, params_SetHttpProxy);
//pass the enum to setProxySettings
Object[] params_setProxySettings = new Object[1];
params_setProxySettings[0] = Enum.valueOf((Class<Enum>) proxySettingsClass, "STATIC");
setProxySettings.invoke(config, params_setProxySettings);
//save the settings
manager.updateNetwork(config);
manager.disconnect();
manager.reconnect();
}
catch(Exception e)
{
Log.v("wifiProxy", e.toString());
}
}
Related
I am using this example to read from configuration file (data such as host name, password, etc) . But they did not include the Configurations class itself.
So I am not really sure how that should be implemented.
Here is how I am trying to read the properties from Main class:
Configurations configs = new Configurations(); // Error: cannot find symbol symbol: class Configurations location: class Main
try {
Configuration config = configs.properties(new File("database.properties"));
String dbHost = config.getString("database.host");
int dbPort = config.getInt("database.port");
String dbUser = config.getString("database.user");
String dbPassword = config.getString("database.password", "secret"); // provide a default
long dbTimeout = config.getLong("database.timeout");
} catch (ConfigurationException cex) {
cex.printStackTrace();
}
And this is how my database.properties file looks:
database.host = "dbname";
datatabase.port = 5005;
datatabase.user = "root";
datatabase.password = "";
database.timeout = 60000
P.S. Sorry for my stupidity, I am very new to Java.
You can use the properties class in java, which has a load method that specifies an inputstream.
Then, you can read your properties file via FileInputStream.
example:
public class Test {
public static void main(String[] args) throws Exception {
Properties properties = new Properties();
InputStream inputStream =
new FileInputStream("D:\\work_space\\java_workspace\\test-mq\\src\\main\\resources\\database.properties");
properties.load(inputStream);
String host = properties.getProperty("database.host");
// get more properties......
System.out.println(host);
}
}
I'm writing my own maven plugin, and I have an issue to load a certain class. This post proposed a way to enrich the ClassRealm to broad class loading scope.
#Mojo(
name = "deploy",
defaultPhase = LifecyclePhase.DEPLOY,
requiresDependencyCollection = ResolutionScope.RUNTIME,
requiresDirectInvocation = true,
requiresOnline = true
)
public class DeployMojo extends AbstractMojo {
#Parameter
private String server;
#Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
#Component
private PluginDescriptor descriptor;
public void execute() throws MojoExecutionException, MojoFailureException {
// Added runtime resources for the project and create the classloader
final var realm = descriptor.getClassRealm();
final ArrayList<String> classpathElements;
try {
classpathElements = new ArrayList<>(project.getRuntimeClasspathElements());
} catch (DependencyResolutionRequiredException e) {
throw new MojoExecutionException("Unable to resolve project dependencies", e);
}
classpathElements.add(project.getBuild().getOutputDirectory());
final var urls = new URL[classpathElements.size()];
for (int i = 0; i < classpathElements.size(); ++i) {
try {
urls[i] = new File(classpathElements.get(i)).toURI().toURL();
realm.addURL(urls[i]);
} catch (MalformedURLException e) {
throw new MojoExecutionException(String.format("Unable to parse classpath: %s as URL", classpathElements.get(i)), e);
}
}
//Some other operations
}
}
However, when I try to get the ClassRealm via descriptor.getClassRealm(), it shows that Cannot access org.codehaus.plexus.classworlds.realm.ClassRealm. Also in the documentation, it mentions that Warning: This is an internal utility method that is only public for technical reasons, it is not part of the public API. In particular, this method can be changed or deleted without prior notice and must not be used by plugins.
I wonder is there a way to enrich the ClassRealm, or this is something that we shouldn't change.
I'm trying to create a new AWS EC2 instance using the AWS Java SDK but getting "Value () for parameter groupId is invalid. The value cannot be empty". Here is my code:
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_WEST_2)
.build();
}
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
String ami_id = "ami-efd0428f"; //ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20170414
Collection<String> securityGroups = new ArrayList<>();
securityGroups.add("launch-wizard-1");
securityGroups.add("sg-9405c2f3");
runInstancesRequest.withImageId(ami_id)
.withInstanceType("t2.medium")
.withMinCount(1)
.withMaxCount(1)
.withKeyName("MyKeyName")
.withSecurityGroups(securityGroups);
RunInstancesResult run_response = ec2.runInstances(runInstancesRequest); // fails here!
String instance_id = run_response.getReservation().getReservationId();
Tag tag = new Tag()
.withKey("Name")
.withValue(tfCompanyName.getText());
Collection<Tag> tags = new ArrayList<>();
tags.add(tag);
CreateTagsRequest tag_request = new CreateTagsRequest();
tag_request.setTags(tags);
CreateTagsResult tag_response = ec2.createTags(tag_request);
String s = String.format("Successfully started EC2 instance %s based on AMI %s",instance_id, ami_id);
System.out.println(s);
Any suggestions?
You might need to add a VPC details also .
PrivateIpAddresses ,Monitoring are among other required fields.
I would recommend you to try creating EC2 Instance manually using AWS Console and see what are the required parameters it is asking?
I have to invoke external java methods in xquery using saxon HE. I could able to invoke the methods with the below code. But the problem is i want to bind my input externally.
final Configuration config = new Configuration();
config.registerExtensionFunction(new ShiftLeft());
final StaticQueryContext sqc = new StaticQueryContext(config);
final XQueryExpression exp = sqc.compileQuery(new FileReader(
"input/names.xq"));
final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
String xml = "<student_list><student><name>George Washington</name><major>Politics</major><phone>312-123-4567</phone><email>gw#example.edu</email></student><student><name>Janet Jones</name><major>Undeclared</major><phone>311-122-2233</phone><email>janetj#example.edu</email></student><student><name>Joe Taylor</name><major>Engineering</major><phone>211-111-2333</phone><email>joe#example.edu</email></student></student_list>";
DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
newInstance.setNamespaceAware(true);
Document parse = newInstance.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
DocumentWrapper sequence = new DocumentWrapper(parse, "", config);
StructuredQName qname = new StructuredQName("", "", "student_list");
dynamicContext.setParameter(qname, sequence);
Properties props = new Properties();
final SequenceIterator iter = exp.iterator(dynamicContext);
props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
props.setProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
QueryResult.serializeSequence(iter, config, writer, props);
System.out.println("Result is " + writer);
names.xq
declare namespace eg="http://example.com/saxon-extension";
declare namespace xs = "http://www.w3.org/2001/XMLSchema";
declare variable $student_list as element(*) external;
<Students>
<value> {
let $n := eg:shift-left(2, 2)
return $n
}</value>
<student_names>
{ $student_list//student_list/student/name }
</student_names>
</Students>
But getting the below error
Error at procedure student_list on line 3 of students.xml:
XPTY0004: Required item type of value of variable $student_list is element(); supplied
value has item type document-node(element(Q{}student_list))
net.sf.saxon.trans.XPathException: Required item type of value of variable $student_list is element(); supplied value has item type document- node(element(Q{}student_list))
at net.sf.saxon.expr.ItemTypeCheckingFunction.testConformance(ItemTypeCheckingFunction.java:69)
at net.sf.saxon.expr.ItemTypeCheckingFunction.mapItem(ItemTypeCheckingFunction.java:50)
at net.sf.saxon.expr.ItemMappingIterator.next(ItemMappingIterator.java:95)
at net.sf.saxon.expr.CardinalityCheckingIterator.<init>(CardinalityCheckingIterator.java:52)
at net.sf.saxon.type.TypeHierarchy.applyFunctionConversionRules(TypeHierarchy.java:230)
at net.sf.saxon.expr.instruct.GlobalParameterSet.convertParameterValue(GlobalParameterSet.java:105)
at net.sf.saxon.expr.instruct.Bindery.useGlobalParameter(Bindery.java:136)
at net.sf.saxon.expr.instruct.GlobalParam.evaluateVariable(GlobalParam.java:62)
at net.sf.saxon.expr.GlobalVariableReference.evaluateVariable(GlobalVariableReference.java:105)
at net.sf.saxon.expr.VariableReference.evaluateItem(VariableReference.java:460)
at net.sf.saxon.expr.Atomizer.evaluateItem(Atomizer.java:313)
at net.sf.saxon.expr.Atomizer.evaluateItem(Atomizer.java:35)
at net.sf.saxon.expr.AtomicSequenceConverter.evaluateItem(AtomicSequenceConverter.java:275)
at net.sf.saxon.expr.AtomicSequenceConverter.evaluateItem(AtomicSequenceConverter.java:30)
at net.sf.saxon.functions.Doc.doc(Doc.java:235)
at net.sf.saxon.functions.Doc.evaluateItem(Doc.java:190)
at net.sf.saxon.functions.Doc.evaluateItem(Doc.java:28)
at net.sf.saxon.expr.SimpleStepExpression.iterate(SimpleStepExpression.java:85)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:842)
at net.sf.saxon.expr.sort.DocumentSorter.iterate(DocumentSorter.java:168)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:842)
at net.sf.saxon.expr.sort.DocumentSorter.iterate(DocumentSorter.java:168)
at net.sf.saxon.expr.Expression.process(Expression.java:552)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:450)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:389)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:669)
at net.sf.saxon.expr.instruct.Instruction.process(Instruction.java:144)
at net.sf.saxon.expr.instruct.ElementCreator.constructElement(ElementCreator.java:539)
at net.sf.saxon.expr.instruct.ElementCreator.evaluateItem(ElementCreator.java:476)
at net.sf.saxon.expr.instruct.Instruction.iterate(Instruction.java:363)
at net.sf.saxon.query.XQueryExpression.iterator(XQueryExpression.java:332)
at com.example.saxon.ExternalMethodCaller.main(ExternalMethodCaller.java:77)
Thanks in advance..
Unless you have a very good reason not to, my advice is to use Snappi (the Saxon 9 API, or s9api):
Processor saxon = new Processor(false);
saxon.registerExtensionFunction(new MyExtension());
XQueryCompiler compiler = saxon.newXQueryCompiler();
XQueryExecutable exec = compiler.compile(new File("input/names.xq"));
XQueryEvaluator query = exec.load();
DocumentBuilder builder = saxon.newDocumentBuilder();
String students = "<xml>...</xml>";
Source src = new StreamSource(new StringReader(students));
XdmNode doc = builder.build(src);
query.setExternalVariable(new QName("student_list"), doc);
XdmValue result = query.evaluate();
With MyExtension looking something like the following:
public class MyExtension
implements ExtensionFunction
{
#Override
public QName getName()
{
return new QName("http://example.org/my-project", "my-fun");
}
#Override
public SequenceType getResultType()
{
return SequenceType.makeSequenceType(
ItemType.INTEGER, OccurrenceIndicator.ONE);
}
#Override
public SequenceType[] getArgumentTypes()
{
return new SequenceType[] {
SequenceType.makeSequenceType(
ItemType.INTEGER, OccurrenceIndicator.ONE),
SequenceType.makeSequenceType(
ItemType.INTEGER, OccurrenceIndicator.ONE)
};
}
#Override
public XdmValue call(XdmValue[] args) throws SaxonApiException
{
long first = ((XdmAtomicValue)args[0].itemAt(0)).getLongValue();
long second = ((XdmAtomicValue)args[0].itemAt(0)).getLongValue();
long result = ...;
return new XdmAtomicValue(result);
}
}
See the documentation at http://www.saxonica.com/documentation9.5/extensibility/integratedfunctions/ext-simple-J.html for details.
EXPath also has a project called tools-saxon, containing several tools for using Saxon in Java. Including extension functions. It introduces the concept of a function library, which is convenient if you have several extension functions. It also introduces a function definition builder, allowing one to build a function definition with as less boiler plate code as possible (and providing convenient shortcuts for type sequences). In the above code, replace the function registering (the first 2 lines) by:
Processor saxon = new Processor(false);
Library lib = new MyLibrary();
lib.register(saxon.getUnderlyingConfiguration());
and replace the extension class with the 2 following classes (a library and a function, resp.):
public class MyLibrary
extends Library
{
public MyLibrary()
{
super("http://example.org/my-project", "my");
}
#Override
protected Function[] functions()
{
return new Function[] {
new MyFunction(this)
};
}
}
public class MyFunction
extends Function
{
public MyFunction(Library lib)
{
super(lib);
}
#Override
protected Definition makeDefinition()
{
return library()
.function(this, "my-fun")
.returns(Types.SINGLE_INTEGER)
.param(Types.SINGLE_INTEGER, "first")
.param(Types.SINGLE_INTEGER, "second")
.make();
}
#Override
public Sequence call(XPathContext ctxt, Sequence[] args)
throws XPathException
{
Parameters params = checkParams(args);
long first = params.asLong(0, true);
long second = params.asLong(1, true);
long result = 0;
return Return.value(result);
}
}
See all informatio on the project home on Github, at https://github.com/expath/tools-saxon.
Note: not tested.
I can't deploy the agent in JADE implemented in Java, any alternatives ?
package package1;
import jade.core.Agent;
public class JadePFE extends Agent {
#Override
protected void setup() {
System.out.println("Hello agent 007");
}
}
I think you mean to start the JADE platform, this is the contents of the my main method which launches the whole thing. Hope it helps
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] args1 = new String[3];
args1[0] = "-gui";
args1[1] = "-agents";
args1[2] = "agentName:package.agentClassName";
jade.Boot.main(args1);
}
}
If I have understand, you want know how deploy an agent (and maybe start the platform) directly from the code.
I show you how:
import jade.core.Runtime;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.*;
public class Start {
public static void main(String args[]) throws InterruptedException, StaleProxyException {
// Get a hold on JADE runtime
Runtime runTime = Runtime.instance();
// Exit the JVM when there are no more containers around
runTime.setCloseVM(true);
// Create a profile and the main container and start RMA
Profile mainProfile = new ProfileImpl(true);
AgentContainer mainContainer = runTime.createMainContainer(mainProfile);
AgentController rma = mainContainer.createNewAgent("rma", "jade.tools.rma.rma", null);
rma.start();
Thread.sleep(500);
// Create a Sniffer
AgentController sniffer = mainContainer.createNewAgent(
"mySniffer", "jade.tools.sniffer.Sniffer",
new Object[]{"BuyerAgent1;BuyerAgent2;ShipperAgent1;ShipperAgent2"});
sniffer.start();
Thread.sleep(500);
// Create a Introspector
AgentController introspector = mainContainer.createNewAgent(
"myIntrospector", "jade.tools.introspector.Introspector",
null);
introspector.start();
Thread.sleep(500);
// Prepare for create and fire new agents:
Profile anotherProfile;
AgentContainer anotherContainer;
AgentController agent;
/* Create a new profile and a new non-main container, connecting to the
default main container (i.e. on this host, port 1099)
NB. Two containers CAN'T share the same Profile object: create a new one. */
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a BuyerAgent...");
agent = anotherContainer.createNewAgent("BuyerAgent1", "transfersimulation.BuyerAgent", new Object[0]);
agent.start();
Thread.sleep(900);
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a BuyerAgent...");
agent = anotherContainer.createNewAgent("BuyerAgent2", "transfersimulation.BuyerAgent", new Object[0]);
agent.start();
Thread.sleep(900);
anotherProfile = new ProfileImpl(false);
anotherContainer = runTime.createAgentContainer(anotherProfile);
System.out.println("Starting up a ShipperAgent...");
agent = anotherContainer.createNewAgent("ShipperAgent1", "transfersimulation.ShipperAgent", new Object[0]);
agent.start();
Thread.sleep(900);
return;
}
}
This works if no other JADE Platform is already running.