ExtLibUtil.getCurrentSessionAsSigner open mail.box - xpages

Opening mail.box with ExtLibUtil.getCurrentSessionAsSigner does not work for mail.box.
All elements are signed with the same id.
I'd like to copy mails, created by Anonymous, to mail.box. Any ideas, workarounds?
package de.egvpb.surveys;
import java.io.Serializable;
import lotus.domino.Database;
import lotus.domino.Session;
import com.ibm.xsp.extlib.util.ExtLibUtil;
public class SessionAsSignerBean implements Serializable{
private static final long serialVersionUID = 1L;
private Database mailBoxDb ;
public SessionAsSignerBean(){
this.mailBoxDb = this.getMailBoxDbAsSigner() ;
}
private Database getMailBoxDbAsSigner() {
Session s = ExtLibUtil.getCurrentSessionAsSigner() ;
Database result = null ;
Database currentDb = null ;
String server = "" ;
String filepath = "" ;
try {
// Anonymous has reader access for currentDb; database is opend
currentDb = s.getCurrentDatabase() ;
if( currentDb.isOpen() ) {
System.out.println( "getMailBoxDbAsSigner, currentDB is open: " + currentDb.getFilePath() + " on " + currentDb.getServer() );
} else {
System.out.println( "getMailBoxDbAsSigner, currentDB is NOT open");
}
server = currentDb.getServer() ;
// Anonymous has no Access for names.nsf; database is opend
filepath = "names.nsf" ;
result = s.getDatabase(server, filepath) ;
if( result.isOpen() == false ) {
System.out.println( "getMailBoxDbAsSigner, failed to open database " + filepath + " on " + server );
} else {
System.out.println( "getMailBoxDbAsSigner, database opend " + filepath + " on " + server );
}
// Anonymous has no Access for mail.box; database is NOT opend
filepath = "mail.box" ;
result = s.getDatabase(server, filepath) ;
if( result.isOpen() == false ) {
System.out.println( "getMailBoxDbAsSigner, failed to open database " + filepath + " on " + server );
} else {
System.out.println( "getMailBoxDbAsSigner, opend database " + filepath + " on " + server );
}
} catch (Exception e) {
e.printStackTrace() ;
}
return result ;
}
// ====
public Database getMailBoxDb() {
return mailBoxDb;
}
public void setMailBoxDb(Database mailBoxDb) {
this.mailBoxDb = mailBoxDb;
}
}

I can't see anything wrong in your code, although for best practice I would recommend setting server to s.getServerName(), "" has different meanings for XPiNC.
Does your signer have access to mail.box? This should work and I've used such code before, amongst other places in XPages OpenLog Logger. If there are multiple mail.box databases set up, Domino will automatically still get the relevant one.

Related

Execute an API call with authentication from VBA

I am not good at VBA programming (quite the basics), so I would like some of your input in the following matter as I couldn't find the correct answer for my concern. I would like to execute an API call with authentication using VBA. I have the below code but in Java (for test purposes), but my aim is to receive the responses in Excel. The idea is to login and fetch the records requested, and return it in form of XML or anything that would be readable ultimately in a wide Excel user form.
How to go about this? I do not need necessarily a-ready-code, any heads-up start would be appreciated.
package tests;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import com.tgmtSystems.core.util.XML_Utils;
public class TestQueryService
{
static String url = ".....";
static String ACCOUNT = "......";
static String USERNAME = ".....";
static String PASSWORD = "***********";
static String SERVICE = "queryservice.do";
static String QUERY_SEARCH_INSTANCE_ID = "14289081";
public static class ListResponse
{
String[ ] itemInstanceIds;
String projectInstanceId;
String templateInstanceId;
}
public static void main( String[ ] args )
throws Exception
{
String credentials = TestQueryService.login( );
ListResponse listResponse = listItems( credentials );
getItem( credentials, listResponse, listResponse.itemInstanceIds[ 0 ] );
//This will return the 10 first records identified by their Ids ( itemInstanceId )
getItems( credentials, listResponse, "11324721,11324744,11324745,11324746,11324748,11324751,11324758,11324829,11324830,11324836" );
//This will return All Ids, if there are more than 50, there will be an error, you can only fetch 50 at a time.
//getItems( credentials, listResponse, StringUtils.join( listResponse.itemInstanceIds, "," ) );
}
public static String login( )
throws Exception
{
String xmlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><REQUEST><action>login</action><accountName>" + ACCOUNT + "</accountName><username>" + USERNAME + "</username><password>" + PASSWORD + "</password></REQUEST>";
Document loginResponseDoc = sendRequest( xmlRequest );
String credentials = XML_Utils.getNodeValue( "credentials", loginResponseDoc );
return credentials;
}
public static ListResponse listItems( String credentials )
throws Exception
{
String xmlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><REQUEST><action>listItems</action><credentials>" + credentials + "</credentials><querySearchInstanceId>" + QUERY_SEARCH_INSTANCE_ID + "</querySearchInstanceId></REQUEST>";
Document responseDoc = sendRequest( xmlRequest );
ListResponse listResponse = new ListResponse( );
listResponse.itemInstanceIds = StringUtils.split( XML_Utils.getNodeValue( "itemInstanceIds", responseDoc ), "," );
listResponse.projectInstanceId = XML_Utils.getNodeValue( "projectInstanceId", responseDoc );
listResponse.templateInstanceId = XML_Utils.getNodeValue( "templateInstanceId", responseDoc );
return listResponse;
}
public static Document getItem( String credentials, ListResponse listResponse, String itemInstanceId )
throws Exception
{
String xmlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><REQUEST><action>getItem</action><credentials>" + credentials + "</credentials><templateInstanceId>" + listResponse.templateInstanceId + "</templateInstanceId><projectInstanceId>" + listResponse.projectInstanceId + "</projectInstanceId><itemInstanceId>" + itemInstanceId + "</itemInstanceId></REQUEST>";
return sendRequest( xmlRequest );
}
public static Document getItems( String credentials, ListResponse listResponse, String itemInstancesId )
throws Exception
{
String xmlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><REQUEST><action>getItems</action><credentials>" + credentials + "</credentials><templateInstanceId>" + listResponse.templateInstanceId + "</templateInstanceId><projectInstanceId>" + listResponse.projectInstanceId + "</projectInstanceId><itemInstancesId>" + itemInstancesId + "</itemInstancesId></REQUEST>";
return sendRequest( xmlRequest );
}
public static Document sendRequest( String xmlRequest )
throws Exception
{
String type = "text/xml";
System.out.println( "REQUEST\n" + xmlRequest );
URL u = new URL( url + SERVICE );
HttpURLConnection conn = (HttpURLConnection) u.openConnection( );
conn.setDoOutput( true );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", type );
conn.setRequestProperty( "Content-Length", String.valueOf( xmlRequest.length( ) ) );
OutputStream os = conn.getOutputStream( );
os.write( xmlRequest.getBytes( ) );
StringBuilder stringBuilder = new StringBuilder( );
try
{
InputStream inputStream = conn.getInputStream( );
if ( inputStream != null )
{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( inputStream ) );
char[ ] charBuffer = new char[ 128 ];
int bytesRead = - 1;
while ( ( bytesRead = bufferedReader.read( charBuffer ) ) > 0 )
{
stringBuilder.append( charBuffer, 0, bytesRead );
}
bufferedReader.close( );
}
else
{
stringBuilder.append( "" );
}
}
catch ( Exception ex )
{
throw ex;
}
String responseXML = stringBuilder.toString( );
responseXML = responseXML.trim( );
System.out.println( "RESPONSE\n" + responseXML );
conn.disconnect( );
return XML_Utils.getDocument( responseXML );
}
}

Cassandra exception while live schema change

For our project we need live schema changes. For these purposes we created test. It adds and deletes tables in cassandra. I'm using 10 threads with datastax driver. But I am getting this Exception in some threads.
Exception in thread "Thread-7"
com.datastax.driver.core.exceptions.NoHostAvailableException: All
host(s) tried for query failed (tried: localhost/127.0.0.1
(com.datastax.driver.core.exceptions.DriverException: Timeout during
read))
Cassandra is alive. I can still execute queries throw cqlsh.
Threads does'n fail. Thread can add tables, then suddenly log this exception and again add tables. Exception can appear several times in one thread.
Each thread has its own session.
Looking to the cassandra.yaml:
concurrent_writes and reads = 32
increasing of MAX_HEAP_SIZE and HEAP_NEWSIZE in cassandra-env.sh doesn't help me.
Cassandra version 2.0.7
Could someone suggest how to deal with it?
public class AddTableThread extends Thread {
private Cluster cluster;
private Session session;
private final String KEYSPACE = "cas";
private final String HOST = "localhost";
private final int PORT = 9042;
private boolean isRunning = true;
// counter for the added tables
private int i = 0;
// Number of the tables that thread has to add
private int fin = -2;
public AddTableThread() {
connect();
}
public AddTableThread setTablesCount(int f) {
this.fin = f;
System.out.println(this.getName() + " : must add " + fin + " tables");
return this;
}
#Override
public void run() {
System.out.println(this.getName() + " : starting thread \n");
while (isRunning) {
String name = createName();
try {
session.execute(createTableQuery(name));
System.out.println(this.getName() + " : table is created "
+ name);
i++;
} catch (com.datastax.driver.core.exceptions.NoHostAvailableException e) {
System.out
.println("\n\n" + this.getName() + "!!!!FAILED!!!!!!");
System.out.println(this.getName() + " : added " + i + " tables");
System.out.println(this.getName() + " : table " + name
+ " wasn't added");
}
try {
Thread.sleep((new Random().nextInt(5000)));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (i == fin) {
isRunning = false;
}
}
close();
log();
}
// creates query that creates table in keyspace with name tableName
private String createTableQuery(String tableName) {
return "CREATE TABLE cas." + tableName
+ "(id timeuuid PRIMARY KEY, text varchar, value int);";
}
public void finish() {
isRunning = false;
}
private void log() {
System.out.println("\n" + this.getName() + " : finish");
System.out.println(this.getName() + " : added " + i + " tables");
System.out.println("_____________________\n");
}
// generates unique table name
private String createName() {
return "cf_" + UUIDGen.getTimeUUID().toString().replace("-", "_");
}
private void connect() {
SocketOptions so = new SocketOptions();
so.setConnectTimeoutMillis(20000);
so.setReadTimeoutMillis(20000);
cluster = Cluster.builder().withSocketOptions(so).addContactPoint(HOST)
.withPort(PORT).build();
session = cluster.connect(KEYSPACE);
}
private void close() {
session.close();
cluster.close();
}
}
Creating takes time. So try to increment:
read_request_timeout_in_ms: 5000
and
request_timeout_in_ms: 10000
And try to uncomment
rpc_max_threads: 2048
Experiment with these parameters.

Impersonation with different machine's account (remote user)

Is it possible to logon to different machine's account with impersonation? I have to access the folder and read its contents temporarily. After reading process program will revert back to old account which has no access to that folder. I am able to impersonate with different account under same domain and it works. However, I have to update my code for accessing to different machine. I want to modify this code:
public WindowsImpersonationContext ImpersonateUser(string sUsername, string sDomain, string sPassword)
{
// initialize tokens
IntPtr pExistingTokenHandle = new IntPtr(0);
IntPtr pDuplicateTokenHandle = new IntPtr(0);
pExistingTokenHandle = IntPtr.Zero;
pDuplicateTokenHandle = IntPtr.Zero;
// if domain name was blank, assume local machine
if (sDomain == "")
sDomain = System.Environment.MachineName;
try
{
string sResult = null;
const int LOGON32_PROVIDER_DEFAULT = 0;
// create token
const int LOGON32_LOGON_INTERACTIVE = 2;
//const int SecurityImpersonation = 2;
// get handle to token
bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
// did impersonation fail?
if (false == bImpersonated)
{
int nErrorCode = Marshal.GetLastWin32Error();
sResult = "Error while logging. Error Code: " + nErrorCode + "\r\n";
// show the reason why LogonUser failed
MessageBox.Show(this, sResult, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
// Get identity before impersonation
sResult += "Before impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
bool bRetVal = DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle);
// did DuplicateToken fail?
if (false == bRetVal)
{
int nErrorCode = Marshal.GetLastWin32Error();
CloseHandle(pExistingTokenHandle); // close existing handle
sResult += "DuplicateToken() failed with error code: " + nErrorCode + "\r\n";
// show the reason why DuplicateToken failed
MessageBox.Show(this, sResult, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
else
{
// create new identity using new primary token
WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
// check the identity after impersonation
sResult += "After impersonation: " + WindowsIdentity.GetCurrent().Name + "\r\n";
MessageBox.Show(this, sResult, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
return impersonatedUser;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
// close handle(s)
if (pExistingTokenHandle != IntPtr.Zero)
CloseHandle(pExistingTokenHandle);
if (pDuplicateTokenHandle != IntPtr.Zero)
CloseHandle(pDuplicateTokenHandle);
}
}

how to append log details in log file in MFC (VC++)?

i have created one method to write to Log file but each time it overrite the log details , i want to create a new entry everytime for logging details.My log method is as below :
void CNDSConnectDlg::WriteLogData()
{
CString strUserName = "";
m_editUserName.GetWindowText(strUserName);
FILE * pFile = NULL;
int iErr = 0;
iErr = fopen_s(&pFile,"NDSLog.txt","w");
if (iErr == 0)
{
CString strConnectionStatus = "";
CString strServerAddress = "";
CString strDateTime = "";
SYSTEMTIME systime;
GetLocalTime(&systime);
if(m_bConnectionStaus == true)
{
strConnectionStatus = "Success";
}
else
{
strConnectionStatus = "Failure";
}
strUserName.Format("%s",strUserName);
strConnectionStatus.Format("%s",strConnectionStatus);
strServerAddress.Format("%s",m_strIPAddress);
strDateTime.Format("%i:%i:%i\\%02i-%02i-%02i",
systime.wHour,
systime.wMinute,
systime.wSecond,
systime.wYear,
systime.wMonth,
systime.wDay);
fputs("UserName = " + strUserName + " connected to "
"ServerAddress = " +strServerAddress + " at "
"Date/Time = " + strDateTime + " "
"ConnectionStatus = " +strConnectionStatus + " ",pFile);
fclose (pFile);
}
else
{
MessageBox("Error in writing to Log","NDS",MB_ICONERROR | MB_OK);
}
}
Any help is highly appreciated .
Thanks in Advance.
Open file with "a" (append) instead of "w".
Open file with a+ instead of a.

SharePoint 2007 Object Model: How can I make a new site collection, move the original main site to be a subsite of the new site collection?

Here's my current setup:
one site collection on a SharePoint 2007 (MOSS Enterprise) box (32 GB total in size)
one main site with many subsites (mostly created from the team site template, if that matters) that is part of the one site collection on the box
What I'm trying to do*:
**If there is a better order, or method for the following, I'm open to changing it*
Create a new site collection, with a main default site, on same SP instance (this is done, easy to do in SP Object Model)
Move rootweb (a) to be a subsite in the new location, under the main site
Current structure:
rootweb (a)
\
many sub sites (sub a)
What new structure should look like:
newrootweb(b)
\
oldrootweb (a)
\
old many sub sites (sub a)
Here's my code for step #2:
Notes:
* SPImport in the object model under SharePoint.Administration, is what is being used here
* This code currently errors out with "Object reference not an instance of an object", when it fires the error event handler
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Deployment;
public static bool FullImport(string baseFilename, bool CommandLineVerbose, bool bfileCompression, string fileLocation, bool HaltOnNonfatalError,
bool HaltOnWarning, bool IgnoreWebParts, string LogFilePath, string destinationUrl)
{
#region my try at import
string message = string.Empty;
bool bSuccess = false;
try
{
SPImportSettings settings = new SPImportSettings();
settings.BaseFileName = baseFilename;
settings.CommandLineVerbose = CommandLineVerbose;
settings.FileCompression = bfileCompression;
settings.FileLocation = fileLocation;
settings.HaltOnNonfatalError = HaltOnNonfatalError;
settings.HaltOnWarning = HaltOnWarning;
settings.IgnoreWebParts = IgnoreWebParts;
settings.IncludeSecurity = SPIncludeSecurity.All;
settings.LogFilePath = fileLocation;
settings.WebUrl = destinationUrl;
settings.SuppressAfterEvents = true;
settings.UpdateVersions = SPUpdateVersions.Append;
settings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ImportAll;
SPImport import = new SPImport(settings);
import.Started += delegate(System.Object o, SPDeploymentEventArgs e)
{
//started
message = "Current Status: " + e.Status.ToString() + " " + e.ObjectsProcessed.ToString() + " of " + e.ObjectsTotal + " objects processed thus far.";
message = e.Status.ToString();
};
import.Completed += delegate(System.Object o, SPDeploymentEventArgs e)
{
//done
message = "Current Status: " + e.Status.ToString() + " " + e.ObjectsProcessed.ToString() + " of " + e.ObjectsTotal + " objects processed.";
};
import.Error += delegate(System.Object o, SPDeploymentErrorEventArgs e)
{
//broken
message = "Error Message: " + e.ErrorMessage.ToString() + " Error Type: " + e.ErrorType + " Error Recommendation: " + e.Recommendation
+ " Deployment Object: " + e.DeploymentObject.ToString();
System.Console.WriteLine("Error");
};
import.ProgressUpdated += delegate(System.Object o, SPDeploymentEventArgs e)
{
//something happened
message = "Current Status: " + e.Status.ToString() + " " + e.ObjectsProcessed.ToString() + " of " + e.ObjectsTotal + " objects processed thus far.";
};
import.Run();
bSuccess = true;
}
catch (Exception ex)
{
bSuccess = false;
message = string.Format("Error: The site collection '{0}' could not be imported. The message was '{1}'. And the stacktrace was '{2}'", destinationUrl, ex.Message, ex.StackTrace);
}
#endregion
return bSuccess;
}
Here is the code calling the above method:
[TestMethod]
public void MOSS07_ObjectModel_ImportSiteCollection()
{
bool bSuccess = ObjectModelManager.MOSS07.Deployment.SiteCollection.FullImport("SiteCollBAckup.cmp", true, true, #"C:\SPBACKUP\SPExports", false, false, false, #"C:\SPBACKUP\SPExports", "http://spinstancename/TestImport");
Assert.IsTrue(bSuccess);
}
Instead of trying to code this up, have you tried to use the SharePoint Content Deployment Wizard from Codeplex?
Export your current hierarchy, and import it to the new place using this tool.
Regards,
M

Resources