Active directory Change password - Java - active-directory

I am trying to change the password of Active directory user and get error code 65. Please see below the source code I used.
public class ADConnection {
DirContext ldapContext;
String baseName = ",CN=Users,DC=wso2,DC=test";
public ADConnection() {
try {
Hashtable ldapEnv = new Hashtable(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldaps://192.168.18.xx:636");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrator"
+ baseName);
ldapEnv.put(Context.SECURITY_CREDENTIALS, "xxxxxx");
ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
ldapContext = new InitialDirContext(ldapEnv);
} catch (Exception e) {
System.out.println(" bind error: " + e);
e.printStackTrace();
System.exit(-1);
}
}
public void updatePassword(String username, String password) {
try {
String quotedPassword = "\"" + password + "\"";
char unicodePwd[] = quotedPassword.toCharArray();
byte pwdArray[] = new byte[unicodePwd.length * 2];
for (int i = 0; i < unicodePwd.length; i++) {
pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
}
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("UnicodePwd", pwdArray));
ldapContext.modifyAttributes("cn=" + username + baseName, mods);
//ldapContext.modifyAttributes("cn=" + username, mods);
} catch (Exception e) {
System.out.println("update password error: " + e);
System.exit(-1);
}
}
public static void main(String[] args) {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// the keystore that holds trusted root certificates
System.setProperty("javax.net.ssl.trustStore", "client-truststore.jks");
//System.setProperty("javax.net.debug", "all");
ADConnection adc = new ADConnection();
adc.updatePassword("admin", "pass#word3");
}
}
I used the code from following link.
http://blogs.msdn.com/b/alextch/archive/2012/05/15/how-to-set-active-directory-password-from-java-application.aspx
What is the wrong with this ?
Thanks

Related

Sqlite The database file is locked database is locked

I constantly write an error, the database is locked. I just can not understand why this is happening.
db_login.cs
private db_controller _dbctrl = new db_controller();
public SqliteDataReader dataread;
private string query;
//this two inputField,
public void LoginToGo()
{
login = _login.captionText.text;
pass = _pass.text.ToString();
query = "SELECT id from users where users = '" + login + "' AND pass = '" + pass + "'";
try
{
dataread = _dbctrl.ExecuteReader(query);
if(dataread.HasRows & dataread != null)
{
while (dataread.Read())
{
VerifyAdmin();
_dbctrl.Disconnect();
}
}
else
{
errortxt.text = "Неверный логин или пароль, пожалуйста повторите!";
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void VerifyAdmin() //Who are you, admin or user
{
login = _login.captionText.text;
query_access = "SELECT root from users where users = '" + login + "'";
try
{
dataread = _dbctrl.ExecuteReader(query_access);
while (dataread.Read())
{
if(dataread[0].ToString() == "0" || dataread[0].ToString() == null)
{
MainMenu();
}
else
{
AdminMenu();
}
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void AdminMenu()
{
JOIN.SetActive(false);
ADMIN.SetActive(true);
}
public void MainMenu()
{
JOIN.SetActive(false);
MAIN.SetActive(true);
}
db_controller.cs
public SqliteConnection con_db;
public SqliteCommand cmd_db;
public SqliteDataReader rdr_db;
public void connections()
{
try
{
if(Application.platform != RuntimePlatform.Android)
{
path = Application.dataPath + "/StreamingAssets/db.bytes"; // Путь для Windows
}
else
{
path = Application.persistentDataPath + "/db.bytes"; // Путь для Android
if(!File.Exists(path))
{
WWW load = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "db.bytes");
while (!load.isDone) { }
File.WriteAllBytes(path, load.bytes);
}
}
con_db = new SqliteConnection("URI=file:" + path);
con_db.Open();
if (con_db.State == ConnectionState.Open)
{
debugText.text = path.ToString() + " - is connected";
Debug.Log(path.ToString());
}
}
catch (Exception ex)
{
debugText.text = ex.ToString();
}
}
//Тут я создаю метод отключения
public void Disconnect()
{
con_db.Close();
}
public SqliteDataReader ExecuteReader(string query)
{
connections();
try
{
cmd_db = new SqliteCommand(query, con_db);
rdr_db = cmd_db.ExecuteReader();
return rdr_db;
}
catch (Exception ex) { debugText.text = ex.ToString(); return null; }
}
//Тут я записываю данные. Заодно решил проверить закрыто ли соединение.
public void SetDB()
{
if (con_db.State == ConnectionState.Open)
{
Debug.Log("open");
}
else
{
Debug.Log("close!");
}
//The connection is closed. But I can not complete the request cmd_db.ExecuteNonQuery();
connections();
try
{
brand = AutoName.captionText.text;
model = AutoModel.captionText.text;
years = OldAuto.captionText.text;
number = GosNumber.text.ToString();
nusers = UserName.text.ToString();
dbirthday = DBirthday.captionText.text;
mbirthday = MBirthday.captionText.text;
ybirthday = YBirthday.captionText.text;
mobile = Mobile.text.ToString();
cmd_db = new SqliteCommand("INSERT INTO clients(brand,model,years,number,nusers,dbirthday,mbirthday,ybirthday,mobile,groupmodel) values('" + brand + "', '" + model + "','" + years + "','" + number + "','" + nusers + "','" + dbirthday + "','" + mbirthday + "','" + ybirthday + "','" + mobile + "','" +groupmodel+ "')" , con_db);
cmd_db.ExecuteNonQuery(); //Swears, says that the base is locked. And why? I just read the data and the connection was closed.
}
catch (Exception ex) { debugText.text = ex.ToString(); }
Disconnect();
}
the documentation says:
This error code occurs when you try to do two incompatible things with the database at the same time from the same connection to the database.
But the connection with the base is closed.
Maybe I'm missing something, or not doing the right thing. I ask for help to clarify this issue.

Android Wear File does not appear

I created a file to read the sensors of my Android Wear. I can tell it is working because my storage is being filled up, but I can't see the folder of the readings. Can you help me out finding out what is wrong with the code?
public class Logging extends Activity implements SensorEventListener {
DecimalFormat df =new DecimalFormat("##.##");
Boolean flag=true;
FileOutputStream outputStream;
TextView displayReading1;
TextView displayReading2;
TextView displayReading3;
TextView displayReading4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File Project=getDir("Project", Context.MODE_PRIVATE);
if(!Project.exists())
Project.mkdir();
File fileWithinProject=new File (Project+"/","Project.txt");
if(!fileWithinProject.exists())
try {
fileWithinProject.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// final File file=new File (dirPath,"Project.txt");
/* File file = new File(dirPath, "Project.txt");
try {
if (!file.exists())
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}*/
setContentView(R.layout.activity_logging);
Button start=(Button)findViewById(R.id.StartButton);
Button stop=(Button)findViewById(R.id.StopButton);
//BUTTON START
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=true;
Toast.makeText(getApplicationContext(),"Start Recording Readings",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), ("File in: "+ Project), Toast.LENGTH_LONG).show();
}
}); {
}
//BUTTON STOP
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=false;
Toast.makeText(getApplicationContext(),"Done recording readings",Toast.LENGTH_SHORT).show();
}
});{
}
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor accSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor rotSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
Sensor gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
Sensor gyroSensor = sensorManager.getDefaultSensor((Sensor.TYPE_GYROSCOPE));
sensorManager.registerListener(this, accSensor, 100000000);
sensorManager.registerListener(this, rotSensor, 100000000);
sensorManager.registerListener(this, gravitySensor, 100000000);
sensorManager.registerListener(this, gyroSensor, 100000000);
displayReading1 = (TextView) findViewById(R.id.acc_sensor);
displayReading2 = (TextView) findViewById(R.id.rotational_sensor);
displayReading3 = (TextView) findViewById(R.id.gravity_sensor);
displayReading4 = (TextView) findViewById(R.id.gyro_sensor);
displayReading1.setTextSize(14f);
displayReading2.setTextSize(14f);
displayReading3.setTextSize(14f);
displayReading4.setTextSize(14f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_logging, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSensorChanged (SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
displayReading1.setText("Accelerometer (m/s2): " +"\nX"+" " +df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X11=event.values[0];
float X12=event.values[1];
float X13=event.values[2];
if( flag) {
try {
// Toast.makeText(getApplicationContext(), ("current location newFile.getAbsolutePath()), Toast.LENGTH_LONG).show();
outputStream = openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(((df.format(X11) + df.format(X12) + df.format(X13)
)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
displayReading2.setText("Rotational Vector: " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X21=event.values[0];
float X22=event.values[1];
float X23=event.values[2];
if( flag) {
try {
outputStream=openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(("Rotational Vector : " +"\nX"+" " +df.format(X21) + "\nY"+" " + df.format(X22) + "\nZ"+" " + df.format(X23)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}}
if (event.sensor.getType() == Sensor.TYPE_GRAVITY)
displayReading3.setText("Gravity (m/s2): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE)
displayReading4.setText("Gyroscope (rad/s): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X31=event.values[0];
float X32=event.values[1];
float X33=event.values[2];
if( flag) {
try {
outputStream = openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(("Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33)
).getBytes());
//Toast.makeText(getApplicationContext(), "Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (!flag){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}

Customizing DBTrigger message in adf

Hi I am trying to customize DBTrigger message in bean Here is code for it, it is displaying my customized message but as well it is displaying DBTrigger message below to my message, Kindly help me to get out of this.
public void saveLataActionListenerNew(ActionEvent actionEvent) {
System.out.println("----on click saved ");
try {
OperationBinding operationBinding = (OperationBinding)getBindings().getOperationBinding("Commit");
Object result = operationBinding.execute();
System.out.println("Errors : " + operationBinding.getErrors());
if (operationBinding.getErrors() != null) {
Iterator it = operationBinding.getErrors().iterator();
System.out.println("error = " + it);
System.out.println("size of Errors - " + operationBinding.getErrors().size());
while (it.hasNext()) {
DMLException error = (DMLException)it.next();
String errorCause = "" + error.getCause();
System.out.println("error.getCause() : " + errorCause);
if (errorCause != null && errorCause.contains("ORA-00001: unique constraint")) {
uniqueConstraint = "Lata is Exists for given State";
showMessage(uniqueConstraint, FacesMessage.SEVERITY_ERROR);
return;
}
}
}
uniqueConstraint = "Record is saved successfully";
showMessage(uniqueConstraint, FacesMessage.SEVERITY_INFO);
System.out.println("---record saved successfully");
// addPlaceCodePfl.setRendered(false);
// addPlaceCodePgl.clearInitialState();
// addPlaceCodePfl.
} catch (Exception e) {
uniqueConstraint = e.getMessage();
showMessage(uniqueConstraint, FacesMessage.SEVERITY_ERROR);
e.printStackTrace();
}

How to get alert when a message in delivered in window form application?

private void buttonSend_Click(object sender, EventArgs e)
{
InsertChatDetails();
//textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "" + System.Environment.GetEnvironmentVariable("Computername") + Environment.NewLine;
textBoxChat.Text += textBoxMessage.Text + Environment.NewLine;
textBoxMessage.Text = "";
}
public void InsertChatDetails() //Inserting Values
{
try
{
CommonCS CommonSample1 = new CommonCS();
BusinessCS BFSample1 = new BusinessCS();
CommonSample1.Id = "1";
CommonSample1.FromUser = textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "-->" + Program.UserName + Environment.NewLine;
//CommonSample1.FromUser = textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "" + System.Environment.GetEnvironmentVariable("Computername") + Environment.NewLine;
CommonSample1.ToUser = "";
CommonSample1.MessageText = textBoxMessage.Text;
CommonSample1.SentOn = DateTime.Now;
CommonSample1.StatusReport = 0;
BFSample1.InsertChatDetails(CommonSample1);
}
catch (Exception)
{
}
}
Not sure from your code what you are trying to do, but if its synchronous you can trace it after SendMessageToWinMachine() ,else you can use CallBack Method for asynchronus call.

loading image to jsp (struts2) from database

I have problem with loading image from database to jsp view. It looks like action are execute but stop in middle.
I log when execute() method start and when its end. In log file i can see start this method but there are no end.
I have action:
public class ShowImageAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Log LOG = LogFactory.getLog(ShowImageAction.class);
private int id;
public String execute() {
LOG.info("Enter execute()");
MessageBean messageBean = (MessageBean) sessionParameters
.get(SessionParameters.BANNER_EDIT);
IFiles filesEJB = EJBLocator.getFiles();
if (messageBean != null) {
id = messageBean.getBannerId();
}
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
bytes = FileUtils.readFileToByteArray(file.getImage());
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
LOG.info("Exit execute()");
return NONE;
}
jsp:
<div class="OneFilteringRow">
Podgląd<br />
<img src="/ebok-bm/ShowImageAction" alt="Podgląd banera" />
</div>
struts.xml
<action name="ShowImageAction"
class="pl.bm.action.content.ShowImageAction">
</action>
Problem was in:
FileBean file = filesEJB.file(id);
I get bytes from database and try to save it to tmpFile. Now I get bytes and writes them to a temporary file and immediately transmit it to the action and everything is ok.
Now I have:
FileBean file = filesEJB.file(id);
LOG.info("Id = " + id);
if (file != null) {
byte[] bytes = null;
try {
LOG.info("File: name = " + file.getName() + ". type = "
+ file.getType());
if (file.getImage() != null) {
**bytes = file.getImage();**
HttpServletResponse response = ServletActionContext
.getResponse();
response.setContentType(file.getType());
OutputStream out = response.getOutputStream();
out.write(bytes);
out.close();
} else {
LOG.info("execute(): Nie udało się pobrać pliku z bazy danych!");
}
} catch (IOException e) {
LOG.error(e);
}
}
Switch to your own result implements Result class and write output here.Other in struts.xmlaction result type specified own with approx mate parameters.
refer:generate own image as action result

Resources