Export table in Postgis to a shape file without a specific column - shapefile

I Would like to export a postgreSQL (Postgis) table to a Shape file, but without a cetrain column. I don't want to delete the column in the db first. How do I exclude this certain column?
This is the export function:
private void exportShapeFile(String name, String path) {
try {
DataStore pgDatastore = Snippets.createPostgisDataStore();
SimpleFeatureCollection sfc = Snippets.getSimpleFeatureCollection(pgDatastore, name);
final SimpleFeatureType TYPE = Snippets.getPostgisSimpleFeatureType(pgDatastore, name);
String filename = path + "\\" + name + ".shp";
File newFile = new File(filename);
CoordinateReferenceSystem sourceCRS = Snippets.getCRS(name);
Object[] a = sourceCRS.getIdentifiers().toArray();
String crsOrig = a[0].toString();
String wkt = null;
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", newFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
File directory = new File(txtFieldDir.getText());
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(TYPE);
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(sfc);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
pgDatastore.dispose();
newDataStore.dispose();
}
} else {
Snippets.appendToPane(txtLog,"ERROR:" + typeName + " does not support read/write access.\n", MainDialog.colRed);
}
} catch (MalformedURLException e) {
Snippets.appendToPane(txtLog,e.toString() + "\n", MainDialog.colRed);
e.printStackTrace();
} catch (IOException e) {
Snippets.appendToPane(txtLog,e.toString() + "\n", MainDialog.colRed);
e.printStackTrace();
}

You need to generate a new schema for your shapefile and then retype your features to that schema. DataUtilities provides useful methods for this, createSubType to generate a new schema limited to a shorter list of attributes, and reType to change a filter into one that matches the new schema.

Related

How to save several pieces of information from a JavaFX form to a File

I can not seem to figure out how to store the data in the TextFields in a text file using JavaFX and accepting a certain number of entries. For example: One would fill out the form 3times and all of those 3 pieces of information would be in the txt file. How would I implement an ArrayList into the method in order to display?
I have already tried to implement a String ArrayList but it does not display the data in the TextFields when I press "Save Information", all that displays is [, , , ]
public void saveInfo(ActionEvent e) {
ArrayList<String> list = new ArrayList<>();
File fileIt = new File("InfoGathered.txt");
try {
PrintWriter output = new PrintWriter(fileIt);
for (int i = 0; i < ; i++) {
String s1 = new String();
output.println(tfFirstName.getText() + tfLastName.getText() + tfdBirth.getText() + tfEmpID.getText());
list.add(s1);
}
output.write(list.toString());
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
I am expecting the TextFields to appear within the File such as [Sam Smith 12/03/94 123-AB, Lena Smith 12/12/91 127-AB, Sam Smith 02/18/95 726-HF ]
There are so many things fundamentally wrong in your code, I do not even know where to start. But if it is the solution you want for your given problem, below code will write the text of TextFields to the file in your desired format.
public void saveInfo(ActionEvent e) {
File fileIt = new File("InfoGathered.txt");
try (PrintWriter output = new PrintWriter(fileIt)){
String outString = tfFirstName.getText() + " "
+ tfLastName.getText() + " "
+ tfdBirth.getText() + " "
+ tfEmpID.getText();
output.write(outString);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}

Regex issue on pattern matching

I have a question on regex.
I have a text file that contains meta-urls in the following form:
www.abc.com/.services/
www.abc.com/./wireless
I want to compare all the patterns from that file with my URL, and execute an action if I find a match. This matching process is hard to understand for me.
Assuming splitarray[0] contains the first line of text file:
String url = page.getWebURL().getURL();
URL url1 = new URL(url);
how can we compare url1 with splitarray[0]?
UPDATED
BufferedReader readbuffer = null;
try {
readbuffer = new BufferedReader(new FileReader("filters.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String strRead;
try {
while ((strRead=readbuffer.readLine())!=null){
String splitarray[] = strRead.split(",");
String firstentry = splitarray[0];
String secondentry = splitarray[1];
String thirdentry = splitarray[2];
//String fourthentry = splitarray[3];
//String fifthentry = splitarray[4];
System.out.println(firstentry + " " + secondentry+ " " +thirdentry);
URL url1 = new URL("http://www.abc.com/ship/reach/news-and");
Pattern p = Pattern.compile("http://www.abc.com/.*/reach");
Matcher m = p.matcher(url1.toString());
if (m.matches()) {
//Do whatever
System.out.println("Yes Done");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But if I want that any url which start with the pattern giving in the splitarray[0]. how can I implement this?
I was able to solve the problem after looking on some example in this website.
http://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/

Unable to read the SharePoint List using java

Here i am trying to read the list of sharepoint. For this i have done the following:
I have downloaded the WSDL file which i got from The URL like: sharepointsite.com/_vti_bin/Lists.asmx?WSDL.
and i have executed the following command to generate the classes in the directory
“C:\Program Files\Java\jdk1.6.0_12\bin\wsimport.exe” -p com.microsoft.schemas.sharepoint.soap -keep -extension Lists.wsdl.
Imported those classes in my eclipse IDE java application.
and i have written the following code
/* Creates a port connected to the SharePoint Web Service given.
* Authentication is done here. It also prints the authentication details
* in the console.
* #param userName SharePoint username
* #param password SharePoint password
* #return port ListsSoap port, connected with SharePoint
* #throws Exception in case of invalid parameters or connection error.
*/
public static ListsSoap sharePointListsAuth(String userName, String password) throws Exception {
ListsSoap port = null;
if (userName != null && password != null) {
try {
Lists service = new Lists();
port = service.getListsSoap();
System.out.println("Web Service Auth Username: " + userName);
((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userName);
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
} catch (Exception e) {
throw new Exception("Error: " + e.toString());
}
} else {
throw new Exception("Couldn't authenticate: Invalid connection details given.");
}
return port;
}
/**
* Creates a string from an XML file with start and end indicators
* #param docToString document to convert
* #return string of the xml document
*/
public static String xmlToString(Document docToString) {
String returnString = "\n-------------- XML START --------------\n";
try {
//create string from xml tree
//Output the XML
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans;
trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult streamResult = new StreamResult(sw);
DOMSource source = new DOMSource(docToString);
trans.transform(source, streamResult);
String xmlString = sw.toString();
//print the XML
returnString = returnString + xmlString;
} catch (TransformerException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
}
returnString = returnString + "-------------- XML END --------------";
return returnString;
}
/**
02
* Connects to a SharePoint Lists Web Service through the given open port,
03
* and reads all the elements of the given list. Only the ID and the given
04
* attributes (column names) are displayed, as well as a dump of the SOAP
05
* response from the Web Service (for debugging purposes).
06
* #param port an already authentificated SharePoint Online SOAP port
07
* #param listName original name of the Sharepoint list that is going to be read
08
* #param listColumnNames arraylist containing the various names of the Columns
09
* of the SharePoint list that are going to be read. If the column name isn't
10
* found, then an exception will be thrown
11
* #param rowLimit limits the number of rows (list items) that are going to
12
* be returned
13
* #throws Exception
14
*/
public static void displaySharePointList(ListsSoap port, String listName, ArrayList<String> listColumnNames, String rowLimit) throws Exception {
if (port != null && listName != null && listColumnNames != null && rowLimit != null) {
try {
//Here are additional parameters that may be set
String viewName = "";
GetListItems.ViewFields viewFields = null;
GetListItems.Query query = null;
GetListItems.QueryOptions queryOptions = null;
String webID = "";
//Calling the List Web Service
GetListItemsResponse.GetListItemsResult result = port.getListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, webID);
Object listResult = result.getContent().get(0);
if ((listResult != null) && (listResult instanceof ElementNSImpl)) {
ElementNSImpl node = (ElementNSImpl) listResult;
//Dumps the retrieved info in the console
Document document = node.getOwnerDocument();
System.out.println("SharePoint Online Lists Web Service Response:" + Manager.xmlToString(document));
//selects a list of nodes which have z:row elements
NodeList list = node.getElementsByTagName("z:row");
System.out.println("=> " + list.getLength() + " results from SharePoint Online");
//Displaying every result received from SharePoint, with its ID
for (int i = 0; i < list.getLength(); i++) {
//Gets the attributes of the current row/element
NamedNodeMap attributes = list.item(i).getAttributes();
System.out.println("******** Item ID: " + attributes.getNamedItem("ows_ID").getNodeValue()+" ********");
//Displays all the attributes of the list item that correspond to the column names given
for (String columnName : listColumnNames) {
String internalColumnName = "ows_" + columnName;
if (attributes.getNamedItem(internalColumnName) != null) {
System.out.println(columnName + ": " + attributes.getNamedItem(internalColumnName).getNodeValue());
} else {
throw new Exception("Couldn't find the '" + columnName + "' column in the '" + listName + "' list in SharePoint.\n");
}
}
}
} else {
throw new Exception(listName + " list response from SharePoint is either null or corrupt\n");
}
} catch (Exception ex) {
throw new Exception("Exception. See stacktrace." + ex.toString() + "\n");
}
}
}
public static void main(String[] args) {
try {
//Authentication parameters
String userName = "domain\\username";
String password = "pass";
//Opening the SOAP port of the Lists Web Service
ListsSoap port = Manager.sharePointListsAuth(userName, password);
/*
* Lists Web service parameters
* The list names below must be the *original* names of the list.
* if a list or column was renamed from SharePoint afterwards,
* these parameters don't change.
*/
String listName = "listname";
String rowLimit = "2";
ArrayList<String> listColumnNames = new ArrayList<String>();
listColumnNames.add("Name");
listColumnNames.add("ID");
//Displays the lists items in the console
Manager.displaySharePointList(port, listName, listColumnNames, rowLimit);
} catch (Exception ex) {
System.err.println(ex);
}
}
I am getting following exception :
Web Service Auth Username: "domain\username"
java.lang.Exception: Exception. See stacktrace.javax.xml.ws.soap.SOAPFaultException: Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.
It would be helpfull if i get the specific exception from the server.With this expection i am unable to track my pgm.
I dont know where did i go wrong? am i missing anything ? any configuration is required ?
Thanks in advance for your help
I had the same problem, try with an Authenticator :
new BasicAuthentication(userName,password).authenticate();
My BasicAuthentication class :
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class BasicAuthentication extends Authenticator
{
private String username;
private String password;
public BasicAuthentication(String username, String password)
{
this.username = username;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return (new PasswordAuthentication(username,password.toCharArray()));
}
public void authenticate()
{
Authenticator.setDefault(this);
}
}

pig puzzle: re-writing an involved reducer as a simple pig script?

There are account ids, each with a timestamp grouped by username. foreach of these username groups I want all pairs of (oldest account, other account).
I have a java reducer that does that, can I rewrite it as a simple pig script?
Schema:
{group:(username),A: {(id , create_dt)}
Input:
(batman,{(id1,100), (id2,200), (id3,50)})
(lulu ,{(id7,100), (id9,50)})
Desired output:
(batman,{(id3,id1), (id3,id2)})
(lulu ,{(id9,id7)})
Not that anyone seems to care, but here goes. You have to create a UDF:
desired = foreach my_input generate group as n, FIND_PAIRS(A) as pairs_bag;
And the UDF:
public class FindPairs extends EvalFunc<DataBag> {
#Override
public DataBag exec(Tuple input) throws IOException {
Long pivotCreatedDate = Long.MAX_VALUE;
Long pivot = null;
DataBag accountsBag = (DataBag) input.get(0);
for (Tuple account : accountsBag){
Long accountId = Long.parseLong(account.get(0).toString());
Long creationDate = Long.parseLong(account.get(4).toString());
if (creationDate < pivotCreatedDate ) {
// pivot is the one with the minimal creation_dt
pivot = accountId;
pivotCreatedDate = creationDate;
}
}
DataBag allPairs = BagFactory.getInstance().newDefaultBag();
if (pivot != null){
for (Tuple account : accountsBag){
Long accountId = Long.parseLong(account.get(0).toString());
Long creationDate = Long.parseLong(account.get(4).toString());
if (!accountId.equals(pivot)) {
// we don't want any self-pairs
Tuple output = TupleFactory.getInstance().newTuple(2);
if (pivot < accountId){
output.set(0, pivot.toString());
output.set(1, accountId.toString());
}
else {
output.set(0, accountId.toString());
output.set(1, pivot.toString());
}
allPairs.add(output);
}
}
return allPairs;
}
and if you wanna play real nicely, add this:
/**
* Letting pig know that we emit a bag with tuples, each representing a pair of accounts
*/
#Override
public Schema outputSchema(Schema input) {
try{
Schema pairSchema = new Schema();
pairSchema.add(new FieldSchema(null, DataType.BYTEARRAY));
pairSchema.add(new FieldSchema(null, DataType.BYTEARRAY));
return new Schema(
new FieldSchema(null,
new Schema(pairSchema), DataType.BAG));
}catch (Exception e){
return null;
}
}
}

subsonic 3.0 active record update

I am able to retrieve database values and insert database values, but I can't figure out what the Update() syntax should be with a where statement.
Environment -> ASP.Net, C#
Settings.ttinclude
const string Namespace = "subsonic_db.Data";
const string ConnectionStringName = "subsonic_dbConnectionString";
//This is the name of your database and is used in naming
//the repository. By default we set it to the connection string name
const string DatabaseName = "subsonic_db";
Retreive example
var product = equipment.SingleOrDefault(x => x.id == 1);
Insert Example
equipment my_equipment = new equipment();
try
{
// insert
my_equipment.parent_id = 0;
my_equipment.primary_id = 0;
my_equipment.product_code = product_code.Text;
my_equipment.product_description = product_description.Text;
my_equipment.product_type_id = Convert.ToInt32(product_type_id.SelectedItem.Value);
my_equipment.created_date = DateTime.Now;
my_equipment.serial_number = serial_number.Text;
my_equipment.Save();
}
catch (Exception err)
{
lblError.Text = err.Message;
}
Edit: Think that I was just too tired last night, it is pretty easy to update. Just use the retrieve function and use the Update() on that.
var equip = Equipment.SingleOrDefault(x => x.id == 1);
lblGeneral.Text = equip.product_description;
equip.product_description = "Test";
equip.Update();
Resolved. View answer above.