WMI Win32_SoundDevice J-Interop throws Unknown name exception - java

I am trying to get Win32_SoundDevice and Win32_VideoControllerHardware id but getting Win32_SoundDevice instance throws Unknow Name Exception
here is my code
package com.az;
import static org.jinterop.dcom.core.JIProgId.valueOf;
import static org.jinterop.dcom.impls.JIObjectFactory.narrowObject;
import static org.jinterop.dcom.impls.automation.IJIDispatch.IID;
import java.awt.Label;
import java.util.logging.Level;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIArray;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.automation.IJIDispatch;
import org.jinterop.dcom.impls.automation.IJIEnumVariant;
public class PerformanceMonitor extends JApplet {
String domain = "az.com.us";
String hostname = "mc-us-az";
String username = "az";
String password = "test_az_";
public JIComServer comServer = null;
public JISession dcomSession = null;
public IJIDispatch wbemServices = null;
public Object[] params = null;
public static final String soundCardInfo = "Win32_SoundDevice";
public void setWindowsCredentials(String domain, String hostname, String username, String password) {
try {
dcomSession = init(domain, username, password);
comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"), hostname, dcomSession);
IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
params = new Object[] { new JIString(hostname), new JIString("ROOT\\CIMV2"), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(),
JIVariant.OPTIONAL_PARAM(), new Integer(0), JIVariant.OPTIONAL_PARAM() };
JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
getWMISoundCard(getJIVariants(wbemLocator, soundCardInfo));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dcomSession != null) {
try {
JISession.destroySession(dcomSession);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
private void getWMISoundCard(JIVariant[] diskMonit) {
try {
IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(diskMonit[0].getObjectAsComObject());
JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
IJIComObject object2 = newEnumvariant.getObjectAsComObject();
IJIEnumVariant enumVARIANT = (IJIEnumVariant) narrowObject(object2.queryInterface(IJIEnumVariant.IID));
JIVariant countVariant = wbemObjectSet.get("Count");
int numberOfServices = countVariant.getObjectAsInt();
for (int i = 0; i < numberOfServices; i++) {
Object[] elements = enumVARIANT.next(1);
JIArray aJIArray = (JIArray) elements[0];
JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();
for (JIVariant variant : array) {
IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());
JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] { 1 });
JIVariant deviceID = (JIVariant) (wbemObjectDispatch.get("DeviceID"));
System.out.println("SoundCard Device ID =" + deviceID.getObjectAsString2());
}
}
} catch (JIException e) {
e.printStackTrace();
}
}
public JIVariant[] getJIVariants(IJIDispatch wbemServices, String task) {
JIVariant[] arrJIVariant = null;
try {
params = new Object[] { new JIString(task), new Integer(0), JIVariant.OPTIONAL_PARAM() };
arrJIVariant = wbemServices.callMethodA("InstancesOf", params);
} catch (JIException e) {
e.printStackTrace();
}
return arrJIVariant;
}
private static JISession init(String domain, String user, String pass) throws Exception {
JISystem.getLogger().setLevel(Level.OFF);
JISystem.setAutoRegisteration(true);
JISession dcomSession = JISession.createSession(domain, user, pass);
dcomSession.useSessionSecurity(false);
return dcomSession;
}
public static void main(String[] args) {
PerformanceMonitor performanceMonitor = new PerformanceMonitor();
performanceMonitor.setWindowsCredentials(performanceMonitor.domain, performanceMonitor.hostname, performanceMonitor.username, performanceMonitor.password);
}
}
Stack Trace
org.jinterop.dcom.common.JIException: Unknown name. [0x80020006]
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:910)
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:856)
at org.jinterop.dcom.core.JIComObjectImpl.call(JIComObjectImpl.java:266)
at org.jinterop.dcom.core.JIComObjectImpl.call(JIComObjectImpl.java:153)
at org.jinterop.dcom.impls.automation.JIDispatchImpl.getIDsOfNames(JIDispatchImpl.java:109)
at org.jinterop.dcom.impls.automation.JIDispatchImpl.callMethodA(JIDispatchImpl.java:477)
at com.az.PerformanceMonitor.getJIVariants(PerformanceMonitor.java:682)
at com.az.PerformanceMonitor.setWindowsCredentials(PerformanceMonitor.java:123)
at com.az.PerformanceMonitor.init(PerformanceMonitor.java:80)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.jinterop.dcom.common.JIRuntimeException: Unknown name. [0x80020006]
at org.jinterop.dcom.core.JICallBuilder.readResult(JICallBuilder.java:1079)
at org.jinterop.dcom.core.JICallBuilder.read(JICallBuilder.java:957)
at ndr.NdrObject.decode(NdrObject.java:36)
at rpc.ConnectionOrientedEndpoint.call(ConnectionOrientedEndpoint.java:137)
at rpc.Stub.call(Stub.java:113)
at org.jinterop.dcom.core.JIComServer.call(JIComServer.java:901)
... 10 more

Just replace this line
getWMISoundCard(getJIVariants(wbemLocator, soundCardInfo));
with this
getWMISoundCard(getJIVariants(wbemServices, soundCardInfo));
and problem solved

Related

error: cannot find symbol, won't find my bean

I was given code that I have to make do something else. When I go to compile my servlet, it doesn't recognize my bean. I've deleted, recompiled, and tried from all different directories. I have no clue why this isn't working.
import BH.*;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.function.*;
import static java.util.Arrays.asList;
import java.text.DateFormat;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class sessionServlet extends HttpServlet {
private List<String[]> the_sessions;
private DateFormat df;
public static ReentrantLock thelock = new ReentrantLock();
public void init() throws ServletException {
the_sessions=new ArrayList<String[]>();
df=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
if ((!(req.getParameter("task")==null))&&(req.getParameter("task").trim().equals("deploy"))) {
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<hr /><center><h1>sessionServlet Deployed</h1></center><hr />");
out.println("</body>");
out.println("</html>");
return;
}
Consumer <String> forwardTo =(s) ->ForwardTo(s,req,res);
boolean is_first_visit=true;
String[] this_session=new String[3];
String manager = req.getParameter("manager");
for (String [] a_session :the_sessions) {
if (a_session[0].equals(manager)) { //Found an active session
is_first_visit=false;
this_session=a_session;
break;
}
}
if ((req.getParameter("task")==null)&&(!is_first_visit)) {
the_sessions.remove(this_session);
is_first_visit=true; // just used http://hoare.cs.umsl.edu/servlet/js_test/sessionServlet
}
req.setAttribute("thesessioncount",the_sessions.size());
if (is_first_visit) {
if (the_sessions.size()==10) {
forwardTo.accept("noSessions.jsp"); //No Available Sessions
return;
}
String randomStr = getRandomString();
String[] new_session = {randomStr,df.format(new Date()),"need a name"};
the_sessions.add(new_session);
this_session=new_session;
req.setAttribute("manager",randomStr);
forwardTo.accept("startSession.jsp");
return;
}
String the_name="";
String the_pw="";
if (this_session[2].equals("need a name")) { //No name given yet
the_name=req.getParameter("whoisit");
the_pw=req.getParameter("passwd");
if ((the_name==null)||(the_name.trim().length()==0)||checkPW(the_name,the_pw)) { //checkPW returns false if correct
the_sessions.remove(this_session);
req.setAttribute("thesessioncount",the_sessions.size());
forwardTo.accept("startSession.jsp");
return; // didn't enter a name in startSession
}
}
this_session[2]=the_name.trim();
req.setAttribute("thename", this_session[2]);
if (tooLong(this_session[1],df.format(new Date()))) { //Has the session timed out?
the_sessions.remove(this_session);
forwardTo.accept("Expired.jsp");
return;
} else {
this_session[1]=df.format(new Date()); //reset the last session activity time
NotesBean thesenotes=new NotesBean();
if(req.getParameter("task").trim().equals("9")){
the_sessions.remove(this_session);
forwardTo.accept("exit.jsp");
return;
}
thelock.lock();
if (!req.getParameter("task").trim().equals("0")) { //add ACC here, also show/update posts
thesenotes.setAll(req.getParameter("java_source"),Integer.parseInt(req.getParameter("version")));
if (req.getParameter("task").trim().equals("2")) {
thesenotes.setNotes(req.getParameter("notes"),req.getParameter("java_source"),Integer.parseInt(req.getParameter("version")));
}
}
req.setAttribute("thesessioncount",the_sessions.size());
req.setAttribute("theBean",thesenotes);
req.setAttribute("manager",manager);
//req.setAttribute("theURL", "http://www.umsl.edu/~siegelj/turing.jpg");
forwardTo.accept("getNotes.jsp");
thelock.unlock();
return;
}
}//end doGet
boolean tooLong(String now,String then){
//Check amount of time that passed
return false;
}
boolean checkPW(String name,String password){
AccountBean theAccount = new AccountBean();
theAccount.setAccount(name);
if(theAccount.isPassword(password))
return false;
return true;
}
public void log(String s){
FileWriter fileWriter = null;
try {
String content =s+" at :"+new Date(System.currentTimeMillis()).toString()+"\n";
File theLogFile = new File("C:/Tomcat/webapps/js_test/session.log");
fileWriter = new FileWriter(theLogFile,true);
fileWriter.write(content);
} catch (IOException ex) {
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
}
}
}
void ForwardTo(String s,HttpServletRequest req, HttpServletResponse res)
{
RequestDispatcher rd= req.getRequestDispatcher(s);
try {
rd.forward(req, res);
} catch (IOException|ServletException is) {
log(" req from "+s+" not forwarded at ");
try {
throw is;
} catch (Exception e) {
}
}
}
public void destroy()
{
log("The instance was destroyed");
}
public String getRandomString(){
byte[] randbyte=new byte[10];
Random rand = new Random(System.currentTimeMillis());
for (int idx = 0; idx <10; ++idx) {
int randomInt = rand.nextInt(26); //0<=randomInt<26
//System.out.println(randomInt);
randbyte[idx]=(byte)(randomInt+65);
}
try {
String rs=new String(randbyte, "UTF-8");
//System.out.println(rs);
return rs;
} catch (Exception e) {
//System.out.println("bad string");
return "bad";
}
}
}
AccountBean.java
package mybeans;
import BH.*;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.ArrayList;
import java.util.Arrays;
import static java.util.Arrays.asList;
import java.sql.*;
public class AccountBean implements java.io.Serializable {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/cs4010";
static final String USER = "cs4010";
static final String PASS = "cs4010";
private String account="";
private String password="";
public AccountBean(){
}
public void setAccount(String a)
{
account = a;
}
public String getAccount()
{
return account;
}
public void setPassword(String p)
{
password = p;
}
public String getPassword(){
return password;
}
public void createAccount()
{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmt = conn.createStatement();
// System.out.println("here: "+Bytes_Hex.String2HexString(n));
String this_query="INSERT INTO ries_userpass (username, password) VALUES ("+account+","+password+");";
// System.out.println(this_query);
stmt.executeUpdate(this_query);
stmt.close();
conn.close();
} catch (Exception e) {
}
return ;
}
public boolean isPassword(String p) //make this to use
{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmt = conn.createStatement();
String this_query=" SELECT * from ries_userpass WHERE username="+account+";";
ResultSet rs = stmt.executeQuery(this_query);
while (rs.next()) {
password=Bytes_Hex.HexString2String(rs.getString("posts"));
if(password.equals(p))
{
rs.close();
stmt.close();
conn.close();
return true;
}
}
rs.close();
stmt.close();
conn.close();
}
catch (Exception e) {
return false;
}
return false;
}
}
add this statement import mybeans.*;, since you are using AccountBean but you are not importing that class package;
import BH.*;
import mybeans.*;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.function.*;
import static java.util.Arrays.asList;
import java.text.DateFormat;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Random;
public class sessionServlet extends HttpServlet {
private List<String[]> the_sessions;
private DateFormat df;
public static ReentrantLock thelock = new ReentrantLock();
public void init() throws ServletException {
the_sessions=new ArrayList<String[]>();
df=DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG);
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
if ((!(req.getParameter("task")==null))&&(req.getParameter("task").trim().equals("deploy"))) {
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<hr /><center><h1>sessionServlet Deployed</h1></center><hr />");
out.println("</body>");
out.println("</html>");
return;
}
Consumer <String> forwardTo =(s) ->ForwardTo(s,req,res);
boolean is_first_visit=true;
String[] this_session=new String[3];
String manager = req.getParameter("manager");
for (String [] a_session :the_sessions) {
if (a_session[0].equals(manager)) { //Found an active session
is_first_visit=false;
this_session=a_session;
break;
}
}
if ((req.getParameter("task")==null)&&(!is_first_visit)) {
the_sessions.remove(this_session);
is_first_visit=true; // just used http://hoare.cs.umsl.edu/servlet/js_test/sessionServlet
}
req.setAttribute("thesessioncount",the_sessions.size());
if (is_first_visit) {
if (the_sessions.size()==10) {
forwardTo.accept("noSessions.jsp"); //No Available Sessions
return;
}
String randomStr = getRandomString();
String[] new_session = {randomStr,df.format(new Date()),"need a name"};
the_sessions.add(new_session);
this_session=new_session;
req.setAttribute("manager",randomStr);
forwardTo.accept("startSession.jsp");
return;
}
String the_name="";
String the_pw="";
if (this_session[2].equals("need a name")) { //No name given yet
the_name=req.getParameter("whoisit");
the_pw=req.getParameter("passwd");
if ((the_name==null)||(the_name.trim().length()==0)||checkPW(the_name,the_pw)) { //checkPW returns false if correct
the_sessions.remove(this_session);
req.setAttribute("thesessioncount",the_sessions.size());
forwardTo.accept("startSession.jsp");
return; // didn't enter a name in startSession
}
}
this_session[2]=the_name.trim();
req.setAttribute("thename", this_session[2]);
if (tooLong(this_session[1],df.format(new Date()))) { //Has the session timed out?
the_sessions.remove(this_session);
forwardTo.accept("Expired.jsp");
return;
} else {
this_session[1]=df.format(new Date()); //reset the last session activity time
NotesBean thesenotes=new NotesBean();
if(req.getParameter("task").trim().equals("9")){
the_sessions.remove(this_session);
forwardTo.accept("exit.jsp");
return;
}
thelock.lock();
if (!req.getParameter("task").trim().equals("0")) { //add ACC here, also show/update posts
thesenotes.setAll(req.getParameter("java_source"),Integer.parseInt(req.getParameter("version")));
if (req.getParameter("task").trim().equals("2")) {
thesenotes.setNotes(req.getParameter("notes"),req.getParameter("java_source"),Integer.parseInt(req.getParameter("version")));
}
}
req.setAttribute("thesessioncount",the_sessions.size());
req.setAttribute("theBean",thesenotes);
req.setAttribute("manager",manager);
//req.setAttribute("theURL", "http://www.umsl.edu/~siegelj/turing.jpg");
forwardTo.accept("getNotes.jsp");
thelock.unlock();
return;
}
}//end doGet
boolean tooLong(String now,String then){
//Check amount of time that passed
return false;
}
boolean checkPW(String name,String password){
AccountBean theAccount = new AccountBean();
theAccount.setAccount(name);
if(theAccount.isPassword(password))
return false;
return true;
}
public void log(String s){
FileWriter fileWriter = null;
try {
String content =s+" at :"+new Date(System.currentTimeMillis()).toString()+"\n";
File theLogFile = new File("C:/Tomcat/webapps/js_test/session.log");
fileWriter = new FileWriter(theLogFile,true);
fileWriter.write(content);
} catch (IOException ex) {
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
}
}
}
void ForwardTo(String s,HttpServletRequest req, HttpServletResponse res)
{
RequestDispatcher rd= req.getRequestDispatcher(s);
try {
rd.forward(req, res);
} catch (IOException|ServletException is) {
log(" req from "+s+" not forwarded at ");
try {
throw is;
} catch (Exception e) {
}
}
}
public void destroy()
{
log("The instance was destroyed");
}
public String getRandomString(){
byte[] randbyte=new byte[10];
Random rand = new Random(System.currentTimeMillis());
for (int idx = 0; idx <10; ++idx) {
int randomInt = rand.nextInt(26); //0<=randomInt<26
//System.out.println(randomInt);
randbyte[idx]=(byte)(randomInt+65);
}
try {
String rs=new String(randbyte, "UTF-8");
//System.out.println(rs);
return rs;
} catch (Exception e) {
//System.out.println("bad string");
return "bad";
}
}
}

I'm getting warning from PostConstruct annotated init method

I'm getting this warning from #PostConstruct annotated init method
Nis 18, 2014 2:46:10 PM com.sun.faces.vendor.WebContainerInjectionProvider getAnnotatedMethodForMethodArr
WARNING: JSF1047: Method 'public void com.revir.managed.bean.PickListBean.init() throws java.lang.Exception' marked with the 'javax.annotation.PostConstruct' annotation cannot declare any checked exceptions. This method will be ignored.
So my method is ignored, what do I have to do to fix this problem ?
package com.revir.managed.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import org.springframework.beans.factory.annotation.Autowired;
#ManagedBean(name = "pickListBean")
#ViewScoped
public class PickListBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private DualListModel<TrvrTani> tanis;
private DualListModel<TrvrIlac> ilacs;
int tanisize = 0;
String taniadi = null;
Long taniidp = null;
public Long getTaniidp() {
return taniidp;
}
public void setTaniidp(Long taniidp) {
this.taniidp = taniidp;
}
String tanikodu = null;
#Autowired(required=false)
private TrvrTaniDAO tanidao;
public TrvrTaniDAO getTanidao() {
return tanidao;
}
public void setTanidao(TrvrTaniDAO tanidao) {
this.tanidao = tanidao;
}
List<TrvrTani> sourcetani;
List<TrvrTani> targettani;
List<TrvrIlac> sourceilac;
List<TrvrIlac> targetilac;
#PostConstruct
public void init(){
try {
sourcetani = new ArrayList<TrvrTani>();
targettani = new ArrayList<TrvrTani>();
tanidao = new TrvrTaniDAO();
List<TrvrTani> taniList = tanidao.findAll();
for (TrvrTani tani : taniList) {
Long taniid = tani.getTaniid();
sourcetani.add(new TrvrTani(taniid, tani.getTaniadi(), tani
.getTanikodu()));
}
tanis = new DualListModel<TrvrTani>(sourcetani, targettani);
sourceilac = new ArrayList<TrvrIlac>();
targetilac = new ArrayList<TrvrIlac>();
ilacdao = new TrvrIlacDAO();
List<TrvrIlac> ilacList = ilacdao.findAll();
for (TrvrIlac ilac : ilacList) {
sourceilac.add(new TrvrIlac(ilac.getIlacid(), ilac.getIlacad(),
ilac.getBarkod(), null));
}
ilacs = new DualListModel<TrvrIlac>(sourceilac, targetilac);
} catch (Exception e) {
System.out.println("Hata mesajı : " +e);
throw e;
}
}
public DualListModel<TrvrIlac> getIlacs() {
return ilacs;
}
public void setIlacs(DualListModel<TrvrIlac> ilacs) {
this.ilacs = ilacs;
}
public DualListModel<TrvrTani> getTanis() {
return tanis;
}
public void setTanis(DualListModel<TrvrTani> tanis) {
this.tanis = tanis;
}
public void onTransferTani(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((TrvrTani) item).getTaniadi()).append("<br />");
targetlist(tanisize, taniadi, taniidp, tanikodu);
}
FacesMessage msgtani = new FacesMessage();
msgtani.setSeverity(FacesMessage.SEVERITY_INFO);
msgtani.setSummary("Tanı Eklendi");
msgtani.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msgtani);
}
public void targetlist(int tanisize, String taniadi, Long taniidp,
String tanikodu) {
tanisize = tanis.getTarget().size();
System.out.println(" ************target************* : "
+ tanis.getTarget().size());
for (int h = 0; h < tanisize; h++) {
/* elemanin adi, id si ve kodu */
taniadi = tanis.getTarget().get(h).getTaniadi();
System.out.println(" ************taniadi1************* : "
+ taniadi);
taniidp = tanis.getTarget().get(h).getTaniid();
System.out.println(" ************taniid2************* : "
+ taniidp);
tanikodu = tanis.getTarget().get(h).getTanikodu();
System.out.println(" ************tanikodu3************* : "
+ tanikodu);
}
}
public void onTransferIlac(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((TrvrIlac) item).getIlacad()).append("<br />");
}
FacesMessage msgilac = new FacesMessage();
msgilac.setSeverity(FacesMessage.SEVERITY_INFO);
msgilac.setSummary("İlaç Eklendi");
msgilac.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msgilac);
}
}
Remove the throws Exception from the init method. Use try catch to prevent any exception from being thrown. Once you remove the exception declaration, the compiler will show you of any exceptions that may be thrown, so add try catch there.

JFOREX SDK - How to send HTTPS GET request to www server ssl connection

how to add this
public class JavaHttpsExample
{
public static void main(String[] args)
throws Exception
{
String httpsURL = "https://localhost/send.php&json=somevalue";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
in.close();
}
}
to
Jforex maven sdk for eclipse:
http://www.dukascopy.com/client/jforexlib/JForex-SDK.zip
and
http://www.dukascopy.com/wiki/#IClient_functionality
package singlejartest_old;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.*;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* This small program demonstrates how to initialize Dukascopy client and start a strategy
*/
public class MainStopFromConsole {
private static final Logger LOGGER = LoggerFactory.getLogger(MainStopFromConsole.class);
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String userName = "";
private static String password = "";
public static void main(String[] args) throws Exception {
//get the instance of the IClient interface
final IClient client = ClientFactory.getDefaultInstance();
//set the listener that will receive system events
client.setSystemListener(new ISystemListener() {
private int lightReconnects = 3;
#Override
public void onStart(long processId) {
LOGGER.info("Strategy started: " + processId);
}
#Override
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
if (client.getStartedStrategies().size() == 0) {
System.exit(0);
}
}
#Override
public void onConnect() {
LOGGER.info("Connected");
lightReconnects = 3;
}
#Override
public void onDisconnect() {
LOGGER.warn("Disconnected");
if (lightReconnects > 0) {
LOGGER.error("TRY TO RECONNECT, reconnects left: " + lightReconnects);
client.reconnect();
--lightReconnects;
} else {
try {
//sleep for 10 seconds before attempting to reconnect
Thread.sleep(10000);
} catch (InterruptedException e) {
//ignore
}
try {
client.connect(jnlpUrl, userName, password);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
});
LOGGER.info("Connecting...");
//connect to the server using jnlp, user name and password
client.connect(jnlpUrl, userName, password);
//wait for it to connect
int i = 10; //wait max ten seconds
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("Failed to connect Dukascopy servers");
System.exit(1);
}
//subscribe to the instruments
Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
LOGGER.info("Subscribing instruments...");
client.setSubscribedInstruments(instruments);
//start the strategy
LOGGER.info("Starting strategy");
final long strategyId = client.startStrategy(new IStrategy(){
public Instrument instrument = Instrument.EURUSD;
private IConsole console;
public void onStart(IContext context) throws JFException {
console = context.getConsole();
}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if ( instrument == this.instrument){
console.getOut().println(" bar: " + period + " " + askBar);
}
}
public void onTick(Instrument instrument, ITick tick) throws JFException { }
public void onMessage(IMessage message) throws JFException { }
public void onAccount(IAccount account) throws JFException { }
public void onStop() throws JFException { }
});
//now it's running
//every second check if "stop" had been typed in the console - if so - then stop the strategy
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Scanner s = new Scanner(System.in);
while(true){
while(s.hasNext()){
String str = s.next();
if(str.equalsIgnoreCase("stop")){
System.out.println("Strategy stop by console command.");
client.stopStrategy(strategyId);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
i need send some values(account balance or open positions) to WWW serwer from strategy
Thanks
zix
package master;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.*;
import java.awt.Color;
import java.awt.List;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Array;
import java.net.URL;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JFrame;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import singlejartest.JavaHttpsExample;
public class MainStopFromConsole {
private static final Logger LOGGER = LoggerFactory.getLogger(MainStopFromConsole.class);
private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
private static String userName = "DEMO2PRFwj";
private static String password = "PRFwj";
//static String[] columns = {"Open Time", "Id", "Label", "Comment", "Instrument", "Side", "Amount", "Original Amount", "Open Price", "Stop Loss", "Take Profit", "Profit (Pips)", "Profit Currency", "Profit in USD", "Commission", "Commission USD"};
static String[] columns = {"Id", "Instrument", "Side", "Amount", "Open Price", "Stop Loss", "Take Profit"};
//static String[][] data = {{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16"},
static String[][] data = new String[50][11];
//static String[][] data = null;
//static JFrame jf = new JFrame();
public static void main(String[] args) throws Exception {
//get the instance of the IClient interface
final IClient client = ClientFactory.getDefaultInstance();
//set the listener that will receive system events
client.setSystemListener(new ISystemListener() {
private int lightReconnects = 3;
public void onStart(long procid) {
//IConsole console = context.getConsole();
LOGGER.info("Strategy started: ");
}
public void onStop(long processId) {
LOGGER.info("Strategy stopped: " + processId);
if (client.getStartedStrategies().size() == 0) {
System.exit(0);
}
}
#Override
public void onConnect() {
LOGGER.info("Connected");
lightReconnects = 3;
}
#Override
public void onDisconnect() {
LOGGER.warn("Disconnected");
if (lightReconnects > 0) {
LOGGER.error("TRY TO RECONNECT, reconnects left: " + lightReconnects);
client.reconnect();
--lightReconnects;
} else {
try {
//sleep for 10 seconds before attempting to reconnect
Thread.sleep(10000);
} catch (InterruptedException e) {
//ignore
}
try {
client.connect(jnlpUrl, userName, password);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
});
LOGGER.info("Connecting...");
//connect to the server using jnlp, user name and password
client.connect(jnlpUrl, userName, password);
//wait for it to connect
int i = 10; //wait max ten seconds
while (i > 0 && !client.isConnected()) {
Thread.sleep(1000);
i--;
}
if (!client.isConnected()) {
LOGGER.error("Failed to connect Dukascopy servers");
System.exit(1);
}
//subscribe to the instruments
Set<Instrument> instruments = new HashSet<Instrument>();
instruments.add(Instrument.EURUSD);
LOGGER.info("Subscribing instruments...");
client.setSubscribedInstruments(instruments);
//start the strategy
LOGGER.info("Starting strategy");
final long strategyId = client.startStrategy(new IStrategy(){
public Instrument instrument = Instrument.EURUSD;
private IConsole console;
private IEngine engine;
public void onStart(IContext context) throws JFException {
console = context.getConsole();
engine = context.getEngine();
}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if ( instrument == this.instrument){
//console.getOut().println(" bar: " + period + " " + askBar);
}
}
public void onTick(Instrument instrument, ITick tick) throws JFException {
try {
int xx = 0;
//data[0][1] = "1";
for(IOrder o : engine.getOrders()){
if(o.getProfitLossInUSD() != 987654231){
console.getOut().println("Order: " + o.getInstrument() + " " + o.getProfitLossInPips() + " " + o.getOrderCommand());
// Copy orders to array
String userHash = "1";
String positionOpenTime = "" + o.getFillTime();
String positionId = "" + o.getId();
String positionInstrument = "" + o.getInstrument();
String positionIsbuy = "" + o.getOrderCommand().isLong();
String positionVolume = "" + o.getAmount();
String positionOpen = "" + o.getOpenPrice();
String positionSl = "" + o.getStopLossPrice();
String positionTp = "" + o.getTakeProfitPrice();
String positionComment = "" + o.getComment();
data[xx][0] = userHash;
data[xx][1] = positionOpenTime;
data[xx][2] = positionId;
data[xx][3] = positionInstrument;
data[xx][4] = positionIsbuy;
data[xx][5] = positionVolume;
data[xx][6] = positionOpen;
data[xx][7] = positionSl;
data[xx][8] = positionTp;
data[xx][9] = positionComment;
xx++;
}
}
xx=0;
/*
int i = 0;
int j = 0;
String string = "";
for(j = 0; j<10; j++){
for(i = 0; i<10; i++){
string += data[j][i] + "#";
}
string += "$$";
}
}
console.getOut().println("=====================================================================================" );
console.getOut().println(string);
*/
console.getOut().println("=====================================================================================" );
String txt ="";
txt = Arrays.deepToString(data);
txt = txt.replaceAll(",", "aa");
txt = txt.replaceAll(" ", "zz");
System.out.println(txt);
console.getOut().println("=====================================================================================" );
//=================================================================== send get == need commerciall ssl like startssl.com and serveralias and servername in virtualhost
URL hp = new URL("https://breakermind.com/index.php?line="+txt);
HttpsURLConnection hpCon = (HttpsURLConnection) hp.openConnection();
boolean isProxy = hpCon.usingProxy();
System.out.println("is using proxy " + isProxy);
InputStream obj = hpCon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
String s;
while ((s = br.readLine()) != null) {
s = s.replaceAll("zz", " ");
s = s.replaceAll("aa", ",");
System.out.println(">>>" + s);
}
//===================================================================== end
} catch (Exception e) {
console.getErr().println(e.getMessage());
e.printStackTrace(console.getErr());
// context.stop();
}
console.getOut().println("=====================================================================================" );
}
public void onMessage(IMessage message) throws JFException { }
public void onAccount(IAccount account) throws JFException { }
public void onStop() throws JFException { }
});
//now it's running
//every second check if "stop" had been typed in the console - if so - then stop the strategy
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Scanner s = new Scanner(System.in);
while(true){
while(s.hasNext()){
String str = s.next();
if(str.equalsIgnoreCase("stop")){
System.out.println("Strategy stop by console command.");
client.stopStrategy(strategyId);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}

How do I print XML sended or received in Apache XML-RPC

I'm running a simple client/server XML-RPC app to understand better the Apache XMLRPC library.
But I would like to be able to print or debug the XML output that the client sends and the XML received at server. How could I find these data??
//StartServer.java
public class StartServer {
public static void main(String args[]) throws Exception {
Server server = new Server();
}
}
//Server.java
import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServer;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.WebServer;
public class Server {
private static final int port = 3000;
public Server() throws Exception {
WebServer webServer = new WebServer(port);
XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();
PropertyHandlerMapping phm = new PropertyHandlerMapping();
phm.addHandler("reply", ReplyClass.class);
xmlRpcServer.setHandlerMapping(phm);
XmlRpcServerConfigImpl serverConfig =
(XmlRpcServerConfigImpl) xmlRpcServer.getConfig();
serverConfig.setEnabledForExtensions(true);
serverConfig.setContentLengthOptional(false);
webServer.start();
}
}
//ReplyClass.java
public class ReplyClass {
public int reply(Object params[]){
for(int i = 0; i< params.length; i++){
System.out.println( "Params :"+params[i].toString());
}
return 0;
}
public int foo(int x){
System.out.println("foo : "+ x);
return 1;
}
}
//XMLRPCtest
import java.net.URL;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcLocalTransportFactory;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
public class XMLRPCtest {
private XmlRpcClient client;
public XMLRPCtest() {
try {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://localhost:3000"));
config.setEnabledForExtensions(true);
client = new XmlRpcClient();
client.setConfig(config);
} catch (Exception exception) {
exception.printStackTrace();
}
}
public Object execute(String command, Object[] params) {
try {
Object reply = client.execute(command, params);
return reply;
} catch (XmlRpcException e) {
e.printStackTrace();
return null;
}
}
public static void main(String args[]) {
try {
XMLRPCtest client = new XMLRPCtest();
int data[] = {};
Object[] params = new Object[]{1};
Integer result = (Integer) client.execute("reply.foo", params);
System.out.println("Result: " + result);
} catch (Exception exception) {
exception.printStackTrace();
}
}
}

Change AD Password with Java

I have a good connection to AD. I can authenticate and check error messages from failed auths.
The issue I'm having comes from trying to change the password. I have an LDAPContext established at this point (yes it is an SSL connection). The issue comes from not knowing what value to use in the "username" parameter. I've tried all variations I can think of and end up getting one of three errors:
A) NO_OBJECT - I'm assuming this means it is connecting to AD properly but can't find what I'm looking for.
B) DIR_ERROR - I'm assuming this means it can get into AD properly but doesn't know wtf I want it to do after that.
C) Some type of ref error that only happens when I don't qualify the DC, so I think that's pretty much a given.
Here is the code I am using:
public void changePassword(String username, String password) {
ModificationItem[] mods = new ModificationItem[1];
String newQuotedPassword = "\"" + password + "\"";
byte[] newUnicodePassword = newQuotedPassword.getBytes();
try {
newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
try {
ldapContext.modifyAttributes(username, mods);
} catch (NamingException e) {
System.out.println("Error changing password for '" + username + "': " + e.getMessage());
e.printStackTrace();
}
}
Spring has an LDAP module that works very nicely. I'll bet it will do what you need.
Here is a working example:
Main.java:
package io.fouad.ldap;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
public class Main
{
public static void main(String[] args)
{
final String LDAP_SERVERS = "ldap://AD_SERVER:636 ldap://AD_SERVER2:636"; // separated by single spaces
final String LDAP_CONNECT_TIMEOUT_MS = "10000"; // 10 seconds
final String LDAP_READ_TIMEOUT_MS = "10000"; // 10 seconds
final String AUTHENTICATION_DOMAIN = "domain.com";
final String USERNAME = "username";
final String OLD_PASSWORD = "123";
final String NEW_PASSWORD = "456";
final String TARGET_BASE_DN = "dc=domain,dc=com";
Hashtable<String, String> ldapEnv = new Hashtable<>();
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, LDAP_SERVERS);
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put("java.naming.ldap.version", "3");
ldapEnv.put(Context.SECURITY_PRINCIPAL, USERNAME + "#" + AUTHENTICATION_DOMAIN);
ldapEnv.put(Context.SECURITY_CREDENTIALS, OLD_PASSWORD);
ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
ldapEnv.put("java.naming.ldap.factory.socket", "io.fouad.ldap.MySSLSocketFactory");
//ldapEnv.put("com.sun.jndi.ldap.connect.timeout", LDAP_CONNECT_TIMEOUT_MS);
//ldapEnv.put("com.sun.jndi.ldap.read.timeout", LDAP_READ_TIMEOUT_MS);
DirContext ldapContext = null;
try
{
ldapContext = new InitialDirContext(ldapEnv);
}
catch(AuthenticationException e)
{
System.out.println("Wrong username/password!");
e.printStackTrace();
}
catch(NamingException e)
{
e.printStackTrace();
}
if(ldapContext == null) return;
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration objects = null;
try
{
objects = ldapContext.search(TARGET_BASE_DN, String.format("(&(objectClass=user)(sAMAccountName=%s))", USERNAME), searchControls);
}
catch(NamingException e)
{
e.printStackTrace();
}
if(objects == null) return;
try
{
if(objects.hasMore())
{
SearchResult entry = (SearchResult) objects.next();
ModificationItem[] mods = new ModificationItem[2];
mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", getPasswordByteArray(OLD_PASSWORD)));
mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", getPasswordByteArray(NEW_PASSWORD)));
ldapContext.modifyAttributes(entry.getName() + "," + TARGET_BASE_DN, mods);
System.out.println("Successfully changed the password!");
}
else
{
System.out.println("User (" + USERNAME + ") was not found!");
}
}
catch(NamingException e)
{
e.printStackTrace();
}
System.out.println("DONE!");
}
private static byte[] getPasswordByteArray(String password)
{
String quotedPassword = "\"" + password + "\"";
try
{
return quotedPassword.getBytes("UTF-16LE");
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
return null;
}
}
}
MySSLSocketFactory.java: (Use it at your own risk)
package io.fouad.ldap;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class MySSLSocketFactory extends SSLSocketFactory
{
private SSLSocketFactory socketFactory;
public MySSLSocketFactory()
{
try
{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] {new X509TrustManager()
{
#Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s){}
#Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s){}
#Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
}}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
}
catch(Exception ex)
{
ex.printStackTrace(System.err);
}
}
public static SocketFactory getDefault()
{
return new MySSLSocketFactory();
}
#Override
public String[] getDefaultCipherSuites()
{
return socketFactory.getDefaultCipherSuites();
}
#Override
public String[] getSupportedCipherSuites()
{
return socketFactory.getSupportedCipherSuites();
}
#Override
public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException
{
return socketFactory.createSocket(socket, string, i, bln);
}
#Override
public Socket createSocket(String string, int i) throws IOException
{
return socketFactory.createSocket(string, i);
}
#Override
public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException
{
return socketFactory.createSocket(string, i, ia, i1);
}
#Override
public Socket createSocket(InetAddress ia, int i) throws IOException
{
return socketFactory.createSocket(ia, i);
}
#Override
public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException
{
return socketFactory.createSocket(ia, i, ia1, i1);
}
}
We have a reference for Java fro JNDI here http://ldapwiki.willeke.com/wiki/Set%20Active%20Directory%20Password%20From%20Java
You cannot change the password of a user by just modifying the property that stores it. Instead, you need to use a special LDAP operation SetPassword. I couldn't find a Java reference, but a C# one, and a Perl one.

Categories

Resources