/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

package com.opengamma.language.identifier;

import com.opengamma.language.convert.AbstractMappedConverter;
import com.opengamma.language.convert.TypeMap;
import com.opengamma.language.definition.JavaTypeInfo;

/**
 * Converts ExternalSchemeRank to/from an array of strings.
 */
public class ExternalSchemeRankConverter extends AbstractMappedConverter {

  private static final JavaTypeInfo<String[]> STRING_ARRAY = JavaTypeInfo.builder(String[].class).get();
  private static final JavaTypeInfo<ExternalSchemeRank> EXTERNAL_SCHEME_RANK = JavaTypeInfo.builder(ExternalSchemeRank.class).get();

  /**
   * Default instance.
   */
  public static final ExternalSchemeRankConverter INSTANCE = new ExternalSchemeRankConverter();

  protected ExternalSchemeRankConverter() {
    conversion(TypeMap.ZERO_LOSS, STRING_ARRAY, EXTERNAL_SCHEME_RANK, new Action<String[], ExternalSchemeRank>() {
      @Override
      protected ExternalSchemeRank convert(final String[] value) {
        return ExternalSchemeRank.ofStrings(value);
      }
    });
    conversion(TypeMap.MINOR_LOSS, EXTERNAL_SCHEME_RANK, STRING_ARRAY, new Action<ExternalSchemeRank, String[]>() {
      @Override
      protected String[] convert(final ExternalSchemeRank value) {
        return value.asStrings();
      }
    });
  }

}

/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

package com.opengamma.language.identifier;

import com.opengamma.language.convert.AbstractMappedConverter;
import com.opengamma.language.convert.TypeMap;
import com.opengamma.language.definition.JavaTypeInfo;

/**
 * Converts ExternalSchemeRank to/from an array of strings.
 */
public class ExternalSchemeRankConverter extends AbstractMappedConverter {

  private static final JavaTypeInfo<String[]> STRING_ARRAY = JavaTypeInfo.builder(String[].class).allowNull().get();
  private static final JavaTypeInfo<ExternalSchemeRank> EXTERNAL_SCHEME_RANK = JavaTypeInfo.builder(ExternalSchemeRank.class).allowNull().get();

  /**
   * Default instance.
   */
  public static final ExternalSchemeRankConverter INSTANCE = new ExternalSchemeRankConverter();

  protected ExternalSchemeRankConverter() {
    conversion(TypeMap.ZERO_LOSS, STRING_ARRAY, EXTERNAL_SCHEME_RANK, new Action<String[], ExternalSchemeRank>() {
      @Override
      protected ExternalSchemeRank convert(final String[] value) {
        return ExternalSchemeRank.ofStrings(value);
      }
    });
    conversion(TypeMap.MINOR_LOSS, EXTERNAL_SCHEME_RANK, STRING_ARRAY, new Action<ExternalSchemeRank, String[]>() {
      @Override
      protected String[] convert(final ExternalSchemeRank value) {
        return value.asStrings();
      }
    });
  }

}

Allow NULL scheme rank conversions.

Allow NULL scheme rank conversions.


package entities;

import java.awt.Graphics2D;
import java.util.Random;

public class Entity {
  public static Random r;
  protected int cellX, cellY;

  public Entity() {
    this.r = new Random();
  }

  public Entity(int cellX, int cellY) {
    this.r = new Random();
    this.cellX = cellX;
    this.cellY = cellY;
  }

  public void setPosition(int cellX, int cellY) {
    this.cellX = cellX;
    this.cellY = cellY;
  }

  public void update() {}

  public void update(boolean[] keys) {}

  public void draw(Graphics2D g2d) {}

  public boolean collide(Entity entity) {
    if (entity.cellX == this.cellX && entity.cellY == this.cellY)
      return true;
    return false;
  }
}

package entities;

import java.awt.Graphics2D;
import java.util.Random;

public class Entity {
  public Random r;
  protected int cellX, cellY;

  public Entity() {
    this.r = new Random();
  }

  public Entity(int cellX, int cellY) {
    this.r = new Random();
    this.cellX = cellX;
    this.cellY = cellY;
  }

  public void setPosition(int cellX, int cellY) {
    this.cellX = cellX;
    this.cellY = cellY;
  }

  public void update() {}

  public void update(boolean[] keys) {}

  public void draw(Graphics2D g2d) {}

  public boolean collide(Entity entity) {
    if (entity.cellX == this.cellX && entity.cellY == this.cellY)
      return true;
    return false;
  }
}

Remove static modifier of r

Remove static modifier of r


package org.bricolages.streaming;

import lombok.Getter;
import lombok.Setter;

import org.bricolages.streaming.preflight.domains.DomainDefaultValues;
import org.bricolages.streaming.s3.ObjectMapper;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "bricolage")
public class Config {
    @Getter
    private final EventQueue eventQueue = new EventQueue();
    @Getter
    private final LogQueue logQueue = new LogQueue();
    @Getter
    private List<ObjectMapper.Entry> mappings = new ArrayList<>();

    @Setter
    static class EventQueue {
        String url;
        int visibilityTimeout;
        int maxNumberOfMessages;
        int waitTimeSeconds;
    }

    @Setter
    static class LogQueue {
        String url;
    }

    // preflight
    @Getter
    @Setter
    private String srcDs;
    @Getter
    @Setter
    private String destDs;
    @Getter
    @Setter
    private DomainDefaultValues defaults;
}

package org.bricolages.streaming;

import lombok.Getter;
import lombok.Setter;

import org.bricolages.streaming.s3.ObjectMapper;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "bricolage")
public class Config {
    @Getter
    private final EventQueue eventQueue = new EventQueue();
    @Getter
    private final LogQueue logQueue = new LogQueue();
    @Getter
    private List<ObjectMapper.Entry> mappings = new ArrayList<>();

    @Setter
    static class EventQueue {
        String url;
        int visibilityTimeout;
        int maxNumberOfMessages;
        int waitTimeSeconds;
    }

    @Setter
    static class LogQueue {
        String url;
    }

    // preflight
    @Getter
    @Setter
    private String srcDs;
    @Getter
    @Setter
    private String destDs;
}

Delete useless property (I do not clear why it was)


package seedu.address.ui;

import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import seedu.address.model.task.ReadOnlyTask;

public class TaskCard extends UiPart{

    private static final String FXML = "TaskListCard.fxml";

    @FXML
    private HBox cardPane;
    @FXML
    private Label detail;
    @FXML
    private Label id;
    @FXML
    private Label dbd;
    @FXML
    private Label dbt;
    @FXML
    private Label priority;
    @FXML
    private Label tags;

    private ReadOnlyTask task;
    private int displayedIndex;

    public TaskCard(){

    }

    public static TaskCard load(ReadOnlyTask task, int displayedIndex){
        TaskCard card = new TaskCard();
        card.task = task;
        card.displayedIndex = displayedIndex;
        return UiPartLoader.loadUiPart(card);
    }

    @FXML
    public void initialize() {
        detail.setText(task.getDetail().details);
        id.setText(displayedIndex + ". ");
        dbd.setText(task.getDueByDate().getFriendlyString());
        dbt.setText(task.getDueByTime().getFriendlyString());
        priority.setText(task.getPriority().value);
        tags.setText(task.tagsString());
    }

    public HBox getLayout() {
        return cardPane;
    }

    @Override
    public void setNode(Node node) {
        cardPane = (HBox)node;
    }

    @Override
    public String getFxmlPath() {
        return FXML;
    }
}

package seedu.address.ui;

import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import seedu.address.model.task.ReadOnlyTask;

public class TaskCard extends UiPart{

    private static final String FXML = "TaskListCard.fxml";

    @FXML
    private HBox cardPane;
    @FXML
    private Label detail;
    @FXML
    private Label id;
    @FXML
    private Label dbd;
    @FXML
    private Label dbt;
    @FXML
    private Label priority;
    @FXML
    private Label tags;

    private ReadOnlyTask task;
    private int displayedIndex;

    public TaskCard(){

    }

    public static TaskCard load(ReadOnlyTask task, int displayedIndex){
        TaskCard card = new TaskCard();
        card.task = task;
        card.displayedIndex = displayedIndex;
        return UiPartLoader.loadUiPart(card);
    }

    @FXML
    public void initialize() {
        detail.setText(task.getDetail().details);
        id.setText(displayedIndex + ". ");
        dbd.setText(task.getDueByDate().getFriendlyString());
        dbt.setText(task.getDueByTime().getFriendlyString());
        priority.setText(task.getPriority().value);
        tags.setText(task.tagsString());
        tags.setTextFill(Color.GOLD);
    }

    public HBox getLayout() {
        return cardPane;
    }

    @Override
    public void setNode(Node node) {
        cardPane = (HBox)node;
    }

    @Override
    public String getFxmlPath() {
        return FXML;
    }
}

Include task fields into taskcard - index,task,tag,due,priority


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem38;

/**
 * Given a binary tree, can you write a method to calculate every path to every leaf in the tree.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class PathToEveryLeaf {
}

/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem38;

import com.github.pedrovgs.binarytree.BinaryNode;
import java.util.LinkedList;
import java.util.List;

/**
 * Given a binary tree, can you write a method to calculate every path to every leaf in the tree.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class PathToEveryLeaf {

  /**
   * Recursive algorithm to solve this problem. The complexity order of this algorithm is O(N)
   * where N is the number of elements in the array in time and space terms.
   */
  public List<List<BinaryNode>> calculate(BinaryNode<Integer> root) {
    if (root == null) {
      throw new IllegalArgumentException("You can't pass a null instance of BinaryNode");
    }
    return calculatePathToLeafs(root, new LinkedList<BinaryNode>());
  }

  private static List<List<BinaryNode>> calculatePathToLeafs(BinaryNode<Integer> root,
      List<BinaryNode> path) {
    List<List<BinaryNode>> paths = new LinkedList<List<BinaryNode>>();
    if (root == null) {
      return paths;
    } else if (root.getLeft() == null && root.getRight() == null) {
      path.add(root);
      paths.add(path);
      return paths;
    } else {
      path.add(root);
      paths.addAll(calculatePathToLeafs(root.getLeft(), new LinkedList<BinaryNode>(path)));
      paths.addAll(calculatePathToLeafs(root.getRight(), new LinkedList<BinaryNode>(path)));
      return paths;
    }
  }
}

Add recursive solution to problem 38

Add recursive solution to problem 38


/*
 * Copyright 2015 Google Inc.
 *
 * 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.google.j2cl.ast;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.j2cl.ast.annotations.Visitable;
import com.google.j2cl.ast.processors.common.Processor;
import com.google.j2cl.common.SourcePosition;

/** A base class for Statement. */
@Visitable
public abstract class Statement extends Node implements HasSourcePosition, Cloneable<Statement> {
  // unknown by default.
  private SourcePosition sourcePosition;

  public Statement(SourcePosition sourcePosition) {
    setSourcePosition(sourcePosition);
  }

  @Override
  public SourcePosition getSourcePosition() {
    return sourcePosition;
  }

  public void setSourcePosition(SourcePosition sourcePosition) {
    this.sourcePosition = checkNotNull(sourcePosition);
  }

  @Override
  public abstract Statement clone();

  @Override
  public Node accept(Processor processor) {
    return Visitor_Statement.visit(processor, this);
  }
}

/*
 * Copyright 2015 Google Inc.
 *
 * 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.google.j2cl.ast;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.j2cl.ast.annotations.Visitable;
import com.google.j2cl.ast.processors.common.Processor;
import com.google.j2cl.common.SourcePosition;

/** A base class for Statement. */
@Visitable
public abstract class Statement extends Node implements HasSourcePosition, Cloneable<Statement> {
  // unknown by default.
  private SourcePosition sourcePosition;

  public Statement(SourcePosition sourcePosition) {
    setSourcePosition(sourcePosition);
  }

  @Override
  public final SourcePosition getSourcePosition() {
    return sourcePosition;
  }

  public final void setSourcePosition(SourcePosition sourcePosition) {
    this.sourcePosition = checkNotNull(sourcePosition);
  }

  @Override
  public abstract Statement clone();

  @Override
  public Node accept(Processor processor) {
    return Visitor_Statement.visit(processor, this);
  }
}

Make set/getSourcePosition final on Node.

PiperOrigin-RevId: 304549770


/*
 * Copyright (c) 2015 Uber Technologies, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.uber.tchannel.schemes;

import io.netty.buffer.Unpooled;

public class DefaultRawRequestHandler implements RawRequestHandler {
    @Override
    public RawResponse handle(RawRequest request) {

        RawResponse response = new RawResponse(
                request.getId(),
                request.getTransportHeaders(),
                Unpooled.wrappedBuffer(new byte[]{0x00, 0x00}),
                Unpooled.wrappedBuffer(new byte[]{0x00, 0x00}),
                Unpooled.wrappedBuffer(new byte[]{0x00, 0x00})
        );

        return response;
    }
}

/*
 * Copyright (c) 2015 Uber Technologies, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.uber.tchannel.schemes;

public class DefaultRawRequestHandler implements RawRequestHandler {
    @Override
    public RawResponse handle(RawRequest request) {

        return new RawResponse(
                request.getId(),
                request.getTransportHeaders(),
                request.getArg1(),
                request.getArg2(),
                request.getArg3()
        );

    }
}

Make the DefaultRawRequest handler just echo back the request.


/*
 * Copyright 2020 The JSpecify Authors.
 *
 * 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.
 */

import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;

@DefaultNonNull
class InstanceOfCheck {
  Object x0(Object o) {
    if (o instanceof Object) {
      return o;
    } else {
      return o;
    }
  }

  Object x1(@NullnessUnspecified Object o) {
    if (o instanceof Object) {
      return o;
    } else {
      // jspecify_nullness_not_enough_information
      return o;
    }
  }

  Object x2(@Nullable Object o) {
    if (o instanceof Object) {
      return o;
    } else {
      // jspecify_nullness_mismatch
      return o;
    }
  }
}

/*
 * Copyright 2020 The JSpecify Authors.
 *
 * 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.
 */

import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;

@DefaultNonNull
class InstanceOfCheck {
  Object x0(Object o) {
    if (o instanceof Foo) {
      return o;
    } else {
      return o;
    }
  }

  Object x1(@NullnessUnspecified Object o) {
    if (o instanceof Foo) {
      return o;
    } else {
      // jspecify_nullness_not_enough_information
      return o;
    }
  }

  Object x2(@Nullable Object o) {
    if (o instanceof Foo) {
      return o;
    } else {
      // jspecify_nullness_mismatch
      return o;
    }
  }

  class Foo {}
}

Check `instanceof Foo` instead of `instanceof Object`.

The latter is entirely equivalent to a null check. Thus, if the result
is `false`, tools may want to recognize that the value is `null`.

Perhaps there should be a sample that checks just that, but `instanceof
Object` is rare enough that recognizing it is more of a "nice to have"
than an essential. (We already try to avoid assuming most dataflow logic
in our samples, but we've made exceptions for common cases that we
expect ~every tool to want to recognize.)

Fixes https://github.com/jspecify/jspecify/issues/164


package bj.pranie.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by Sebastian Sokolowski on 05.09.17.
 */
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login").setViewName("index");
        registry.addViewController("/user/regulations").setViewName("/user/regulations");
    }

}

package bj.pranie.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by Sebastian Sokolowski on 05.09.17.
 */
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login").setViewName("index");
        registry.addViewController("/user/regulations").setViewName("user/regulations");
    }

}

FIx missing regulations page issue

FIx missing regulations page issue


package com.arnaudpiroelle.muzei.marvel.source.command;

import android.content.Context;
import android.content.Intent;

import com.arnaudpiroelle.muzei.marvel.R;
import com.arnaudpiroelle.muzei.marvel.core.inject.Injector;
import com.google.android.apps.muzei.api.Artwork;
import com.google.android.apps.muzei.api.UserCommand;

import static com.arnaudpiroelle.muzei.marvel.core.inject.Injector.getContext;

public class PublishCommand extends UserCommand implements Command {

    public PublishCommand() {
        super(2, getContext().getString(R.string.command_publish));
    }

    @Override
    public void execute(Artwork artwork) {
        Context context = Injector.getContext();

        String detailUrl = artwork.getImageUri().toString();
        String artist = context.getResources().getString(R.string.marvel_copyright).trim();

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");

        String appUrl = context.getString(R.string.app_url);
        String notifText = String.format(context.getString(R.string.share_template), artwork.getTitle().trim(), artist, detailUrl, appUrl);

        shareIntent.putExtra(Intent.EXTRA_TEXT, notifText);
        shareIntent = Intent.createChooser(shareIntent, context.getString(R.string.share_with));
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(shareIntent, getContext().getString(R.string.chooser_market)));
    }
}

package com.arnaudpiroelle.muzei.marvel.source.command;

import android.content.Context;
import android.content.Intent;

import com.arnaudpiroelle.muzei.marvel.R;
import com.arnaudpiroelle.muzei.marvel.core.inject.Injector;
import com.google.android.apps.muzei.api.Artwork;
import com.google.android.apps.muzei.api.UserCommand;

import static com.arnaudpiroelle.muzei.marvel.core.inject.Injector.getContext;

public class PublishCommand extends UserCommand implements Command {

    public PublishCommand() {
        super(2, getContext().getString(R.string.command_publish));
    }

    @Override
    public void execute(Artwork artwork) {
        Context context = Injector.getContext();

        String detailUrl = artwork.getImageUri().toString();
        String artist = context.getResources().getString(R.string.marvel_copyright).trim();

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        String appUrl = context.getString(R.string.app_url);
        String notifText = String.format(context.getString(R.string.share_template), artwork.getTitle().trim(), artist, detailUrl, appUrl);

        shareIntent.putExtra(Intent.EXTRA_TEXT, notifText);
        context.startActivity(shareIntent);
    }
}

Fix crash for share image

Fix crash for share image


package org.graphwalker.io.factory;

/*
 * #%L
 * GraphWalker Input/Output
 * %%
 * Copyright (C) 2011 - 2014 GraphWalker
 * %%
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * #L%
 */

/**
 * Created by krikar on 8/20/14.
 */
public class YEdParsingException extends RuntimeException {

  public YEdParsingException(Throwable throwable) {
    super(throwable);
  }

  public YEdParsingException(String message) {
    super(message);
  }
}

Fix git mvn problem with white space

Fix git mvn problem with white space


package org.littleshoot.proxy.mitm;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;

import org.littleshoot.proxy.MitmManager;

/**
 * {@link MitmManager} that uses the given host name to create a dynamic
 * certificate for. If a port is given, it will be truncated.
 */
public class HostNameMitmManager implements MitmManager {

    private BouncyCastleSslEngineSource sslEngineSource;

    public HostNameMitmManager() throws RootCertificateException {
        this(new Authority());
    }

    public HostNameMitmManager(Authority authority)
            throws RootCertificateException {
        try {
            sslEngineSource = new BouncyCastleSslEngineSource(authority, true,
                    true);
        } catch (final Exception e) {
            throw new RootCertificateException(
                    "Errors during assembling root CA.", e);
        }
    }

    public SSLEngine serverSslEngine() {
        return sslEngineSource.newSslEngine();
    }

    public SSLEngine clientSslEngineFor(SSLSession serverSslSession,
            String serverHostAndPort) {
        try {
            String serverName = serverHostAndPort.split(":")[0];
            SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();
            return sslEngineSource.createCertForHost(serverName, san);
        } catch (Exception e) {
            throw new FakeCertificateException(
                    "Creation dynamic certificate failed for "
                            + serverHostAndPort, e);
        }
    }
}

package org.littleshoot.proxy.mitm;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;

import org.littleshoot.proxy.MitmManager;

/**
 * {@link MitmManager} that uses the given host name to create a dynamic
 * certificate for. If a port is given, it will be truncated.
 */
public class HostNameMitmManager implements MitmManager {

    private BouncyCastleSslEngineSource sslEngineSource;

    public HostNameMitmManager() throws RootCertificateException {
        this(new Authority());
    }

    public HostNameMitmManager(Authority authority)
            throws RootCertificateException {
        try {
            boolean trustAllServers = false;
            boolean sendCerts = true;
            sslEngineSource = new BouncyCastleSslEngineSource(authority,
                    trustAllServers, sendCerts);
        } catch (final Exception e) {
            throw new RootCertificateException(
                    "Errors during assembling root CA.", e);
        }
    }

    public SSLEngine serverSslEngine() {
        return sslEngineSource.newSslEngine();
    }

    public SSLEngine clientSslEngineFor(SSLSession serverSslSession,
            String serverHostAndPort) {
        try {
            String serverName = serverHostAndPort.split(":")[0];
            SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();
            return sslEngineSource.createCertForHost(serverName, san);
        } catch (Exception e) {
            throw new FakeCertificateException(
                    "Creation dynamic certificate failed for "
                            + serverHostAndPort, e);
        }
    }
}

Disable trust all servers by default.

Disable trust all servers by default.


package org.synyx.urlaubsverwaltung;

import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;

import static org.testcontainers.containers.MariaDBContainer.IMAGE;

@DirtiesContext
public abstract class TestContainersBase {

    static MariaDBContainer<?> mariaDB = new MariaDBContainer<>(IMAGE + ":10.5");

    @DynamicPropertySource
    static void mariaDBProperties(DynamicPropertyRegistry registry) {
        mariaDB.start();
        registry.add("spring.datasource.url", mariaDB::getJdbcUrl);
        registry.add("spring.datasource.username", mariaDB::getUsername);
        registry.add("spring.datasource.password", mariaDB::getPassword);
    }
}

package org.synyx.urlaubsverwaltung;

import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;

import static org.testcontainers.containers.MariaDBContainer.NAME;

@DirtiesContext
public abstract class TestContainersBase {

    static MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5");

    @DynamicPropertySource
    static void mariaDBProperties(DynamicPropertyRegistry registry) {
        mariaDB.start();
        registry.add("spring.datasource.url", mariaDB::getJdbcUrl);
        registry.add("spring.datasource.username", mariaDB::getUsername);
        registry.add("spring.datasource.password", mariaDB::getPassword);
    }
}

Replace testcontainers deprecated image constant with name


/*
 * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.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 org.traccar.api;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import java.text.SimpleDateFormat;

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    private ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperProvider() {
        mapper.setConfig(mapper.getSerializationConfig().with(
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")));
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }

}

/*
 * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.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 org.traccar.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import java.text.SimpleDateFormat;

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    private ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperProvider() {
        mapper.setConfig(mapper.getSerializationConfig().without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS));
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }

}

Change serialization date format again

Change serialization date format again


package com.elmakers.mine.bukkit.magic;

import javax.annotation.Nonnull;

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;

import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;

public class MobTrigger extends CustomTrigger {
    boolean requiresTarget = false;

    public MobTrigger(@Nonnull MageController controller, @Nonnull String key, @Nonnull ConfigurationSection configuration) {
        super(controller, key, configuration);
        requiresTarget = configuration.getBoolean("requires_target");
    }

    public boolean isValid(Mage mage) {
        if (!isValid(mage)) return false;
        if (requiresTarget) {
            Entity entity = mage.getEntity();
            if (entity instanceof Creature) {
                return ((Creature)entity).getTarget() != null;
            }
        }
        return true;
    }
}

package com.elmakers.mine.bukkit.magic;

import javax.annotation.Nonnull;

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Entity;

import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;

public class MobTrigger extends CustomTrigger {
    boolean requiresTarget = false;

    public MobTrigger(@Nonnull MageController controller, @Nonnull String key, @Nonnull ConfigurationSection configuration) {
        super(controller, key, configuration);
        requiresTarget = configuration.getBoolean("requires_target");
    }

    @Override
    public boolean isValid(Mage mage) {
        if (!super.isValid(mage)) return false;
        if (requiresTarget) {
            Entity entity = mage.getEntity();
            if (entity instanceof Creature) {
                return ((Creature)entity).getTarget() != null;
            }
        }
        return true;
    }
}

Fix mob trigger infinite recursion

Fix mob trigger infinite recursion


/**
 * Copyright (c) 2020 Bosch.IO GmbH and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.eclipse.hawkbit.repository;

import java.io.Serializable;

public interface Identifiable<T extends Serializable> {

    T getId();
}

/**
 * Copyright (c) 2020 Bosch.IO GmbH and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.eclipse.hawkbit.repository;

import java.io.Serializable;

@FunctionalInterface
public interface Identifiable<T extends Serializable> {

    T getId();
}

Use best practise annotation for SAM interfaces in Java 8

Signed-off-by: Ammar Bikic <417bcc2872fb8ed5fe45ce0124fb7650d1b6cf9d@bosch.io>


class Node {
    String getType() { return ""; }

    String foo(Node left, Node right) {
        String leftType = left.getType().substring(1);
<selection>        String rightType = right.getType().substring(1);
</selection>
        String type = "A".substring(1);
        return leftType + rightType + type;
    }
}

class Node {
    String getType() { return ""; }

    String foo(Node left, Node right) {
        String leftType = left.getType().substring(1);
<selection>        String rightType = right.getType().substring(1); //line comment
</selection>
        String type = "A".substring(1);
        return leftType + rightType + type;
    }
}

Java: Trim surrounding whitespaces because they don't survive in the refactoring - test data fixed (IDEA-191738)


/*
 * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.lttng.scope.lttng.kernel.core.activator.internal;

import java.io.IOException;

import org.lttng.scope.common.core.ScopeCoreActivator;
import org.lttng.scope.lami.core.module.LamiAnalysisFactoryException;

/**
 * Plugin activator
 *
 * @noreference This class should not be accessed outside of this plugin.
 */
public class Activator extends ScopeCoreActivator {

    /**
     * Return the singleton instance of this activator.
     *
     * @return The singleton instance
     */
    public static Activator instance() {
        return ScopeCoreActivator.getInstance(Activator.class);
    }

    @Override
    protected void startActions() {
        try {
            LttngAnalysesLoader.load();
        } catch (LamiAnalysisFactoryException | IOException e) {
            // Not the end of the world if the analyses are not available
            logWarning("Cannot find LTTng analyses configuration files: " + e.getMessage()); //$NON-NLS-1$
        }
    }

    @Override
    protected void stopActions() {
    }

}

/*
 * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.lttng.scope.lttng.kernel.core.activator.internal;

import org.lttng.scope.common.core.ScopeCoreActivator;

/**
 * Plugin activator
 *
 * @noreference This class should not be accessed outside of this plugin.
 */
public class Activator extends ScopeCoreActivator {

    /**
     * Return the singleton instance of this activator.
     *
     * @return The singleton instance
     */
    public static Activator instance() {
        return ScopeCoreActivator.getInstance(Activator.class);
    }

    @Override
    protected void startActions() {
//        try {
//            LttngAnalysesLoader.load();
//        } catch (LamiAnalysisFactoryException | IOException e) {
//            // Not the end of the world if the analyses are not available
//            logWarning("Cannot find LTTng analyses configuration files: " + e.getMessage()); //$NON-NLS-1$
//        }
    }

    @Override
    protected void stopActions() {
    }

}

Disable the built-in LTTng-Analyses connectors

Too annoying when developping, we'll bring them back later.

Signed-off-by: Alexandre Montplaisir <0b9d8e7da097b5bbfe36e48cca5acfe475f18227@efficios.com>


package org.zstack.storage.primary.smp;

import org.zstack.header.core.Completion;

/**
 * Created by xing5 on 2016/3/27.
 */
public abstract class BackupStorageKvmUploader {
    public abstract void uploadBits(String bsPath, String psPath, Completion completion);
}

package org.zstack.storage.primary.smp;

import org.zstack.header.core.ReturnValueCompletion;

/**
 * Created by xing5 on 2016/3/27.
 */
public abstract class BackupStorageKvmUploader {
    // When uploading an image from 'psPath' to backup storage, the 'bsPath'
    // might be allocated by the backup storage and returned by the completion,
    // instead of being known ahead of time.
    public abstract void uploadBits(String bsPath, String psPath, ReturnValueCompletion<String> completion);
}

Update the method signature of 'uploadBits()'

Signed-off-by: David Lee <15c338f3b79a63a0d5423e9c6562cd312918fe74@gmail.com>


package com.hubspot.baragon.service.edgecache.cloudflare.client;

public class CloudflareClientException extends Exception {

  public CloudflareClientException(String message, Throwable t) {
    super(message, t);
  }

}

package com.hubspot.baragon.service.edgecache.cloudflare.client;

public class CloudflareClientException extends Exception {

  public CloudflareClientException(String message, Throwable t) {
    super(message, t);
  }

  public CloudflareClientException(String message) {
    super(message);
  }

}

Add exception class for Cloudflare interactions.


/*
 * Created on 11-Jan-2006
 */
package uk.org.ponder.rsf.test.sitemap;

import java.util.HashMap;

import uk.org.ponder.rsf.bare.junit.PlainRSFTests;
import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters;
import uk.org.ponder.rsf.viewstate.support.BasicViewParametersParser;

public class TestSiteMap extends PlainRSFTests {
  public void testParseECVP() {
    BasicViewParametersParser bvpp = (BasicViewParametersParser) applicationContext.getBean("viewParametersParser");
    HashMap attrmap = new HashMap();
    attrmap.put("flowtoken", "ec38f0");
    EntityCentredViewParameters ecvp = (EntityCentredViewParameters) bvpp.parse("/recipe/3652/", attrmap);
    System.out.println("ECVP for entity " + ecvp.entity.ID + " of type " + ecvp.entity.entityname);
  }

}

/*
 * Created on 11-Jan-2006
 */
package uk.org.ponder.rsf.test.sitemap;

import java.util.HashMap;

import uk.org.ponder.rsf.bare.junit.PlainRSFTests;
import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters;
import uk.org.ponder.rsf.viewstate.support.BasicViewParametersParser;

public class TestSiteMap extends PlainRSFTests {
  public TestSiteMap() {
    contributeConfigLocation("classpath:uk/org/ponder/rsf/test/sitemap/sitemap-context.xml");
  }

  public void testParseECVP() {
    BasicViewParametersParser bvpp = (BasicViewParametersParser) applicationContext.getBean("viewParametersParser");
    HashMap attrmap = new HashMap();
    attrmap.put("flowtoken", "ec38f0");
    EntityCentredViewParameters ecvp = (EntityCentredViewParameters) bvpp.parse("/recipe/3652/", attrmap);
    System.out.println("ECVP for entity " + ecvp.entity.ID + " of type " + ecvp.entity.entityname);
  }

}

Fix for loading SiteMap entry on Spring 2.x


package coffee;

import dagger.Component;
import javax.inject.Singleton;

public class CoffeeApp {
  @Singleton
  @Component(modules = { DripCoffeeModule.class })
  public interface Coffee {
    CoffeeMaker maker();
  }

  public static void main(String[] args) {
    Coffee coffee = DaggerCoffeeApp_Coffee.builder().build();
    coffee.maker().brew();
  }
}

package coffee;

import dagger.Component;
import javax.inject.Singleton;

public class CoffeeApp {
  @Singleton
  @Component(modules = { DripCoffeeModule.class })
  public interface CoffeeShop {
    CoffeeMaker maker();
  }

  public static void main(String[] args) {
    CoffeeShop coffeeShop = DaggerCoffeeApp_CoffeeShop.builder().build();
    coffeeShop.maker().brew();
  }
}

Align the user's guide's usage of CoffeeShop with the sample code

Fixes https://github.com/google/dagger/pull/809
Closes https://github.com/google/dagger/pull/810

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=167519876


package eve.corp.manager;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

package eve.corp.manager;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;

@SpringBootApplication
public class Application {

    @ControllerAdvice
    static class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
        public JsonpAdvice() {
            super("callback");
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Add JSONP support which is now included in Spring 4.1


package org.scenarioo.pizza.pageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import static org.junit.jupiter.api.Assertions.*;

public class SelectPizzaPage extends BasePage {

    public static void assertPageIsShown() {
        assertTrue(getStepElement().isDisplayed(), "Expected page to be displayed");
    }

    public static void selectPizzaVerdura() {
        getWebDriver().findElement(By.id("v")).click();
    }

    public static void clickNextButton() {
        getStepElement().findElement(By.className("next")).click();
    }

    private static WebElement getStepElement() {
        return getWebDriver().findElement(By.id("step-selectPizza"));
    }

}

package org.scenarioo.pizza.pageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import static org.junit.jupiter.api.Assertions.*;

public class SelectPizzaPage extends BasePage {

    public static void assertPageIsShown() {
        assertTrue(getStepElement().isDisplayed(), "Expected page to be displayed");
    }

    public static void selectPizzaVerdura() {
        getWebDriver().findElement(By.id("pizza-verdura")).click();
    }

    public static void clickNextButton() {
        getStepElement().findElement(By.className("next")).click();
    }

    private static WebElement getStepElement() {
        return getWebDriver().findElement(By.id("step-selectPizza"));
    }

}

Adjust tests to new pizza ids

Adjust tests to new pizza ids


package atg.tools.ant.types;

import atg.tools.ant.util.ModuleUtils;
import org.apache.tools.ant.types.resources.FileResource;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author msicker
 * @version 2.0
 */
public class AtgInstallation
        extends FileResource {

    private final Map<String, Module> modules = new ConcurrentHashMap<String, Module>();

    /**
     * Sets the base ATG installation directory. For example, one might have ATG installed in
     * {@code $HOME/ATG/ATG11.0}, so you would use the following:
     * <pre>
     *     {@code <atg:atg id="atg.installation" home="${user.home}/ATG/ATG11.0"/>}
     * </pre>
     *
     * @param home
     *         directory where ATG is installed.
     */
    public void setHome(final File home) {
        setFile(home);
    }

    public File getHome() {
        return getFile();
    }

    protected Module getModule(final String name) {
        final Module cached = modules.get(name);
        if (cached != null) {
            return cached;
        }
        final Module module = new Module();
        module.setAtg(this);
        module.setModule(ModuleUtils.moduleNameToPath(name));
        modules.put(name, module);
        return module;
    }
}

package atg.tools.ant.types;

import org.apache.tools.ant.types.resources.FileResource;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author msicker
 * @version 2.0
 */
public class AtgInstallation
        extends FileResource {

    private final Map<String, Module> modules = new ConcurrentHashMap<String, Module>();

    /**
     * Sets the base ATG installation directory. For example, one might have ATG installed in
     * {@code $HOME/ATG/ATG11.0}, so you would use the following:
     * <pre>
     *     {@code <atg:atg id="atg.installation" home="${user.home}/ATG/ATG11.0"/>}
     * </pre>
     *
     * @param home
     *         directory where ATG is installed.
     */
    public void setHome(final File home) {
        setFile(home);
    }

    public File getHome() {
        return getFile();
    }

    protected Module getModule(final String name) {
        final Module cached = modules.get(name);
        if (cached != null) {
            return cached;
        }
        final Module module = new Module();
        module.setAtg(this);
        module.setModule(name);
        modules.put(name, module);
        return module;
    }
}

Fix bug in module name.

Fix bug in module name.


package de.springbootbuch.webmvc;

import java.io.IOException;
import javax.inject.Provider;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Part of springbootbuch.de.
 *
 * @author Michael J. Simons
 * @author @rotnroll666
 */
@Component
public class DemoFilter implements Filter {
	private static final Logger LOG = LoggerFactory
		.getLogger(DemoFilter.class);

	private final Provider<ShoppingCart> shoppingCart;

	public DemoFilter(
		Provider<ShoppingCart> shoppingCart) {
		this.shoppingCart = shoppingCart;
	}

	// Init und Destroy der Übersicht
	// halber nicht gezeigt

	@Override
	public void init(
		FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(
		ServletRequest request,
		ServletResponse response,
		FilterChain chain
	) throws IOException, ServletException {
		chain.doFilter(request, response);
		LOG.info(
			"Shopping cart is {} empty",
			shoppingCart.get()
				.getContent().isEmpty() ? "" : "not"
		);
	}

	@Override
	public void destroy() {
	}
}

package de.springbootbuch.webmvc;

import java.io.IOException;
import javax.inject.Provider;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Part of springbootbuch.de.
 *
 * @author Michael J. Simons
 * @author @rotnroll666
 */
@Component
public class DemoFilter implements Filter {
	private static final Logger LOG = LoggerFactory
		.getLogger(DemoFilter.class);

	private final Provider<ShoppingCart> shoppingCart;

	public DemoFilter(
		Provider<ShoppingCart> shoppingCart) {
		this.shoppingCart = shoppingCart;
	}

	// Init und Destroy der Übersicht
	// halber nicht gezeigt

	@Override
	public void init(
		FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(
		ServletRequest request,
		ServletResponse response,
		FilterChain chain
	) throws IOException, ServletException {
		chain.doFilter(request, response);
		if(request instanceof HttpServletRequest && ((HttpServletRequest)request).getSession(false) != null) {
			LOG.info(
				"Request from {}",
				shoppingCart.get()
					.getContent().isEmpty() ? "" : "not"
			);
		}
	}

	@Override
	public void destroy() {
	}
}

Fix bug when no session scope

Fix bug when no session scope


package io.quarkus.container.image.deployment;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Optional;

import org.junit.jupiter.api.Test;

class ContainerImageConfigEffectiveGroupTest {

    public static final String USER_NAME_SYSTEM_PROPERTY = "user.name";

    private ContainerImageConfig sut = new ContainerImageConfig();

    @Test
    void testFromLowercaseUsername() {
        testWithNewUsername("test", () -> {
            sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY));
            assertEquals(sut.getEffectiveGroup(), Optional.of("test"));
        });
    }

    @Test
    void testFromUppercaseUsername() {
        testWithNewUsername("TEST", () -> {
            sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY));
            assertEquals(sut.getEffectiveGroup(), Optional.of("test"));
        });
    }

    @Test
    void testFromOther() {
        testWithNewUsername("WhateveR", () -> {
            sut.group = Optional.of("OtheR");
            assertEquals(sut.getEffectiveGroup(), Optional.of("OtheR"));
        });
    }

    private void testWithNewUsername(String newUserName, Runnable test) {
        String previousUsernameValue = System.getProperty(USER_NAME_SYSTEM_PROPERTY);
        System.setProperty(USER_NAME_SYSTEM_PROPERTY, newUserName);

        test.run();

        System.setProperty(USER_NAME_SYSTEM_PROPERTY, previousUsernameValue);
    }
}

package io.quarkus.container.image.deployment;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Optional;

import org.junit.jupiter.api.Test;

class ContainerImageConfigEffectiveGroupTest {

    public static final String USER_NAME_SYSTEM_PROPERTY = "user.name";

    private ContainerImageConfig sut = new ContainerImageConfig();

    @Test
    void testFromLowercaseUsername() {
        testWithNewUsername("test", () -> {
            sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY));
            assertEquals(sut.getEffectiveGroup(), Optional.of("test"));
        });
    }

    @Test
    void testFromUppercaseUsername() {
        testWithNewUsername("TEST", () -> {
            sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY));
            assertEquals(sut.getEffectiveGroup(), Optional.of("test"));
        });
    }

    @Test
    void testFromSpaceInUsername() {
        testWithNewUsername("user name", () -> {
            sut.group = Optional.of(System.getProperty(USER_NAME_SYSTEM_PROPERTY));
            assertEquals(sut.getEffectiveGroup(), Optional.of("user-name"));
        });
    }

    @Test
    void testFromOther() {
        testWithNewUsername("WhateveR", () -> {
            sut.group = Optional.of("OtheR");
            assertEquals(sut.getEffectiveGroup(), Optional.of("OtheR"));
        });
    }

    private void testWithNewUsername(String newUserName, Runnable test) {
        String previousUsernameValue = System.getProperty(USER_NAME_SYSTEM_PROPERTY);
        System.setProperty(USER_NAME_SYSTEM_PROPERTY, newUserName);

        test.run();

        System.setProperty(USER_NAME_SYSTEM_PROPERTY, previousUsernameValue);
    }
}

Test for spaces removal from quarkus.container-image.group when it's set to the username


package seedu.doit.logic;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.time.LocalDateTime;
import java.util.Optional;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.doit.logic.parser.DateTimeParser;

/**
 * Tests if DateTimeParser is parsing the date correctly
 **/

public class DateTimeParserTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    private void assertSameDate(LocalDateTime time1, LocalDateTime time2) {
        LocalDateTime diff = time1.minusHours(time2.getHour()).minusMinutes(time2.getMinute()).minusSeconds(time2.getSecond());
        assertEquals(time1, diff);
    }

    @Test
    public void check_ifDateParsedCorrectly() throws Exception {
        Optional<LocalDateTime> t = DateTimeParser.parseDateTime("03/20/17");
        assertSameDate(t.get(), LocalDateTime.of(2017, 3, 20, 0, 0));
    }

    @Test
    public void parseEmptyString() {
        Optional<LocalDateTime> dateParsed = DateTimeParser.parseDateTime("");
        assertFalse(dateParsed.isPresent());
    }

    @Test
    public void parseNullString() throws Exception {
        thrown.expect(NullPointerException.class);
        DateTimeParser.parseDateTime(null);
    }

    @Test
    public void parseRubbishString() {
        Optional<LocalDateTime> dateParsed = DateTimeParser.parseDateTime("jsadf");
        assertFalse(dateParsed.isPresent());
    }

}

package seedu.doit.logic;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import java.time.LocalDateTime;
import java.util.Optional;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.doit.logic.parser.DateTimeParser;

/**
 * Tests if DateTimeParser is parsing the date correctly
 **/

public class DateTimeParserTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();
    private void assertSameDate(LocalDateTime time1, LocalDateTime time2) {
        LocalDateTime diff = time1.minusHours(time2.getHour()).minusMinutes(time2.getMinute())
            .minusSeconds(time2.getSecond());
        assertEquals(time1, diff);
    }

    @Test
    public void check_ifDateParsedCorrectly() throws Exception {
        Optional<LocalDateTime> t = DateTimeParser.parseDateTime("03/20/17");
        assertSameDate(t.get(), LocalDateTime.of(2017, 3, 20, 0, 0));
    }

    @Test
    public void parseEmptyString() {
        Optional<LocalDateTime> dateParsed = DateTimeParser.parseDateTime("");
        assertFalse(dateParsed.isPresent());
    }

    @Test
    public void parseNullString() throws Exception {
        thrown.expect(NullPointerException.class);
        DateTimeParser.parseDateTime(null);
    }

    @Test
    public void parseRubbishString() {
        Optional<LocalDateTime> dateParsed = DateTimeParser.parseDateTime("jsadf");
        assertFalse(dateParsed.isPresent());
    }

}

Fix line longer than 120 characters error


/*
 * Copyright 2012-2021 the original author or authors.
 *
 * 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
 *
 *      https://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 org.springframework.boot.deployment;

import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

/**
 * Deployment tests for Wildfly.
 *
 * @author Christoph Dreis
 * @author Scott Frederick
 */
@Testcontainers(disabledWithoutDocker = true)
class WildflyDeploymentTests extends AbstractDeploymentTests {

	@Container
	static WarDeploymentContainer container = new WarDeploymentContainer("jboss/wildfly:latest",
			"/opt/jboss/wildfly/standalone/deployments", DEFAULT_PORT);

	@Override
	WarDeploymentContainer getContainer() {
		return container;
	}

}

/*
 * Copyright 2012-2021 the original author or authors.
 *
 * 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
 *
 *      https://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 org.springframework.boot.deployment;

import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

/**
 * Deployment tests for Wildfly.
 *
 * @author Christoph Dreis
 * @author Scott Frederick
 */
@Testcontainers(disabledWithoutDocker = true)
class WildflyDeploymentTests extends AbstractDeploymentTests {

	@Container
	static WarDeploymentContainer container = new WarDeploymentContainer("jboss/wildfly:24.0.0.Final",
			"/opt/jboss/wildfly/standalone/deployments", DEFAULT_PORT);

	@Override
	WarDeploymentContainer getContainer() {
		return container;
	}

}

Downgrade Wildfly to work around basic auth bug

As described in https://issues.redhat.com/browse/WFLY-15478, Wildfly
25.0.0.Final rejects all requests that use basic auth with a 401
response. 25.0.0.Final is, at the time of writing, the latest available
Wildfly Docker image so we need to downgrade to 24.0.0.Final.

Closes gh-28956


//@@author A0142102E
package guitests;

import seedu.tasklist.testutil.TypicalTestTasks;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class ClearCommandTest extends TaskListGuiTest {

    @Test
    public void clear() {

        //verify a non-empty list can be cleared
        assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
        assertClearCommandSuccess();

        //verify other commands can work after a clear command
        commandBox.runCommand(TypicalTestTasks.task8.getAddCommand());
        assertTrue(taskListPanel.isListMatching(TypicalTestTasks.task8));
        commandBox.runCommand("delete 1");
        assertListSize(0);

        //verify clear command works when the list is empty
        assertClearCommandSuccess();
    }

    private void assertClearCommandSuccess() {
        commandBox.runCommand("clear");
        assertListSize(0);
        assertResultMessage("Your Smart Scheduler has been cleared!");
    }
}

//@@author A0142102E
package guitests;

import seedu.tasklist.testutil.TypicalTestTasks;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class ClearCommandTest extends TaskListGuiTest {

    @Test
    public void clear() {

        //verify a non-empty list can be cleared
        assertClearCommandSuccess();

        //verify other commands can work after a clear command
        commandBox.runCommand(TypicalTestTasks.task8.getAddCommand());
        commandBox.runCommand("delete 1");
        assertListSize(0);

        //verify clear command works when the list is empty
        assertClearCommandSuccess();
    }

    private void assertClearCommandSuccess() {
        commandBox.runCommand("clear");
        assertListSize(0);
        assertResultMessage("Your Smart Scheduler has been cleared!");
    }
}

Fix tests for clear command

Fix tests for clear command


package fr.utc.assos.uvweb.util;

/**
 * A helper class containing a few parameters for the application's animations.
 */
public class AnimationUtils {
	public static final long CARD_ANIMATION_DELAY_MILLIS = 50;
	public static final long CARD_ANIMATION_DURATION_MILLIS = 750;
}

package fr.utc.assos.uvweb.util;

/**
 * A helper class containing a few parameters for the application's animations.
 */
public class AnimationUtils {
	public static final long CARD_ANIMATION_DELAY_MILLIS = 100;
	public static final long CARD_ANIMATION_DURATION_MILLIS = 800;
}

Tweak CardAnimation values a bit

Tweak CardAnimation values a bit


package tars.model.task;

import tars.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's priority in tars.
 */
public class Priority {
    public static final String MESSAGE_PRIORITY_CONSTRAINTS = "Task priority should be h / m / l";
    public static final String PRIORITY_VALIDATION_REGEX = "[\\p{Lower} ]+";

    public static final String PRIORITY_HIGH = "high";
    public static final String PRIORITY_MEDIUM = "medium";
    public static final String PRIORITY_LOW = "low";

    public static final String PRIORITY_H = "h";
    public static final String PRIORITY_M = "m";
    public static final String PRIORITY_L = "l";

    private String priorityLevel;

    /**
     * Validates given task priority level.
     *
     * @throws IllegalValueException
     *             if given priority level string is invalid.
     */
    public Priority(String priorityLevel) throws IllegalValueException {
        assert priorityLevel != null;
        priorityLevel = priorityLevel.trim();
        if (!isValidPriorityLevel(priorityLevel)) {
            throw new IllegalValueException(MESSAGE_PRIORITY_CONSTRAINTS);
        }
        this.priorityLevel = priorityLevel;
    }

    /**
     * Returns true if a given string is a valid task priority level.
     */
    public static boolean isValidPriorityLevel(String level) {
        return level.matches(PRIORITY_VALIDATION_REGEX);
    }

    @Override
    public String toString() {
        String level = "";

        switch (priorityLevel) {
        case PRIORITY_H:
            level = PRIORITY_HIGH;
            break;
        case PRIORITY_M:
            level = PRIORITY_MEDIUM;
            break;
        case PRIORITY_L:
            level = PRIORITY_LOW;
            break;
        }

        return level;
    }

    public void setLevel(String priorityLevel) {
        this.priorityLevel = priorityLevel;
    }

}

package tars.model.task;

import tars.commons.exceptions.IllegalValueException;

/**
 * Represents a Task's priority in tars.
 */
public class Priority {
    public static final String MESSAGE_PRIORITY_CONSTRAINTS = "Task priority should be h / m / l";
    public static final String PRIORITY_VALIDATION_REGEX = "[\\p{Lower} ]+";

    public String priorityLevel;

    /**
     * Validates given task priority level.
     *
     * @throws IllegalValueException
     *             if given priority level string is invalid.
     */
    public Priority(String priorityLevel) throws IllegalValueException {
        assert priorityLevel != null;
        priorityLevel = priorityLevel.trim();
        if (!isValidPriorityLevel(priorityLevel)) {
            throw new IllegalValueException(MESSAGE_PRIORITY_CONSTRAINTS);
        }
        this.priorityLevel = priorityLevel;
    }

    /**
     * Returns true if a given string is a valid task priority level.
     */
    public static boolean isValidPriorityLevel(String level) {
        return level.matches(PRIORITY_VALIDATION_REGEX);
    }

    @Override
    public String toString() {
        return priorityLevel;
    }

    public void setLevel(String priorityLevel) {
        this.priorityLevel = priorityLevel;
    }

}

Move format priority to ReadOnlyTars.java


import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.scene.control.Button;
import javafx.geometry.Pos;

public class SudokuGUI extends BorderPane {

  public SudokuGUI() {
    drawGUI();
  }

  private void drawGUI() {
    Text tMessage = new Text();
    SudokuPane sPane = new SudokuPane();
    Button btSolve = new Button("Solve");
    Button btClear = new Button("Clear");

    btSolve.setOnAction(e -> solve(sPane, tMessage));
    btClear.setOnAction(e -> clear(sPane, tMessage));

    HBox hbControl = new HBox(10);
    hbControl.getChildren().addAll(btSolve, btClear);
    hbControl.setAlignment(Pos.CENTER);

    setTop(tMessage);
    setCenter(sPane);
    setBottom(hbControl);
    setAlignment(tMessage, Pos.CENTER);
  }

  private void solve(SudokuPane sPane, Text tMessage) {
    try {
      if (!sPane.solve()) {
        tMessage.setText("Only 1-9 or empty spaces allowed");
      }
    } catch (IllegalArgumentException ex) {
      tMessage.setText("Invalid Sudoku Grid");
    }
  }

  private void clear(SudokuPane sPane, Text tMessage) {
    sPane.clear();
    tMessage.setText("");
  }
}

import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.scene.control.Button;
import javafx.geometry.Pos;

public class SudokuGUI extends BorderPane {

  public SudokuGUI() {
    drawGUI();
  }

  private void drawGUI() {
    Text tMessage = new Text();
    SudokuPane sPane = new SudokuPane();
    Button btSolve = new Button("Solve");
    Button btClear = new Button("Clear");

    btSolve.setOnAction(e -> solve(sPane, tMessage, btSolve));
    btClear.setOnAction(e -> clear(sPane, tMessage, btSolve));

    HBox hbControl = new HBox(10);
    hbControl.getChildren().addAll(btSolve, btClear);
    hbControl.setAlignment(Pos.CENTER);

    setTop(tMessage);
    setCenter(sPane);
    setBottom(hbControl);
    setAlignment(tMessage, Pos.CENTER);
  }

  private void solve(SudokuPane sPane, Text tMessage, Button btSolve) {
    try {
      if (!sPane.solve()) {
        tMessage.setText("Only 1-9 or empty spaces allowed");
      } else {
        btSolve.setDisable(true);
      }
    } catch (IllegalArgumentException ex) {
      tMessage.setText("Invalid Sudoku Grid");
    }
  }

  private void clear(SudokuPane sPane, Text tMessage, Button btSolve) {
    sPane.clear();
    tMessage.setText("");
    btSolve.setDisable(false);
  }
}

Disable Solve button after a valid solution is found


/*
 * Copyright 2016-2017 Red Hat, Inc, and individual contributors.
 *
 * 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 io.openshift.booster;

import java.net.URL;

import com.jayway.restassured.RestAssured;
import io.openshift.booster.service.GreetingProperties;
import org.arquillian.cube.openshift.impl.enricher.RouteURL;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Before;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class OpenShiftIT extends AbstractBoosterApplicationTest {

    @RouteURL("${app.name}")
    private URL baseURL;

    @Before
    public void setup() throws Exception {
        RestAssured.baseURI = baseURL + "api/greeting";
    }

    protected GreetingProperties getProperties() {
        return new GreetingProperties();
    }

}

/*
 * Copyright 2016-2017 Red Hat, Inc, and individual contributors.
 *
 * 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 io.openshift.booster;

import java.net.URL;

import com.jayway.restassured.RestAssured;
import io.openshift.booster.service.GreetingProperties;
import org.arquillian.cube.openshift.impl.enricher.AwaitRoute;
import org.arquillian.cube.openshift.impl.enricher.RouteURL;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Before;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class OpenShiftIT extends AbstractBoosterApplicationTest {

    @AwaitRoute(path = "/health")
    @RouteURL("${app.name}")
    private URL baseURL;

    @Before
    public void setup() throws Exception {
        RestAssured.baseURI = baseURL + "api/greeting";
    }

    protected GreetingProperties getProperties() {
        return new GreetingProperties();
    }

}

Add @AwaitRule to integration test

Add @AwaitRule to integration test

Done to ensure that Arquillian waits for the application to standup
properly before executing the test method


/*
 * Copyright 2016 Attribyte, LLC
 *
 * 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 org.attribyte.wp.model;

/**
 * Metadata associated with a post, user, or
 * other object.
 */
public class Meta {

   /**
    * Creates metadata.
    * @param id The id.
    * @param key The key.
    * @param value The value.
    */
   public Meta(final long id, final String key, final String value) {
      this.id = id;
      this.key = key;
      this.value = value;
   }

   /**
    * The unique id.
    */
   public final long id;

   /**
    * The key.
    */
   public final String key;

   /**
    * The value.
    */
   public final String value;
}

/*
 * Copyright 2016 Attribyte, LLC
 *
 * 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 org.attribyte.wp.model;

/**
 * Metadata associated with a post, user, or
 * other object.
 */
public class Meta {

   /**
    * Creates metadata with no assigned id.
    * @param key The key.
    * @param value The value.
    */
   public Meta(final String key, final String value) {
      this(0L, key, value);
   }

   /**
    * Creates metadata.
    * @param id The id.
    * @param key The key.
    * @param value The value.
    */
   public Meta(final long id, final String key, final String value) {
      this.id = id;
      this.key = key;
      this.value = value;
   }

   /**
    * The unique id.
    */
   public final long id;

   /**
    * The key.
    */
   public final String key;

   /**
    * The value.
    */
   public final String value;
}

Add constructor that does not require id.


package pl.koszela.jan.domain;

import java.util.Objects;

/**
 * Created on 12.08.2017.
 *
 * @author Jan Koszela
 */
public class Order {

  private String productName;
  private int quantity;

  public Order(String productName, int quantity) {
    this.productName = productName;
    this.quantity = quantity;
  }

  public String getProductName() {
    return this.productName;
  }

  public int getQuantity() {
    return this.quantity;
  }

  public void setProductName(String productName) {
    this.productName = productName;
  }

  public void setQuantity(int quantity) {
    this.quantity = quantity;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Order order = (Order) o;
    return Objects.equals(productName, order.productName);
  }

  @Override
  public int hashCode() {
    return Objects.hash(productName, quantity);
  }
}

package pl.koszela.jan.domain;

import java.util.Objects;

/**
 * Created on 12.08.2017.
 *
 * @author Jan Koszela
 */
public class Order {

  private Product product;
  private int quantity;

  public Order(String productName, int quantity) {
    this.product = Product.builder()
        .item(productName)
        .build();
    this.quantity = quantity;
  }

  public Product getProduct() {
    return this.product;
  }

  public int getQuantity() {
    return this.quantity;
  }

  public void setProduct(Product productName) {
    this.product = productName;
  }

  public void setQuantity(int quantity) {
    this.quantity = quantity;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    Order order = (Order) o;
    return Objects.equals(product, order.product);
  }

  @Override
  public int hashCode() {
    return Objects.hash(product, quantity);
  }

  @Override
  public String toString() {
    return "Order{" +
        "productName='" + product + '\'' +
        ", quantity=" + quantity +
        '}';
  }
}

Add toString method for debuging purposes


package year2014;

import java.util.Scanner;
import java.util.stream.IntStream;

/**
 *
Digital Root

 *
The digital root of a number is obtained by summing its individual digits,
 * summing those individual digits, and continuing the process until the final sum
 * is a single digit (that is, less than 10). For example, the digital root of 1234 is 1

 *
 * @author John Cameron
 * @see Problem Descrption and Requirements
 */
public class DigitalRoot {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a non-negative integer number: ");

        final int input = Math.abs(scanner.nextInt());

        scanner.close();

        int digitalRoot = input;

        while (digitalRoot > 9)
            digitalRoot = sumIndividualDigits(digitalRoot);

        System.out.println("The digital root of " + input + " is " + digitalRoot);

    }

    private static int sumIndividualDigits(int input) {
        if (input < 0)
            throw new IllegalArgumentException("Input must be positive");

        char[] chars = String.valueOf(input).toCharArray();

        return IntStream.range(0, chars.length)
                .map(i -> Character.getNumericValue(chars[i])).sum();
    }

}

package year2014;

import java.util.Scanner;

/**
 *
Digital Root

 *
The digital root of a number is obtained by summing its individual digits,
 * summing those individual digits, and continuing the process until the final sum
 * is a single digit (that is, less than 10). For example, the digital root of 1234 is 1

 *
 * @author John Cameron
 * @see Problem Descrption and Requirements
 */
public class DigitalRoot {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a non-negative integer number: ");

        final int input = Math.abs(scanner.nextInt());

        scanner.close();

        int digitalRoot = input;

        while (digitalRoot > 9)
            digitalRoot = sumIndividualDigits(digitalRoot);

        System.out.println("The digital root of " + input + " is " + digitalRoot);

    }

    private static int sumIndividualDigits(int input) {
        if (input < 0)
            throw new IllegalArgumentException("Input must be positive");

        int sum = 0;

        while (input > 0) {

            sum += input % 10;
            input /= 10;

        }

        return sum;

        //String approach method

        /*char[] chars = String.valueOf(input).toCharArray();

        return IntStream.range(0, chars.length)
                .map(i -> Character.getNumericValue(chars[i])).sum();*/
    }

}

Use Integer approach in summing digits

Use Integer approach in summing digits


import static java.lang.reflect.Modifier.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class SuperTest {
  @Test
  public void isNotPublic() {
    int modifiers = Super.class.getModifiers();
    boolean isPublic = isPublic(modifiers);
    assertFalse(isPublic);
  }
}

import static java.lang.reflect.Modifier.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class SuperTest {
  @Test
  public void isNotPublic() {
    int modifiers = Super.class.getModifiers();
    boolean isPublic = isPublic(modifiers);
    assertFalse("Super is public (modifiers: " + modifiers + ").", isPublic);     }
}

Add value of modifiers to assertion message.


package controller;

import java.io.File;
import java.util.List;
import javafx.application.Application;
import javafx.stage.Stage;

public class MainController extends Application {
    private UserInterface userInterface;

    public static void main(String[] args) throws Exception {

	Parser.parserXml("gridInput.xml");

	launch(args);
    }

    @Override
    public void start(Stage s) throws Exception {
	// create our UI
	userInterface = new UserInterface(s, this);
    }

    public void initializeSimulationWithData(File XMLData) {
	try {
	    List<TestCell> cellList = Parser.parserXml(XMLData
		    .getAbsolutePath());

	} catch (Exception e) {
	    System.out.println("Error processing file, make sure it's XML.");
	}
    }

    public void startSimulation() {
	// TODO Auto-generated method stub

    }

    public void stopSimulation() {
	// TODO Auto-generated method stub

    }

    public void stepSimulation() {
	// TODO Auto-generated method stub

    }

}

package controller;

import java.io.File;
import java.util.List;
import javafx.application.Application;
import javafx.stage.Stage;

public class MainController extends Application {
    private UserInterface userInterface;

    public static void main(String[] args) throws Exception {

	Parser.parserXml("gridInput.xml");

	launch(args);
    }

    @Override
    public void start(Stage s) throws Exception {
	// create our UI
	userInterface = new UserInterface(s, this);
    }

    public void initializeSimulationWithData(File XMLData) {
	try {
	    @SuppressWarnings("unchecked")
        List<TestCell> cellList = Parser.parserXml(XMLData
		    .getAbsolutePath());
	    initializeSimulationObjects(cellList);
	} catch (Exception e) {
	    System.out.println("Error processing file, make sure it's XML.");
	}
    }

    private void initializeSimulationObjects(List<TestCell> cellList){
        for (TestCell c : cellList){
            try {
                //create a patch object at the x and y location

                //create a cell object
                String classPathAndName = "simulationObjects."+c.cellType;
                Class<?> cellClass = Class.forName(classPathAndName);
                System.out.println(cellClass);
                Object cell = cellClass.newInstance();
                //assign the cell to the patch
                //add the patch to grid manager

            }
            catch (ClassNotFoundException e) {
                System.out.println("One or more cell classes from your XML file could not be found.");
            }
            catch (InstantiationException e) {
                System.out.println("One or more paramaters could not be applied to the simulation.");
            }
            catch (IllegalAccessException e) {
                System.out.println("Couldn't create a class from the XML file: illegal access.");
            }
        }
    }

    public void startSimulation() {
	// TODO Auto-generated method stub

    }

    public void stopSimulation() {
	// TODO Auto-generated method stub

    }

    public void stepSimulation() {
	// TODO Auto-generated method stub

    }

}

Use the parser and initialize cell classes using reflection.


package com.africastalking;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Body;

interface IToken {

    @FormUrlEncoded
    @POST("checkout/token/create")
    Call<String> createCheckoutToken(@Field("phoneNumber") String phoneNumber);

    @Headers("Content-Type: application-json")
    @POST("auth-token/generate")
    Call<String> generateAuthToken(@Body String body);
}

package com.africastalking;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Body;

interface IToken {

    @FormUrlEncoded
    @POST("checkout/token/create")
    Call<String> createCheckoutToken(@Field("phoneNumber") String phoneNumber);

    @Headers("Content-Type: application/json")
    @POST("auth-token/generate")
    Call<String> generateAuthToken(@Body String body);
}

Fix content type on auth token service

Fix content type on auth token service


package io.bitsquare.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

// TODO route over tor
public class HttpClient {

    private final String baseUrl;

    public HttpClient(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String requestWithGET(String param) throws IOException, HttpException {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(baseUrl + param);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            if (connection.getResponseCode() == 200) {
                return convertInputStreamToString(connection.getInputStream());
            } else {
                connection.getErrorStream().close();
                throw new HttpException(convertInputStreamToString(connection.getErrorStream()));
            }
        } finally {
            if (connection != null)
                connection.getInputStream().close();
        }
    }

    private String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }

    @Override
    public String toString() {
        return "HttpClient{" +
                "baseUrl='" + baseUrl + '\'' +
                '}';
    }
}

package io.bitsquare.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

// TODO route over tor
public class HttpClient {

    private final String baseUrl;

    public HttpClient(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public String requestWithGET(String param) throws IOException, HttpException {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(baseUrl + param);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10_000);
            connection.setReadTimeout(10_000);

            if (connection.getResponseCode() == 200) {
                return convertInputStreamToString(connection.getInputStream());
            } else {
                String error = convertInputStreamToString(connection.getErrorStream());
                connection.getErrorStream().close();
                throw new HttpException(error);
            }
        } finally {
            if (connection != null)
                connection.getInputStream().close();
        }
    }

    private String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }

    @Override
    public String toString() {
        return "HttpClient{" +
                "baseUrl='" + baseUrl + '\'' +
                '}';
    }
}

Read HTTP error stream before closing it

It wasn't causing problems, but it looks odd.


package gov.nih.nci.calab.service.workflow;

/**
 * Generalizes Mask functionality for masking Aliquot, File, etc.
 * @author doswellj
 * @param strType Type of Mask (e.g., aliquot, file, run, etc.)
 * @param strId	  The id associated to the type
 * @param strDescription The mask description associated to the mask type and Id.
 *
 */
public class MaskService
{
    public void setMask(String strType, String strId, String strDescription)
    {
        if (strType.equals("aliquot"))
        {
            //TODO Find Aliquot record based on the its id and set the status to "Masked" and its Description
        }
        if (strType.equals("file"))
        {
        	//TODO Find File record based on the its id and set the status to "Masked" and its Description
        }

    }

}

package gov.nih.nci.calab.service.workflow;

/**
 * Generalizes Mask functionality for masking Aliquot, File, etc.
 * @author doswellj
 * @param strType Type of Mask (e.g., aliquot, file, run, etc.)
 * @param strId	  The id associated to the type
 * @param strDescription The mask description associated to the mask type and Id.
 *
 */
public class MaskService
{

	//This functionality is pending the completed Object Model
	public void setMask(String strType, String strId, String strDescription)
    {
        if (strType.equals("aliquot"))
        {
            //TODO Find Aliquot record based on the strID

        	//TODO Set File Status record to "Masked".

        }
        if (strType.equals("file"))
        {
        	//TODO Find File record based on the its strID

        	//TODO Set File Status record to "Masked".
        }

    }

}

Mask Service is pending the completed object model

SVN-Revision: 7136


package org.jboss.as.remoting;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.jboss.dmr.ModelNode;

/**
 * Protocols that can be used for a remoting connection
 *
 * @author Stuart Douglas
 */
public enum Protocol {

    REMOTE("remote"),
    HTTP_REMOTING("http-remoting"),
    HTTPS_REMOTING("https-remoting");

    private static final Map<String, Protocol> MAP;

    static {
        final Map<String, Protocol> map = new HashMap<String, Protocol>();
        for (Protocol value : values()) {
            map.put(value.localName, value);
        }
        MAP = map;
    }

    public static Protocol forName(String localName) {
        final Protocol value = localName != null ? MAP.get(localName.toLowerCase()) : null;
        return value == null ? Protocol.valueOf(localName.toUpperCase(Locale.ENGLISH)) : value;
    }

    private final String localName;

    Protocol(final String localName) {
        this.localName = localName;
    }

    @Override
    public String toString() {
        return localName;
    }

    public ModelNode toModelNode() {
        return new ModelNode().set(toString());
    }
}

package org.jboss.as.remoting;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.jboss.dmr.ModelNode;

/**
 * Protocols that can be used for a remoting connection
 *
 * @author Stuart Douglas
 */
public enum Protocol {

    REMOTE("remote"),
    HTTP_REMOTING("http-remoting"),
    HTTPS_REMOTING("https-remoting");

    private static final Map<String, Protocol> MAP;

    static {
        final Map<String, Protocol> map = new HashMap<String, Protocol>();
        for (Protocol value : values()) {
            map.put(value.localName, value);
        }
        MAP = map;
    }

    public static Protocol forName(String localName) {
        final Protocol value = localName != null ? MAP.get(localName.toLowerCase(Locale.ENGLISH)) : null;
        return value == null && localName != null ? Protocol.valueOf(localName.toUpperCase(Locale.ENGLISH)) : value;
    }

    private final String localName;

    Protocol(final String localName) {
        this.localName = localName;
    }

    @Override
    public String toString() {
        return localName;
    }

    public ModelNode toModelNode() {
        return new ModelNode().set(toString());
    }
}

Fix NPE warning; use locale for toLowerCase


package com.vtence.molecule.http;

public final class HeaderNames {
    public static final String ACCEPT_ENCODING = "Accept-Encoding";
    public static final String ACCEPT_LANGUAGE = "Accept-Language";
    public static final String ALLOW = "Allow";
    public static final String CACHE_CONTROL = "Cache-Control";
    public static final String CONTENT_ENCODING = "Content-Encoding";
    public static final String CONTENT_LANGUAGE = "Content-Language";
    public static final String CONTENT_LENGTH = "Content-Length";
    public static final String CONTENT_TYPE = "Content-Type";
    public static final String DATE = "Date";
    public static final String ETAG = "ETag";
    public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
    public static final String IF_NONE_MATCH = "If-None-Match";
    public static final String LAST_MODIFIED = "Last-Modified";
    public static final String LOCATION = "Location";
    public static final String SERVER = "Server";
    public static final String TRANSFER_ENCODING = "Transfer-Encoding";

    private HeaderNames() {}

    public final class Response {
    }
}

package com.vtence.molecule.http;

public interface HeaderNames {
    static final String ACCEPT_ENCODING = "Accept-Encoding";
    static final String ACCEPT_LANGUAGE = "Accept-Language";
    static final String ALLOW = "Allow";
    static final String CACHE_CONTROL = "Cache-Control";
    static final String CONTENT_ENCODING = "Content-Encoding";
    static final String CONTENT_LANGUAGE = "Content-Language";
    static final String CONTENT_LENGTH = "Content-Length";
    static final String CONTENT_TYPE = "Content-Type";
    static final String DATE = "Date";
    static final String ETAG = "ETag";
    static final String IF_MODIFIED_SINCE = "If-Modified-Since";
    static final String IF_NONE_MATCH = "If-None-Match";
    static final String LAST_MODIFIED = "Last-Modified";
    static final String LOCATION = "Location";
    static final String SERVER = "Server";
    static final String TRANSFER_ENCODING = "Transfer-Encoding";
}

Make header names an interface with constants


package ee.shy.cli.command;

import ee.shy.cli.Command;
import ee.shy.cli.SuperCommand;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class CompletionCommand implements Command {
    private final Command rootCommand;

    public CompletionCommand(Command rootCommand) {
        this.rootCommand = rootCommand;
    }

    @Override
    public void execute(String[] args) throws IOException {
        List<String> argsList = new ArrayList<>(Arrays.asList(args));
        argsList.add(null);

        Command command = rootCommand;
        for (String arg : argsList) {
            if (command instanceof SuperCommand) {
                Map<String, Command> subCommands = ((SuperCommand) command).getSubCommands();
                Command subCommand = subCommands.get(arg);
                if (subCommand != null) {
                    command = subCommand;
                }
                else {
                    System.out.println(String.join(" ", subCommands.keySet()));
                    break;
                }
            }
            else if (command instanceof HelpCommand) {
                command = ((HelpCommand) command).getRootCommand();
            }
        }
    }

    @Override
    public String getHelp() {
        return null;
    }
}

package ee.shy.cli.command;

import ee.shy.cli.Command;
import ee.shy.cli.SuperCommand;

import java.io.IOException;
import java.util.Map;

public class CompletionCommand implements Command {
    private final Command rootCommand;

    public CompletionCommand(Command rootCommand) {
        this.rootCommand = rootCommand;
    }

    @Override
    public void execute(String[] args) throws IOException {
        Command command = rootCommand;
        for (int i = 0; i <= args.length; i++) { // loop for one extra time for supercommands without arguments
            if (command instanceof SuperCommand) {
                Map<String, Command> subCommands = ((SuperCommand) command).getSubCommands();
                Command subCommand;
                if ((i < args.length - 1) // complete subcommand even if fully typed (don't nest yet)
                        && ((subCommand = subCommands.get(args[i])) != null)) {
                    command = subCommand;
                }
                else {
                    System.out.println(String.join(" ", subCommands.keySet()));
                    break;
                }
            }
            else if (command instanceof HelpCommand) {
                command = ((HelpCommand) command).getRootCommand(); // changed command point without parsing extra argument
                i--; // step back for that extra argument
            }
        }
    }

    @Override
    public String getHelp() {
        return null;
    }
}

Fix bash completion for HelpCommand and fully typed subcommands