Java tutorial
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package com.ucuenca.pentaho.plugin.step; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.jena.atlas.json.JSON; import org.apache.jena.atlas.json.JsonObject; import org.eclipse.jetty.util.thread.ExecutorThreadPool; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.json.JSONException; import org.json.JSONObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.Props; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import javax.net.ssl.HttpsURLConnection; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.QuerySolutionMap; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.ResultSetFormatter; import com.hp.hpl.jena.rdf.model.ModelFactory; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.io.BufferedReader; import java.io.InputStreamReader; import com.hp.hpl.jena.ontology.OntModelSpec; import java.awt.Desktop; import java.net.URI; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.sparql.engine.binding.Binding; import java.util.ArrayList; import java.util.Arrays; /** . * @author Fabian Pealoza Marin * @version 1 */ /** * This class is part of the demo step plug-in implementation. It demonstrates * the basics of developing a plug-in step for PDI. * * The demo step its to configure a elda's instace to do publication of linked * data "Elda Pdi Step". The user may select the name of the new field. */ public class EldaPDIStepDialog extends BaseStepDialog implements StepDialogInterface { /** * The PKG member is used when looking up internationalized strings. The * properties file with localized keys is expected to reside in {the package * of the class specified}/messages/messages_{locale}.properties */ private static Class<?> PKG = EldaPDIStepMeta.class; // for i18n purposes private final static String USER_AGENT = "Mozilla/5.0"; // this is the object the stores the step's settings // the dialog reads the settings from it when opening // the dialog writes the settings to it when confirmed private EldaPDIStepMeta meta; private EldaPDIStepData data; // text field holding the name of the field to add to the row stream private Text wHelloFieldName; private Text wChooseOutput; private Text wTextServName; private Text wTextServPort; private Text wTextHowService; private Text wTextBaseUri; private Button wLoadValues; private Button wChooseDirectory; private Button wOpenBrowser; private Button wPreCatch; private Button wAddFila; private Button wStopService; private Button wCheckService; private Button wAgregarLista; private Button wQuitarLista; private Listener lsReadUri; private Listener lsLoadValues; private Listener lsChooseDirectory; private Listener lsCheckService; private Listener lsStopService; private Listener lsOpenBrowser; private Listener lsPrecatch; private Listener lsAddRow; private Listener lsAgregarLista; private Listener lsQuitarLista; private List singleSelectList; private List mutliSelectList; private ModifyListener lsUpdateInstrucctions; private FormData fdmitabla; private FormData fdmitabla2; private Table table; //entidades private Table table2; //propiedades private static String OS = System.getProperty("os.name").toLowerCase(); private int numt = 2; private static final Logger log = Logger.getLogger(EldaPDIStep.class.getName()); private TableView wAnnTable; private Composite wClassifyComp, wAnnotateComp, wRelationComp; private CTabFolder wTabFolder; private TransMeta transMeta; ArrayList<String> PropiedadesSeleccionadasUsuario = new ArrayList<String>(); ArrayList<String> PropiedadesSeleccionadasNamesUsuario = new ArrayList<String>(); private LinkedList ListSource = new LinkedList<String>(); private LinkedList ListProper = new LinkedList<String>(); private LinkedList ListSourceNames = new LinkedList<String>(); //nombres seleccionados private LinkedList ListProperNames = new LinkedList<String>(); //valores puestos por los usuario private LinkedList ListLabelEntidad = new LinkedList<String>(); //Label por entidad private int indiceUltimaEntidad = -1; private ArrayList<ArrayList<String>> arrayPropiedades = new ArrayList<ArrayList<String>>(); ArrayList<String> propiedadesTodasCargadas = new ArrayList<String>(); //utilizada para el combo private ArrayList combos = new ArrayList(); Thread executorThread; MiHilo1 elHilo = new MiHilo1(); ExecutorTask task = new ExecutorTask(); ArrayList<String> listIndicesPropiedadesCargadas = new ArrayList<String>(); //utilizado todas las propiedades del combo , indices de la entidades ya cargadas /** * The constructor should simply invoke super() and save the incoming meta * object to a local variable, so it can conveniently read and write * settings from/to it. * * @param parent * the SWT shell to open the dialog in * @param in * the meta object holding the step's settings * @param transMeta * transformation description * @param sname * the step name */ public EldaPDIStepDialog(Shell parent, Object in, TransMeta transMeta, String sname) { super(parent, (BaseStepMeta) in, transMeta, sname); meta = (EldaPDIStepMeta) in; this.transMeta = transMeta; } /** * This method is called by Spoon when the user opens the settings dialog of * the step. It should open the dialog and return only once the dialog has * been closed by the user. * * If the user confirms the dialog, the meta object (passed in the * constructor) must be updated to reflect the new step settings. The * changed flag of the meta object must reflect whether the step * configuration was changed by the dialog. * * If the user cancels the dialog, the meta object must not be updated, and * its changed flag must remain unaltered. * * The open() method must return the name of the step after the user has * confirmed the dialog, or null if the user cancelled the dialog. */ public String open() { // store some convenient SWT variables Shell parent = getParent(); Display display = parent.getDisplay(); // SWT code for preparing the dialog shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX); props.setLook(shell); setShellImage(shell, meta); // Save the value of the changed flag on the meta object. If the user // cancels // the dialog, it will be restored to this saved value. // The "changed" variable is inherited from BaseStepDialog changed = meta.hasChanged(); // The ModifyListener used on all controls. It will update the meta // object to // indicate that changes are being made. ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { meta.setChanged(); } }; // ------------------------------------------------------- // // SWT code for building the actual settings dialog // // ------------------------------------------------------- // FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "Elda.Shell.Title")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname = new Label(shell, SWT.RIGHT); wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepName")); props.setLook(wlStepname); fdlStepname = new FormData(); fdlStepname.left = new FormAttachment(0, 0); fdlStepname.right = new FormAttachment(middle, -margin); fdlStepname.top = new FormAttachment(0, margin); wlStepname.setLayoutData(fdlStepname); wStepname = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wStepname.setText(stepname); props.setLook(wStepname); wStepname.addModifyListener(lsMod); fdStepname = new FormData(); fdStepname.left = new FormAttachment(middle, 0); fdStepname.top = new FormAttachment(0, margin); fdStepname.right = new FormAttachment(100, 0); wStepname.setLayoutData(fdStepname); //-------------------fin step name //Label to say Elda Parameters Label wlabelElda = new Label(shell, SWT.RIGHT); wlabelElda.setText(BaseMessages.getString(PKG, "Elda.label.EldaParameters")); props.setLook(wlabelElda); FormData fdlValName1 = new FormData(); fdlValName1.left = new FormAttachment(0, 0); fdlValName1.right = new FormAttachment(middle, -margin); fdlValName1.top = new FormAttachment(wlStepname, margin + 10); wlabelElda.setLayoutData(fdlValName1); // output field value -----SPARQL service Label wlValName = new Label(shell, SWT.RIGHT); wlValName.setText(BaseMessages.getString(PKG, "Elda.FieldName.Label")); props.setLook(wlValName); FormData fdlValName = new FormData(); fdlValName.left = new FormAttachment(0, 0); fdlValName.right = new FormAttachment(middle, -margin); fdlValName.top = new FormAttachment(wlabelElda, margin); // fdlValName.top = new FormAttachment(10, margin); wlValName.setLayoutData(fdlValName); wHelloFieldName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wHelloFieldName); wHelloFieldName.addModifyListener(lsMod); FormData fdValName = new FormData(); fdValName.left = new FormAttachment(middle, 0); // fdValName.right = new FormAttachment(100, 0); fdValName.top = new FormAttachment(wlabelElda, margin); wHelloFieldName.setLayoutData(fdValName); wHelloFieldName.setEditable(true); // ------------ //-------------fin service label y text // precatch data BOTON wPreCatch = new Button(shell, SWT.PUSH); wPreCatch.setText(BaseMessages.getString(PKG, "System.Tooltip.Precatch")); wPreCatch.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.Precatch")); FormData fdwPreCatch = new FormData(); fdwPreCatch = new FormData(); fdwPreCatch.right = new FormAttachment(100, 0); fdwPreCatch.top = new FormAttachment(wlabelElda, margin); wPreCatch.setLayoutData(fdwPreCatch); //---------LOAD VALUES wLoadValues = new Button(shell, SWT.PUSH | SWT.SINGLE | SWT.MEDIUM | SWT.BORDER); wLoadValues.setText(BaseMessages.getString(PKG, "Elda.Load.Tables")); wLoadValues.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.ChooseFile")); FormData fdChooseFile = new FormData(); fdChooseFile = new FormData(); fdChooseFile.right = new FormAttachment(100, 0); fdChooseFile.top = new FormAttachment(wPreCatch, margin); wLoadValues.setLayoutData(fdChooseFile); fdValName.right = new FormAttachment(wPreCatch, 0); //derecha spaql service //--------------base URI---- Label wlabelBaseUri = new Label(shell, SWT.RIGHT); wlabelBaseUri.setText(BaseMessages.getString(PKG, "Elda.label.BaseUri")); props.setLook(wlabelBaseUri); FormData fdlBaseUri = new FormData(); fdlBaseUri.left = new FormAttachment(0, 0); fdlBaseUri.right = new FormAttachment(middle, -margin); fdlBaseUri.top = new FormAttachment(wHelloFieldName, margin + 5); wlabelBaseUri.setLayoutData(fdlBaseUri); // text para service Port wTextBaseUri = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wTextBaseUri); wTextBaseUri.setText(""); // wStepname.addModifyListener(lsMod); FormData fdtextBaseUri = new FormData(); fdtextBaseUri.left = new FormAttachment(middle, 0); fdtextBaseUri.top = new FormAttachment(wHelloFieldName, margin + 5); //fdtextBaseUri.right = new FormAttachment(100, 0); fdtextBaseUri.right = new FormAttachment(wLoadValues, 0); wTextBaseUri.setLayoutData(fdtextBaseUri); // fin base URI ----------- // OK and cancel buttons wOK = new Button(shell, SWT.PUSH); wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); // lista /* singleSelectList = new List(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); mutliSelectList = new List(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); (new Label(shell, SWT.NULL)).setText("SINGLE"); (new Label(shell, SWT.NULL)).setText("MULTI"); String[] items = new String[] { " ", " " }; String[] items2 = new String[] { " ", " " }; for (int i = 0; i < items.length; i++) { singleSelectList.add(items[i]); singleSelectList.add(items[i]); mutliSelectList.add(items2[i]); mutliSelectList.add(items2[i]); } FormData fdlist1 = new FormData(); fdlist1.top = new FormAttachment(wChooseOutput, margin + 5); // fdlist1.left = new FormAttachment(middle, 0); fdlist1.left = new FormAttachment(0, 0); fdlist1.width = 500; fdlist1.height = 250; // ---------------- // botones para agregar la lista wAgregarLista = new Button(shell, SWT.PUSH); wAgregarLista.setText(BaseMessages.getString(PKG, "System.Button.AddList")); FormData fdAL = new FormData(); fdAL.top = new FormAttachment(this.wChooseOutput, margin + 5); fdAL.left = new FormAttachment(singleSelectList, margin + 5); wAgregarLista.setLayoutData(fdAL); wQuitarLista = new Button(shell, SWT.PUSH); wQuitarLista.setText(BaseMessages.getString(PKG, "System.Button.DellList")); FormData fdDL = new FormData(); fdDL.top = new FormAttachment(this.wAgregarLista, margin + 5); fdDL.left = new FormAttachment(singleSelectList, margin + 5); wQuitarLista.setLayoutData(fdDL); // ------------------------- FormData fdlist2 = new FormData(); fdlist2.top = new FormAttachment(wChooseOutput, margin + 5); fdlist2.right = new FormAttachment(100, 0); // fdlist2.left = new FormAttachment(singleSelectList, margin + 5); fdlist2.left = new FormAttachment(wAgregarLista, margin + 5); fdlist2.height = 250; mutliSelectList.setLayoutData(fdlist2); singleSelectList.setLayoutData(fdlist1);*/ // GridLayout gridLayout = new GridLayout(2, true); // shell.setLayout(gridLayout); /** * // checkbox star service wCheckService = new Button(shell, SWT.PUSH); * props.setLook(wCheckService); * * wCheckService.setText(BaseMessages.getString(PKG, * "FusekiLoader.Check.label")); * wCheckService.setToolTipText(BaseMessages.getString(PKG, * "FukekiLoader.Check.tooltip")); FormData fdBotonCheck = new * FormData(); fdBotonCheck = new FormData(); fdBotonCheck.right = new * FormAttachment(middle, -margin); fdBotonCheck.top = new * FormAttachment(wlValNameO, margin + 5); // fdBotonCheck.right = new * FormAttachment(wOpenBrowser, margin); * wCheckService.setLayoutData(fdBotonCheck); * * wStopService = new Button(shell, SWT.PUSH); * props.setLook(wStopService); * * wStopService.setText(BaseMessages.getString(PKG, * "FusekiLoader.Stopservice")); * * FormData fdBotonstop = new FormData(); fdBotonstop = new FormData(); * fdBotonstop.left = new FormAttachment(wCheckService, margin); * fdBotonstop.top = new FormAttachment(wlValNameO, margin + 5); * wStopService.setEnabled(false); * wStopService.setLayoutData(fdBotonstop); * * wOpenBrowser = new Button(shell, SWT.PUSH); * props.setLook(wOpenBrowser); * * wOpenBrowser.setText(BaseMessages.getString(PKG, * "FusekiLoader.BotonBrowser")); * wOpenBrowser.setToolTipText(BaseMessages.getString(PKG, * "FukekiLoader.BotonBrowser.tooltip")); FormData fdBotonBrowser = new * FormData(); fdBotonBrowser = new FormData(); fdBotonBrowser.left = * new FormAttachment(wStopService, margin); fdBotonBrowser.top = new * FormAttachment(wlValNameO, margin + 5); * wOpenBrowser.setLayoutData(fdBotonBrowser); * wOpenBrowser.setEnabled(false); */ //--------------- label Entidades Label wlabelEntidades = new Label(shell, SWT.RIGHT); wlabelEntidades.setText(BaseMessages.getString(PKG, "Elda.label.Entitidadeslabel")); wlabelEntidades.setAlignment(SWT.LEFT); props.setLook(wlabelEntidades); FormData fdlVEntidades = new FormData(); fdlVEntidades.left = new FormAttachment(1, 0); fdlVEntidades.top = new FormAttachment(wTextBaseUri, margin); fdlVEntidades.width = 700; wlabelEntidades.setLayoutData(fdlVEntidades); //--------------- label Propiedades Label wlabelPropiedades = new Label(shell, SWT.RIGHT); wlabelPropiedades.setText(" " + BaseMessages.getString(PKG, "Elda.label.Propiedadeslabel")); wlabelPropiedades.setAlignment(SWT.LEFT); props.setLook(wlabelPropiedades); FormData fdlVPropiedades = new FormData(); fdlVPropiedades.top = new FormAttachment(wTextBaseUri, margin); fdlVPropiedades.right = new FormAttachment(100, 0); // fdlist2.left = new FormAttachment(singleSelectList, margin + 5); fdlVPropiedades.left = new FormAttachment(wlabelEntidades, margin + 5); wlabelPropiedades.setLayoutData(fdlVPropiedades); // ------------------------------------ tabla 1------------------------------------------------- table = new Table(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); table.setLinesVisible(true); table.setHeaderVisible(true); Button selectAll = new Button(parent, SWT.PUSH); //selectAll.setFont(FontUtils.getMsSansSerifFont()); //selectAll.setLayoutData(gridData); selectAll.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { table.selectAll(); } }); String[] titles = { BaseMessages.getString(PKG, "Elda.table.col1"), BaseMessages.getString(PKG, "Elda.table.col2"), BaseMessages.getString(PKG, "Elda.table.col3") }; for (int i = 0; i < titles.length; i++) { TableColumn column = new TableColumn(table, SWT.NONE); if (i == 0) { column.setText(titles[i] + " "); } else { column.setText(titles[i]); } column.pack(); } //Listener cuando se se seleccion la tabla 1 table.addListener(SWT.Selection, new Listener() { //@Override public void handleEvent(Event event) { String string = event.detail == SWT.CHECK ? "Checked" : "Selected"; System.out.println(event.item + " " + string); //comentar //cargo valore en la segunda tabla TableItem fila1 = table.getItem(table.getSelectionIndex()); if ((fila1.getChecked() && indiceUltimaEntidad != table.getSelectionIndex()) || table.getItemCount() == 1) { //se carga de nuevo si seleccion un entidad destinta y activo el check recorrertabla2();//antes de cargar una nueva entidad guardo la configuracion de la entidad anterior indiceUltimaEntidad = table.getSelectionIndex(); //actualizo ultimo indice System.out.println("listar propiedades de " + fila1.getText()); /* String mitem = event.item.toString(); String urlEntidad = ""; int k1=0;int k2=0; for (int i=0; i < mitem.length();i++){ if (mitem.substring(i,i+1).compareTo("{")==0) {k1 =i+1;} if (mitem.substring(i,i+1).compareTo("}")==0) {k2 =i;} } urlEntidad = mitem.substring(k1, k2);*/ String urlEntidad = fila1.getText().trim(); //url de la entidad cargarTablaPropiedadesEntidad(urlEntidad); //cargar combo por entidad TableItem[] items = table.getItems(); TableEditor editor = new TableEditor(table); CCombo combo = new CCombo(table, SWT.NONE); for (int i = 0; i < propiedadesTodasCargadas.size(); i++) { combo.add(propiedadesTodasCargadas.get(i)); } combo.setEditable(false); Integer indexProper = obtenerPropiedadSeleccionada(table.getSelectionIndex()); if (indexProper > 0) { combo.select(indexProper); } combos.add(combo); editor.grabHorizontal = true; items[table.getSelectionIndex()].setData(editor); editor.setEditor(combo, items[table.getSelectionIndex()], 2); // fin carga el combo } else if (indiceUltimaEntidad != table.getSelectionIndex() && !fila1.getChecked()) { //si cambio a una entidad no seleccionada borraremos la tabla 2. recorrertabla2();//antes de cargar una nueva entidad guardo la configuracion de la entidad anterior table2.removeAll(); indiceUltimaEntidad = -1; //actualizo ultimo indice cuando selecciona una no cargada } } /** * Metodo para cargar la seleccion del meta en el combo la primera vez * @param selectionIndex * @return */ private Integer obtenerPropiedadSeleccionada(int selectionIndex) { // TODO Auto-generated method stub Integer resp = -1; System.out.println("meta.getListLabelxEntidad()" + meta.getListLabelxEntidad()); if (meta.getListLabelxEntidad() != null) { if ((meta.getListLabelxEntidad().compareTo("[]") != 0) && (meta.getListLabelxEntidad() != null)) { ArrayList<String> ListLabelxEntidad = cleanspaces(meta.getListLabelxEntidad()); for (int i = 0; i < propiedadesTodasCargadas.size(); i++) { if (selectionIndex < ListLabelxEntidad.size()) { if (propiedadesTodasCargadas.get(i).trim() .compareTo(ListLabelxEntidad.get(selectionIndex)) == 0) { resp = i; } } } } } return resp; } }); final int EDITABLECOLUMN = 1; final TableEditor editor = new TableEditor(table); table.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Clean up any previous editor control Control oldEditor = editor.getEditor(); if (oldEditor != null) oldEditor.dispose(); // Identify the selected row TableItem item = (TableItem) e.item; if (item == null) return; // The control that will be the editor must be a child of the Table Text newEditor = new Text(table, SWT.NONE); newEditor.setText(item.getText(EDITABLECOLUMN)); newEditor.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { Text text = (Text) editor.getEditor(); editor.getItem().setText(EDITABLECOLUMN, text.getText()); } }); newEditor.selectAll(); newEditor.setFocus(); editor.setEditor(newEditor, item, EDITABLECOLUMN); } }); // posicionar tabla 1 fdmitabla = new FormData(); fdmitabla.left = new FormAttachment(1, 0); fdmitabla.top = new FormAttachment(wlabelEntidades, margin + 10); fdmitabla.height = 250; fdmitabla.width = 700; table.setLayoutData(fdmitabla); // dar numero de filas inicial de filas en 4 for (int i = 0; i < 4; i++) { new TableItem(table, SWT.NONE); } //-------------------------tabla 1 -------------------------- //----------------------tabla 2 table2 = new Table(shell, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); table2.setLinesVisible(true); table2.setHeaderVisible(true); Button selectAll2 = new Button(parent, SWT.PUSH); //selectAll.setFont(FontUtils.getMsSansSerifFont()); //selectAll.setLayoutData(gridData); selectAll2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { table2.selectAll(); } }); //dos columnas String[] titles2 = { BaseMessages.getString(PKG, "Elda.table.Column"), BaseMessages.getString(PKG, "Elda.table.col2"), }; //lleno el nombre de las columnas for (int i = 0; i < titles2.length; i++) { TableColumn column = new TableColumn(table2, SWT.NONE); if (i == 0) { column.setText(titles2[i] + " "); } else { column.setText(titles2[i]); } column.pack(); } //seleccionan tabla2 table2.addListener(SWT.Selection, new Listener() { //@Override public void handleEvent(Event event) { String string = event.detail == SWT.CHECK ? "Checked" : "Selected"; System.out.println(event.item + " " + string); //comentar //TableItem fila2 = table2.getItem(table2.getSelectionIndex()); /*if (fila2.getChecked()){ //si se ha seleccionada se pasara a la lista PropiedadesSeleccionadasUsuario.add(fila2.getText()); PropiedadesSeleccionadasNamesUsuario.add(fila2.getText(1)); }else { //lo deselecciona lo quita de la lista for (int i =0; i <PropiedadesSeleccionadasUsuario.size();i++){ if(PropiedadesSeleccionadasUsuario.get(i).compareTo(fila2.getText())==0){ PropiedadesSeleccionadasUsuario.remove(i); PropiedadesSeleccionadasNamesUsuario.remove(i); } } } */ System.out.println("table selection index " + table2.getSelectionIndex()); if (table2.getSelectionIndex() >= 0) { //validacion mac TableItem fila2 = table2.getItem(table2.getSelectionIndex()); if (!fila2.getChecked()) { //lo deselecciona lo quita de la lista for (int i = 0; i < PropiedadesSeleccionadasUsuario.size(); i++) { if (PropiedadesSeleccionadasUsuario.get(i).trim().compareTo(fila2.getText()) == 0) { PropiedadesSeleccionadasUsuario.remove(i); if (PropiedadesSeleccionadasNamesUsuario.size() > i) { PropiedadesSeleccionadasNamesUsuario.remove(i); } } } } } } }); //editable column 1 en table2 final int EDITABLECOLUMN2 = 1; final TableEditor editor2 = new TableEditor(table2); table2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Clean up any previous editor control Control oldEditor = editor2.getEditor(); if (oldEditor != null) oldEditor.dispose(); // Identify the selected row TableItem item = (TableItem) e.item; if (item == null) return; // The control that will be the editor must be a child of the Table Text newEditor = new Text(table2, SWT.NONE); newEditor.setText(item.getText(EDITABLECOLUMN2)); newEditor.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { Text text = (Text) editor2.getEditor(); editor2.getItem().setText(EDITABLECOLUMN2, text.getText()); } }); newEditor.selectAll(); newEditor.setFocus(); editor2.setEditor(newEditor, item, EDITABLECOLUMN2); } }); // posicionar tabla 2 fdmitabla2 = new FormData(); fdmitabla2.top = new FormAttachment(wlabelEntidades, margin + 10); fdmitabla2.right = new FormAttachment(100, 0); // fdlist2.left = new FormAttachment(singleSelectList, margin + 5); fdmitabla2.left = new FormAttachment(table, margin + 5); fdmitabla2.height = 250; table2.setLayoutData(fdmitabla2); // dar numero de filas inicial de filas en 4 for (int i = 0; i < 4; i++) { new TableItem(table2, SWT.NONE); } //------------------------------ // ---------------------------------------- // label to choose output Label wlValNameO = new Label(shell, SWT.RIGHT); wlValNameO.setText(BaseMessages.getString(PKG, "Elda.FieldName.LabelOutput")); props.setLook(wlValNameO); FormData fdlValNameO = new FormData(); fdlValNameO.left = new FormAttachment(0, 0); fdlValNameO.right = new FormAttachment(middle, -margin); // fdlValNameO.top = new FormAttachment(wPreCatch, margin + 5); fdlValNameO.top = new FormAttachment(table2, margin + 5); // fdlValName.top = new FormAttachment(10, margin); wlValNameO.setLayoutData(fdlValNameO); // text to output wChooseOutput = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wChooseOutput); // wChooseOutput.addModifyListener(lsMod); FormData fdValNameO = new FormData(); fdValNameO.left = new FormAttachment(middle, 0); // fdValNameO.right = new FormAttachment(100, 0); // fdValNameO.top = new FormAttachment(wPreCatch, margin + 5); fdValNameO.top = new FormAttachment(table2, margin + 5); wChooseOutput.setLayoutData(fdValNameO); wChooseOutput.setEditable(false); // booton to choose directory wChooseDirectory = new Button(shell, SWT.PUSH | SWT.SINGLE | SWT.MEDIUM | SWT.BORDER); props.setLook(wChooseDirectory); wChooseDirectory.setText(BaseMessages.getString(PKG, "FusekiLoader.Output.ChooseDirectory")); wChooseDirectory.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.ChooseDirectory")); FormData fdChooseDirectory = new FormData(); fdChooseDirectory = new FormData(); fdChooseDirectory.right = new FormAttachment(100, 0); // fdChooseDirectory.top = new FormAttachment(wPreCatch, margin + 5); fdChooseDirectory.top = new FormAttachment(table2, margin + 5); wChooseDirectory.setLayoutData(fdChooseDirectory); fdValNameO.right = new FormAttachment(wChooseDirectory, -margin); wChooseOutput.setLayoutData(fdValNameO); //-------------------------------- //------------------------------- HOw start service Label wLabelHowService = new Label(shell, SWT.RIGHT); wLabelHowService.setText(BaseMessages.getString(PKG, "FusekiLoader.label.HowService")); props.setLook(wLabelHowService); FormData fdlHowService = new FormData(); fdlHowService.left = new FormAttachment(0, 0); fdlHowService.right = new FormAttachment(middle, -margin); // fdlHowService.top = new FormAttachment(wCheckService, margin + 5); fdlHowService.top = new FormAttachment(wChooseOutput, margin + 5); wLabelHowService.setLayoutData(fdlHowService); // text para service Port wTextHowService = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); wTextHowService.setData(new GridData(GridData.FILL_BOTH)); wTextHowService.setText("go to " + meta.getDirectory() + "/elda , execute elda with the next command 'java -jar start.jar' , now in your browser go to the url : http://localhost:8080/" + ObtenerNombreUrl(wTextBaseUri.getText().trim()) + "/ + and an entity label that your choice "); props.setLook(wTextHowService); // wStepname.addModifyListener(lsMod); FormData fdtextservHow = new FormData(); fdtextservHow.left = new FormAttachment(middle, 0); //fdtextservHow.top = new FormAttachment(singleSelectList, margin + 10); fdtextservHow.top = new FormAttachment(wChooseOutput, margin + 10); fdtextservHow.right = new FormAttachment(100, 0); wTextHowService.setLayoutData(fdtextservHow); wTextHowService.setEditable(false); // ---------------------------- BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, wTextHowService); // Add listeners for cancel and OK lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; lsLoadValues = new Listener() { public void handleEvent(Event e) { if (!wHelloFieldName.getText().trim().isEmpty()) { cargartablas(); } else { MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.ERROR.ServiceNoSet")); dialog.open(); } } }; lsChooseDirectory = new Listener() { public void handleEvent(Event e) { ChooseDirectory(); } }; lsCheckService = new Listener() { public void handleEvent(Event e) { StartService(); } }; lsStopService = new Listener() { public void handleEvent(Event e) { stop(); } }; lsUpdateInstrucctions = new ModifyListener() { public void handleEvent(Event e) { UpdateInstrucctions(); } public void modifyText(ModifyEvent arg0) { UpdateInstrucctions(); } }; lsOpenBrowser = new Listener() { public void handleEvent(Event e) { OpenBrowser(); } }; lsPrecatch = new Listener() { public void handleEvent(Event e) { PreCargar(); } }; wCancel.addListener(SWT.Selection, lsCancel); wOK.addListener(SWT.Selection, lsOK); wLoadValues.addListener(SWT.Selection, lsLoadValues); // wOpenBrowser.addListener(SWT.Selection, lsOpenBrowser); // wCheckService.addListener(SWT.Selection, lsCheckService); this.wChooseDirectory.addListener(SWT.Selection, lsChooseDirectory); this.wPreCatch.addListener(SWT.Selection, lsPrecatch); //this.wAgregarLista.addListener(SWT.Selection, lsAgregarLista); //this.wQuitarLista.addListener(SWT.Selection, lsQuitarLista); // this.wStopService.addListener(SWT.Selection, lsStopService); /* * wTextServPort.addListener(SWT.Verify, new Listener() { public void * handleEvent(Event e) { String string = e.text; char[] chars = new * char[string.length()]; string.getChars(0, chars.length, chars, 0); * for (int i = 0; i < chars.length; i++) { if (!('0' <= chars[i] && * chars[i] <= '9')) { e.doit = false; return; } } } }); */ // wTextServName.addModifyListener(lsUpdateInstrucctions); // wTextServPort.addModifyListener(lsUpdateInstrucctions); wChooseOutput.addModifyListener(lsUpdateInstrucctions); // default listener (for hitting "enter") lsDef = new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wStepname.addSelectionListener(lsDef); wHelloFieldName.addSelectionListener(lsDef); // Detect X or ALT-F4 or something that kills this window and cancel the // dialog properly shell.addShellListener(new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } }); // Set/Restore the dialog size based on last position on screen // The setSize() method is inherited from BaseStepDialog setSize(); // populate the dialog with the values from the meta object populateDialog(); // restore the changed flag to original value, as the modify listeners // fire during dialog population meta.setChanged(changed); // open dialog and enter event loop shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } // at this point the dialog has closed, so either ok() or cancel() have // been executed // The "stepname" variable is inherited from BaseStepDialog return stepname; } protected void UpdateInstrucctions() { /* * TableItem miti = table.getItem(0); * meta.setFuDataset(miti.getText(1)); * * TableItem miti2 = table.getItem(1); * meta.setFuGraph(miti2.getText(1)); * * TableItem miti3 = table.getItem(2); * meta.setFuQuery(miti3.getText(1)); String cmd = * "; ./fuseki-server --port="; if (isWindows()) { cmd = * "; fuseki-server --port="; } wTextHowService .setText( * "To start the service,first run spoon as Administrator, go to the terminal and type: cd " * + wChooseOutput.getText() + "/fuseki" + cmd + wTextServPort.getText() * + * " --config=config.ttl To access the service go to: http://localhost:" * + wTextServPort.getText() + * "/control-panel.tpl To perform some queries make a request to http://localhost:" * + wTextServPort.getText() + "/" + this.wTextServName.getText() + * "/query?query=" + meta.getFuQuery() + ""); * * try { File file = new File( * "plugins/steps/FusekiLoader/fuseki/README_to_PLAY.TXT"); * BufferedWriter output = new BufferedWriter(new FileWriter(file)); * output.write(wTextHowService.getText()); output.close(); } catch * (IOException e) { e.printStackTrace(); } */ } /** * This helper method puts the step configuration stored in the meta object * and puts it into the dialog controls. */ private void populateDialog() { wStepname.selectAll(); if (meta.getOutputField() != null) { wHelloFieldName.setText(meta.getOutputField().trim()); } if (meta.getDirectory() != null) { wChooseOutput.setText(meta.getDirectory().trim()); } if (meta.getEbaseUri() != null) { wTextBaseUri.setText(meta.getEbaseUri().trim()); } //cargo los valores de las tablas que seleccion cuando dio ok ArrayList<String> myListSelect; myListSelect = cleanspaces(meta.getListSelect()); ArrayList<String> myListSelectNames; myListSelectNames = cleanspaces(meta.getListSelectNames()); ArrayList<String> myListProper; myListProper = cargaListaPropiedades(meta.getListProper()); PropiedadesSeleccionadasUsuario = cargaListaPropiedades(meta.getListProper()); ArrayList<String> myListProperNames; myListProperNames = cargaListaPropiedades(meta.getListProperNames()); PropiedadesSeleccionadasNamesUsuario = cargaListaPropiedades(meta.getListProperNames()); //System.out.println("##### populate proper1 "+PropiedadesSeleccionadasUsuario.size()); //System.out.println("##### populate proper2 "+PropiedadesSeleccionadasNamesUsuario.size()); ArrayList<String> myListEntidadesCargadas; myListEntidadesCargadas = cleanspaces(meta.getListEntidadesCargadas()); if (!meta.getOutputField().trim().isEmpty()) { // cargartablas(); //carga las tablas consultando en la base } //despues de cargar las tablas cargo los valores seleccionados por el usuario tabla1 //cargo las entidades consultadas anteriormente if (!myListSelect.get(0).trim().isEmpty() && myListSelect.size() >= 1) { table.removeAll(); for (int l = 0; l < myListEntidadesCargadas.size(); l++) { new TableItem(table, SWT.NONE); TableEditor meditor1 = new TableEditor(table); TableItem miti = table.getItem(l); miti.setText(0, myListEntidadesCargadas.get(l)); } } //seteo las configuraciones del meta if (!myListSelect.get(0).trim().isEmpty() && myListSelect.size() >= 1) { for (int k = 0; k < table.getItemCount(); k++) { TableItem fila = table.getItem(k); for (int l = 0; l < myListSelect.size(); l++) { if (fila.getText().trim().compareTo(myListSelect.get(l).trim()) == 0) { //si es la entidad era seleccionada la activo el check y le doy el valor fila.setChecked(true); if (l < myListSelectNames.size()) { //validacion exista el nombre fila.setText(1, myListSelectNames.get(l)); } //cargar el combo valores del meta //cargar combo por entidad if (meta.getPropiedadesTodasCargadas() != null && meta.getPropiedadesTodasCargadas() != "[]") { TableItem[] items = table.getItems(); TableEditor editor = new TableEditor(table); CCombo combo = new CCombo(table, SWT.NONE); arrayPropiedades = obtenerTodasPropiedadesIndices(meta.getPropiedadesTodasCargadas()); // para tener cargado lo del meta System.out.println("entidad " + k + " propiedades " + arrayPropiedades); ArrayList<String> PropiedadesaCargar = new ArrayList<String>(); PropiedadesaCargar = obtenerPropiedadesPorIndice( obtenerTodasPropiedadesIndices(meta.getPropiedadesTodasCargadas()), k); //solo las propiedades correspondi for (int i = 0; i < PropiedadesaCargar.size(); i++) { //for (int i=0;i<propiedadesTodasCargadas.size();i++){ combo.add(PropiedadesaCargar.get(i)); } combo.setEditable(false); Integer indexProper = obtenerPropiedadSeleccionada(l, PropiedadesaCargar); if (indexProper > 0) { combo.select(indexProper); } combos.add(combo); // combos.set(k, combo); editor.grabHorizontal = true; items[k].setData(editor); //k es el id dentro de la tabla 1 al cual se debe poner el combo editor.setEditor(combo, items[k], 2); } // fin carga el combo //-----------fin cargar los combos } //fila.getText().trim().compareTo(myListSelect.get(l).trim()) } } } wTextHowService.setText("go to " + meta.getDirectory() + "/elda , execute elda with the next command 'java -jar start.jar' , now in your browser go to the url : http://localhost:8080/" + ObtenerNombreUrl(wTextBaseUri.getText().trim()) + "/ + and an entity label that your choice "); } /** * Called when the user cancels the dialog. */ private void cancel() { // The "stepname" variable will be the return value for the open() // method. // Setting to null to indicate that dialog was cancelled. stepname = null; // Restoring original "changed" flag on the met aobject meta.setChanged(changed); // close the SWT dialog window dispose(); } /** * Called when the user confirms the dialog */ private void ok() { // The "stepname" variable will be the return value for the open() // method. boolean validado = true; // Setting to step name from the dialog control stepname = wStepname.getText(); // Setting the settings to the meta object if (wHelloFieldName.getText().trim().isEmpty()) { //Validacion servicio MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "FusekiLoader.input.empty")); dialog.open(); wHelloFieldName.setFocus(); validado = false; } if (wChooseOutput.getText().trim().isEmpty()) { //validacion Directorio de Salida MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "FusekiLoader.output.empty")); dialog.open(); wChooseOutput.setFocus(); validado = false; } if (wTextBaseUri.getText().trim().isEmpty()) { //validacion Base URI MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.BaseUri.empty")); dialog.open(); wTextBaseUri.setFocus(); validado = false; } LinkedList listEntidades = new LinkedList<String>(); //todas las cargadas // pasar la lista seleccionada ListSource.clear(); ListSourceNames.clear(); for (int k = 0; k < table.getItemCount(); k++) { TableItem fila = table.getItem(k); //System.out.println(fila.getChecked()+" "+fila.getText()); fila.getText(1); if (fila.getChecked()) { //si se ha seleccionada se pasara a la lista ListSource.add(fila.getText()); ListSourceNames.add(fila.getText(1)); //nombre puesto x el usuario } listEntidades.add(fila.getText()); //entidades cargadas /* String propiedad = ""; if (!combos.isEmpty() && combos.size()>k){ CCombo cmb = (CCombo)combos.get(k); propiedad = cmb.getText(); // propiedad System.out.println("LABEL ENTIDAD "+propiedad); } ListLabelEntidad.add(propiedad); * */ } //propiedad sort //label por entidad agrego el item seleccionado del combo for (int i = 0; i < combos.size(); i++) { String propiedad = ""; if (!combos.isEmpty() && combos.size() > i) { CCombo cmb = (CCombo) combos.get(i); propiedad = cmb.getText(); // propiedad System.out.println("LABEL ENTIDAD " + propiedad); } ListLabelEntidad.add(propiedad); } // //--------------- recorrertabla2();//guardo los valores de la tabla 2. meta.setListSelect(ListSource.toString()); meta.setListSelectNames(ListSourceNames.toString()); meta.setListProper(PropiedadesSeleccionadasUsuario.toString()); meta.setListProperNames(PropiedadesSeleccionadasNamesUsuario.toString()); System.out.println("##### ok proper1 " + PropiedadesSeleccionadasUsuario.size()); System.out.println("##### ok proper2 " + PropiedadesSeleccionadasNamesUsuario.size()); // close the SWT dialog window meta.setOutputField(wHelloFieldName.getText()); meta.setServicio(wHelloFieldName.getText()); meta.setDirectory(wChooseOutput.getText()); meta.setEbaseUri(wTextBaseUri.getText().trim()); meta.setListEntidadesCargadas(listEntidades.toString()); meta.setChanged(); if (validado) { // si todas las validacion son correctas se iniciara el proceso meta.setValidate("true"); dispose(); // solo cuando esta todo correcto dejo cerrar la ventana } else { meta.setValidate("false"); } meta.setListLabelxEntidad(ListLabelEntidad.toString()); System.out.println("LABEL ENTIDAD " + ListLabelEntidad.toString()); meta.setPropiedadesTodasCargadas(arrayPropiedades.toString()); System.out.println(" PropiedadesTodasCargadas " + arrayPropiedades.toString()); System.out.println(" Combos " + combos.toString()); } //eliminar private void LoadFile() { try { /* DirectoryDialog dialog = new DirectoryDialog(shell, SWT.OPEN); dialog.setText(BaseMessages.getString(PKG, "Elda.FieldName.ChooseEndpoint")); String result = dialog.open(); wHelloFieldName.setText(dialog.getFilterPath() ); meta.setInputName(dialog.getFilterPath()); */ FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setText(BaseMessages.getString(PKG, "FusekiLoader.FieldName.Choose")); String result = dialog.open(); wHelloFieldName.setText(dialog.getFilterPath() + "/" + dialog.getFileName()); meta.setInputName(dialog.getFileName()); cargartablas(); //singleSelectList.setRedraw(true); //mutliSelectList.setRedraw(true); } catch (Exception e) { log.log(Level.SEVERE, e.toString(), e); } } /* funcion para cargar tablas con las entidades y propiedades del modelo*/ public void cargartablas() { meta.setListSelect(ListSource.toString()); meta.setListProper(ListProper.toString()); ArrayList<String> propiedades = new ArrayList<String>(); ArrayList<String> objetos = new ArrayList<String>(); //Servicio = "http://localhost:3030/myservice/query"; /* String[] schemes = {"http","https"}; // DEFAULT schemes = "http", "https", "ftp" UrlValidator urlValidator = new UrlValidator(schemes); if (urlValidator.isValid("ftp://foo.bar.com/")) { System.out.println("url is valid"); } else { System.out.println("url is invalid"); }*/ //validacion URL servicio y acceso Boolean urlCorrecto = true; Boolean urlAcceso = true; try { URL url = new URL(wHelloFieldName.getText().trim()); URLConnection conn = url.openConnection(); conn.connect(); } catch (MalformedURLException e) { // URL mal formada logBasic("URL " + wHelloFieldName.getText() + " malformada "); System.out.println("URL " + wHelloFieldName.getText() + " malformada "); urlCorrecto = false; MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.url.malformed") + wHelloFieldName.getText()); dialog.open(); wHelloFieldName.setFocus(); } catch (IOException e) { // no hay conexion logBasic("Servicio a consultar caido " + wHelloFieldName.getText()); System.out.println("Servicio a consultar caido " + wHelloFieldName.getText()); urlAcceso = false; MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.url.inalcanzable") + wHelloFieldName.getText()); dialog.open(); wHelloFieldName.setFocus(); } if (urlCorrecto && urlAcceso) { logBasic("Servicio a consultar " + wHelloFieldName.getText()); //objetos = ConsultarFuseki(wHelloFieldName.getText()); propiedades = ConsultarFusekiPropiedades(wHelloFieldName.getText().trim()); objetos = ConsultarFuseki(wHelloFieldName.getText().trim()); //objetos = this.listarEntidadesRdf((String) wHelloFieldName // .getText()); //propiedades = listarPropiedades((String) wHelloFieldName.getText()); ArrayList<String> EntidadesSeleccionadas = new ArrayList<String>(); ArrayList<String> PropiedadesSeleccionadas = new ArrayList<String>(); ArrayList<String> EntidadesSeleccionadasNames = new ArrayList<String>(); ArrayList<String> PropiedadesSeleccionadasNames = new ArrayList<String>(); Boolean esel = false; //entidad fue seleccionada Boolean psel = false; //propiedad seleccionada if ((meta.getListSelect().compareTo("[]") != 0) && (meta.getListSelect() != null)) { EntidadesSeleccionadas = cleanspaces(meta.getListSelect()); EntidadesSeleccionadasNames = cleanspaces(meta.getListSelectNames()); esel = true; } if ((meta.getListProper().compareTo("[]") != 0) && (meta.getListProper() != null)) { psel = true; PropiedadesSeleccionadas = cleanspaces(meta.getListProper()); PropiedadesSeleccionadasNames = cleanspaces(meta.getListProperNames()); } //Cargando la tabla 1 table.removeAll(); //entidades for (int i = 0; i < objetos.size(); i++) { //if(i>=4){new TableItem(table, SWT.NONE);} //crear item suficientes new TableItem(table, SWT.NONE); TableEditor meditor1 = new TableEditor(table); TableItem miti = table.getItem(i); miti.setText(0, (String) objetos.get(i)); if (esel) { for (int k = 0; k < EntidadesSeleccionadas.size(); k++) { System.out.println(miti.getText() + " " + EntidadesSeleccionadas.get(k)); if (miti.getText().compareTo(EntidadesSeleccionadas.get(k)) == 0) { miti.setChecked(true); miti.setText(1, EntidadesSeleccionadasNames.get(k)); } } } meditor1.setItem(miti); } if (table.getItemCount() > 1) { //por defecto seleccion table.setSelection(0); //selecciono el primer elemento //table.select(arg0) table2.removeAll(); TableItem fila1 = table.getItem(table.getSelectionIndex()); if (!fila1.getText().isEmpty()) { //si no esta vacio el valor de la primera fila tabla1 fila1.setChecked(true); String urlEntidad = fila1.getText(); cargarTablaPropiedadesEntidad(urlEntidad); //propiedadesTodasCargadas } } //table2.removeAll(); //propiedades /* for (int i = 0; i < propiedades.size(); i++) { new TableItem(table2, SWT.NONE); TableEditor meditor2 = new TableEditor(table2); TableItem miti2 = table2.getItem(i); miti2.setText(0, (String) propiedades.get(i)); if(psel){ for(int k =0; k < PropiedadesSeleccionadas.size();k++) { if(miti2.getText().compareTo(PropiedadesSeleccionadas.get(k))==0){ miti2.setChecked(true); miti2.setText(1, PropiedadesSeleccionadasNames.get(k)); } } } meditor2.setItem(miti2); //singleSelectList.add((String) propiedades.get(i), i); } */ } } public void recorrertabla2() { ArrayList<String> listProper = new ArrayList<String>(); ArrayList<String> listProperNames = new ArrayList<String>(); for (int i = 0; i < table2.getItemCount(); i++) { TableItem fila2 = table2.getItem(i); if (fila2.getChecked()) { //si se ha seleccionada se pasara a la lista listProper.add(fila2.getText()); listProperNames.add(fila2.getText(1)); //nombre asignado por el usuario } } //obtengo del listado for (int i = 0; i < listProper.size(); i++) { int band = 0; for (int j = 0; j < PropiedadesSeleccionadasUsuario.size(); j++) { if (listProper.get(i).trim().compareTo(PropiedadesSeleccionadasUsuario.get(j).trim()) == 0) { band = 1; //si existian antes actualizo el valor if (PropiedadesSeleccionadasNamesUsuario.size() > j) { PropiedadesSeleccionadasNamesUsuario.set(j, listProperNames.get(i).trim()); } } } //si no existian antes simplemente agrego if (band == 0) { PropiedadesSeleccionadasUsuario.add(listProper.get(i).trim()); PropiedadesSeleccionadasNamesUsuario.add(listProperNames.get(i).trim()); } } } /** * Metodo para cargar las propiedades por entidad */ public void cargarTablaPropiedadesEntidad(String UrlEntidad) { ArrayList<String> propiedades = new ArrayList<String>(); //validacion URL servicio y acceso Boolean urlCorrecto = true; Boolean urlAcceso = true; try { URL url = new URL(wHelloFieldName.getText().trim()); URLConnection conn = url.openConnection(); conn.connect(); } catch (MalformedURLException e) { // URL mal formada logBasic("URL " + wHelloFieldName.getText() + " malformada "); System.out.println("URL " + wHelloFieldName.getText() + " malformada "); urlCorrecto = false; MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.url.malformed") + wHelloFieldName.getText()); dialog.open(); wHelloFieldName.setFocus(); } catch (IOException e) { // no hay conexion logBasic("Servicio a consultar caido " + wHelloFieldName.getText()); System.out.println("Servicio a consultar caido " + wHelloFieldName.getText()); urlAcceso = false; MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "Elda.url.inalcanzable") + wHelloFieldName.getText()); dialog.open(); wHelloFieldName.setFocus(); } if (urlCorrecto && urlAcceso) { //cuando hay servicio procedo a consultar //envio url del servicio y la url de la entidad propiedades = ConsultarPropiedadesXentidad(wHelloFieldName.getText().trim(), UrlEntidad); propiedadesTodasCargadas = propiedades; ArrayList<String> PropiedadesSeleccionadas = new ArrayList<String>(); ArrayList<String> PropiedadesSeleccionadasNames = new ArrayList<String>(); Boolean psel = false; //propiedad seleccionada if (!PropiedadesSeleccionadasUsuario.isEmpty()) { psel = true; //si esta vacio antes lo carga con todos los valores } table2.removeAll(); //propiedades for (int i = 0; i < propiedades.size(); i++) { new TableItem(table2, SWT.NONE); TableEditor meditor2 = new TableEditor(table2); TableItem miti2 = table2.getItem(i); miti2.setText(0, (String) propiedades.get(i)); //cargo la propiedad if (psel) { for (int k = 0; k < PropiedadesSeleccionadasUsuario.size(); k++) { if (miti2.getText().trim().compareTo(PropiedadesSeleccionadasUsuario.get(k).trim()) == 0) { // comparo para ver si son las propiedades seleccionadas miti2.setChecked(true); if (k < PropiedadesSeleccionadasNamesUsuario.size()) { //validacion exista nombre para esa propiedad miti2.setText(1, PropiedadesSeleccionadasNamesUsuario.get(k).trim()); } } } } meditor2.setItem(miti2); //singleSelectList.add((String) propiedades.get(i), i); //guardo todas las Propiedades para pasar al meta----- combo if (!listIndicesPropiedadesCargadas.contains(String.valueOf(table.getSelectionIndex()))) { //compruebo no haber ya guaradado estas propiedades ArrayList<String> listItem = new ArrayList<String>(); listItem.add(propiedades.get(i).trim()); //propiedad listItem.add(String.valueOf(table.getSelectionIndex())); // entidad item index arrayPropiedades.add(listItem); } //------------------------- } listIndicesPropiedadesCargadas.add(String.valueOf(table.getSelectionIndex())); //una ves cargada todas las propiedes la guardo en la lista de las ya cargadas } } private void agregarfila(int r) { TableItem item = new TableItem(table, SWT.NONE, r); item.setText(0, ""); item.setText(1, ""); } public ArrayList<String> cleanspaces(String limpiar) { // logError("nameontology "+meta.getNameOntology()); //System.out.println("/////////////////////////////////////////////////////////////////1") ; // System.out.println("//////// LIMPIAR" + limpiar) ; String replace = limpiar.replace("[", ""); String replace1 = replace.replace("]", ""); // System.out.println("//////// replace1" + replace1) ; String replace2 = replace1.replaceAll("\\s+", ""); // System.out.println("//////// replace2" + replace2) ; ArrayList<String> myList = new ArrayList<String>(Arrays.asList(replace2.split(","))); // System.out.println("/////////////////////////////////////////////////////////////////2") ; return myList; } public ArrayList<String> cargaListaPropiedades(String limpiar) { // logError("nameontology "+meta.getNameOntology()); // System.out.println("/////////////////////////////////////////////////////////////////1") ; // System.out.println("//////// LIMPIAR " + limpiar) ; String replace = limpiar.replace("[", ""); String replace1 = replace.replace("]", ""); // System.out.println("//////// replace1 " + replace1) ; ArrayList<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(","))); // System.out.println("//////// lista size" + myList.size()) ; // System.out.println("/////////////////////////////////////////////////////////////////2") ; return myList; } private void ChooseDirectory() { try { DirectoryDialog dialog = new DirectoryDialog(shell, SWT.OPEN); dialog.setText(BaseMessages.getString(PKG, "FusekiLoader.FieldName.LabelOutput")); String result = dialog.open(); this.wChooseOutput.setText(dialog.getFilterPath()); meta.setDirectory(dialog.getFilterPath()); wTextHowService.setText("go to " + meta.getDirectory() + "/elda , execute elda with the next command 'java -jar start.jar' , now in your browser go to the url : http://localhost:8080/" + ObtenerNombreUrl(wTextBaseUri.getText().trim()) + "/ + and an entity label that your choice "); } catch (Exception e) { log.log(Level.SEVERE, e.toString(), e); } } private void StartService() { // comprobar si se ejecuto el plugin File fDest = new File(meta.getDirectorioFuseki() + "/fuseki"); if (!fDest.exists()) { MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "FusekiLoader.Check.Error") + meta.getDirectorioFuseki() + "/fuseki"); dialog.open(); } else { execute(); // String output = executeCommand(command,dir); logBasic("Fuseki server start"); //wOpenBrowser.setEnabled(true); } } private String ObtenerNombreUrl(String ebaseUri) { String resp = ""; //System.out.println("base Uri "+ebaseUri); for (int i = ebaseUri.length() - 1; i >= 0; i--) { //System.out.println("i "+i + " "+ebaseUri.substring(i,i)); if (ebaseUri.substring(i, i + 1).compareTo("/") != 0) { resp = ebaseUri.substring(i, i + 1) + resp; } else if (i != ebaseUri.length() - 1) { i = -1; //termino de concatenar } } //System.out.println("base urif "+resp); return resp; } private String executeCommand(String command, File dir) { StringBuffer output = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(command, null, dir); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); } private void OpenBrowser() { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI("http://localhost:" + meta.getPortName() + "/")); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } } else { openUrlInBrowser("http://localhost:" + meta.getPortName() + "/"); } } private void openUrlInBrowser(String url) { // open in mac Runtime runtime = Runtime.getRuntime(); String[] args = { "osascript", "-e", "open location \"" + url + "\"" }; try { Process process = runtime.exec(args); } catch (IOException e) { logBasic(e.getMessage()); } } public void execute() { String command = "./fuseki-server --port=" + meta.getPortName() + " --config=config.ttl "; if (isWindows()) { System.out.println("Es un Windows"); command = "cmd fuseki-server --port=" + wTextServPort.getText() + " --config=config.ttl "; } File dir = new File(meta.getDirectorioFuseki() + "/fuseki");// path // ---------------------------- // ------------------------ task = new ExecutorTask(); task.setCommand(command); task.setDir(dir); Thread executorThread = new Thread(task); executorThread = new Thread(task); try { executorThread.start(); } catch (Exception e) { MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR); dialog.setText("ERROR"); dialog.setMessage(e.getMessage()); dialog.open(); } /* * elHilo= new MiHilo1(); elHilo.setCommand(command); * elHilo.setDir(dir); elHilo.start(); */ //this.wStopService.setEnabled(true); //this.wCheckService.setEnabled(false); //this.wOpenBrowser.setEnabled(true); } public void stop() { // elHilo.detenElHilo(); task.detenElHilo(); //this.wStopService.setEnabled(false); //this.wCheckService.setEnabled(true); //this.wOpenBrowser.setEnabled(false); } public static boolean isWindows() { return (OS.indexOf("win") >= 0); } private String lookupGetterMethod(String nameMethod) { String value = ""; for (StepMeta stepMeta : this.transMeta.findPreviousSteps(this.stepMeta)) { StepMetaInterface stepMetaIn = stepMeta.getStepMetaInterface(); try { for (Method method : stepMetaIn.getClass().getDeclaredMethods()) { if (method.getName().equals(nameMethod)) { value = (String) method.invoke(stepMetaIn); break; } } } catch (IllegalAccessException ne) { logBasic(ne.getMessage()); value = ""; } catch (IllegalArgumentException se) { logBasic(se.getMessage()); value = ""; } catch (InvocationTargetException ae) { logBasic(ae.getMessage()); value = ""; } finally { if (value != null) break; } } return value; } private void PreCargar() { if (!transMeta.findPreviousSteps(stepMeta).isEmpty()) { String filename = lookupGetterMethod("getFileoutput"); //String baseUri = lookupGetterMethod("getBaseUri"); String baseUri = lookupGetterMethod("getMapBaseURI"); String serviceName = lookupGetterMethod("getServiceName"); String PortName = lookupGetterMethod("getPortName"); if (!serviceName.equals("") && !PortName.equals("")) { //Esta conectado a Fuseki // wHelloFieldName.setText("http://localhost:" + PortName + "/" + serviceName + "/query"); stop(); //Detengo el servicio anterior //cargo los parametros para el servicio meta.setDirectorioFuseki(lookupGetterMethod("getDirectory")); meta.setPortName(PortName); StartService(); //Inicio el Servicio Fuseki } else { MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "ELda.ERROR.FusekiNOfound") + "baseUri"); dialog.open(); } /* if (!directorio.equals("") && !filename.equals("")) { this.wHelloFieldName.setText(directorio + System.getProperty("file.separator") + filename); meta.setInputName(filename); } else { MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "FusekiLoader.ERROR.PreviewStepOntology")); dialog.open(); }*/ if (!baseUri.equals("")) { //precargar base URI del r2rml meta.setEbaseUri(baseUri); this.wTextBaseUri.setText(baseUri); } else { //precargar base URI del Fuseki baseUri = lookupGetterMethod("getFubaseURI"); if (baseUri.equals("")) { MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR); dialog.setText("ERROR"); dialog.setMessage( BaseMessages.getString(PKG, "FusekiLoader.ERROR.PreviewStepOntology") + "baseUri"); dialog.open(); } else { //cargo del fuseki meta.setEbaseUri(baseUri); this.wTextBaseUri.setText(baseUri); } } } else { MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR); dialog.setText("ERROR"); dialog.setMessage(BaseMessages.getString(PKG, "FusekiLoader.ERROR.PreviewStep")); dialog.open(); } } // ---------------listar clases y propiedades private ArrayList listarClases(String ruta) { ArrayList<String> mili = new ArrayList<String>(); OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); try { model.read(ruta); } catch (Exception eox) { System.out.println("error read " + ruta + eox); } if (!model.isEmpty()) { for (Iterator<OntClass> i = model.listClasses(); i.hasNext();) { OntClass cls = i.next(); if (cls.getLocalName() != null) { // Para que no se recorran // clases vacias // outputRow[0]=cls.getURI()+" "+cls.getLocalName();//para // que salgan los nombres // System.out.println(cls.getNameSpace()); // outputRow[0] = "Ontologia" + myList.get(ii); // cls.getLocalName(); // dataLoader.sequence++; // int dataIndex = databaseLoad ? 3:0; // outputRow[dataIndex] = nameontology.trim(); mili.add(cls.getURI() + " type:class"); // outputRow[dataIndex+2] = "rdf:type"; // outputRow[dataIndex+3] = "rdfs:class"; /** * outputRow[0] = nameontology; outputRow[1] = cls.getURI(); * outputRow[2] = "rdf:type"; outputRow[3] = "rdfs:class"; */ } } // end for to search classes } // fin comprobacion return mili; } public ArrayList listarPropiedades(String ruta) { ArrayList<String> mili = new ArrayList<String>(); OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); try { model.read(ruta); } catch (Exception eox) { System.out.println("error read " + ruta + eox); } if (!model.isEmpty()) { // to search properties for (Iterator<OntProperty> j = model.listAllOntProperties(); j.hasNext();) { OntProperty proper = j.next(); if (proper.getLocalName() != null) { // outputRow[dataIndex] = nameontology.trim(); //mili.add(proper.getURI() + " type:property"); mili.add(proper.getURI()); } } } // fin comprobacion return mili; } // ----------------------------------- public ArrayList listarEntidadesRdf(String ruta) { ArrayList<String> mili = new ArrayList<String>(); ArrayList<QuerySolution> solutions = new ArrayList<QuerySolution>(); OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); try { model.read(ruta); } catch (Exception eox) { System.out.println("error read " + ruta + eox); } if (!model.isEmpty()) { // to query sparql // QuerySolutionMap initialBindings = new QuerySolutionMap(); // initialBindings.add("blog", blog); // here's the query String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + " select distinct ?object " + " WHERE {" + " ?s rdf:type ?object " + " } LIMIT 100 "; // create the query object Query query = QueryFactory.create(queryString); // execute the query over the model, providing the // initial bindings for all variables QueryExecution exec = // QueryExecutionFactory.create(query, model, initialBindings); QueryExecutionFactory.create(query, model); ResultSet results = exec.execSelect(); solutions = (ArrayList<QuerySolution>) ResultSetFormatter.toList(results); solutions.toArray(); // Output query results ResultSetFormatter.out(System.out, results, query); solutions.get(0).get("?object"); for (int i = 0; i < solutions.size(); i++) { mili.add(solutions.get(i).get("?object").toString()); } // java.util.List<String> mil2 = ResultSetFormatter.toList(results); // List<String> values = new ArrayList<String>() } // fin comprobacion return mili; } // ----------------------------------- throws MalformedURLException public ArrayList ConsultarFuseki(String Servicio) { ArrayList<String> mili = new ArrayList<String>(); String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + " select distinct ?object " + "FROM <" + wTextBaseUri.getText().trim() + ">" + " WHERE {" + " ?s rdf:type ?object " + " } LIMIT 100 "; if (wTextBaseUri.getText().trim().isEmpty()) { //si esta vacio busco sin graph queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>" + " select distinct ?object " + " WHERE {" + " ?s rdf:type ?object " + " } LIMIT 100 "; } // now creating query object Query query = QueryFactory.create(queryString); // http://localhost:3030/myservice/query // **this actually was the main problem I couldn't figure out.** //QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query); //QueryExecution qexec = QueryExecutionFactory.sparqlService("http://localhost:3030/myservice/query", query); //QueryExecution qexec = QueryExecutionFactory.sparqlService("http://localhost:3030/#myds/sparql", query); //ocalhost:3030/myservice/query?query //qexec = QueryExecutionFactory.sparqlService("http://localhost:3030/sparql.tpl", query); QueryExecution qexec = QueryExecutionFactory.sparqlService(Servicio, query); //after it goes standard query execution and result processing which can // be found in almost any Jena/SPARQL tutorial. System.out.println(" servicio " + Servicio + "query " + query); try { ResultSet results = qexec.execSelect(); ArrayList<QuerySolution> solutions = new ArrayList<QuerySolution>(); solutions = (ArrayList<QuerySolution>) ResultSetFormatter.toList(results); solutions.toArray(); // Output query results ResultSetFormatter.out(System.out, results, query); if (solutions.size() > 0) { // validacion lista vacia solutions.get(0).get("?object"); System.out.println("accediendo fuseki entro antes for"); for (int i = 0; i < solutions.size(); i++) { mili.add(solutions.get(i).get("?object").toString()); System.out.println("accediendo fuseki entro " + solutions.get(i).get("?object").toString()); } } //-------public RepositorySpace obtainRepositorySpace(final String repositorySpaceURL) throws XMLException, IOException, MalformedURLException { throw new MalformedURLException("s"); } catch (MalformedURLException d) { logBasic(" ERROR " + d.getMessage() + "BAD url"); } finally { qexec.close(); } //after it goes standard query execution and result processing which can // be found in almost any Jena/SPARQL tutorial. /* try { ResultSet results = qexec.execSelect(); for (; results.hasNext();) { // Result processing is done here. } } finally { qexec.close(); }*/ return mili; } /** * Metodo para obtener todas las propiedades del endPoint * @param Servicio * @return */ public ArrayList ConsultarFusekiPropiedades(String Servicio) { ArrayList<String> mili = new ArrayList<String>(); String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + " SELECT DISTINCT ?pred WHERE { ?pred a rdf:Property } ORDER BY ?pred " + " LIMIT 100 "; // now creating query object Query query = QueryFactory.create(queryString); //QueryExecution qexec = QueryExecutionFactory.sparqlService("http://localhost:3030/myservice/query", query); QueryExecution qexec = QueryExecutionFactory.sparqlService(Servicio, query); //after it goes standard query execution and result processing which can // be found in almost any Jena/SPARQL tutorial. System.out.println("accediendo fuseki "); try { ResultSet results = qexec.execSelect(); ArrayList<QuerySolution> solutions = new ArrayList<QuerySolution>(); solutions = (ArrayList<QuerySolution>) ResultSetFormatter.toList(results); solutions.toArray(); // Output query results ResultSetFormatter.out(System.out, results, query); if (solutions.size() > 0) { // validacion lista vacia solutions.get(0).get("?pred"); System.out.println("accediendo fuseki entro antes for"); for (int i = 0; i < solutions.size(); i++) { mili.add(solutions.get(i).get("?pred").toString()); System.out .println("accediendo servicio propiedades " + solutions.get(i).get("?pred").toString()); } } //------- throw new MalformedURLException("s"); } catch (MalformedURLException d) { logBasic("Query Entidades " + d.getMessage() + " try"); } finally { qexec.close(); } return mili; } /** * Metodo para consultar en el servicio las propiedades por entidad * @param Servicio * @param urlEntidad * @return */ public ArrayList ConsultarPropiedadesXentidad(String Servicio, String urlEntidad) { //select distinct ?p where {?s a <http://purl.org/ontology/bibo/Thesis> . ?s ?p ?o} ArrayList<String> mili = new ArrayList<String>(); String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "SELECT DISTINCT ?pred where {?s a <" + urlEntidad.trim() + "> . ?s ?pred ?o} ORDER BY ?pred" + " LIMIT 100 "; // now creating query object Query query = QueryFactory.create(queryString); //QueryExecution qexec = QueryExecutionFactory.sparqlService("http://localhost:3030/myservice/query", query); QueryExecution qexec = QueryExecutionFactory.sparqlService(Servicio, query); //after it goes standard query execution and result processing which can // be found in almost any Jena/SPARQL tutorial. System.out.println("accediendo a ConsultarPropiedadesXentidad "); try { ResultSet results = qexec.execSelect(); ArrayList<QuerySolution> solutions = new ArrayList<QuerySolution>(); solutions = (ArrayList<QuerySolution>) ResultSetFormatter.toList(results); solutions.toArray(); // Output query results ResultSetFormatter.out(System.out, results, query); if (solutions.size() > 0) { // validacion lista vacia solutions.get(0).get("?pred"); System.out.println("accediendo ConsultarPropiedadesXentidad for " + urlEntidad); for (int i = 0; i < solutions.size(); i++) { mili.add(solutions.get(i).get("?pred").toString()); System.out.println("ConsultarPropiedadesXentidad encontro propiedad " + solutions.get(i).get("?pred").toString()); } } //------- // throw new MalformedURLException("s"); } /* catch (MalformedURLException d){ logBasic("Query Entidades " + d.getMessage() + " try"); }*/ finally { qexec.close(); } return mili; } /** * devuelve en ArrayList<ArrayList<String>> las del meta meta.getPropiedadesTodasCargadas() * @param limpiar ArrayList<ArrayList<String>> propiedad indice * @return */ private static ArrayList<ArrayList<String>> obtenerTodasPropiedadesIndices(String limpiar) { ArrayList<ArrayList<String>> arrayPropiedades = new ArrayList<ArrayList<String>>(); if (limpiar != null) { String replace = limpiar.replace("[", ""); String replace1 = replace.replace("]", ""); // System.out.println("//////// replace1" + replace1) ; String replace2 = replace1.replaceAll("\\s+", ""); // System.out.println("//////// replace2" + replace2) ; ArrayList<String> myList = new ArrayList<String>(Arrays.asList(replace2.split(","))); System.out.println(myList); ArrayList<String> listItem = new ArrayList<String>(); for (int i = 0; i < myList.size(); i++) { listItem = new ArrayList<String>(); listItem.add(myList.get(i)); listItem.add(myList.get(i + 1)); arrayPropiedades.add(listItem); i++; } myList = obtenerPropiedadesPorIndice(arrayPropiedades, 2); } return arrayPropiedades; } /** * Obtengo solo todas las propiedades de cierta entidad * @param ArrayList<ArrayList<String>> meta * @param indice * @return */ private static ArrayList<String> obtenerPropiedadesPorIndice(ArrayList<ArrayList<String>> arrayPropiedades2, int indice) { ArrayList<String> resp = new ArrayList<String>(); for (int i = 0; i < arrayPropiedades2.size(); i++) { ArrayList<String> listItem = new ArrayList<String>(); listItem = arrayPropiedades2.get(i); if (listItem.get(1).compareTo(String.valueOf(indice)) == 0) { resp.add(listItem.get(0)); } } return resp; } /** * Metodo para cargar la seleccion del meta en el combo la primera vez * @param selectionIndex , lista de propiedades donde buscar * @return */ private Integer obtenerPropiedadSeleccionada(int selectionIndex, ArrayList<String> propiedadesDondeBuscar) { //ArrayList<String> propiedadesDondeBuscar= new ArrayList<String>(); Integer resp = -1; System.out.println("meta.getListLabelxEntidad()" + meta.getListLabelxEntidad()); if (meta.getListLabelxEntidad() != null) { if ((meta.getListLabelxEntidad().compareTo("[]") != 0) && (meta.getListLabelxEntidad() != null)) { ArrayList<String> ListLabelxEntidad = cleanspaces(meta.getListLabelxEntidad()); for (int i = 0; i < propiedadesDondeBuscar.size(); i++) { if (selectionIndex < ListLabelxEntidad.size()) { if (propiedadesDondeBuscar.get(i).trim() .compareTo(ListLabelxEntidad.get(selectionIndex)) == 0) { resp = i; } } } } } return resp; } }// fin class class MiHilo1 extends Thread { // boolean que pondremos a false cuando queramos parar el hilo protected LogChannelInterface log; private boolean continuar = true; public String command; public File dir; public boolean line = true; public Process p = null; public void detenElHilo() { p.destroy(); line = false; } // Metodo del hilo public void run() { StringBuffer output = new StringBuffer(); int i = 0; int j = 10000; try { p = Runtime.getRuntime().exec(command, null, dir); while (line) { i++; if (i > j) { // System.out.print(i); j = 0; } } System.out.print("stop service"); p.destroy(); } catch (Exception e) { e.printStackTrace(); logBasic(" ERROR " + e.getMessage() + "The service was not created. Please execute spoon like administrator"); System.out.println(e.getMessage()); } } public void logBasic(String message) { log.logBasic(message); } public void setCommand(String s1) { this.command = s1; } public void setDir(File s2) { this.dir = s2; } } class ExecutorTask implements Runnable { protected LogChannelInterface log; public String command; public File dir; public Process p = null; public boolean line = true; public void run() { StringBuffer output = new StringBuffer(); try { p = Runtime.getRuntime().exec(command, null, dir); int i = 0; int j = 10000; while (line) { i++; if (i > j) { // System.out.print(i); j = 0; } } System.out.print("stop service"); p.destroy(); } catch (IOException e) { e.printStackTrace(); logBasic(" ERROR " + e + "The service was not created. Please execute spoon like administrator"); } } public void setCommand(String s1) { this.command = s1; } public void setDir(File s2) { this.dir = s2; } public void logBasic(String message) { log.logBasic(message); } public void detenElHilo() { if (p != null) { p.destroy(); line = false; } } }