@Override
 public void iconPicked(int requestCode, int resultCode, Intent in) {
   Drawable ic = null;
   String iconType = null;
   String pkgName = null;
   String iconSource = null;
   if (requestCode == IconPicker.REQUEST_PICK_GALLERY) {
     if (resultCode == Activity.RESULT_OK) {
       File mImage =
           new File(
               mActivity.getFilesDir() + "/lockscreen_" + System.currentTimeMillis() + ".png");
       if (mImageTmp.exists()) {
         mImageTmp.renameTo(mImage);
       }
       mImage.setReadOnly();
       iconType = GlowPadView.ICON_FILE;
       iconSource = mImage.toString();
       ic = new BitmapDrawable(getResources(), BitmapFactory.decodeFile(mImage.toString()));
     } else {
       if (mImageTmp.exists()) {
         mImageTmp.delete();
       }
       return;
     }
   } else if (requestCode == IconPicker.REQUEST_PICK_SYSTEM) {
     String resourceName = in.getStringExtra(IconPicker.RESOURCE_NAME);
     ic =
         mResources
             .getDrawable(mResources.getIdentifier(resourceName, "drawable", "android"))
             .mutate();
     iconType = GlowPadView.ICON_RESOURCE;
     iconSource = resourceName;
   } else if (requestCode == IconPicker.REQUEST_PICK_ICON_PACK
       && resultCode == Activity.RESULT_OK) {
     String resourceName = in.getStringExtra(IconPicker.RESOURCE_NAME);
     pkgName = in.getStringExtra(IconPicker.PACKAGE_NAME);
     try {
       Context rContext = mActivity.createPackageContext(pkgName, 0);
       int id = rContext.getResources().getIdentifier(resourceName, "drawable", pkgName);
       ic = rContext.getResources().getDrawable(id);
     } catch (NameNotFoundException e) {
       e.printStackTrace();
     }
     iconType = GlowPadView.ICON_RESOURCE;
     iconSource = resourceName;
   } else {
     return;
   }
   TargetInfo tmpIcon = new TargetInfo(null);
   tmpIcon.iconType = iconType;
   tmpIcon.iconSource = iconSource;
   tmpIcon.pkgName = pkgName;
   mDialogIcon.setTag(tmpIcon);
   mDialogIcon.setImageDrawable(ic);
 }
 // FREEHEP added synchronized
 public synchronized void update(TargetInfo linkTarget) {
   File outputFile = linkTarget.getOutput();
   String outputName = outputFile.getName();
   //
   //   if output file doesn't exist or predates the start of the
   //        compile or link step (most likely a compilation error) then
   //        do not write add a history entry
   //
   if (outputFile.exists()
       && !CUtil.isSignificantlyBefore(outputFile.lastModified(), historyFile.lastModified())) {
     dirty = true;
     history.remove(outputName);
     SourceHistory[] sourceHistories = linkTarget.getSourceHistories(outputDirPath);
     TargetHistory newHistory =
         new TargetHistory(
             linkTarget.getConfiguration().getIdentifier(),
             outputName,
             outputFile.lastModified(),
             sourceHistories);
     history.put(outputName, newHistory);
   }
 }
 // FREEHEP added synchronized
 public synchronized void markForRebuild(TargetInfo targetInfo) {
   //
   //     if it must already be rebuilt, no need to check further
   //
   if (!targetInfo.getRebuild()) {
     TargetHistory history =
         get(targetInfo.getConfiguration().toString(), targetInfo.getOutput().getName());
     if (history == null) {
       targetInfo.mustRebuild();
     } else {
       SourceHistory[] sourceHistories = history.getSources();
       File[] sources = targetInfo.getSources();
       if (sourceHistories.length != sources.length) {
         targetInfo.mustRebuild();
       } else {
         Hashtable sourceMap = new Hashtable(sources.length);
         for (int i = 0; i < sources.length; i++) {
           try {
             sourceMap.put(sources[i].getCanonicalPath(), sources[i]);
           } catch (IOException ex) {
             sourceMap.put(sources[i].getAbsolutePath(), sources[i]);
           }
         }
         for (int i = 0; i < sourceHistories.length; i++) {
           //
           //   relative file name, must absolutize it on output
           // directory
           //
           String absPath = sourceHistories[i].getAbsolutePath(outputDir);
           File match = (File) sourceMap.get(absPath);
           if (match != null) {
             try {
               match = (File) sourceMap.get(new File(absPath).getCanonicalPath());
             } catch (IOException ex) {
               targetInfo.mustRebuild();
               break;
             }
           }
           if (match == null || match.lastModified() != sourceHistories[i].getLastModified()) {
             targetInfo.mustRebuild();
             break;
           }
         }
       }
     }
   }
 }
 /** Updates a target in the GlowPadView */
 private void setTarget(
     int position, String uri, Drawable draw, String iconType, String iconSource, String pkgName) {
   TargetInfo item = mTargetStore.get(position);
   StateListDrawable state = (StateListDrawable) item.icon;
   LayerDrawable inActiveLayer = (LayerDrawable) state.getStateDrawable(0);
   LayerDrawable activeLayer = (LayerDrawable) state.getStateDrawable(1);
   inActiveLayer.setDrawableByLayerId(1, draw);
   boolean isSystem = iconType != null && iconType.equals(GlowPadView.ICON_RESOURCE);
   if (!isSystem) {
     final Drawable activeBack =
         mResources.getDrawable(com.android.internal.R.drawable.ic_lockscreen_target_activated);
     activeLayer.setDrawableByLayerId(0, new InsetDrawable(activeBack, 0, 0, 0, 0));
     activeLayer.setDrawableByLayerId(1, draw);
   } else {
     InsetDrawable empty =
         new InsetDrawable(mResources.getDrawable(android.R.color.transparent), 0, 0, 0, 0);
     activeLayer.setDrawableByLayerId(1, empty);
     int activeId =
         mResources.getIdentifier(
             iconSource.replaceAll("_normal", "_activated"), "drawable", "android");
     Drawable back = null;
     if (activeId != 0) {
       back = mResources.getDrawable(activeId);
       activeLayer.setDrawableByLayerId(0, back);
     } else {
       final Drawable activeBack =
           mResources.getDrawable(com.android.internal.R.drawable.ic_lockscreen_target_activated);
       activeLayer.setDrawableByLayerId(0, new InsetDrawable(activeBack, 0, 0, 0, 0));
     }
   }
   item.defaultIcon = mDialogIcon.getDrawable().getConstantState().newDrawable().mutate();
   item.uri = uri;
   item.iconType = iconType;
   item.iconSource = iconSource;
   item.pkgName = pkgName;
 }
  @Override
  public void visit(final File parentDir, final String filename) throws BuildException {
    final File fullPath = new File(parentDir, filename);
    //
    // see if any processor wants to bid
    // on this one
    ProcessorConfiguration selectedCompiler = null;
    int bid = 0;
    if (this.processors != null) {
      for (final ProcessorConfiguration processor : this.processors) {
        final int newBid = processor.bid(fullPath.toString());
        if (newBid > bid) {
          bid = newBid;
          selectedCompiler = processor;
        }
      }
    }
    //
    // no processor interested in file
    // log diagnostic message
    if (bid <= 0) {
      if (this.linker != null) {
        final int linkerbid = this.linker.bid(filename);
        if (linkerbid > 0) {
          this.objectFiles.addElement(fullPath);
          if (linkerbid == 1) {
            this.task.log(
                "Unrecognized file type " + fullPath.toString() + " will be passed to linker");
          }
        }
      }
    } else {
      //
      // get output file name
      //
      final String[] outputFileNames =
          selectedCompiler.getOutputFileNames(filename, this.versionInfo);
      this.sourceFiles[0] = fullPath;
      //
      // if there is some output for this task
      // (that is a source file and not an header file)
      //
      for (final String outputFileName : outputFileNames) {
        //
        // see if the same output file has already been registered
        //
        StringBuffer sb = new StringBuffer(FilenameUtils.removeExtension(outputFileName));
        sb.append(
            "."
                + fullPath.getAbsolutePath().hashCode()
                + "."
                + FilenameUtils.getExtension(outputFileName));
        String newOutputFileName = sb.toString();

        final TargetInfo previousTarget = this.targets.get(newOutputFileName);
        if (previousTarget == null) {
          this.targets.put(
              newOutputFileName,
              new TargetInfo(
                  selectedCompiler,
                  this.sourceFiles,
                  null,
                  new File(this.outputDir, newOutputFileName),
                  selectedCompiler.getRebuild()));
        } else {
          if (!previousTarget.getSources()[0].equals(this.sourceFiles[0])) {
            final StringBuffer builder = new StringBuffer("Output filename conflict: ");
            builder.append(outputFileName);
            builder.append(" would be produced from ");
            builder.append(previousTarget.getSources()[0].toString());
            builder.append(" and ");
            builder.append(filename);
            throw new BuildException(builder.toString());
          }
        }
      }
    }
  }
 @Override
 public void onTrigger(View v, final int target) {
   mTargetIndex = target;
   if ((target != 0 && (mIsScreenLarge || !mIsLandscape))
       || (target != 2 && !mIsScreenLarge && mIsLandscape)) {
     AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
     builder.setTitle(R.string.lockscreen_target_edit_title);
     builder.setMessage(R.string.lockscreen_target_edit_msg);
     View view = View.inflate(mActivity, R.layout.lockscreen_shortcut_dialog, null);
     view.findViewById(R.id.icon)
         .setOnClickListener(
             new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                 if (!mDialogLabel.getText().equals(EMPTY_LABEL)) {
                   try {
                     mImageTmp.createNewFile();
                     mImageTmp.setWritable(true, false);
                     mIconPicker.pickIcon(getId(), mImageTmp);
                   } catch (IOException e) {
                   }
                 }
               }
             });
     view.findViewById(R.id.label)
         .setOnClickListener(
             new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                 mPicker.pickShortcut(
                     new String[] {EMPTY_LABEL},
                     new ShortcutIconResource[] {
                       ShortcutIconResource.fromContext(mActivity, android.R.drawable.ic_delete)
                     },
                     getId());
               }
             });
     mDialogIcon = ((ImageButton) view.findViewById(R.id.icon));
     mDialogLabel = ((Button) view.findViewById(R.id.label));
     TargetInfo item = mTargetStore.get(target);
     mDialogIcon.setImageDrawable(mTargetStore.get(target).defaultIcon.mutate());
     TargetInfo tmpIcon = new TargetInfo(null);
     tmpIcon.iconType = item.iconType;
     tmpIcon.iconSource = item.iconSource;
     tmpIcon.pkgName = item.pkgName;
     mDialogIcon.setTag(tmpIcon);
     if (mTargetStore.get(target).uri.equals(GlowPadView.EMPTY_TARGET)) {
       mDialogLabel.setText(EMPTY_LABEL);
     } else {
       mDialogLabel.setText(mPicker.getFriendlyNameForUri(mTargetStore.get(target).uri));
     }
     mDialogLabel.setTag(mTargetStore.get(target).uri);
     builder.setView(view);
     builder.setPositiveButton(
         R.string.ok,
         new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialog, int which) {
             TargetInfo vObject = (TargetInfo) mDialogIcon.getTag();
             String type = null, source = null, pkgName = null;
             int targetInset = mTargetInset;
             if (vObject != null) {
               type = vObject.iconType;
               source = vObject.iconSource;
               pkgName = vObject.pkgName;
             }
             if (type != null && type.equals(GlowPadView.ICON_RESOURCE)) {
               targetInset = 0;
             }
             InsetDrawable pD =
                 new InsetDrawable(
                     mDialogIcon.getDrawable(),
                     targetInset,
                     targetInset,
                     targetInset,
                     targetInset);
             setTarget(mTargetIndex, mDialogLabel.getTag().toString(), pD, type, source, pkgName);
           }
         });
     builder.setNegativeButton(R.string.cancel, null);
     builder.setCancelable(false);
     AlertDialog dialog = builder.create();
     dialog.show();
     ((TextView) dialog.findViewById(android.R.id.message))
         .setTextAppearance(mActivity, android.R.style.TextAppearance_DeviceDefault_Small);
   }
 }
 public void visit(File parentDir, String filename) throws BuildException {
   File fullPath = new File(parentDir, filename);
   //
   //   see if any processor wants to bid
   //       on this one
   ProcessorConfiguration selectedCompiler = null;
   int bid = 0;
   if (processors != null) {
     for (int k = 0; k < processors.length; k++) {
       int newBid = processors[k].bid(fullPath.toString());
       if (newBid > bid) {
         bid = newBid;
         selectedCompiler = processors[k];
       }
     }
   }
   //
   //   no processor interested in file
   //      log diagnostic message
   if (bid <= 0) {
     if (linker != null) {
       int linkerbid = linker.bid(filename);
       if (linkerbid > 0) {
         objectFiles.addElement(fullPath);
         if (linkerbid == 1) {
           task.log("Unrecognized file type " + fullPath.toString() + " will be passed to linker");
         }
       }
     }
   } else {
     //
     //  get output file name
     //
     String[] outputFileNames = selectedCompiler.getOutputFileNames(filename, versionInfo);
     sourceFiles[0] = fullPath;
     //
     //   if there is some output for this task
     //      (that is a source file and not an header file)
     //
     for (int i = 0; i < outputFileNames.length; i++) {
       //
       //   see if the same output file has already been registered
       //
       TargetInfo previousTarget = (TargetInfo) targets.get(outputFileNames[i]);
       if (previousTarget == null) {
         targets.put(
             outputFileNames[i],
             new TargetInfo(
                 selectedCompiler,
                 sourceFiles,
                 null,
                 new File(outputDir, outputFileNames[i]),
                 selectedCompiler.getRebuild()));
       } else {
         if (!previousTarget.getSources()[0].equals(sourceFiles[0])) {
           StringBuffer builder = new StringBuffer("Output filename conflict: ");
           builder.append(outputFileNames[i]);
           builder.append(" would be produced from ");
           builder.append(previousTarget.getSources()[0].toString());
           builder.append(" and ");
           builder.append(filename);
           throw new BuildException(builder.toString());
         }
       }
     }
   }
 }
  private SimpleFeatureCollection calculateRisk(
      SimpleFeatureCollection features,
      JDBCDataStore dataStore,
      String storeName,
      Integer precision,
      String connectionParams,
      int processing,
      int formula,
      int target,
      String materials,
      String scenarios,
      String entities,
      String severeness,
      String fpfield,
      int batch,
      boolean simulation,
      Geometry damageArea,
      Map<Integer, Double> damageValues,
      List<TargetInfo> changedTargets,
      Map<Integer, Map<Integer, Double>> cffs,
      List<String> psc,
      Map<Integer, Map<Integer, Double>> padrs,
      Map<Integer, Double> piss,
      List<Integer> distances,
      boolean extendedSchema)
      throws IOException, SQLException {

    if (precision == null) {
      precision = 3;
    }

    DefaultTransaction transaction = new DefaultTransaction();
    Connection conn = null;
    try {
      conn = dataStore.getConnection(transaction);

      // output FeatureType (risk)
      //  - id_geo_arco
      //  - geometria
      //  - rischio1
      //  - rischio2
      SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
      tb.add(
          "id_geo_arco", features.getSchema().getDescriptor("id_geo_arco").getType().getBinding());
      tb.add(
          "geometria",
          MultiLineString.class,
          features.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem());

      if (extendedSchema) {
        tb.add("rischio_sociale", Double.class);
        tb.add("rischio_ambientale", Double.class);
        tb.add("nr_corsie", Integer.class);
        tb.add("lunghezza", Integer.class);
        tb.add("nr_incidenti", Integer.class);
      } else {
        tb.add("rischio1", Double.class);
        tb.add("rischio2", Double.class);
      }
      // fake layer name (risk) used for WPS output. Layer risk must be defined in GeoServer
      // catalog
      tb.setName(new NameImpl(features.getSchema().getName().getNamespaceURI(), "risk"));
      SimpleFeatureType ft = tb.buildFeatureType();

      // feature level (1, 2, 3)
      int level = FormulaUtils.getLevel(features);

      LOGGER.info("Doing calculus for level " + level);

      Formula formulaDescriptor = Formula.load(conn, processing, formula, target);

      if (formulaDescriptor == null) {
        throw new ProcessException("Unable to load formula " + formula);
      }

      if (((!formulaDescriptor.hasGrid() && level == 3)
              || (!formulaDescriptor.hasNoGrid() && level < 3))
          && !extendedSchema) {
        LOGGER.info("Formula not supported on this level, returning empty collection");
        return new EmptyFeatureCollection(ft);
      } else {
        // iterator on source
        SimpleFeatureIterator iter = features.features();

        // result builder
        SimpleFeatureBuilder fb = new SimpleFeatureBuilder(ft);
        ListFeatureCollection result = new ListFeatureCollection(ft);
        int count = 0;
        Double[] risk = new Double[] {0.0, 0.0};

        // iterate source features
        try {
          // we will calculate risk in batch of arcs
          // we store each feature of the batch in a map
          // indexed by id
          Map<Number, SimpleFeature> temp = new HashMap<Number, SimpleFeature>();
          StringBuilder ids = new StringBuilder();
          String fk_partner = null;

          while (iter.hasNext()) {
            SimpleFeature feature = iter.next();
            Number id = (Number) feature.getAttribute("id_geo_arco");
            fk_partner = (String) feature.getAttribute("fk_partner");
            fb.add(id);
            fb.add(feature.getDefaultGeometry());
            if (formulaDescriptor.takeFromSource()) {
              risk[0] = ((Number) feature.getAttribute("rischio1")).doubleValue();
              risk[1] = ((Number) feature.getAttribute("rischio2")).doubleValue();
            }
            fb.add(risk[0]);
            fb.add(risk[1]);
            if (extendedSchema) {
              fb.add((Number) feature.getAttribute("nr_corsie"));
              fb.add((Number) feature.getAttribute("lunghezza"));
              fb.add((Number) feature.getAttribute("nr_incidenti"));
            }
            temp.put(id.intValue(), fb.buildFeature(id + ""));

            if (simulation) {
              Double pis = piss.get(id.intValue());
              Map<Integer, Double> padr = padrs.get(id.intValue());
              Map<Integer, Double> cff = cffs.get(id.intValue());

              Map<Integer, Map<Integer, Double>> simulationTargets =
                  new HashMap<Integer, Map<Integer, Double>>();

              if (!changedTargets.isEmpty()) {
                for (int distance : distances) {
                  Geometry buffer =
                      BufferUtils.iterativeBuffer(
                          (Geometry) feature.getDefaultGeometry(), (double) distance, 100);
                  for (TargetInfo targetInfo : changedTargets) {
                    if (targetInfo.getGeometry() != null) {
                      Geometry intersection = buffer.intersection(targetInfo.getGeometry());
                      if (intersection != null && intersection.getArea() > 0) {
                        Map<Integer, Double> distancesMap =
                            simulationTargets.get(targetInfo.getType());
                        if (distancesMap == null) {
                          distancesMap = new HashMap<Integer, Double>();
                          simulationTargets.put(targetInfo.getType(), distancesMap);
                        }
                        double value = 0.0;
                        if (targetInfo.isHuman()) {
                          value =
                              intersection.getArea()
                                  / targetInfo.getGeometry().getArea()
                                  * targetInfo.getValue();
                        } else {
                          value = intersection.getArea();
                        }
                        if (targetInfo.isRemoved()) {
                          value = -value;
                        }
                        distancesMap.put(distance, value);
                      }
                    }
                  }
                }
              }

              FormulaUtils.calculateSimulationFormulaValuesOnSingleArc(
                  conn,
                  level,
                  processing,
                  formulaDescriptor,
                  id.intValue(),
                  fk_partner,
                  materials,
                  scenarios,
                  entities,
                  severeness,
                  fpfield,
                  target,
                  simulationTargets,
                  temp,
                  precision,
                  cff,
                  psc,
                  padr,
                  pis,
                  null,
                  extendedSchema);

              result.addAll(temp.values());
              temp = new HashMap<Number, SimpleFeature>();
            } else if (damageArea != null) {
              Geometry arcGeometry = (Geometry) feature.getDefaultGeometry();
              if (arcGeometry != null && arcGeometry.intersects(damageArea)) {
                FormulaUtils.calculateSimulationFormulaValuesOnSingleArc(
                    conn,
                    level,
                    processing,
                    formulaDescriptor,
                    id.intValue(),
                    fk_partner,
                    materials,
                    scenarios,
                    entities,
                    severeness,
                    fpfield,
                    target,
                    null,
                    temp,
                    precision,
                    null,
                    null,
                    null,
                    null,
                    damageValues,
                    extendedSchema);
                result.addAll(temp.values());
              }
              temp = new HashMap<Number, SimpleFeature>();
            } else {
              ids.append("," + id);
              count++;
              // calculate batch items a time
              if (count % batch == 0) {
                LOGGER.info("Calculated " + count + " values");
                FormulaUtils.calculateFormulaValues(
                    conn,
                    level,
                    processing,
                    formulaDescriptor,
                    ids.toString().substring(1),
                    fk_partner,
                    materials,
                    scenarios,
                    entities,
                    severeness,
                    fpfield,
                    target,
                    temp,
                    precision,
                    extendedSchema);
                result.addAll(temp.values());
                ids = new StringBuilder();
                temp = new HashMap<Number, SimpleFeature>();
              }
            }
          }

          // final calculus for remaining items not in batch size
          LOGGER.info("Calculating remaining items");
          if (ids.length() > 0) {
            FormulaUtils.calculateFormulaValues(
                conn,
                level,
                processing,
                formulaDescriptor,
                ids.toString().substring(1),
                fk_partner,
                materials,
                scenarios,
                entities,
                severeness,
                fpfield,
                target,
                temp,
                precision,
                extendedSchema);
          }
          result.addAll(temp.values());

          LOGGER.info("Calculated " + result.size() + " values");

        } finally {
          iter.close();
        }
        return result;
      }

    } finally {
      transaction.close();
      if (conn != null) {
        conn.close();
      }
    }
  }