snmp4j map table to pojo - java

I have a pojo like this :
public class IpAddress {
private String index ;
private String ip ;
private String netmask ;
// Getter & Setter ....
}
now i wrote a code with snmp4j for fetch table and map result to list of this pojo :
public class MainClass {
private static final Address address = GenericAddress.parse("udp://10.10.10.2/161");
public static void main(String[] args) throws Exception {
CommunityTarget<Address> target = new CommunityTarget<>();
target.setCommunity(new OctetString("private"));
target.setAddress(address);
target.setRetries(5);
target.setTimeout(15000);
target.setVersion(SnmpConstants.version2c);
List<IpAddress> ipAddressList = doWalkTable(".1.3.6.1.2.1.4.20", target);
System.out.println(ipAddressList);
}
public static List<IpAddress> doWalkTable(String tableOid, Target<Address> target) throws IOException {
List<IpAddress> ipAddressList = new ArrayList<>();
TransportMapping<? extends Address> transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
transport.listen();
TableUtils tableUtils = new TableUtils(snmp, new DefaultPDUFactory());
List<TableEvent> events = tableUtils.getTable(target, new OID[]{new OID(tableOid)}, null, null);
if (events == null || events.size() == 0) {
System.out.println("Error: Unable to read table...");
return ipAddressList;
}
for (TableEvent event : events) {
if (event == null) {
continue;
}
if (event.isError()) {
System.out.println("Error: table OID [" + tableOid + "] " + event.getErrorMessage());
continue;
}
VariableBinding[] varBindings = event.getColumns();
if (varBindings == null || varBindings.length == 0) {
continue;
}
for (VariableBinding varBinding : varBindings) {
if (varBinding == null) {
continue;
}
// -> How can fill ipAddressList ????
}
System.out.println("------------------------------------------------------");
}
snmp.close();
return ipAddressList;
}
}
this is result of snmptable :
# snmptable -v 2c -c public 10.10.10.2 IP-MIB::ipAddrTable
ipAdEntAddr ipAdEntIfIndex ipAdEntNetMask ipAdEntBcastAddr ipAdEntReasmMaxSize
10.10.10.2 2 255.255.255.0 1 18024
115.54.20.12 4 255.255.255.0 1 18024
My problem is :
1) there is any solution to find out OID is table or tree ?
2) I can not understand how can detect row and columns from TableEvent .
result does not have any identifier for calculate number of rows or number of columns .

Related

Neo4j browser freezes the whole system

I'm using an embedded Neo4j instance in my Spring Boot project (I'm using Spring JPA and Neo4j separately and I'm not using Spring-Boot-Neo4j stuff) and I want to visualise the graph I build using the Neo4j browser that I downloaded from here with the addition of a custom init.coffee that allows it to display images inside the nodes
This is the code I use in order to build my graph. The "buildGraph" function is executed when a request is being received by one of my RestControllers
(the reason I include all of my business logic implementation is because it may help detecting relationships/nodes etc being created/handled in a wrong way)
#Component
public class GraphBuilder
{
private String dbPath;
private int numberOFConnectionsForKeyIndividuals;
private String neo4jBoltAddress;
#Autowired
PersonService personService;
private final GraphDatabaseService graphDb;
public GraphBuilder(#Value("${dbPath}") String dbPath,
#Value("${neo4jBoltAddress}") String neo4jBoltAddress,
#Value("${numberOFConnectionsForKeyIndividuals}") int numberOFConnectionsForKeyIndividuals)
{
GraphDatabaseSettings.BoltConnector bolt = GraphDatabaseSettings.boltConnector( "0" );
this.dbPath = dbPath;
this.neo4jBoltAddress = neo4jBoltAddress;
this.numberOFConnectionsForKeyIndividuals = numberOFConnectionsForKeyIndividuals;
graphDb = new GraphDatabaseFactory()
.newEmbeddedDatabaseBuilder( new File(dbPath) )
.setConfig( bolt.type, "BOLT" )
.setConfig( bolt.enabled, "true" )
.setConfig( bolt.address, neo4jBoltAddress )
.newGraphDatabase();
registerShutdownHook( graphDb );
}
public void buildGraph()
{
List<Long> AsIDs = new ArrayList<>();
Map<Long,Long> personIdToNodeMap = new HashMap<>();
Map<String,List<Long>> nameToId = new HashMap<>();
Map<Long,List<Association>> associationsMap = new HashMap<>();
try ( Transaction tx = graphDb.beginTx() )
{
Schema schema = graphDb.schema();
for(Person person : personService.findAllPersons())
{
Node personNode = graphDb.createNode(new Label() {
#Override
public String name() {
return "Person";
}
});
//mapping persons to their respective nodes
personIdToNodeMap.put(person.getPersonId(),personNode.getId());
//mapping names to the ids of the persons
if(nameToId.get(person.getName()) == null)
{
nameToId.put(person.getName(), new ArrayList<>());
}
nameToId.get(person.getName()).add(person.getPersonId());
personNode.setProperty("Name", person.getName());
for(int a = 0 ; a < person.getAliases().size() ; a++)
{
personNode.setProperty("Alias " + a+1, person.getAliases().get(a).getAlias());
}
personNode.setProperty("Additional Name Information", person.getAdditionalNameInformation() != null ? person.getAdditionalNameInformation() : "");
personNode.setProperty("Id", person.getPersonId());
personNode.setProperty("Date of Birth", person.getDob() != null ? person.getDob() : "");
for(int f = 0 ; f < person.getFacebook().size() ; f++)
{
personNode.setProperty("Facebook " + f+1, person.getFacebook().get(f).getFacebookPage() + " (" + person.getFacebook().get(f).getAdditionalFacebookPageInformation() + ")");
}
personNode.setProperty("Additional Information", person.getInfo() != null ? person.getInfo() : "");
personNode.setProperty("image_url","http://localhost:8888/files/"+person.getPictureFilePath());
personNode.setProperty("Node Type", "Person");
if(person.getAssociations().size() > numberOFConnectionsForKeyIndividuals)
{
personNode.setProperty("Key_Individual","Yes");
}
for(A A : person.getAs())
{
Node ANode = graphDb.createNode(new Label() {
#Override
public String name() {
return "A";
}
});
ANode.setProperty("A", A.getA());
//TODO elaborate more on the A with additional properties
ANode.setProperty("Node Type", "A");
personNode.createRelationshipTo( ANode, EdgeTypes.HAS_DONE );
ANode.setProperty("image_url","http://localhost:8888/images/A.png");
AsIDs.add(ANode.getId());
}
for(Association association : person.getAssociations())
{
if(associationsMap.get(person.getPersonId()) == null)
{
associationsMap.put(person.getPersonId(), new ArrayList<>());
}
associationsMap.get(person.getPersonId()).add(association);
}
}
//Validating and building the association edges
//iterating through the nodes
for(Long personFromId : associationsMap.keySet())
{
//iterating through the associations registered for the node
for(Association associationFrom : associationsMap.get(personFromId))
{
String personNameFrom = associationFrom.getPersonNameFrom();
String personNameTo = associationFrom.getPersonNameTo();
//iterating through the persons whose name matches the other end of the association
if(nameToId.get(personNameTo) != null)
{
for(Long personToId : nameToId.get(personNameTo))
{
//iterating through the associations of the person at the other end of the association
if(associationsMap.get(personToId) != null)
{
List<Association> associationsToRemove = new ArrayList<>();
for(Association associationTo : associationsMap.get(personToId))
{
if(associationTo.getPersonNameTo().equals(personNameFrom) && nameToId.get(personNameFrom).contains(personFromId))
{
if(nameToId.get(personNameFrom).size() == 1)
{
Relationship relationship = graphDb.getNodeById(personIdToNodeMap.get(personFromId))
.createRelationshipTo( graphDb.getNodeById(personIdToNodeMap.get(personToId)), EdgeTypes.ASSOCIATES_WITH );
if(associationFrom.getType() != null)
{
relationship.setProperty("Association Type",associationFrom.getType());
}
associationsToRemove.add(associationTo);
}
else
{
boolean alreadyConnected = false;
for(Relationship rel : graphDb.getNodeById(personIdToNodeMap.get(personFromId)).getRelationships())
{
if( ( rel.getOtherNode(graphDb.getNodeById(personIdToNodeMap.get(personFromId))).
equals(graphDb.getNodeById(personIdToNodeMap.get(personToId))) ) )
{
alreadyConnected = true;
break;
}
}
if(!alreadyConnected)
{
Relationship relationship = graphDb.getNodeById(personIdToNodeMap.get(personFromId))
.createRelationshipTo( graphDb.getNodeById(personIdToNodeMap.get(personToId)), EdgeTypes.PROBABLY_ASSOCIATES_WITH );
if(associationFrom.getType() != null)
{
relationship.setProperty("Association Type",associationFrom.getType());
}
}
// associationsToRemove.add(associationTo);
}
}
}
associationsMap.get(personToId).removeAll(associationsToRemove);
}
}
}
}
}
tx.success();
}
Map<Long,List<String>> AToNamesMap = new HashMap<>();
//detecting names referred in the A's description
try(Transaction txAs = graphDb.beginTx() )
{
for(Long id : AsIDs)
{
Node ANode = graphDb.getNodeById(id);
String A = (String) ANode.getProperty("A");
for(String name : nameToId.keySet())
{
if(A.contains(name)) {
if(AToNamesMap.get(id) == null)
{
AToNamesMap.put(id,new ArrayList<>());
}
AToNamesMap.get(id).add(name);
}
}
}
List<Long> groupedAs = new ArrayList<>();
for(Long id : AsIDs)
{
if(AToNamesMap.get(id)!= null && AToNamesMap.get(id).size() > 1)
{
for(Long otherAID : AToNamesMap.keySet())
{
if(id != otherAID && !groupedAs.contains(otherAID) && !groupedAs.contains(id))
{
if(compareNamesLists(AToNamesMap.get(id), AToNamesMap.get(otherAID)))
{
Relationship rel = graphDb.getNodeById(otherAID).getSingleRelationship(EdgeTypes.HAS_DONE,Direction.INCOMING);
Node otherPersonNode = rel.getStartNode();
if(nameToId.get(otherPersonNode.getProperty("Name")) != null && nameToId.get(otherPersonNode.getProperty("Name")).size() > 1)
{
otherPersonNode.createRelationshipTo(graphDb.getNodeById(id), EdgeTypes.HAS_PROBABLY_DONE);
}
else
{
otherPersonNode.createRelationshipTo(graphDb.getNodeById(id), EdgeTypes.HAD_DONE);
}
rel.delete();
graphDb.getNodeById(otherAID).delete();
groupedAs.add(otherAID);
}
}
}
}
groupedAs.add(id);
}
txAs.success();
}
}
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
}
When I open the browser and connect it to the bolt that I expose for my embedded neo4j, the browser is able to show all the nodes in my graph database (at the moment less than 100) and it then freezes, causing the entire system to freeze (MacBook Pro 2016, 16GB). This happens around 3/5 times.
I know that the way I make my transactions is not ideal, but as I said all this processing happens before the neo4j browser starts.
Can you advise me on how to solve this issue?
Can you see anything in my code (connection left open etc) Is this a known issue for the neo4j browser?

paging in Java for a lookup

I am trying to implement paging in an already running application, it works like mongodb where you get a query with bunch of parameters like
searchConditions ,limit( how many docs you want), skip ( skip these many docs)
and so on
and the response is back in json my task is to generate the previous and next link to the query that means previous page and the next page as per query
I came up with a method below
public Paging generateLink(RequestFilter filter) {
int prev_skip;
int prev_limit;
String pagePrev = "";
String pageNext = "";
int next_skip;
int next_limit;
String searchCondition = JsonUtils.toSimpleJsonString(filter.getSearch());
String url = "http://isgswmdi1n1.nam.nsroot.net:7014/account-search/rest/api/v1/pmm";
//properties.getProperty("paging.link");
System.out.println(url);
Paging pagingOption = new Paging();
Result result = new Result();
int count = luceneSearchService.searchCount(filter);
try {
if (count > 1) {
if (filter.getSkip() > 0) {
prev_skip = Math.max((filter.getSkip() - 1), 0);
prev_limit = filter.getLimit();
pagePrev = url + "?search=" + searchCondition + "&skip=" + prev_skip + "$limit=" + prev_limit;
} else{
result.setPaging(null);
return null;
}
if (count > (filter.getLimit() + filter.getSkip())) {
next_skip = (filter.getSkip() + filter.getLimit());
next_limit = filter.getLimit();
pageNext = url + "?search=" + searchCondition + "&skip=" + next_skip + "$limit=" + next_limit;
} else{
result.setPaging(null);
return null;
}
pagingOption.setPagePrev(pagePrev);
pagingOption.setPageNext(pageNext);
result.setPaging(pagingOption);
}
return pagingOption;
} catch (NullPointerException n)
{
n.printStackTrace();
return pagingOption;
}
}
call to generateLink method
return Result.ok(resultRow, generateLink(filter));
the ok response method in the Result class
public static Result ok(List<ResultRow> resultRows, Paging paging) {
if (paging != null) {
return new Result(resultRows, 200, "Completed", paging);
} else
return new Result(resultRows, 200, "Completed");
}
Underlying paging class
public class Paging implements Serializable {
public String getPagePrev() {
return pagePrev;
}
public void setPagePrev(String pagePrev) {
this.pagePrev = pagePrev;
}
#JsonProperty("pagePrev")
private String pagePrev;
public String getPageNext() {
return pageNext;
}
public void setPageNext(String pageNext) {
this.pageNext = pageNext;
}
#JsonProperty("pageNext")
private String pageNext;
}
but my test method is failing
#Test
public void search_allFilterParamsAreDefined_hp() throws Exception {
// given
Map<String, Serializable> searchConditions = singletonMap("shortName", "GO");
List<String> returnFields = asList("shortname", "gfcid");
String returnFieldsStr = returnFields.stream().collect(joining(","));
RequestFilter filter = RequestFilter.create(searchConditions, returnFieldsStr, 5, 10, true);
int resultSize = 20;
List<ResultRow> searchResult = getSearchResult(resultSize);
when(luceneSearchService.search(filter)).thenReturn(searchResult);
when(luceneSearchService.searchCount(filter)).thenReturn(resultSize);
// do
Result result = searchCoordinator.search(filter);
// verify
assertEquals(searchResult, result.getRows());
assertReturnFields(returnFields, result.getRows());
assertNotNull(result.getPaging());
Map<String, String> nextParams = getQueryParams(result.getPaging().getPageNext());
assertParam(nextParams, "search", toSimpleJsonString(searchConditions));
assertParam(nextParams, "skip", "15");
assertParam(nextParams, "limit", "10");
}

Jackrabbit - Unable to retrieve properties of node

I have created folder using superuser and provided read-only access to folder for application user.
When trying to query all accessible folders(nt:folder), getting properties list as empty.
Partial code to reproduce:
Created folder:
public Node createFolder(Session adminSession) {
try {
Node parentNode = adminSession.getNode("/MyCompany/CommonFolder”);
if(!parentNode.hasNode("T1")){
Node node = parentNode.addNode("T1", "nt:folder");
node.addMixin("et:folderProperties");
node.setProperty("et:folderName", "T1");
node.addMixin("rep:AccessControllable");
session.save(); return node;
}else {
System.out.println("Node already exists");
}
} catch (RepositoryException e) {
e.printStackTrace();
}
return null;
}
Sharing to user(Principal based)
accessControlManager = (JackrabbitAccessControlManager)
adminSession.getAccessControlManager();
accessControlPolicy = accessControlManager.getApplicablePolicies(userPrincipal);
// for ex., principal is appuser1
if(accessControlPolicy != null && accessControlPolicy.length > 0) {
accessControlList = (JackrabbitAccessControlList) accessControlPolicy[0];
}else {
accessControlPolicy = accessControlManager.getPolicies(userPrincipal);
accessControlList = (JackrabbitAccessControlList) accessControlPolicy[0];
}
ValueFactory valueFactory = adminSession.getValueFactory();
//Tried all combinations, even providing with "JCR:ALL";
Privilege[] readPrivilege = new javax.jcr.security.Privilege[] {
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_READ),
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_NODE_TYPE_MANAGEMENT),
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_READ_ACCESS_CONTROL)};
Map<String, Value> restrictions = new HashMap<String, Value>();
restrictions.put("rep:nodePath", valueFactory.createValue("/MyCompany/CommonFolder/T1",
PropertyType.PATH));
restrictions.put("rep:glob", valueFactory.createValue(""));
accessControlList.addEntry(userPrincipal, privileges, true , restrictions);
accessControlManager.setPolicy(accessControlList.getPath(), accessControlList);
adminSession.save();
Printing all applicable folders for user
public void printAllFolders(Session userSession) {
QueryManager queryManager;
try {
queryManager = userSession.getWorkspace().getQueryManager();
String sql = "SELECT * FROM [nt:folder]";
Query query= queryManager.createQuery(sql, Query.JCR_SQL2);
QueryResult result = query.execute();
NodeIterator nodeIterator = result.getNodes();
System.out.println("Printing all applicable folders");
while(nodeIterator.hasNext()) {
Node node = nodeIterator.nextNode();
System.out.println("Folder Name:" + node.getName() + "; path: " + node.getPath());
PropertyIterator pIterator = node.getProperties();
while (pIterator.hasNext()){ //Returning empty for path "/MyCompany/CommonFolder/T1"
Property property = pIterator.nextProperty();
if (property.getDefinition().isMultiple()) {
Value[] values = property.getValues();
for(Value v11: values) {
QValueValue value = (QValueValue)v11;
System.out.println(String.format("Multi-valued property for node:
'%s' - %s has values",node.getName(),
property.getName() ,value.getString()));
}
} else {
QValueValue value = (QValueValue) property.getValue();
String strValue = value.getString();
System.out.println(String.format("property for node: '%s' - %s has value
%s",node.getName(),property.getName(),strValue));
}
}
}
} catch (RepositoryException e) {
e.printStackTrace();
}
}
using Jackrabbit(2.6.0 version) and JCR( 2.0 version).
Node child = cl.addNode("ONE");
child.setProperty("message", ("CL Child" + i));
session.save();
PropertyIterator iter = child.getProperties();
System.out.println("Size" + iter.getSize());
while (iter.hasNext()) {
PropertyImpl key = (PropertyImpl) iter.next();
String value = key.getString();
System.out.println("------------->" + key);
System.out.println("------------->" + value);
}

Java export data to (custom-format) text file [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I was asked to work on this back-end scheduled job that export some customers data (from an e-commerce DB) to a custom-format text file. The code that follows is what I found.
I just would like to delete it all, but I can't. Would it be possible for me to improve this without changing it so much?
public class AConverter implements CustomerConverter {
protected final Logger LOG = LoggerFactory.getLogger(AConverter.class);
private final static String SEPARATOR = ";";
private final static String CR = "\n";
public String create(Customer customer) {
if (customer == null)
return null;
LOG.info("Exporting customer, uidpk: {}, userid: {}", customer.getUidPk(), customer.getUserId());
StringBuilder buf = new StringBuilder();
buf.append("<HEAD>");
buf.append(SEPARATOR);
buf.append(String.valueOf(customer.getUidPk()));
buf.append(SEPARATOR);
byte[] fullName = null;
try {
fullName = customer.getFullName().getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
fullName = customer.getFullName().getBytes();
}
String name = null;
try {
name = new String(fullName, "UTF-8");
} catch (UnsupportedEncodingException e) {
name = customer.getFullName();
}
buf.append(limitString(name, 40));
buf.append(SEPARATOR);
final CustomerAddress preferredShippingAddress = customer.getPreferredShippingAddress();
if (preferredShippingAddress != null) {
final String street1 = preferredShippingAddress.getStreet1();
if (street1 != null) {
buf.append(limitString(street1, 40));
}
} else {
buf.append(" ");
}
buf.append(SEPARATOR);
final String addressStr = buildAddressString(customer);
buf.append(limitString(addressStr, 40));
buf.append(SEPARATOR);
buf.append(limitString(customer.getEmail(), 80));
buf.append(SEPARATOR);
if (preferredShippingAddress!=null && preferredShippingAddress.getStreet2() != null) {
buf.append(limitString(preferredShippingAddress.getStreet2(), 40));
} else {
buf.append(" ");
}
buf.append(SEPARATOR);
buf.append(limitString(customer.getPhoneNumber(), 25));
buf.append(SEPARATOR);
if (preferredShippingAddress!=null) {
if(preferredShippingAddress.getCountry()!=null) {
buf.append(preferredShippingAddress.getCountry());
} else {
buf.append(" ");
}
} else {
buf.append(" ");
}
buf.append(SEPARATOR);
if (preferredShippingAddress!=null) {
if(preferredShippingAddress.getCountry()!=null) {
buf.append(preferredShippingAddress.getCountry());
} else {
buf.append(" ");
}
} else {
buf.append(" ");
}
buf.append(SEPARATOR);
String fodselsnummer = " ";
try {
Map<String, AttributeValue> profileValueMap = customer.getProfileValueMap();
AttributeValue attributeValue = profileValueMap.get("CODE");
fodselsnummer = attributeValue.getStringValue();
} catch (Exception e) {
}
buf.append(fodselsnummer);
buf.append(CR);
final String string = buf.toString();
return string;
}
private String buildAddressString(Customer customer) {
final CustomerAddress preferredShippingAddress = customer.getPreferredShippingAddress();
if (preferredShippingAddress != null) {
final String zipOrPostalCode = preferredShippingAddress.getZipOrPostalCode();
final String city = preferredShippingAddress.getCity();
if (zipOrPostalCode != null && city != null) {
return zipOrPostalCode + " " + city;
} else if(zipOrPostalCode == null && city != null) {
return city;
} else if(zipOrPostalCode != null && city == null) {
return zipOrPostalCode;
}
}
return " ";
}
private String limitString(String value, int numOfChars) {
if (value != null && value.length() > numOfChars)
return value.substring(0, numOfChars);
else
return value;
}
}
You say you want to improve it, you'd like to delete it, but you can't. I'm not sure why you can't. I also don't understand why you'd want to delete it. But it sounds to me like the kind of attitude I used to have before I read Refactoring by Martin Fowler. I would strongly suggest you read that book, if you haven't already.
It is certainly possible to improve this code (or any code) without rewriting it all. The most obvious improvements would be to eliminate some of the repetitive code in the create method by creating some utility methods, and then breaking up the create method into several smaller methods à la template methods.
Also, there is a questionable bit of code in the create method that turns the customer's name into a UTF-8 byte stream and then back into a string. I can't imagine what that's for. Finally, it returns null if the customer is null. That is unlikely to be necessary or wise.
For fun, I decided to do a little refactoring on this code. (Note that proper refactoring involves unit tests; I don't have any tests for this code and have not even compiled the code below, much less tested it.) Here is one possible way you could rewrite this code:
public class AConverter implements CustomerConverter {
protected final Logger LOG = LoggerFactory.getLogger(AConverter.class);
private final static String SEPARATOR = ";";
private final static String CR = "\n";
public String create(Customer customer) {
if (customer == null) throw new IllegalArgumentException("no cust");
LOG.info("Exporting customer, uidpk: {}, userid: {}",
customer.getUidPk(), customer.getUserId());
StringBuilder buf = new StringBuilder();
doHead(buf, customer);
doAddress(buf, customer);
doTail(buf, customer);
return buf.toString();
}
private void doHead(StringBuilder buf, Customer customer) {
append(buf, "<HEAD>");
append(buf, String.valueOf(customer.getUidPk()));
append(buf, limitTo(40, customer.getFullName()));
}
private void doAddress(StringBuilder buf, Customer customer) {
append(buf, limitTo(40, street1of(customer)));
append(buf, limitTo(40, addressOf(customer)));
append(buf, limitTo(80, customer.getEmail()));
append(buf, limitTo(40, street2of(customer)));
append(buf, limitTo(25, customer.getPhoneNumber()));
append(buf, countryOf(customer));
append(buf, countryOf(customer));
}
private void doTail(StringBuilder buf, Customer customer) {
buf.append(fodselsnummerOf(customer));
buf.append(CR);
}
private void append(StringBuilder buf, String s) {
buf.append(s).append(SEPARATOR);
}
private String street1of(Customer customer) {
final CustomerAddress shipto = customer.getPreferredShippingAddress();
if (shipto == null) return " ";
if (shipto.getStreet1() != null) return shipto.getStreet1();
return " ";
}
private String street2of(Customer customer) {
final CustomerAddress shipto = customer.getPreferredShippingAddress();
if (shipto == null) return " ";
if (shipto.getStreet2() != null) return shipto.getStreet2();
return " ";
}
private String addressOf(Customer customer) {
final CustomerAddress shipto = customer.getPreferredShippingAddress();
if (shipto == null) return " ";
final String post = preferredShippingAddress.getZipOrPostalCode();
final String city = preferredShippingAddress.getCity();
if (post != null && city != null) return post + " " + city;
if (post == null && city != null) return city;
if (post != null && city == null) return post;
return " ";
}
private String countryOf(Customer customer) {
final CustomerAddress shipto = customer.getPreferredShippingAddress();
if (shipto == null) return " ";
if (shipto.getCountry() != null) return shipto.getCountry();
return " ";
}
private String limitTo(int numOfChars, String value) {
if (value != null && value.length() > numOfChars)
return value.substring(0, numOfChars);
return value;
}
private String fodelsnummerOf(Customer customer) {
try {
Map<String, AttributeValue> profileValueMap =
customer.getProfileValueMap();
AttributeValue attributeValue = profileValueMap.get("CODE");
return attributeValue.getStringValue();
} catch (Exception e) {
return " ";
}
}
}
I also notice that there is a problem with your format for the custom-format text file if any of the fields of the customer data (email address, for example) happen to have a semicolon in them, because that is your separator character. I trust that is a known issue?

SSHD Java example

Can anyone point me to some example code for using SSHD to access a server and execute some commands from a JAVA application. I have looked through the Apache SSHD website and downloads and have not found anything useful yet as far as documentation and example code. I also googled SSHD example code and was unsuccessful.
This one can run,I have checked it.I just delete the import.
version apache sshd-core-0.7.0.jar
public class SshClient extends AbstractFactoryManager implements ClientFactoryManager {
protected IoConnector connector;
protected SessionFactory sessionFactory;
private ServerKeyVerifier serverKeyVerifier;
public SshClient() {
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public ServerKeyVerifier getServerKeyVerifier() {
return serverKeyVerifier;
}
public void setServerKeyVerifier(ServerKeyVerifier serverKeyVerifier) {
this.serverKeyVerifier = serverKeyVerifier;
}
public void start() {
// Register the additional agent forwarding channel if needed
if (getAgentFactory() != null) {
List<NamedFactory<Channel>> factories = getChannelFactories();
if (factories == null) {
factories = new ArrayList<NamedFactory<Channel>>();
} else {
factories = new ArrayList<NamedFactory<Channel>>(factories);
}
factories.add(getAgentFactory().getChannelForwardingFactory());
setChannelFactories(factories);
}
connector = createAcceptor();
if (sessionFactory == null) {
sessionFactory = new SessionFactory();
}
sessionFactory.setClient(this);
connector.setHandler(sessionFactory);
}
protected NioSocketConnector createAcceptor() {
return new NioSocketConnector(getNioWorkers());
}
public void stop() {
connector.dispose();
connector = null;
}
public ConnectFuture connect(String host, int port) throws Exception {
assert host != null;
assert port >= 0;
if (connector == null) {
throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
}
SocketAddress address = new InetSocketAddress(host, port);
return connect(address);
}
public ConnectFuture connect(SocketAddress address) throws Exception {
assert address != null;
if (connector == null) {
throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
}
final ConnectFuture connectFuture = new DefaultConnectFuture(null);
connector.connect(address).addListener(new IoFutureListener<org.apache.mina.core.future.ConnectFuture>() {
public void operationComplete(org.apache.mina.core.future.ConnectFuture future) {
if (future.isCanceled()) {
connectFuture.cancel();
} else if (future.getException() != null) {
connectFuture.setException(future.getException());
} else {
ClientSessionImpl session = (ClientSessionImpl) AbstractSession.getSession(future.getSession());
connectFuture.setSession(session);
}
}
});
return connectFuture;
}
/**
* Setup a default client. The client does not require any additional setup.
*
* #return a newly create SSH client
*/
public static SshClient setUpDefaultClient() {
SshClient client = new SshClient();
// DHG14 uses 2048 bits key which are not supported by the default JCE provider
if (SecurityUtils.isBouncyCastleRegistered()) {
client.setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>>asList(
new DHG14.Factory(),
new DHG1.Factory()));
client.setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
} else {
client.setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>>asList(
new DHG1.Factory()));
client.setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
}
setUpDefaultCiphers(client);
// Compression is not enabled by default
// client.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList(
// new CompressionNone.Factory(),
// new CompressionZlib.Factory(),
// new CompressionDelayedZlib.Factory()));
client.setCompressionFactories(Arrays.<NamedFactory<Compression>>asList(
new CompressionNone.Factory()));
client.setMacFactories(Arrays.<NamedFactory<Mac>>asList(
new HMACMD5.Factory(),
new HMACSHA1.Factory(),
new HMACMD596.Factory(),
new HMACSHA196.Factory()));
client.setSignatureFactories(Arrays.<NamedFactory<Signature>>asList(
new SignatureDSA.Factory(),
new SignatureRSA.Factory()));
return client;
}
private static void setUpDefaultCiphers(SshClient client) {
List<NamedFactory<Cipher>> avail = new LinkedList<NamedFactory<Cipher>>();
avail.add(new AES128CBC.Factory());
avail.add(new TripleDESCBC.Factory());
avail.add(new BlowfishCBC.Factory());
avail.add(new AES192CBC.Factory());
avail.add(new AES256CBC.Factory());
for (Iterator<NamedFactory<Cipher>> i = avail.iterator(); i.hasNext();) {
final NamedFactory<Cipher> f = i.next();
try {
final Cipher c = f.create();
final byte[] key = new byte[c.getBlockSize()];
final byte[] iv = new byte[c.getIVSize()];
c.init(Cipher.Mode.Encrypt, key, iv);
} catch (InvalidKeyException e) {
i.remove();
} catch (Exception e) {
i.remove();
}
}
client.setCipherFactories(avail);
}
/*=================================
Main class implementation
*=================================*/
public static void main(String[] args) throws Exception {
int port = 22;
String host = null;
String login = System.getProperty("user.name");
boolean agentForward = false;
List<String> command = null;
int logLevel = 0;
boolean error = false;
for (int i = 0; i < args.length; i++) {
if (command == null && "-p".equals(args[i])) {
if (i + 1 >= args.length) {
System.err.println("option requires an argument: " + args[i]);
error = true;
break;
}
port = Integer.parseInt(args[++i]);
} else if (command == null && "-l".equals(args[i])) {
if (i + 1 >= args.length) {
System.err.println("option requires an argument: " + args[i]);
error = true;
break;
}
login = args[++i];
} else if (command == null && "-v".equals(args[i])) {
logLevel = 1;
} else if (command == null && "-vv".equals(args[i])) {
logLevel = 2;
} else if (command == null && "-vvv".equals(args[i])) {
logLevel = 3;
} else if ("-A".equals(args[i])) {
agentForward = true;
} else if ("-a".equals(args[i])) {
agentForward = false;
} else if (command == null && args[i].startsWith("-")) {
System.err.println("illegal option: " + args[i]);
error = true;
break;
} else {
if (host == null) {
host = args[i];
} else {
if (command == null) {
command = new ArrayList<String>();
}
command.add(args[i]);
}
}
}
if (host == null) {
System.err.println("hostname required");
error = true;
}
if (error) {
System.err.println("usage: ssh [-A|-a] [-v[v][v]] [-l login] [-p port] hostname [command]");
System.exit(-1);
}
// TODO: handle log level
SshClient client = SshClient.setUpDefaultClient();
client.start();
try {
boolean hasKeys = false;
/*
String authSock = System.getenv(SshAgent.SSH_AUTHSOCKET_ENV_NAME);
if (authSock == null) {
KeyPair[] keys = null;
AgentServer server = new AgentServer();
authSock = server.start();
List<String> files = new ArrayList<String>();
File f = new File(System.getProperty("user.home"), ".ssh/id_dsa");
if (f.exists() && f.isFile() && f.canRead()) {
files.add(f.getAbsolutePath());
}
f = new File(System.getProperty("user.home"), ".ssh/id_rsa");
if (f.exists() && f.isFile() && f.canRead()) {
files.add(f.getAbsolutePath());
}
try {
if (files.size() > 0) {
keys = new FileKeyPairProvider(files.toArray(new String[0]), new PasswordFinder() {
public char[] getPassword() {
try {
System.out.println("Enter password for private key: ");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String password = r.readLine();
return password.toCharArray();
} catch (IOException e) {
return null;
}
}
}).loadKeys();
}
} catch (Exception e) {
}
SshAgent agent = new AgentClient(authSock);
for (KeyPair key : keys) {
agent.addIdentity(key, "");
}
agent.close();
}
if (authSock != null) {
SshAgent agent = new AgentClient(authSock);
hasKeys = agent.getIdentities().size() > 0;
}
client.getProperties().put(SshAgent.SSH_AUTHSOCKET_ENV_NAME, authSock);
*/
ClientSession session = client.connect(host, port).await().getSession();
int ret = ClientSession.WAIT_AUTH;
while ((ret & ClientSession.WAIT_AUTH) != 0) {
if (hasKeys) {
session.authAgent(login);
ret = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
} else {
System.out.print("Password:");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String password = r.readLine();
session.authPassword(login, password);
ret = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
}
}
if ((ret & ClientSession.CLOSED) != 0) {
System.err.println("error");
System.exit(-1);
}
ClientChannel channel;
if (command == null) {
channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
((ChannelShell) channel).setAgentForwarding(agentForward);
channel.setIn(new NoCloseInputStream(System.in));
} else {
channel = session.createChannel(ClientChannel.CHANNEL_EXEC);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(baos);
for (String cmd : command) {
w.append(cmd).append(" ");
}
w.append("\n");
w.close();
channel.setIn(new ByteArrayInputStream(baos.toByteArray()));
}
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open().await();
channel.waitFor(ClientChannel.CLOSED, 0);
session.close(false);
} finally {
client.stop();
}
}
}
public static void main(String[] args) throws IOException, InterruptedException
{
SshClient client = SshClient.setUpDefaultClient();
client.start();
final ClientSession session = client.connect("bob", "bob.mynetwork.com", 22).await().getSession();
int authState = ClientSession.WAIT_AUTH;
while ((authState & ClientSession.WAIT_AUTH) != 0) {
session.addPasswordIdentity("bobspassword");
System.out.println("authenticating...");
final AuthFuture authFuture = session.auth();
authFuture.addListener(new SshFutureListener<AuthFuture>()
{
#Override
public void operationComplete(AuthFuture arg0)
{
System.out.println("Authentication completed with " + ( arg0.isSuccess() ? "success" : "failure"));
}
});
authState = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
}
if ((authState & ClientSession.CLOSED) != 0) {
System.err.println("error");
System.exit(-1);
}
final ClientChannel channel = session.createShellChannel();
channel.setOut(new NoCloseOutputStream(System.out));
channel.setErr(new NoCloseOutputStream(System.err));
channel.open();
executeCommand(channel, "pwd\n");
executeCommand(channel, "ll\n");
channel.waitFor(ClientChannel.CLOSED, 0);
session.close(false);
client.stop();
}
private static void executeCommand(final ClientChannel channel, final String command) throws IOException
{
final InputStream commandInput = new ByteArrayInputStream(command.getBytes());
channel.setIn(new NoCloseInputStream(commandInput));
}
Having tracked development regarding Java support for SSH for many years now, I strongly recommend against using any Java SSH implementation. Noone cares to develop them any further. None of them has proper SSH-Agent support. And SSH without SSH-Agent, especially when running code on top of it, makes those implementations rather useless - unless you are willing to put unencrypted keys or passwords everywhere.
The best solution IMHO is to write a wrapper around the rock-solid OpenSSH implementations.

Categories

Resources