Ejemplo n.º 1
2
  public void updateStockFromSAP() {
    System.out.println(
        "[" + Shared.now() + "] UpdateStockFromSAP " + Shared.lineNumber() + " Update from SAP");
    workingFrame = new Working((JFrame) Shared.getMyMainWindows());
    WaitSplash ws = new WaitSplash(this);

    Shared.centerFrame(workingFrame);
    workingFrame.setVisible(true);

    ws.execute();
    // doIt();
  }
Ejemplo n.º 2
1
  private void updateFlagC(Connection c, TotalPosWebService ws)
      throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException,
          XMLException {
    System.out.println(
        "[" + Shared.now() + "] UpdateStockFromSAP " + Shared.lineNumber() + " Update flagc");
    String myDay = ConnectionDrivers.getLastFlagc();

    String daysFlagc =
        ws.getFlagC(Shared.getConfig("storePrefix") + Shared.getConfig("storeName"), myDay);

    ConnectionDrivers.updateFlagc(daysFlagc, c);
  }
Ejemplo n.º 3
1
  @Override
  public void run() {
    while (shared.shouldContinue()) {
      try {
        Thread.sleep(100);

        if (shared.list.size() != 0 && shared.wasChanged()) {
          calc_average();
          current_element = shared.get_last_element();
          System.out.println("Led: " + current_element + " is " + light() + "\n");
        }
      } catch (InterruptedException ex) {
        // asdada
      }
    }
  }
  public static void BuildAndVerify(BoardDescriptor boardid) {

    IProject theTestProject = null;
    CodeDescriptor codeDescriptor = CodeDescriptor.createDefaultIno();
    NullProgressMonitor monitor = new NullProgressMonitor();
    String projectName = String.format("%03d_", new Integer(mCounter++)) + boardid.getBoardID();
    try {

      theTestProject =
          boardid.createProject(
              projectName,
              null,
              ConfigurationDescriptor.getDefaultDescriptors(),
              codeDescriptor,
              monitor);
      Shared.waitForAllJobsToFinish(); // for the indexer
    } catch (Exception e) {
      e.printStackTrace();
      fail("Failed to create the project:" + projectName);
      return;
    }
    try {
      theTestProject.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
      if (Shared.hasBuildErrors(theTestProject)) {
        fail("Failed to compile the project:" + projectName + " build errors");
      }
    } catch (CoreException e) {
      e.printStackTrace();
      fail("Failed to compile the project:" + boardid.getBoardName() + " exception");
    }
  }
 private Cookie wipeOutSessionCookie() {
   Cookie sessionCookie = new Cookie(Shared.getSessionCookieName(this.tenantInfo.getName()), "");
   sessionCookie.setPath("/openidconnect");
   sessionCookie.setSecure(true);
   sessionCookie.setHttpOnly(true);
   sessionCookie.setMaxAge(0);
   return sessionCookie;
 }
Ejemplo n.º 6
0
  private void updateDescriptions(Connection c, TotalPosWebService ws)
      throws ClassNotFoundException, ClassNotFoundException, InstantiationException,
          IllegalAccessException, XMLException, SQLException {
    String myDay = Shared.getConfig("lastPriceUpdate");

    String descriptions = ws.readDescriptions(myDay);

    ConnectionDrivers.updateItems(descriptions, c);
  }
Ejemplo n.º 7
0
 @Override
 public void run() {
   for (char ch = 'A'; ch <= 'Z'; ch++) {
     l.lock();
     s.setSharedChar(ch);
     System.out.println(ch + " produced by producer.");
     l.unlock();
   }
 }
Ejemplo n.º 8
0
 @Override
 public void run() {
   char ch;
   do {
     l.lock();
     ch = s.getSharedChar();
     System.out.println(ch + " consumed by consumer.");
     l.unlock();
   } while (ch != 'Z');
 }
Ejemplo n.º 9
0
 void texsel(int id) {
   if (id != sh.curtex) {
     HavenPanel.texmiss++;
     if (id == -1) {
       gl.glDisable(GL.GL_TEXTURE_2D);
     } else {
       gl.glEnable(GL.GL_TEXTURE_2D);
       gl.glBindTexture(GL.GL_TEXTURE_2D, id);
     }
     sh.curtex = id;
   } else {
     HavenPanel.texhit++;
   }
 }
  public HttpResponse process() {
    HttpResponse httpResponse;

    try {
      initialize();
      Pair<LogoutSuccessResponse, Cookie> result = processInternal();
      httpResponse = HttpResponse.success(result.getLeft(), result.getRight());
    } catch (ServerException e) {
      Shared.logFailedRequest(logger, e);
      httpResponse = HttpResponse.error(e);
    }

    return httpResponse;
  }
  public boolean doCompile(Collection<CompilationUnitBuilder> builders) {
    List<ICompilationUnit> icus = new ArrayList<ICompilationUnit>();
    for (CompilationUnitBuilder builder : builders) {
      addPackages(Shared.getPackageName(builder.getTypeName()).replace('.', '/'));
      icus.add(new Adapter(builder));
    }
    if (icus.isEmpty()) {
      return false;
    }

    compilerImpl = new CompilerImpl();
    compilerImpl.compile(icus.toArray(new ICompilationUnit[icus.size()]));
    compilerImpl = null;
    return true;
  }
Ejemplo n.º 12
0
  public long run(String key, long by, byte increment) {
    final int now = Shared.init(this, key);

    voltQueueSQL(check, key, now);
    VoltTable checkResult = voltExecuteSQL()[1];
    if (checkResult.getRowCount() == 0) return VoltType.NULL_BIGINT;

    try {
      final byte[] oldRawData = checkResult.fetchRow(0).getVarbinary(1);
      final long old_value = Long.parseLong(new String(oldRawData, "UTF-8"));
      long value = old_value + (increment == 1 ? by : -by);
      if (value < 0l) // Underflow protection: per protocol, this should be an unsigned long...
      value = 0l;
      final byte[] newRawData = Long.toString(value).getBytes("UTF-8");
      voltQueueSQL(update, newRawData, key);
      voltExecuteSQL(true);
      return old_value;
    } catch (Exception x) {
      throw new VoltAbortException(x);
    }
  }
 private static Set<String> readPackages() {
   HashSet<String> pkgs = new HashSet<String>();
   String klass = "java/lang/Object.class";
   URL url = ClassLoader.getSystemClassLoader().getResource(klass);
   try {
     JarURLConnection connection = (JarURLConnection) url.openConnection();
     JarFile f = connection.getJarFile();
     Enumeration<JarEntry> entries = f.entries();
     while (entries.hasMoreElements()) {
       JarEntry e = entries.nextElement();
       String name = e.getName();
       if (name.endsWith(".class")) {
         String pkg = Shared.getSlashedPackageFrom(name);
         addPackageRecursively(pkgs, pkg);
       }
     }
     return pkgs;
   } catch (IOException e) {
     throw new InternalCompilerException("Unable to find JRE", e);
   }
 }
Ejemplo n.º 14
0
  private void updatePrices(Connection c, TotalPosWebService ws)
      throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException,
          XMLException {
    System.out.println(
        "[" + Shared.now() + "] UpdateStockFromSAP " + Shared.lineNumber() + " Actualizar precios");
    String myDay = Shared.getConfig("lastPriceUpdate");
    String newPrices =
        ws.listNewPriceFromDate(
            myDay,
            Shared.getConfig("storePrefix") + Shared.getConfig("storeName"),
            Shared.getConfig("Z"));
    System.out.println("newPrices = " + newPrices);

    ConnectionDrivers.setPrices(c, newPrices);
    ConnectionDrivers.setLastUpdateNow();
  }
Ejemplo n.º 15
0
 private String getProxyQualifiedName() {
   String[] name = Shared.synthesizeTopLevelClassName(serviceIntf, PROXY_SUFFIX);
   return name[0].length() == 0 ? name[1] : name[0] + "." + name[1];
 }
Ejemplo n.º 16
0
 protected String getProxySimpleName() {
   String[] name = Shared.synthesizeTopLevelClassName(serviceIntf, PROXY_SUFFIX);
   return name[1];
 }
Ejemplo n.º 17
0
  /**
   * Generates the client's asynchronous proxy method.
   *
   * @param serializableTypeOracle the type oracle
   */
  protected void generateProxyMethod(
      SourceWriter w,
      SerializableTypeOracle serializableTypeOracle,
      TypeOracle typeOracle,
      JMethod syncMethod,
      JMethod asyncMethod) {

    w.println();

    // Write the method signature
    JType asyncReturnType = asyncMethod.getReturnType().getErasedType();
    w.print("public ");
    w.print(asyncReturnType.getQualifiedSourceName());
    w.print(" ");
    w.print(asyncMethod.getName() + "(");

    boolean needsComma = false;
    NameFactory nameFactory = new NameFactory();
    JParameter[] asyncParams = asyncMethod.getParameters();
    for (int i = 0; i < asyncParams.length; ++i) {
      JParameter param = asyncParams[i];

      if (needsComma) {
        w.print(", ");
      } else {
        needsComma = true;
      }

      /*
       * Ignoring the AsyncCallback parameter, if any method requires a call to
       * SerializationStreamWriter.writeObject we need a try catch block
       */
      JType paramType = param.getType();
      paramType = paramType.getErasedType();

      w.print(paramType.getQualifiedSourceName());
      w.print(" ");

      String paramName = param.getName();
      nameFactory.addName(paramName);
      w.print(paramName);
    }

    w.println(") {");
    w.indent();

    String helperName = nameFactory.createName("helper");
    String helperClassName = RemoteServiceProxy.ServiceHelper.class.getCanonicalName();
    w.println(
        "%s %s = new %s(\"%s\", \"%s\");",
        helperClassName, helperName, helperClassName, getProxySimpleName(), syncMethod.getName());

    w.println("try {");
    w.indent();

    // Write the parameter count followed by the parameter values
    JParameter[] syncParams = syncMethod.getParameters();

    String streamWriterName = nameFactory.createName("streamWriter");
    w.println(
        "%s %s = %s.start(REMOTE_SERVICE_INTERFACE_NAME, %s);",
        SerializationStreamWriter.class.getSimpleName(),
        streamWriterName,
        helperName,
        syncParams.length);

    for (JParameter param : syncParams) {
      JType paramType = param.getType().getErasedType();
      String typeNameExpression = computeTypeNameExpression(paramType);
      assert typeNameExpression != null
          : "Could not compute a type name for " + paramType.getQualifiedSourceName();
      w.println(streamWriterName + ".writeString(" + typeNameExpression + ");");
    }

    // Encode all of the arguments to the asynchronous method, but exclude the
    // last argument which is the callback instance.
    //
    for (int i = 0; i < asyncParams.length - 1; ++i) {
      JParameter asyncParam = asyncParams[i];
      w.print(streamWriterName + ".");
      w.print(Shared.getStreamWriteMethodNameFor(asyncParam.getType()));
      w.println("(" + asyncParam.getName() + ");");
    }

    /*
     * Depending on the return type for the async method, return a
     * RequestBuilder, a Request, or nothing at all.
     */
    JParameter callbackParam = asyncParams[asyncParams.length - 1];
    JType returnType = syncMethod.getReturnType();
    String callbackName = callbackParam.getName();

    if (asyncReturnType == JPrimitiveType.VOID) {
      w.println(
          "%s.finish(%s, ResponseReader.%s);",
          helperName, callbackName, getResponseReaderFor(returnType).name());
    } else if (asyncReturnType.getQualifiedSourceName().equals(RequestBuilder.class.getName())) {
      w.println(
          "return %s.finishForRequestBuilder(%s, ResponseReader.%s);",
          helperName, callbackName, getResponseReaderFor(returnType).name());
    } else if (asyncReturnType.getQualifiedSourceName().equals(Request.class.getName())) {
      w.println(
          "return %s.finish(%s, ResponseReader.%s);",
          helperName, callbackName, getResponseReaderFor(returnType).name());
    } else {
      // This method should have been caught by RemoteServiceAsyncValidator
      throw new RuntimeException(
          "Unhandled return type " + asyncReturnType.getQualifiedSourceName());
    }

    w.outdent();
    w.print("} catch (SerializationException ");
    String exceptionName = nameFactory.createName("ex");
    w.println(exceptionName + ") {");
    w.indent();
    if (!asyncReturnType.getQualifiedSourceName().equals(RequestBuilder.class.getName())) {
      /*
       * If the method returns void or Request, signal the serialization error
       * immediately. If the method returns RequestBuilder, the error will be
       * signaled whenever RequestBuilder.send() is invoked.
       */
      w.println(callbackName + ".onFailure(" + exceptionName + ");");
    }
    if (asyncReturnType.getQualifiedSourceName().equals(RequestBuilder.class.getName())) {
      w.println(
          "return new "
              + FailingRequestBuilder.class.getName()
              + "("
              + exceptionName
              + ", "
              + callbackName
              + ");");
    } else if (asyncReturnType.getQualifiedSourceName().equals(Request.class.getName())) {
      w.println("return new " + FailedRequest.class.getName() + "();");
    } else {
      assert asyncReturnType == JPrimitiveType.VOID;
    }
    w.outdent();
    w.println("}");

    w.outdent();
    w.println("}");
  }
Ejemplo n.º 18
0
 public Price(Date date, Double quant) {
   this.date = date;
   this.quant = Shared.round(quant, 2);
 }
 @Override
 public char[][] getPackageName() {
   String packageName = Shared.getPackageName(builder.getTypeName());
   return CharOperation.splitOn('.', packageName.toCharArray());
 }
Ejemplo n.º 20
0
 Rodent(Shared shared) {
   shared.addRef();
   System.out.println("Rodent()");
 }
Ejemplo n.º 21
0
  /**
   * @throws org.exist.xquery.XPathException
   * @see BasicFunction#eval(Sequence[], Sequence)
   */
  public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    // Check input parameters
    if (args.length != 2) {
      return Sequence.EMPTY_SEQUENCE;
    }

    ValidationReport report = new ValidationReport();
    StreamSource instance = null;
    StreamSource grammars[] = null;

    try {
      report.start();

      // Get inputstream for instance document
      instance = Shared.getStreamSource(args[0].itemAt(0), context);

      // Validate using resource speciefied in second parameter
      grammars = Shared.getStreamSource(args[1], context);

      for (StreamSource grammar : grammars) {
        String grammarUrl = grammar.getSystemId();
        if (grammarUrl != null && !grammarUrl.endsWith(".xsd")) {
          throw new XPathException("Only XML schemas (.xsd) are supported.");
        }
      }

      // Prepare
      String schemaLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
      SchemaFactory factory = SchemaFactory.newInstance(schemaLang);

      // Create grammar
      Schema schema = factory.newSchema(grammars);

      // Setup validator
      Validator validator = schema.newValidator();
      validator.setErrorHandler(report);

      // Perform validation
      validator.validate(instance);

    } catch (MalformedURLException ex) {
      LOG.error(ex.getMessage());
      report.setException(ex);

    } catch (ExistIOException ex) {
      LOG.error(ex.getCause());
      report.setException(ex);

    } catch (Throwable ex) {
      LOG.error(ex);
      report.setException(ex);

    } finally {
      report.stop();

      Shared.closeStreamSource(instance);
      Shared.closeStreamSources(grammars);
    }

    // Create response
    if (isCalledAs("jaxv")) {
      Sequence result = new ValueSequence();
      result.add(new BooleanValue(report.isValid()));
      return result;

    } else /* isCalledAs("jaxv-report") */ {
      MemTreeBuilder builder = context.getDocumentBuilder();
      NodeImpl result = Shared.writeReport(report, builder);
      return result;
    }
  }
Ejemplo n.º 22
0
      /**
       * A callback after the JDT compiler has compiled a .java file and created a matching
       * CompilationUnitDeclaration. We take this opportunity to create a matching CompilationUnit.
       */
      @Override
      public void process(
          CompilationUnitBuilder builder,
          CompilationUnitDeclaration cud,
          List<CompiledClass> compiledClasses) {
        Event event = SpeedTracerLogger.start(DevModeEventType.CSB_PROCESS);
        try {
          Map<MethodDeclaration, JsniMethod> jsniMethods =
              JsniCollector.collectJsniMethods(
                  cud,
                  builder.getSourceMapPath(),
                  builder.getSource(),
                  JsRootScope.INSTANCE,
                  DummyCorrelationFactory.INSTANCE);

          JSORestrictionsChecker.check(jsoState, cud);

          // JSNI check + collect dependencies.
          final Set<String> jsniDeps = new HashSet<String>();
          Map<String, Binding> jsniRefs = new HashMap<String, Binding>();
          JsniChecker.check(
              cud,
              jsoState,
              jsniMethods,
              jsniRefs,
              new JsniChecker.TypeResolver() {
                @Override
                public ReferenceBinding resolveType(String sourceOrBinaryName) {
                  ReferenceBinding resolveType = compiler.resolveType(sourceOrBinaryName);
                  if (resolveType != null) {
                    jsniDeps.add(String.valueOf(resolveType.qualifiedSourceName()));
                  }
                  return resolveType;
                }
              });

          Map<TypeDeclaration, Binding[]> artificialRescues =
              new HashMap<TypeDeclaration, Binding[]>();
          ArtificialRescueChecker.check(cud, builder.isGenerated(), artificialRescues);
          if (compilerContext.shouldCompileMonolithic()) {
            // GWT drives JDT in a way that allows missing references in the source to be resolved
            // to precompiled bytecode on disk (see INameEnvironment). This is done so that
            // annotations can be supplied in bytecode form only. But since no AST is available for
            // these types it creates the danger that some functional class (not just an annotation)
            // gets filled in but is missing AST. This would cause later compiler stages to fail.
            //
            // Library compilation needs to ignore this check since it is expected behavior for the
            // source being compiled in a library to make references to other types which are only
            // available as bytecode coming out of dependency libraries.
            //
            // But if the referenced bytecode did not come from a dependency library but instead was
            // free floating in the classpath, then there is no guarrantee that AST for it was ever
            // seen and translated to JS anywhere in the dependency tree. This would be a mistake.
            //
            // TODO(stalcup): add a more specific check for library compiles such that binary types
            // can be referenced but only if they are an Annotation or if the binary type comes from
            // a dependency library.
            BinaryTypeReferenceRestrictionsChecker.check(cud);
          }

          MethodArgNamesLookup methodArgs =
              MethodParamCollector.collect(cud, builder.getSourceMapPath());

          Interner<String> interner = StringInterner.get();
          String packageName = interner.intern(Shared.getPackageName(builder.getTypeName()));
          List<String> unresolvedQualified = new ArrayList<String>();
          List<String> unresolvedSimple = new ArrayList<String>();
          for (char[] simpleRef : cud.compilationResult().simpleNameReferences) {
            unresolvedSimple.add(interner.intern(String.valueOf(simpleRef)));
          }
          for (char[][] qualifiedRef : cud.compilationResult().qualifiedReferences) {
            unresolvedQualified.add(interner.intern(CharOperation.toString(qualifiedRef)));
          }
          for (String jsniDep : jsniDeps) {
            unresolvedQualified.add(interner.intern(jsniDep));
          }
          ArrayList<String> apiRefs = compiler.collectApiRefs(cud);
          for (int i = 0; i < apiRefs.size(); ++i) {
            apiRefs.set(i, interner.intern(apiRefs.get(i)));
          }
          Dependencies dependencies =
              new Dependencies(packageName, unresolvedQualified, unresolvedSimple, apiRefs);

          List<JDeclaredType> types = Collections.emptyList();
          if (!cud.compilationResult().hasErrors()) {
            // Make a GWT AST.
            types =
                astBuilder.process(
                    cud, builder.getSourceMapPath(), artificialRescues, jsniMethods, jsniRefs);
          }

          for (CompiledClass cc : compiledClasses) {
            allValidClasses.put(cc.getSourceName(), cc);
          }

          builder
              .setClasses(compiledClasses)
              .setTypes(types)
              .setDependencies(dependencies)
              .setJsniMethods(jsniMethods.values())
              .setMethodArgs(methodArgs)
              .setProblems(cud.compilationResult().getProblems());
          buildQueue.add(builder);
        } finally {
          event.end();
        }
      }
Ejemplo n.º 23
0
 public Price getIva() {
   return new Price(
       getDate(), Shared.round(getQuant() * (Double.valueOf(Shared.getConfig().get("iva"))), 2));
 }
Ejemplo n.º 24
0
 public Price(Price p) {
   this.date = p.getDate();
   this.quant = Shared.round(p.getQuant(), 2);
 }
 @Override
 public char[] getMainTypeName() {
   return Shared.getShortName(builder.getTypeName()).toCharArray();
 }
Ejemplo n.º 26
0
  @Override
  public void doIt() {

    System.out.println(
        "[" + Shared.now() + "] UpdateStockFromSAP " + Shared.lineNumber() + " Operando");
    Connection c = null;
    try {
      Shared.createBackup(
          "articulo precio codigo_de_barras costo movimiento_inventario detalles_movimientos");

      TotalPosWebService ws = new TotalPosWebServiceService().getTotalPosWebServicePort();

      c = ConnectionDrivers.cpds.getConnection();
      c.setAutoCommit(false);

      if (mode.equals("MM") || mode.equals("MMBackground")) {

        String ansListMM =
            ws.listMMwithPrices(
                Shared.getConfig("storePrefix") + Shared.getConfig("storeName"),
                Shared.getConfig("Z"),
                ConnectionDrivers.getLastMM());
        // String ansListMM = ws.listMM("4900458128");
        System.out.println(
            "["
                + Shared.now()
                + "] UpdateStockFromSAP "
                + Shared.lineNumber()
                + " ansListMM = "
                + ansListMM);

        String itemsNeeded = ConnectionDrivers.createNewMovement(c, ansListMM);
        ansListMM = null;
        System.out.println(
            "["
                + Shared.now()
                + "] UpdateStockFromSAP "
                + Shared.lineNumber()
                + " itemsNeeded = "
                + itemsNeeded);

        // Update prices too
        updatePrices(c, ws);

        // flagsC
        updateFlagC(c, ws);

        // Descriptions
        updateDescriptions(c, ws);

        System.out.println(
            "[" + Shared.now() + "] UpdateStockFromSAP " + Shared.lineNumber() + " Listo!");
      } else if (mode.equals("Prices")) {
        updatePrices(c, ws);
      } else if (mode.equals("initialStock")) {

        String ansListMM =
            ws.getInitialStockWithPrices(
                Shared.getConfig("storePrefix") + Shared.getConfig("storeName"),
                Shared.getConfig("Z"));
        System.out.println(
            "["
                + Shared.now()
                + "] UpdateStockFromSAP "
                + Shared.lineNumber()
                + "  ansListMM = "
                + ansListMM);
        ConnectionDrivers.getInitialStock(c, ansListMM);

        ConnectionDrivers.disableInitialStock(c);

        System.out.println(
            "[" + Shared.now() + "] UpdateStockFromSAP " + Shared.lineNumber() + " Listo!");
      } else if (mode.equals("profitWorkers")) {
        System.out.println(
            "["
                + Shared.now()
                + "] UpdateStockFromSAP "
                + Shared.lineNumber()
                + " Profit DB Name "
                + Shared.getConfig("profitDatabase"));
        String ans =
            ws.listEmployCode(
                Shared.getConfig("storeNameProfit"), Shared.getConfig("profitDatabase"));
        System.out.println(
            "[" + Shared.now() + "] UpdateStockFromSAP " + Shared.lineNumber() + " Ans = " + ans);
        ConnectionDrivers.updateEmployees(ans);
      }

      System.out.println(
          "["
              + Shared.now()
              + "] UpdateStockFromSAP "
              + Shared.lineNumber()
              + " Haciendo el commit...");
      c.commit();
      System.out.println(
          "["
              + Shared.now()
              + "] UpdateStockFromSAP "
              + Shared.lineNumber()
              + " Terminado commit Exitoso!");

      if (!mode.equals("MMBackground")) {
        MessageBox msg = new MessageBox(MessageBox.SGN_SUCCESS, "Actualizado!");
        msg.show(Shared.getMyMainWindows());
      } else {
        System.exit(0);
      }
    } catch (Exception ex) {
      System.out.println(
          "["
              + Shared.now()
              + "] UpdateStockFromSAP "
              + Shared.lineNumber()
              + " Comenzo la exception");
      try {
        System.out.println(
            "["
                + Shared.now()
                + "] UpdateStockFromSAP "
                + Shared.lineNumber()
                + " Haciendo Rollback");
        c.rollback();
        System.out.println(
            "[" + Shared.now() + "] UpdateStockFromSAP " + Shared.lineNumber() + " Reversado!");
        MessageBox msg =
            new MessageBox(
                MessageBox.SGN_DANGER,
                "Ha ocurrido un error. No se ha guardado ningun cambio.",
                ex);
        msg.show(Shared.getMyMainWindows());
      } catch (Exception ex1) {
        // We are in problems :(
        MessageBox msg =
            new MessageBox(
                MessageBox.SGN_DANGER,
                "Ha ocurrido un error. No se ha guardado ningun cambio.",
                ex);
        msg.show(Shared.getMyMainWindows());
        System.out.println(
            "["
                + Shared.now()
                + "] UpdateStockFromSAP "
                + Shared.lineNumber()
                + "  Ha ocurrido un error. Haciendo Roll back..."
                + ex1.getMessage());
      }
    } finally {
      try {
        c.close();
      } catch (SQLException ex) {
        System.out.println(
            "["
                + Shared.now()
                + "] UpdateStockFromSAP "
                + Shared.lineNumber()
                + " Ha ocurrido un error cerrando la conexion. "
                + ex.getMessage());
      }
    }
  }
 public void addCompiledUnit(CompilationUnit unit) {
   addPackages(Shared.getPackageName(unit.getTypeName()).replace('.', '/'));
   addBinaryTypes(unit.getCompiledClasses());
 }
  private Pair<LogoutSuccessResponse, Cookie> processInternal() throws ServerException {
    String sessionIdString =
        this.httpRequest.getCookieValue(Shared.getSessionCookieName(this.tenantInfo.getName()));
    SessionID sessionId = null;
    SessionManager.Entry entry = null;
    if (sessionIdString != null) {
      sessionId = new SessionID(sessionIdString);
      entry = this.sessionManager.get(sessionId);
    }

    SignedJWT idTokenJwt = this.logoutRequest.getIDTokenHint().getSignedJWT();

    boolean validSignature;
    try {
      validSignature = idTokenJwt.verify(new RSASSAVerifier(this.tenantInfo.getPublicKey()));
    } catch (JOSEException e) {
      throw new ServerException(
          OAuth2Error.SERVER_ERROR.setDescription("error while verifying id_token signature"), e);
    }
    if (!validSignature) {
      throw new ServerException(
          OAuth2Error.INVALID_REQUEST.setDescription("id_token has an invalid signature"));
    }

    ReadOnlyJWTClaimsSet idTokenClaimsSet;
    try {
      idTokenClaimsSet = idTokenJwt.getJWTClaimsSet();
    } catch (ParseException e) {
      throw new ServerException(
          OAuth2Error.INVALID_REQUEST.setDescription("failed to parse claims out of id_token"), e);
    }

    ErrorObject error = validateIdTokenClaims(idTokenClaimsSet, entry);
    if (error != null) {
      throw new ServerException(error);
    }

    ClientID clientId = new ClientID(idTokenClaimsSet.getAudience().get(0));
    ClientInfo clientInfo =
        this.clientInfoRetriever.retrieveClientInfo(this.tenantInfo.getName(), clientId);
    if (clientInfo.getCertSubjectDn() != null) {
      if (this.logoutRequest.getClientAssertion() != null) {
        this.solutionUserAuthenticator.authenticateByClientAssertion(
            this.logoutRequest.getClientAssertion(),
            REQUEST_LIFETIME_MS,
            this.httpRequest.getRequestUrl(),
            this.tenantInfo,
            clientInfo);
      } else {
        throw new ServerException(
            OAuth2Error.INVALID_CLIENT.setDescription(
                "client_assertion parameter is required since client has registered a cert"));
      }
    }

    if (this.logoutRequest.getPostLogoutRedirectionURI() != null) {
      if (!clientInfo
          .getPostLogoutRedirectUris()
          .contains(this.logoutRequest.getPostLogoutRedirectionURI())) {
        throw new ServerException(
            OAuth2Error.INVALID_REQUEST.setDescription("unregistered post_logout_redirect_uri"));
      }
    }

    // SLO using OpenID Connect HTTP-Based Logout 1.0 - draft 03
    // construct iframe links containing logout_uri requests, the browser will send these to other
    // participating clients
    // do not include the client that initiated this logout request as that client has already
    // logged out before sending us this request
    Set<URI> logoutUris = new HashSet<URI>();
    if (entry != null) {
      for (ClientInfo client : entry.getClients()) {
        if (client.getLogoutUri() != null && !client.getID().equals(clientId)) {
          logoutUris.add(client.getLogoutUri());
        }
      }
      this.sessionManager.remove(sessionId);
    }

    return Pair.of(
        new LogoutSuccessResponse(
            this.logoutRequest.getPostLogoutRedirectionURI(),
            this.logoutRequest.getState(),
            sessionId,
            logoutUris),
        (sessionId == null) ? null : wipeOutSessionCookie());
  }
Ejemplo n.º 29
0
 Consumer(Shared s) {
   this.s = s;
   l = s.getLock();
 }
Ejemplo n.º 30
0
  /**
   * @throws org.exist.xquery.XPathException
   * @see BasicFunction#eval(Sequence[], Sequence)
   */
  public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    // Check input parameters
    if (args.length != 2) {
      return Sequence.EMPTY_SEQUENCE;
    }

    ValidationReport report = new ValidationReport();
    InputSource instance = null;
    InputSource grammar = null;

    try {
      report.start();

      // Get inputstream of XML instance document
      instance = Shared.getInputSource(args[0].itemAt(0), context);

      // Validate using resource specified in second parameter
      grammar = Shared.getInputSource(args[1].itemAt(0), context);

      // Special setup for compact notation
      String grammarUrl = grammar.getSystemId();
      SchemaReader schemaReader =
          ((grammarUrl != null) && (grammarUrl.endsWith(".rnc")))
              ? CompactSchemaReader.getInstance()
              : null;

      // Setup validation properties. see Jing interface
      PropertyMapBuilder properties = new PropertyMapBuilder();
      ValidateProperty.ERROR_HANDLER.put(properties, report);

      // Register resolver for xmldb:exist:/// embedded URLs
      ExistResolver resolver = new ExistResolver(brokerPool);
      ValidateProperty.URI_RESOLVER.put(properties, resolver);
      ValidateProperty.ENTITY_RESOLVER.put(properties, resolver);

      // Setup driver
      ValidationDriver driver = new ValidationDriver(properties.toPropertyMap(), schemaReader);

      // Load schema
      driver.loadSchema(grammar);

      // Validate XML instance
      driver.validate(instance);

    } catch (MalformedURLException ex) {
      LOG.error(ex.getMessage());
      report.setException(ex);

    } catch (ExistIOException ex) {
      LOG.error(ex.getCause());
      report.setException(ex);

    } catch (Throwable ex) {
      LOG.error(ex);
      report.setException(ex);

    } finally {
      Shared.closeInputSource(instance);
      Shared.closeInputSource(grammar);
      report.stop();
    }

    // Create response
    if (isCalledAs("jing")) {
      Sequence result = new ValueSequence();
      result.add(new BooleanValue(report.isValid()));
      return result;

    } else /* isCalledAs("jing-report") */ {
      MemTreeBuilder builder = context.getDocumentBuilder();
      NodeImpl result = Shared.writeReport(report, builder);
      return result;
    }
  }