public ASTUnannReferenceType deepClone(ASTUnannReferenceType result) {

    /* generated by template ast.ErrorIfNull*/
    Log.errorIfNull(result, "0xA7006_806 Parameter 'result' must not be null.");

    /* generated by template ast.additionalmethods.DeepCloneWithParameters*/

    super.deepClone(result);

    result.unannClassOrInterfaceType =
        this.unannClassOrInterfaceType.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannClassOrInterfaceType)
                    this.unannClassOrInterfaceType.get().deepClone())
            : Optional.empty();
    result.unannTypeVariable =
        this.unannTypeVariable.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannTypeVariable) this.unannTypeVariable.get().deepClone())
            : Optional.empty();
    result.unannArrayType =
        this.unannArrayType.isPresent()
            ? Optional.ofNullable(
                (java8._ast.ASTUnannArrayType) this.unannArrayType.get().deepClone())
            : Optional.empty();
    result.symbol =
        this.symbol.isPresent()
            ? Optional.ofNullable((Symbol) this.symbol.get())
            : Optional.empty();
    result.enclosingScope =
        this.enclosingScope.isPresent()
            ? Optional.ofNullable((Scope) this.enclosingScope.get())
            : Optional.empty();
    return result;
  }
示例#2
0
 public static Container setup() throws IOException {
   Properties properties = new Properties();
   File revProps = new File("revenj.properties");
   if (revProps.exists() && revProps.isFile()) {
     properties.load(new FileReader(revProps));
   } else {
     String location = System.getProperty("revenj.properties");
     if (location != null) {
       revProps = new File(location);
       if (revProps.exists() && revProps.isFile()) {
         properties.load(new FileReader(revProps));
       } else {
         throw new IOException(
             "Unable to find revenj.properties in alternative location. Searching in: "
                 + revProps.getAbsolutePath());
       }
     } else {
       throw new IOException(
           "Unable to find revenj.properties. Searching in: " + revProps.getAbsolutePath());
     }
   }
   String plugins = properties.getProperty("revenj.pluginsPath");
   File pluginsPath = null;
   if (plugins != null) {
     File pp = new File(plugins);
     pluginsPath = pp.isDirectory() ? pp : null;
   }
   return setup(
       dataSource(properties),
       properties,
       Optional.ofNullable(pluginsPath),
       Optional.ofNullable(Thread.currentThread().getContextClassLoader()));
 }
  @Test
  public void testFindAvailableSeatsForLevels() throws ParseException {
    final NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(seatsDb);
    final SeatDaoImpl seatDao = new SeatDaoImpl();
    seatDao.setNamedParameterJdbcTemplate(template);

    final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    final String dateInString = "2015-12-12";

    final Date date = formatter.parse(dateInString);

    final Optional<Date> reservationDate = Optional.of(date);

    final Integer minVenueLevel = Integer.valueOf(1);
    final Integer maxVenueLevel = Integer.valueOf(3);

    final Optional<Integer> optionalMinLevel = Optional.ofNullable(minVenueLevel);
    final Optional<Integer> optionalMaxLevel = Optional.ofNullable(maxVenueLevel);

    final List<SeatAndShowTimeInfo> seats =
        seatDao.findAvailableSeatsForVenueLevels(
            optionalMinLevel, optionalMaxLevel, reservationDate);

    Assert.assertNotNull(seats);
    Assert.assertEquals(42, seats.size());
  }
示例#4
0
  @Override
  protected RelationPlan visitSampledRelation(SampledRelation node, Void context) {
    if (node.getColumnsToStratifyOn().isPresent()) {
      throw new UnsupportedOperationException("STRATIFY ON is not yet implemented");
    }

    RelationPlan subPlan = process(node.getRelation(), context);

    TupleDescriptor outputDescriptor = analysis.getOutputDescriptor(node);
    double ratio = analysis.getSampleRatio(node);
    Symbol sampleWeightSymbol = null;
    if (node.getType() == SampledRelation.Type.POISSONIZED) {
      sampleWeightSymbol = symbolAllocator.newSymbol("$sampleWeight", BIGINT);
    }
    PlanNode planNode =
        new SampleNode(
            idAllocator.getNextId(),
            subPlan.getRoot(),
            ratio,
            SampleNode.Type.fromType(node.getType()),
            node.isRescaled(),
            Optional.ofNullable(sampleWeightSymbol));
    return new RelationPlan(
        planNode,
        outputDescriptor,
        subPlan.getOutputSymbols(),
        Optional.ofNullable(sampleWeightSymbol));
  }
    public GremlinExecutor create() {
      final BasicThreadFactory threadFactory =
          new BasicThreadFactory.Builder().namingPattern("gremlin-executor-default-%d").build();

      final AtomicBoolean poolCreatedByBuilder = new AtomicBoolean();
      final AtomicBoolean suppliedExecutor = new AtomicBoolean(true);
      final AtomicBoolean suppliedScheduledExecutor = new AtomicBoolean(true);

      final ExecutorService es =
          Optional.ofNullable(executorService)
              .orElseGet(
                  () -> {
                    poolCreatedByBuilder.set(true);
                    suppliedExecutor.set(false);
                    return Executors.newScheduledThreadPool(4, threadFactory);
                  });
      executorService = es;

      final ScheduledExecutorService ses =
          Optional.ofNullable(scheduledExecutorService)
              .orElseGet(
                  () -> {
                    // if the pool is created by the builder and we need another just re-use it,
                    // otherwise create
                    // a new one of those guys
                    suppliedScheduledExecutor.set(false);
                    return (poolCreatedByBuilder.get())
                        ? (ScheduledExecutorService) es
                        : Executors.newScheduledThreadPool(4, threadFactory);
                  });
      scheduledExecutorService = ses;

      return new GremlinExecutor(this, suppliedExecutor.get(), suppliedScheduledExecutor.get());
    }
  public ASTTemplateargument deepClone(ASTTemplateargument result) {

    /* generated by template ast.ErrorIfNull*/
    Log.errorIfNull(result, "0xA7006_977 Parameter 'result' must not be null.");

    /* generated by template ast.additionalmethods.DeepCloneWithParameters*/

    super.deepClone(result);

    result.constantexpression =
        this.constantexpression.isPresent()
            ? Optional.ofNullable(
                (cpp14._ast.ASTConstantexpression) this.constantexpression.get().deepClone())
            : Optional.empty();
    result.typeidP =
        this.typeidP.isPresent()
            ? Optional.ofNullable((cpp14._ast.ASTTypeidP) this.typeidP.get().deepClone())
            : Optional.empty();
    result.idexpression =
        this.idexpression.isPresent()
            ? Optional.ofNullable((cpp14._ast.ASTIdexpression) this.idexpression.get().deepClone())
            : Optional.empty();
    result.symbol =
        this.symbol.isPresent()
            ? Optional.ofNullable((Symbol) this.symbol.get())
            : Optional.empty();
    result.enclosingScope =
        this.enclosingScope.isPresent()
            ? Optional.ofNullable((Scope) this.enclosingScope.get())
            : Optional.empty();
    return result;
  }
示例#7
0
 private void assertCommonSuperType(Type firstType, Type secondType, Type expected) {
   TypeRegistry typeManager = new TypeRegistry();
   assertEquals(
       typeManager.getCommonSuperType(firstType, secondType), Optional.ofNullable(expected));
   assertEquals(
       typeManager.getCommonSuperType(secondType, firstType), Optional.ofNullable(expected));
 }
示例#8
0
  public static Table fromMetastoreApiTable(org.apache.hadoop.hive.metastore.api.Table table) {
    StorageDescriptor storageDescriptor = table.getSd();
    if (storageDescriptor == null) {
      throw new PrestoException(HIVE_INVALID_METADATA, "Table is missing storage descriptor");
    }

    Table.Builder tableBuilder =
        Table.builder()
            .setDatabaseName(table.getDbName())
            .setTableName(table.getTableName())
            .setOwner(nullToEmpty(table.getOwner()))
            .setTableType(table.getTableType())
            .setDataColumns(
                storageDescriptor
                    .getCols()
                    .stream()
                    .map(MetastoreUtil::fromMetastoreApiFieldSchema)
                    .collect(toList()))
            .setPartitionColumns(
                table
                    .getPartitionKeys()
                    .stream()
                    .map(MetastoreUtil::fromMetastoreApiFieldSchema)
                    .collect(toList()))
            .setParameters(
                table.getParameters() == null ? ImmutableMap.of() : table.getParameters())
            .setViewOriginalText(Optional.ofNullable(emptyToNull(table.getViewOriginalText())))
            .setViewExpandedText(Optional.ofNullable(emptyToNull(table.getViewExpandedText())));

    fromMetastoreApiStorageDescriptor(
        storageDescriptor, tableBuilder.getStorageBuilder(), table.getTableName());

    return tableBuilder.build();
  }
示例#9
0
 public static Optional<String> envToOpt(final String envName) {
   Optional<String> system = Optional.ofNullable(System.getenv(envName));
   if (system.isPresent()) {
     return system;
   }
   return Optional.ofNullable(System.getProperty(envName));
 }
示例#10
0
  /**
   * Encode the MRIB into json format.
   *
   * @param mcastRouteTable McastRouteTable
   * @param context CodecContext
   * @return result ObjectNode
   */
  @Override
  public ObjectNode encode(McastRouteTable mcastRouteTable, CodecContext context) {

    final JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
    final ObjectNode macastRouteTabNode = nodeFactory.objectNode();
    ArrayNode mcastGroupNode = context.mapper().createArrayNode();
    Optional<McastRouteTable> mcastRouteTabOpt = Optional.ofNullable(mcastRouteTable);

    // checking whether the McastRouteTable is present.
    if (mcastRouteTabOpt.isPresent()) {
      Map<IpPrefix, McastRouteGroup> mrib4 = mcastRouteTabOpt.get().getMrib4();
      Optional<Map<IpPrefix, McastRouteGroup>> mrib4Opt = Optional.ofNullable(mrib4);

      // checking whether the mrib4 is present.
      if (mrib4Opt.isPresent()) {

        for (McastRouteGroup mg : mrib4Opt.get().values()) {
          Collection<McastRouteSource> mcastRoute = mg.getSources().values();
          Optional<Collection<McastRouteSource>> mcastRouteOpt = Optional.ofNullable(mcastRoute);

          // checking whether the McastRouteSource List is present.
          if (mcastRouteOpt.isPresent()) {
            for (McastRouteSource mcastRouteSource : mcastRouteOpt.get()) {
              mcastGroupNode.add(createMcastGroupNode(mcastRouteSource, context));
            }
            macastRouteTabNode.put(MCAST_GROUP, mcastGroupNode);
          }
        }
      }
    }
    return macastRouteTabNode;
  }
示例#11
0
 private static void test1() {
   Optional.of(new Outer())
       .flatMap(o -> Optional.ofNullable(o.nested))
       .flatMap(n -> Optional.ofNullable(n.inner))
       .flatMap(i -> Optional.ofNullable(i.foo))
       .ifPresent(System.out::println);
 }
示例#12
0
 /**
  * @param userSSH The username to connect to
  * @param password The password to use, nullable
  * @param host The host's address
  * @param remoteDir The remote directory to ssh into
  * @param port The port to to use.
  */
 public SecureShellDetails(
     String userSSH, String password, String host, String remoteDir, int port) {
   this.userSSH = checkNotNull(userSSH, "userSSH can not be null");
   this.password = Optional.ofNullable(password);
   this.host = checkNotNull(host, "host can not be null");
   this.remoteDir = Optional.ofNullable(remoteDir);
   this.port = port;
 }
示例#13
0
 private void assertCommonSuperType(String firstType, String secondType, String expected) {
   assertEquals(
       typeRegistry.getCommonSuperType(createType(firstType), createType(secondType)),
       Optional.ofNullable(expected).map(this::createType));
   assertEquals(
       typeRegistry.getCommonSuperType(createType(secondType), createType(firstType)),
       Optional.ofNullable(expected).map(this::createType));
 }
示例#14
0
  @Test
  public void _07_옵션값_생성() {
    assertThat(inverse(0d), is(Optional.empty()));
    assertThat(inverse(10d), is(Optional.of(0.1d)));

    // ofNullalbe -> null 값 처리
    assertThat(Optional.ofNullable(null), is(Optional.empty()));
    assertThat(Optional.ofNullable("test"), is(Optional.of("test")));
  }
示例#15
0
  public Collection<String> getArguments() {
    Collection<String> args = new ArrayList<>();
    Optional.ofNullable(username).ifPresent(s -> args.addAll(Arrays.asList("-u", s)));
    Optional.ofNullable(password).ifPresent(s -> args.addAll(Arrays.asList("-p", s)));
    Optional.ofNullable(from)
        .ifPresent(d -> args.addAll(Arrays.asList("-f", d.format(DateTimeFormatter.ISO_DATE))));

    return args;
  }
示例#16
0
 @Override
 public void addResponseCookie(final Cookie cookie) {
   Definition c = new Definition(cookie.getName(), cookie.getValue());
   Optional.ofNullable(cookie.getDomain()).ifPresent(c::domain);
   Optional.ofNullable(cookie.getPath()).ifPresent(c::path);
   c.httpOnly(cookie.isHttpOnly());
   c.maxAge(cookie.getMaxAge());
   c.secure(cookie.isSecure());
   rsp.cookie(c);
 }
示例#17
0
 @RequestMapping(value = "/system/content/unpublish", method = RequestMethod.POST)
 public void unpublish(
     HttpServletResponse response,
     @RequestParam(value = "id", required = false) String id,
     @RequestParam(value = "uri", required = false) String uri,
     @RequestParam(value = "publisher") String publisher) {
   setPublishStatusOfItem(
       Optional.ofNullable(id), Optional.ofNullable(uri), Optional.ofNullable(publisher), false);
   response.setStatus(HttpServletResponse.SC_OK);
 }
示例#18
0
    private void whenKeepAlive() {
      boolean publishingEnabled = Subscription.this.publishingEnabled;
      boolean notificationsAvailable = notificationsAvailable();
      boolean publishRequestQueued = publishQueue().isNotEmpty();

      /* Subscription State Table Row 14 */
      if (publishingEnabled && notificationsAvailable && publishRequestQueued) {
        Optional<ServiceRequest<PublishRequest, PublishResponse>> service =
            Optional.ofNullable(publishQueue().poll());

        if (service.isPresent()) {
          setState(State.Normal);
          resetLifetimeCounter();
          returnNotifications(service.get());
          messageSent = true;
          startPublishingTimer();
        } else {
          whenKeepAlive();
        }
      }
      /* Subscription State Table Row 15 */
      else if (publishRequestQueued
          && keepAliveCounter == 1
          && (!publishingEnabled || (publishingEnabled && !notificationsAvailable))) {

        Optional<ServiceRequest<PublishRequest, PublishResponse>> service =
            Optional.ofNullable(publishQueue().poll());

        if (service.isPresent()) {
          returnKeepAlive(service.get());
          resetLifetimeCounter();
          resetKeepAliveCounter();
          startPublishingTimer();
        } else {
          whenKeepAlive();
        }
      }
      /* Subscription State Table Row 16 */
      else if (keepAliveCounter > 1
          && (!publishingEnabled || (publishingEnabled && !notificationsAvailable))) {

        keepAliveCounter--;
        startPublishingTimer();
      }
      /* Subscription State Table Row 17 */
      else if (!publishRequestQueued
          && (keepAliveCounter == 1
              || (keepAliveCounter > 1 && publishingEnabled && notificationsAvailable))) {

        setState(State.Late);
        startPublishingTimer();

        publishQueue().addSubscription(Subscription.this);
      }
    }
  /**
   * Validate a single job for this analytic technology in the context of the bucket/other jobs
   *
   * @param analytic_bucket - the bucket (just for context)
   * @param jobs - the entire list of jobs (not normally required)
   * @param job - the actual job
   * @return the validated bean (check for success:false)
   */
  public static BasicMessageBean validateJob(
      final DataBucketBean analytic_bucket,
      final Collection<AnalyticThreadJobBean> jobs,
      final AnalyticThreadJobBean job) {

    final LinkedList<String> errors = new LinkedList<>();

    // This is for Storm specific validation
    // The core validation checks most of the "boilerplate" type requirements

    // Temporary limitations we'll police
    // - currently can only handle streaming inputs
    // - currently transient outputs have to be streaming

    // inputs

    Optionals.ofNullable(job.inputs())
        .stream()
        .forEach(
            input -> {
              if (!"stream".equals(input.data_service())) {
                errors.add(
                    ErrorUtils.get(
                        ErrorUtils.TEMP_INPUTS_MUST_BE_STREAMING,
                        analytic_bucket.full_name(),
                        job.name(),
                        input.data_service()));
              }
            });

    // output:

    if (null != job.output()) {
      if (Optional.ofNullable(job.output().is_transient()).orElse(false)) {
        final MasterEnrichmentType output_type =
            Optional.ofNullable(job.output().transient_type()).orElse(MasterEnrichmentType.none);
        if (MasterEnrichmentType.streaming != output_type) {
          errors.add(
              ErrorUtils.get(
                  ErrorUtils.TEMP_TRANSIENT_OUTPUTS_MUST_BE_STREAMING,
                  analytic_bucket.full_name(),
                  job.name(),
                  output_type));
        }
      }
    }

    final boolean success = errors.isEmpty();

    return ErrorUtils.buildMessage(
        success,
        StormAnalyticTechnologyUtils.class,
        "validateJobs",
        errors.stream().collect(Collectors.joining(";")));
  }
示例#20
0
  /**
   * Decode json format and insert into the flow table.
   *
   * @param json ObjectNode
   * @param context CodecContext
   * @return mr McastRouteBase
   */
  @Override
  public McastRouteTable decode(ObjectNode json, CodecContext context) {

    String macAddr = null;
    String portNo = null;
    String sAddr = json.path(SOURCE_ADDRESS).asText();
    String gAddr = json.path(GROUP_ADDRESS).asText();
    JsonNode inPntObjNode = (JsonNode) json.path(INGRESS_POINT);
    JsonNode egPntArrNode = (JsonNode) json.path(EGRESS_POINT);

    log.debug("sAddr :" + sAddr + " gAddr :" + gAddr + " inPntObjNode :" + inPntObjNode);
    log.debug("egPntArrNode :" + egPntArrNode.toString());

    McastRouteTable mrib = McastRouteTable.getInstance();
    McastRouteBase mr = mrib.addRoute(sAddr, gAddr);
    Optional<JsonNode> inPntOpt = Optional.ofNullable(inPntObjNode);

    if (inPntOpt.isPresent()) {

      JsonNode inMcastCP = inPntOpt.get().path(MCASTCONNECTPOINT);
      Optional<JsonNode> inCpOpt = Optional.ofNullable(inMcastCP);

      if (inCpOpt.isPresent()) {
        macAddr = inCpOpt.get().path(ELEMENTID).asText();
        portNo = inCpOpt.get().path(PORTNUMBER).asText();
        mr.addIngressPoint(macAddr + "/" + Long.parseLong(portNo));
      }
    }

    Optional<JsonNode> egPntOpt = Optional.ofNullable(egPntArrNode);

    if (egPntOpt.isPresent()) {
      JsonNode egMcastCP = egPntOpt.get().path(MCASTCONNECTPOINT);
      Optional<JsonNode> egMcCpOpt = Optional.ofNullable(egMcastCP);

      if (egMcCpOpt.isPresent()) {
        Iterator<JsonNode> egCpIt = egMcCpOpt.get().elements();

        while (egCpIt.hasNext()) {

          JsonNode egMcastCPObj = egCpIt.next();
          Optional<JsonNode> egMcCpObOpt = Optional.ofNullable(egMcastCPObj);
          if (egMcCpObOpt.isPresent()) {
            macAddr = egMcCpObOpt.get().path(ELEMENTID).asText();
            portNo = egMcCpObOpt.get().path(PORTNUMBER).asText();
            log.debug("macAddr egPort : " + macAddr + " portNo egPort :" + portNo);
            mr.addEgressPoint(
                macAddr + "/" + Long.parseLong(portNo), McastConnectPoint.JoinSource.STATIC);
          }
        }
      }
    }
    return mrib;
  }
示例#21
0
  public static Optional<String> getTorrentName(ByteBuffer torrent) {
    BDecoder decoder = new BDecoder();
    Map<String, Object> root = decoder.decode(torrent.duplicate());

    return Optional.ofNullable((Map<String, Object>) root.get("info"))
        .map(
            info -> {
              return Optional.ofNullable((byte[]) info.get("name.utf-8"))
                  .orElse((byte[]) info.get("name"));
            })
        .map(bytes -> new String(bytes, StandardCharsets.UTF_8));
  }
示例#22
0
    private void whenNormal() {
      boolean publishRequestQueued = publishQueue().isNotEmpty();
      boolean publishingEnabled = Subscription.this.publishingEnabled;
      boolean notificationsAvailable = notificationsAvailable();

      /* Subscription State Table Row 6 */
      if (publishRequestQueued && publishingEnabled && notificationsAvailable) {
        Optional<ServiceRequest<PublishRequest, PublishResponse>> service =
            Optional.ofNullable(publishQueue().poll());

        if (service.isPresent()) {
          resetLifetimeCounter();
          returnNotifications(service.get());
          messageSent = true;
          startPublishingTimer();
        } else {
          whenNormal();
        }
      }
      /* Subscription State Table Row 7 */
      else if (publishRequestQueued
          && !messageSent
          && (!publishingEnabled || (publishingEnabled && !notificationsAvailable))) {
        Optional<ServiceRequest<PublishRequest, PublishResponse>> service =
            Optional.ofNullable(publishQueue().poll());

        if (service.isPresent()) {
          resetLifetimeCounter();
          returnKeepAlive(service.get());
          messageSent = true;
          startPublishingTimer();
        } else {
          whenNormal();
        }
      }
      /* Subscription State Table Row 8 */
      else if (!publishRequestQueued
          && (!messageSent || (publishingEnabled && notificationsAvailable))) {
        setState(State.Late);
        startPublishingTimer();

        publishQueue().addSubscription(Subscription.this);
      }
      /* Subscription State Table Row 9 */
      else if (messageSent
          && (!publishingEnabled || (publishingEnabled && !notificationsAvailable))) {
        setState(State.KeepAlive);
        resetKeepAliveCounter();
        startPublishingTimer();
      } else {
        throw new IllegalStateException("unhandled subscription state");
      }
    }
示例#23
0
  public void save() {
    final Properties properties = new Properties();
    Optional.ofNullable(username).ifPresent(s -> properties.setProperty("username", s));
    Optional.ofNullable(password).ifPresent(s -> properties.setProperty("password", s));
    Optional.ofNullable(from)
        .ifPresent(d -> properties.setProperty("from", d.format(DateTimeFormatter.ISO_DATE)));

    try {
      properties.store(getConfigurationWriter(), null);
    } catch (IOException e) {
      e.printStackTrace(); // TODO logging
    }
  }
 /**
  * Returns a SAML 2.0 Assertion Consumer URL based on service provider application context path.
  *
  * <p>An {@code Optional String} URL is returned based on the context path and configuration
  * properties provided.
  *
  * @param contextPath the context path of the service provider application
  * @param ssoSPConfigProperties the global single-sign-on configuration properties
  * @return a SAML 2.0 Assertion Consumer URL based on service provider application context path
  */
 protected static Optional generateConsumerUrl(
     String contextPath, Properties ssoSPConfigProperties) {
   if ((Optional.ofNullable(contextPath).isPresent())
       && (Optional.ofNullable(ssoSPConfigProperties).isPresent())) {
     return Optional.of(
         ssoSPConfigProperties.getProperty(SSOConstants.SAMLSSOValveConstants.APP_SERVER_URL)
             + contextPath
             + ssoSPConfigProperties.getProperty(
                 SSOConstants.SSOAgentConfiguration.SAML2.CONSUMER_URL_POSTFIX));
   } else {
     return Optional.empty();
   }
 }
  @PostConstruct
  public void init() {
    HttpServletRequest request =
        (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    Optional.ofNullable(request.getParameter("msgId"))
        .map(p -> this.msgService.get(Long.parseLong(p)))
        .ifPresent(this::setCurrent);
    Optional.ofNullable(request.getParameter("itemId"))
        .map(p -> this.itemService.get(Long.parseLong(p)))
        .ifPresent(this::createRequest);

    this.current.setSender(ssb.getLoggedUser());
  }
 private static Optional<String> getFilterColumn(
     Map<String, SerializableNativeValue> filters, String columnName) {
   SerializableNativeValue value = filters.get(columnName);
   if (value == null || value.getValue() == null) {
     return Optional.empty();
   }
   if (Slice.class.isAssignableFrom(value.getType())) {
     return Optional.ofNullable(((Slice) value.getValue()).toStringUtf8());
   }
   if (String.class.isAssignableFrom(value.getType())) {
     return Optional.ofNullable((String) value.getValue());
   }
   return Optional.empty();
 }
  public static void main(String[] args) {

    Sql2o sql2o = new Sql2o("jdbc:mysql://192.168.2.11:3306/db_school", "admin", "admin");

    String ipAddress = Optional.ofNullable(System.getenv("OPENSHIFT_DIY_IP")).orElse("0.0.0.0");
    int ipPort =
        Integer.parseInt(Optional.ofNullable(System.getenv("OPENSHIFT_DIY_PORT")).orElse("8008"));

    ipAddress(ipAddress);
    port(ipPort);

    new StudentController(new StudentService(sql2o));
    new SchoolClassController(new SchoolClassService(sql2o));
    new SchoolTimeTableController(new SchoolTimeTableService(sql2o));
  }
示例#28
0
 @Test
 public void testOptional() {
   Optional<String> fullName = Optional.ofNullable(null);
   Assert.assertEquals("Optional.empty", fullName.toString());
   Assert.assertEquals("[none]", fullName.orElseGet(() -> "[none]"));
   Assert.assertEquals("[none2]", fullName.orElse("[none2]"));
 }
  @Override
  public void start(final Future<Void> startFuture) throws Exception {
    LOGGER.info("starting {0}..", identifier());

    // start the HELLO slacker protocol
    final JsonObject helloMessage =
        new JsonObject().put("i", identifier()).put("d", description()).put("v", version());
    vertx
        .eventBus()
        .send(
            "reg.slacker-server",
            helloMessage,
            result -> {
              if (result.succeeded() && JsonObject.class.isInstance(result.result().body())) {
                final JsonObject response = (JsonObject) result.result().body();
                if (response.containsKey("a")) {
                  // everything went smoothly - register the listener and complete the startup
                  registerListener(response.getString("a"));
                  LOGGER.info("successfully registered {0} executor", identifier());
                  startFuture.complete();
                } else {
                  failStart(startFuture, "no address to bind was received");
                }
              } else {
                // something unexpected happened
                failStart(
                    startFuture,
                    Optional.ofNullable(result.cause())
                        .map(Throwable::getMessage)
                        .orElse("invalid response"));
              }
            });
  }
  public void setUnannClassOrInterfaceType(
      java8._ast.ASTUnannClassOrInterfaceType unannClassOrInterfaceType) {

    /* generated by template ast.additionalmethods.Set*/

    this.unannClassOrInterfaceType = Optional.ofNullable(unannClassOrInterfaceType);
  }