/*
 * Copyright 2012 NGDATA nv
 *
 * 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.lilyproject.indexer.event;

import com.ngdata.sep.WALEditFilter;
import com.ngdata.sep.WALEditFilterProvider;

/**
 * Provides configured instances of {@link IndexerEditFilter} for SEP subscriptions that are related
 * to an {@code IndexUpdater}.
 */
public class IndexerEditFilterProvider implements WALEditFilterProvider {

    @Override
    public WALEditFilter getWALEditFilter(String subscriptionId) {
        if (subscriptionId.startsWith("IndexUpdater_")) {
            return new IndexerEditFilter(subscriptionId);
        } else if ("LinkIndexUpdater".equals(subscriptionId)) {
            return new LinkIndexUpdaterEditFilter();
        } else {
            return null;
        }
    }

}

/*
 * Copyright 2012 NGDATA nv
 *
 * 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.lilyproject.indexer.event;

import com.ngdata.sep.WALEditFilter;
import com.ngdata.sep.WALEditFilterProvider;

/**
 * Provides configured instances of {@link IndexerEditFilter} for SEP subscriptions that are related
 * to an {@code IndexUpdater}.
 */
public class IndexerEditFilterProvider implements WALEditFilterProvider {

    @Override
    public WALEditFilter getWALEditFilter(String subscriptionId) {
        if (subscriptionId.startsWith("Indexer_")) {
            return new IndexerEditFilter(subscriptionId);
        } else if ("LinkIndexUpdater".equals(subscriptionId)) {
            return new LinkIndexUpdaterEditFilter();
        } else {
            return null;
        }
    }

}

Change subscription name to match hbase indexer


package com.cedricziel.idea.fluid.codeInsight;

import com.cedricziel.idea.fluid.lang.psi.FluidFile;
import com.cedricziel.idea.fluid.util.FluidUtil;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.Method;
import icons.FluidIcons;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider {
    @Override
    protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) {
        if (!PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action")).accepts(element)) {
            return;
        }

        Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element);
        if (possibleMatchedTemplates.size() > 0) {
            result.add(
                NavigationGutterIconBuilder
                    .create(FluidIcons.TEMPLATE_LINE_MARKER)
                    .setTargets(possibleMatchedTemplates)
                    .setTooltipText("Navigate to template")
                    .createLineMarkerInfo(element)
            );
        }
    }
}

package com.cedricziel.idea.fluid.codeInsight;

import com.cedricziel.idea.fluid.lang.psi.FluidFile;
import com.cedricziel.idea.fluid.util.FluidUtil;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo;
import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider;
import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.lexer.PhpTokenTypes;
import com.jetbrains.php.lang.psi.elements.Method;
import icons.FluidIcons;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider {
    @Override
    protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) {
        if (!PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withParent(PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action"))).accepts(element)) {
            return;
        }

        Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element.getParent());
        if (possibleMatchedTemplates.size() > 0) {
            result.add(
                NavigationGutterIconBuilder
                    .create(FluidIcons.TEMPLATE_LINE_MARKER)
                    .setTargets(possibleMatchedTemplates)
                    .setTooltipText("Navigate to template")
                    .createLineMarkerInfo(element)
            );
        }
    }
}

[Fluid] Add lineMarker for template to identifier to prevent flickering


package cl.fatman.capital.fund;

public class App
{
    public static void main( String[] args )
    {
    	Controller control = Controller.getInstance();
    	control.setUp();
        System.out.println( "Starting application that load the funds data in the database.");
        control.storeFundData();
        control.tearDown();
        System.out.println( "Finishing application that load the funds data in the database.");
    }
}

package cl.fatman.capital.fund;

public class App
{
    public static void main( String[] args )
    {
    	Controller control = Controller.getInstance();
    	control.setUp();
        System.out.println( "Starting application that load the funds data in the database.");
        control.storeFundData();
        control.storeFomentUnitData();
        control.tearDown();
        System.out.println( "Finishing application that load the funds data in the database.");
    }
}

Include in the application the function to update the foment unit value.


// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara;

import com.google.common.truth.Truth;
import com.google.copybara.config.Config;
import com.google.copybara.config.Config.Yaml;

import com.beust.jcommander.internal.Nullable;

import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CopybaraTest {

  @Test
  public void doNothing() throws IOException, RepoException {
    Config.Yaml config = new Config.Yaml();
    config.setName("name");
    config.setSourceOfTruth(new Repository.Yaml() {
      @Override
      public Repository withOptions(Options options) {
        return new Repository() {
          @Override
          public void checkoutReference(@Nullable String reference, Path workdir)
              throws RepoException {
            try {
              Files.createDirectories(workdir);
              Files.write(workdir.resolve("file.txt"), reference.getBytes());
            } catch (IOException e) {
              throw new RepoException("Unexpected error", e);
            }
          }
        };
      }
    });
    config.setDestinationPath("src/copybara");
    Path workdir = Files.createTempDirectory("workdir");
    new Copybara(workdir).runForSourceRef(config.withOptions(new Options()), "some_sha1");
    Truth.assertThat(Files.readAllLines(workdir.resolve("file.txt"))).contains("some_sha1");
  }
}

// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara;

import com.google.common.truth.Truth;
import com.google.copybara.config.Config;

import com.beust.jcommander.internal.Nullable;

import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class CopybaraTest {

  @Test
  public void doNothing() throws IOException, RepoException {
    Config.Yaml config = new Config.Yaml();
    config.setName("name");
    config.setSourceOfTruth(new Repository.Yaml() {
      @Override
      public Repository withOptions(Options options) {
        return new Repository() {
          @Override
          public void checkoutReference(@Nullable String reference, Path workdir)
              throws RepoException {
            try {
              Files.createDirectories(workdir);
              Files.write(workdir.resolve("file.txt"), reference.getBytes());
            } catch (IOException e) {
              throw new RepoException("Unexpected error", e);
            }
          }
        };
      }
    });
    config.setDestinationPath("src/copybara");
    Path workdir = Files.createTempDirectory("workdir");
    new Copybara(workdir).runForSourceRef(config.withOptions(new Options()), "some_sha1");
    Truth.assertThat(Files.readAllLines(workdir.resolve("file.txt"), StandardCharsets.UTF_8))
        .contains("some_sha1");
  }
}

Use the method available in Java 7 instead of the one in Java 8

Change-Id: I1f2dcd2420eb0b06141f15a1d99d287bdb299361


package io.techery.progresshint.addition;

import android.graphics.Point;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.SeekBar;
import io.techery.progresshint.ProgressHintDelegate;

public class HorizontalProgressHintDelegate extends ProgressHintDelegate {

  public HorizontalProgressHintDelegate(SeekBar seekBar, AttributeSet attrs, int defStyleAttr) {
    super(seekBar, attrs, defStyleAttr);
  }

  @Override protected PointF getHintDragCoordinates(MotionEvent event) {
    float x = event.getRawX() - mSeekBar.getX();
    float y = mSeekBar.getY();
    return new PointF(x, y);
  }

  @Override protected Point getFixedHintOffset() {
    int xOffset = getHorizontalOffset(mSeekBar.getMax() / 2);
    int yOffset = getVerticalOffset();
    return new Point(xOffset, yOffset);
  }

  @Override protected Point getFollowHintOffset() {
    int xOffset = getHorizontalOffset(mSeekBar.getProgress());
    int yOffset = getVerticalOffset();
    return new Point(xOffset, yOffset);
  }

  private int getHorizontalOffset(int progress) {
    return getFollowPosition(progress) - mPopupView.getMeasuredWidth() / 2 + mSeekBar.getHeight() / 2;
  }

  private int getVerticalOffset() {
    return -(mSeekBar.getHeight() + mPopupView.getMeasuredHeight() + mPopupOffset);
  }
}

package io.techery.progresshint.addition;

import android.graphics.Point;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.SeekBar;
import io.techery.progresshint.ProgressHintDelegate;

public class HorizontalProgressHintDelegate extends ProgressHintDelegate {

  public HorizontalProgressHintDelegate(SeekBar seekBar, AttributeSet attrs, int defStyleAttr) {
    super(seekBar, attrs, defStyleAttr);
  }

  @Override protected PointF getHintDragCoordinates(MotionEvent event) {
    float x = event.getRawX() - mSeekBar.getX();
    float y = mSeekBar.getY();
    return new PointF(x, y);
  }

  @Override protected Point getFixedHintOffset() {
    int xOffset = getHorizontalOffset(mSeekBar.getMax() / 2);
    int yOffset = getVerticalOffset();
    return new Point(xOffset, yOffset);
  }

  @Override protected Point getFollowHintOffset() {
    int xOffset = getHorizontalOffset(mSeekBar.getProgress());
    int yOffset = getVerticalOffset();
    return new Point(xOffset, yOffset);
  }

  private int getHorizontalOffset(int progress) {
    return getFollowPosition(progress) - mPopupView.getMeasuredWidth() / 2 + mSeekBar.getHeight() / 2 + 15;
  }

  private int getVerticalOffset() {
    return -(mSeekBar.getHeight() + mPopupView.getMeasuredHeight() + mPopupOffset);
  }
}

Improve (possibly) popup offset for horizontal seekbar


package org.ihtsdo.buildcloud.service.exception;

public class EntityAlreadyExistsException extends Exception {

	public EntityAlreadyExistsException() {
		super("Entity already exists.");
	}
}

package org.ihtsdo.buildcloud.service.exception;

public class EntityAlreadyExistsException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public EntityAlreadyExistsException() {
		super("Entity already exists.");
	}

	public EntityAlreadyExistsException(String string) {
		super("Entity already exists.");
	}
}

Add support for additional information when detecting entity already exists.


package org.sil.bloom.reader;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;

import java.io.File;

/*
    We were storing thumbnails with the extension .png
    but now that we have .jpg thumbnails too, we're keeping
    the extension out of the filename.

    This task cleans up any old thumbnails stored with the old
    naming system.
 */

public class ThumbnailCleanup extends AsyncTask<File, Void, Void> {

    public static final String DID_THUMB_CLEANUP = "didThumbCleanup";

    private SharedPreferences values;

    public ThumbnailCleanup(Context context){
        values = context.getSharedPreferences(BloomReaderApplication.SHARED_PREFERENCES_TAG, 0);
    }

    @Override
    public Void doInBackground(File... files){

        // Only need to run this once
        if (values.getBoolean(DID_THUMB_CLEANUP, false))
            return null;

        File thumbsDirectory = files[0];
        String[] paths = thumbsDirectory.list();
        for(String path : paths){
            if (path.endsWith(".png"))
                new File(path).delete();
        }

        SharedPreferences.Editor valuesEditor = values.edit();
        valuesEditor.putBoolean(DID_THUMB_CLEANUP, true);
        valuesEditor.commit();

        return null;
    }
}

package org.sil.bloom.reader;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;

import java.io.File;

/*
    We were storing thumbnails with the extension .png
    but now that we have .jpg thumbnails too, we're keeping
    the extension out of the filename.

    This task cleans up any old thumbnails stored with the old
    naming system.
 */

public class ThumbnailCleanup extends AsyncTask<File, Void, Void> {

    public static final String DID_THUMB_CLEANUP = "didThumbCleanupRight";

    private SharedPreferences values;

    public ThumbnailCleanup(Context context){
        values = context.getSharedPreferences(BloomReaderApplication.SHARED_PREFERENCES_TAG, 0);
    }

    @Override
    public Void doInBackground(File... files){

        // Only need to run this once
        if (values.getBoolean(DID_THUMB_CLEANUP, false))
            return null;

        File thumbsDirectory = files[0];
        String[] filenames = thumbsDirectory.list();
        for(String filename : filenames){
            if (filename.endsWith(".png"))
                new File(thumbsDirectory + File.separator + filename).delete();
        }

        SharedPreferences.Editor valuesEditor = values.edit();
        valuesEditor.putBoolean(DID_THUMB_CLEANUP, true);
        valuesEditor.commit();

        return null;
    }
}

Fix path error in thumbnail cleanup

[5726] Fix path error in thumbnail cleanup


package leetcode;

/**
 * https://leetcode.com/problems/longest-valid-parentheses/
 */
public class Problem32 {
    public int longestValidParentheses(String s) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem32 prob = new Problem32();
        System.out.println(prob.longestValidParentheses("(()")); // 2
        System.out.println(prob.longestValidParentheses(")()())")); // 4
    }
}

package leetcode;

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

/**
 * https://leetcode.com/problems/longest-valid-parentheses/
 */
public class Problem32 {
    public int longestValidParentheses(String s) {
        return longestValidParentheses(s, 0, 0, 0, 0, new HashMap<>()) * 2;
    }

    private static int longestValidParentheses(String s, int idx, int begin, int end,
                                               int accu, Map<String, Integer> memo) {
        if (idx >= s.length()) {
            return accu;
        }
        String key = idx + "|" + begin + "|" + end;
        if (memo.containsKey(key)) {
            return memo.get(key);
        }
        int c = s.charAt(idx);
        int newBegin = begin;
        int newEnd = end;
        if (c == '(') {
            newBegin++;
        } else { // c == ')'
            newEnd++;
        }
        int a = longestValidParentheses(s, idx + 1, begin, end, accu, memo); // skip
        int b = 0;
        if (newBegin >= newEnd) {
            int newAccu = newEnd;
            b = longestValidParentheses(s, idx + 1, newBegin, newEnd, newAccu, memo);
        }
        int max = Math.max(a, b);
        memo.put(key, max);
        return max;
    }

    public static void main(String[] args) {
        Problem32 prob = new Problem32();
        System.out.println(prob.longestValidParentheses("(()")); // 2
        System.out.println(prob.longestValidParentheses(")()())")); // 4
        System.out.println(prob.longestValidParentheses("(")); // 0
        System.out.println(prob.longestValidParentheses("()(())")); // 6
        System.out.println(prob.longestValidParentheses("((())))")); // 6
        System.out.println(prob.longestValidParentheses("()(()")); // 2
    }
}

Update problem 32 (misunderstood the problem, doh!)


package semantics.model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import semantics.Individuals;
import semantics.KnowBase;

public final class Individual {
  private static final Pattern[] NAME_PATTERNS = {
    Pattern.compile("<.*#(.*)>"),
    Pattern.compile("<.*?:(.*)>"),
    Pattern.compile("<(.*)>"),
    Pattern.compile(".*?:(.*)"),
  };

  private final KnowBase kb;
  private final String   iri;

  public Individual(KnowBase kb, String iri) {
    this.kb  = kb;
    this.iri = iri;
  }

  public String getIri() {
    return iri;
  }

  public String getName() {
    for (Pattern p : NAME_PATTERNS) {
      Matcher m = p.matcher(iri);
      if (m.matches()) {
        return m.group(1);
      }
    }
    return iri;
  }

  public Individuals project(Roleish r) {
    return kb.project(this, r);
  }

  @Override
  public boolean equals(Object other) {
    if (other instanceof Individual) {
      Individual i = (Individual) other;
      return kb.equals(i.kb) && iri.equals(i.iri);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return (kb + "\0" + iri).hashCode();
  }
}

package semantics.model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import semantics.Individuals;
import semantics.KnowBase;

public final class Individual {
  private static final Pattern[] NAME_PATTERNS = {
    Pattern.compile("<.*#(.*)>"),
    Pattern.compile("<.*?:(.*)>"),
    Pattern.compile("<(.*)>"),
    Pattern.compile(".*?:(.*)"),
  };

  private final KnowBase kb;
  private final String   iri;

  public Individual(KnowBase kb, String iri) {
    this.kb  = kb;
    this.iri = iri;
  }

  public String getIri() {
    return iri;
  }

  public String getName() {
    for (Pattern p : NAME_PATTERNS) {
      Matcher m = p.matcher(iri);
      if (m.matches()) {
        return m.group(1);
      }
    }
    return iri;
  }

  public Individuals project(Roleish r) {
    return kb.project(this, r);
  }

  public Individuals project(String iri) {
    return project(new Role(iri));
  }

  @Override
  public boolean equals(Object other) {
    if (other instanceof Individual) {
      Individual i = (Individual) other;
      return kb.equals(i.kb) && iri.equals(i.iri);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return (kb + "\0" + iri).hashCode();
  }
}

Add DWIMy String projection method

Add DWIMy String projection method


package net.mcft.copy.betterstorage.addon.nei;

import net.mcft.copy.betterstorage.addon.Addon;
import net.mcft.copy.betterstorage.client.gui.GuiCraftingStation;
import net.mcft.copy.betterstorage.content.BetterStorageTiles;
import net.mcft.copy.betterstorage.misc.Constants;
import net.minecraft.item.ItemStack;
import codechicken.nei.api.API;
import codechicken.nei.recipe.DefaultOverlayHandler;

public class NEIAddon extends Addon {

	public NEIAddon() {
		super("NotEnoughItems");
	}

	@Override
	public void postInitialize() {

		NEIRecipeHandler handler = new NEIRecipeHandler();
		API.registerRecipeHandler(handler);
		API.registerUsageHandler(handler);

		API.registerGuiOverlay(GuiCraftingStation.class, Constants.modId + ".craftingStation");
		API.registerGuiOverlayHandler(GuiCraftingStation.class, new DefaultOverlayHandler(),
		                              Constants.modId + ".craftingStation");

		API.hideItem(new ItemStack(BetterStorageTiles.lockableDoor));

	}

}

package net.mcft.copy.betterstorage.addon.nei;

import net.mcft.copy.betterstorage.addon.Addon;
import net.mcft.copy.betterstorage.client.gui.GuiCraftingStation;
import net.mcft.copy.betterstorage.content.BetterStorageTiles;
import net.mcft.copy.betterstorage.misc.Constants;
import net.minecraft.item.ItemStack;
import codechicken.nei.api.API;
import codechicken.nei.recipe.DefaultOverlayHandler;
import cpw.mods.fml.common.FMLCommonHandler;

public class NEIAddon extends Addon {

	public NEIAddon() {
		super("NotEnoughItems");
	}

	@Override
	public void postInitialize() {
		if (FMLCommonHandler.instance().getEffectiveSide().isServer()) return;

		NEIRecipeHandler handler = new NEIRecipeHandler();
		API.registerRecipeHandler(handler);
		API.registerUsageHandler(handler);

		API.registerGuiOverlay(GuiCraftingStation.class, Constants.modId + ".craftingStation");
		API.registerGuiOverlayHandler(GuiCraftingStation.class, new DefaultOverlayHandler(),
		                              Constants.modId + ".craftingStation");

		API.hideItem(new ItemStack(BetterStorageTiles.lockableDoor));

	}

}

Fix NEI addon crashing servers

Fix NEI addon crashing servers


package me.proxer.library.enums;

import com.squareup.moshi.Json;

/**
 * Enum holding the available country.
 *
 * @author Ruben Gees
 */
public enum Country {
    @Json(name = "de")GERMANY,
    @Json(name = "en")ENGLAND,
    @Json(name = "us")UNITED_STATES,
    @Json(name = "jp")JAPAN,
    @Json(name = "kr")KOREA,
    @Json(name = "misc")OTHER,
}

package me.proxer.library.enums;

import com.squareup.moshi.Json;

/**
 * Enum holding the available countries.
 *
 * @author Ruben Gees
 */
public enum Country {
    @Json(name = "de")GERMANY,
    @Json(name = "en")ENGLAND,
    @Json(name = "us")UNITED_STATES,
    @Json(name = "jp")JAPAN,
    @Json(name = "kr")KOREA,
    @Json(name = "zh")CHINA,
    @Json(name = "misc")OTHER,
}

Add china to the countries

Add china to the countries


/*
 * Copyright 2010 Proofpoint, 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 io.airlift.log;

import com.google.common.annotations.Beta;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;

import static org.weakref.jmx.guice.ExportBinder.newExporter;

@Beta
public class LogJmxModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        binder.disableCircularProxies();

        binder.bind(LoggingMBean.class).in(Scopes.SINGLETON);
        newExporter(binder).export(LoggingMBean.class).as("io.airlift.log:name=Logging");
    }
}

/*
 * Copyright 2010 Proofpoint, 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 io.airlift.log;

import com.google.common.annotations.Beta;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.Scopes;

import javax.inject.Singleton;

import static org.weakref.jmx.guice.ExportBinder.newExporter;

@Beta
public class LogJmxModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        binder.disableCircularProxies();

        binder.bind(LoggingMBean.class).in(Scopes.SINGLETON);
        newExporter(binder).export(LoggingMBean.class).as("io.airlift.log:name=Logging");
    }

    @Provides
    @Singleton
    public Logging getLogging()
    {
        return Logging.initialize();
    }
}

Add missing binding for Logging

Add missing binding for Logging


/*
 * Copyright 2016-2017 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
 *
 *      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 es.esky.rol.http;

/**
 * @author Cristian Mateos López
 * @since 1.0.0
 */
public class ApiHttpHeaders {
    public static final String TOTAL_COUNT = "X-Total-Count";
}

/*
 * Copyright 2016-2017 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
 *
 *      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 es.esky.rol.http;

import org.springframework.http.HttpHeaders;

/**
 * @author Cristian Mateos López
 * @since 1.0.0
 */
public class ApiHttpHeaders extends HttpHeaders {
    public static final String TOTAL_COUNT = "X-Total-Count";
}

Extend custom headers from spring core headers.


package org.jboss.modules;

import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * Various methods for obtaining caller info.
 *
 * @author Jason T. Greene
 */
class CallerContext {
    private final static class Hack extends SecurityManager {
        @Override
        protected Class<?>[] getClassContext() {
            return super.getClassContext();
        }
    }

    private static Hack hack = AccessController.doPrivileged(new PrivilegedAction<Hack>() {
        @Override
        public Hack run() {
            return new Hack();
        }
    });

    static Class<?> getCallingClass() {
        return hack.getClassContext()[1];
    }
}

package org.jboss.modules;

import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * Various methods for obtaining caller info.
 *
 * @author Jason T. Greene
 */
class CallerContext {
    private final static class Hack extends SecurityManager {
        @Override
        protected Class<?>[] getClassContext() {
            return super.getClassContext();
        }
    }

    private static Hack hack = AccessController.doPrivileged(new PrivilegedAction<Hack>() {
        @Override
        public Hack run() {
            return new Hack();
        }
    });

    static Class<?> getCallingClass() {
        Class<?> stack[] = hack.getClassContext();
        int i = 3;
        while (stack[i] == stack[2]) {
            // skip nested calls fromt the same class
            if (++i >= stack.length)
                return null;
        }

        return stack[i];
    }
}

Allow for nested calls from the same class


package lt.inventi.wicket.component.bootstrap.tab;

import java.util.List;

import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.string.StringValue;

import de.agilecoders.wicket.markup.html.bootstrap.tabs.BootstrapTabbedPanel;

public class RememberingTabbedPanel<T extends ITab> extends BootstrapTabbedPanel<T> {

    public RememberingTabbedPanel(String id, List<T> tabs, IModel<Integer> model) {
        super(id, tabs, model);
    }

    public RememberingTabbedPanel(String id, List<T> tabs) {
        super(id, tabs);
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        StringValue selectedTabId = getPage().getPageParameters().get(getId());
        if (selectedTabId.isEmpty()) {
            setSelectedTab(0);
        } else {
            setSelectedTab(selectedTabId.toInt());
        }
    }

    @Override
    protected WebMarkupContainer newLink(String linkId, final int index) {
        return new Link<Void>(linkId) {
            @Override
            public void onClick() {
                setSelectedTab(index);
                getPage().getPageParameters().set(RememberingTabbedPanel.this.getId(), String.valueOf(index));
            }
        };
    }
}

package lt.inventi.wicket.component.bootstrap.tab;

import java.util.Arrays;
import java.util.List;

import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.string.StringValue;

import de.agilecoders.wicket.markup.html.bootstrap.tabs.BootstrapTabbedPanel;

public class RememberingTabbedPanel<T extends ITab> extends BootstrapTabbedPanel<T> {

    public RememberingTabbedPanel(String id, List<T> tabs, IModel<Integer> model) {
        super(id, tabs, model);
    }

    public RememberingTabbedPanel(String id, List<T> tabs) {
        super(id, tabs);
    }

    public RememberingTabbedPanel(String id, T... tabs) {
        super(id, Arrays.asList(tabs));
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        StringValue selectedTabId = getPage().getPageParameters().get(getId());
        if (selectedTabId.isEmpty()) {
            setSelectedTab(0);
        } else {
            setSelectedTab(selectedTabId.toInt());
        }
    }

    @Override
    protected WebMarkupContainer newLink(String linkId, final int index) {
        return new Link<Void>(linkId) {
            @Override
            public void onClick() {
                setSelectedTab(index);
                getPage().getPageParameters().set(RememberingTabbedPanel.this.getId(), String.valueOf(index));
            }
        };
    }
}

Add a vararg constructor for the Tabbed Panel


package assignment2;

import be.ac.ua.ansymo.adbc.annotations.invariant;

@invariant("$this.isTwoOrNoLeaf() == true")
public class FullBinTree extends BinTree {

	public FullBinTree(long id) {
		super(id);
	}

}

package assignment2;

import be.ac.ua.ansymo.adbc.annotations.invariant;

@invariant({"$super", "$this.isTwoOrNoLeaf() == true"})
public class FullBinTree extends BinTree {

	public FullBinTree(long id) {
		super(id);
	}

}

Add contraints from parent class.

Add contraints from parent class.


/*! ******************************************************************************
 *
 * Pentaho Data Integration
 *
 * Copyright (C) 2017 by Hitachi Vantara : http://www.pentaho.com
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.pentaho.big.data.kettle.plugins.recordsfromstream;

import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.trans.steps.rowsfromresult.RowsFromResultMeta;

@Step( id = "RecordsFromStream", image = "get-records-from-stream.svg",
  i18nPackageName = "org.pentaho.big.data.kettle.plugins.recordsfromstream",
  name = "RecordsFromStream.TypeLongDesc",
  description = "RecordsFromStream.TypeTooltipDesc",
  categoryDescription = "i18n:org.pentaho.di.trans.step:BaseStep.Category.Streaming",
  documentationUrl = "Products/Data_Integration/Transformation_Step_Reference/Get_Records_From_Stream")
public class RecordsFromStreamMeta extends RowsFromResultMeta {
}

/*! ******************************************************************************
 *
 * Pentaho Data Integration
 *
 * Copyright (C) 2017 by Hitachi Vantara : http://www.pentaho.com
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.pentaho.big.data.kettle.plugins.recordsfromstream;

import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.trans.steps.rowsfromresult.RowsFromResultMeta;

@Step( id = "RecordsFromStream", image = "get-records-from-stream.svg",
  i18nPackageName = "org.pentaho.big.data.kettle.plugins.recordsfromstream",
  name = "RecordsFromStream.TypeLongDesc",
  description = "RecordsFromStream.TypeTooltipDesc",
  categoryDescription = "i18n:org.pentaho.di.trans.step:BaseStep.Category.Streaming",
  documentationUrl = "Products/Data_Integration/Transformation_Step_Reference/Get_Records_From_Stream" )
public class RecordsFromStreamMeta extends RowsFromResultMeta {
}

Fix to check style violation

[BACKLOG-19262] Fix to check style violation


package com.jeromecompsci.dgui;

import java.lang.reflect.InvocationTargetException;

/**
 * @author Derek Wang
 */
abstract class BindableWidget extends Widget {
    public void bind(final Object obj, final String methodName) {
        addBindingAsListener(new Binding() {
            @Override Class getTargetClass() {
                return obj.getClass();
            }
            @Override Object getTargetObject() {
                return obj;
            }
            @Override String getTargetMethodName() {
                return methodName;
            }
        });
    }

    public void bind(final Class cls, final String methodName) {
        addBindingAsListener(new Binding() {
            @Override Class getTargetClass() {
                return cls;
            }
            @Override Object getTargetObject() {
                return null;
            }
            @Override String getTargetMethodName() {
                return methodName;
            }
        });
    }

    abstract void addBindingAsListener(final Binding binding);
}

/**
 * @author Derek Wang
 */
abstract class Binding {

    abstract Class getTargetClass();
    abstract Object getTargetObject();
    abstract String getTargetMethodName();

    void executeBoundMethod() {
        try {
            getTargetClass().getMethod(getTargetMethodName()).invoke(getTargetObject());
        } catch (NoSuchMethodException e) {
            e.printStackTrace(System.err);
        } catch (IllegalAccessException e) {
            e.printStackTrace(System.err);
        } catch (InvocationTargetException e) {
            e.printStackTrace(System.err);
        }
    }
}

package com.jeromecompsci.dgui;

import java.lang.reflect.InvocationTargetException;

/**
 * @author Derek Wang
 */
abstract class BindableWidget extends Widget {
    public void bind(final Object obj, final String methodName) {
        addBindingAsListener(new Binding(obj.getClass(), obj, methodName));
    }

    public void bind(final Class cls, final String methodName) {
        addBindingAsListener(new Binding(cls, null, methodName));
    }

    abstract void addBindingAsListener(final Binding binding);
}

/**
 * @author Derek Wang
 */
class Binding {

    private Class targetClass;
    private Object targetObject;
    private String targetMethodName;

    public Binding(Class targetClass, Object targetObject, String targetMethodName) {
        this.targetClass = targetClass;
        this.targetObject = targetObject;
        this.targetMethodName = targetMethodName;
    }

    void executeBoundMethod() {
        try {
            targetClass.getMethod(targetMethodName).invoke(targetObject);
        } catch (NoSuchMethodException e) {
            e.printStackTrace(System.err);
        } catch (IllegalAccessException e) {
            e.printStackTrace(System.err);
        } catch (InvocationTargetException e) {
            e.printStackTrace(System.err);
        }
    }
}

Simplify Binding logic -- no need for abstract methods, a custom constructor does the job nicely


package executors;

/**
 * Transform user commands in Nmap commands
 */
public class CommandCreator {

    public String createCommand(String userCommand) {
        String[] tokens =  userCommand.split("\\s+");

        switch(tokens[0]) {
            case "security":
                switch (tokens[1]) {
                    case "tls":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "ecrypt2lvl":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "open_ports":
                        return "nmap " + tokens[2];
                    default :
                        return null;
                }
            default :
                return null;
        }
    }
}

package executors;

/**
 * Transform user commands in Nmap commands
 */
public class CommandCreator {

    public String createCommand(String userCommand) {
        String[] tokens =  userCommand.split("\\s+");

        switch(tokens[0]) {
            case "security":
                switch (tokens[1]) {
                    case "tls":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "ecrypt2lvl":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "open_ports":
                        return "nmap " + tokens[2];
                    default :
                        return null;
                }
            case "availability2":
                return "curl +X GET " + tokens[1];
            default :
                return null;
        }
    }
}

Add availability2 comand, this command uses curl to do the availability check.


package com.iyzipay;

import com.iyzipay.exception.HttpClientException;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HashGenerator {

    private HashGenerator() {
    }

    public static String generateHash(String apiKey, String secretKey, String randomString, Object request) {
        StringBuilder hash = new StringBuilder();
        byte[] result = null;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA1");
            String input = apiKey + randomString + secretKey + request;
            result = crypt.digest(input.getBytes());
            for (int i = 0; i < result.length; i++) {
                hash.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
            }
        } catch (NoSuchAlgorithmException e) {
            throw new HttpClientException("Hash cannot be generated", e);
        }
        return DatatypeConverter.printBase64Binary(result);
    }
}

package com.iyzipay;

import com.iyzipay.exception.HttpClientException;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HashGenerator {

    private HashGenerator() {
    }

    public static String generateHash(String apiKey, String secretKey, String randomString, Object request) {
        StringBuilder hash = new StringBuilder();
        byte[] result = null;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA1");
            String input = apiKey + randomString + secretKey + request;
            result = crypt.digest(input.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new HttpClientException("Hash cannot be generated", e);
        }
        return DatatypeConverter.printBase64Binary(result);
    }
}

Remove unused code block which is not affect hash calculation


import static semantics.Util.head;

public class Subtypes from "wine.rdf" {
  public static void main(String[] args) {
    [⊤]           top   = head(query-for(":Wine"));
    [«:Wine»]     wine  = head(query-for(":Wine" ⊓ ⎨":TaylorPort"⎬));
    [∃▽·⎨«:Red»⎬] exist = head(query-for(∃":hasColor"·⎨":Red"⎬));
    [∀△·⎨«:Red»⎬] all   = head(query-for(∀":hasColor"·⎨":Red"⎬));
  }
}

import static semantics.Util.head;

public class Subtypes from "wine.rdf" {
  public static void main(String[] args) {
    ⊤           top   = head(query-for(":Wine"));
    «:Wine»     wine  = head(query-for(":Wine" ⊓ ⎨":TaylorPort"⎬));
    ∃▽·⎨«:Red»⎬ exist = head(query-for(∃":hasColor"·⎨":Red"⎬));
    ∀△·⎨«:Red»⎬ all   = head(query-for(∀":hasColor"·⎨":Red"⎬));
  }
}

Remove now-unnecessary brackets from subtype test

They were needed to disambiguate the types from expressions, but that's
fixed now, so they're not needed anymore.


package peergos.shared.user;

import jsinterop.annotations.*;

import java.util.*;
import java.util.concurrent.*;

public class JavaScriptPoster implements HttpPoster {
    NativeJSHttp http = new NativeJSHttp();

    @Override
    public CompletableFuture<byte[]> post(String url, byte[] payload, boolean unzip) {
        return http.post(url, payload);
    }

    @Override
    public CompletableFuture<byte[]> postUnzip(String url, byte[] payload) {
        return post(url, payload, true);
    }

    @Override
    public CompletableFuture<byte[]> postMultipart(String url, List<byte[]> files) {
        return http.postMultipart(url, files);
    }

    @Override
    public CompletableFuture<byte[]> get(String url) {
        return http.get(url);
    }

    // This is an ugly hack to convert Uint8Array to a valid byte[]
    @JsMethod
    public static byte[] convertToBytes(short[] uints) {
        byte[] res = new byte[uints.length];
        for (int i=0; i < res.length; i++)
            res[i] = (byte) uints[i];
        return res;
    }
}

package peergos.shared.user;

import jsinterop.annotations.*;

import java.util.*;
import java.util.concurrent.*;

public class JavaScriptPoster implements HttpPoster {
    NativeJSHttp http = new NativeJSHttp();

    @Override
    public CompletableFuture<byte[]> post(String url, byte[] payload, boolean unzip) {
        return http.post(url, payload);
    }

    @Override
    public CompletableFuture<byte[]> postUnzip(String url, byte[] payload) {
        return post(url, payload, true);
    }

    @Override
    public CompletableFuture<byte[]> postMultipart(String url, List<byte[]> files) {
        return http.postMultipart(url, files);
    }

    @Override
    public CompletableFuture<byte[]> get(String url) {
        return http.get(url);
    }

    @JsMethod
    public static byte[] emptyArray() {
        return new byte[0];
    }

    // This is an ugly hack to convert Uint8Array to a valid byte[]
    @JsMethod
    public static byte[] convertToBytes(short[] uints) {
        byte[] res = new byte[uints.length];
        for (int i=0; i < res.length; i++)
            res[i] = (byte) uints[i];
        return res;
    }
}

Add a util method so JS can get the annotations GWT does to a byte[] object.


package wssec;

import org.apache.xml.security.c14n.Canonicalizer;
import org.w3c.dom.Document;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.dom.DOMSource;
import java.io.ByteArrayInputStream;

public class SOAPUtil {

    /**
     * Convert a DOM Document into a soap message.
     *

     *
     * @param doc
     * @return
     * @throws Exception
     */
    public static SOAPMessage toSOAPMessage(Document doc) throws Exception {
        Canonicalizer c14n =
                Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
        byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);
        ByteArrayInputStream in = new ByteArrayInputStream(canonicalMessage);
        MessageFactory factory = MessageFactory.newInstance();
        return factory.createMessage(null, in);
    }

    /**
     * Update soap message.
     *

     *
     * @param doc
     * @param message
     * @return
     * @throws Exception
     */
    public static SOAPMessage updateSOAPMessage(Document doc,
                                                SOAPMessage message)
            throws Exception {
        DOMSource domSource = new DOMSource(doc);
        message.getSOAPPart().setContent(domSource);
        return message;
    }
}

package wssec;

import org.apache.xml.security.c14n.Canonicalizer;
import org.w3c.dom.Document;

import org.apache.axis.Message;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.dom.DOMSource;
import java.io.ByteArrayInputStream;

public class SOAPUtil {

    /**
     * Convert a DOM Document into a soap message.
     *

     *
     * @param doc
     * @return
     * @throws Exception
     */
    public static SOAPMessage toSOAPMessage(Document doc) throws Exception {
        Canonicalizer c14n =
                Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
        byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);
        ByteArrayInputStream in = new ByteArrayInputStream(canonicalMessage);
        MessageFactory factory = MessageFactory.newInstance();
        return factory.createMessage(null, in);
    }

    /**
     * Convert a DOM Document into an Axis message.
     *

     *
     * @param doc
     * @return
     * @throws Exception
     */
    public static Message toAxisMessage(Document doc) throws Exception {
        Canonicalizer c14n =
                Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
        byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);
        ByteArrayInputStream in = new ByteArrayInputStream(canonicalMessage);
        return new Message(in);
    }

    /**
     * Update soap message.
     *

     *
     * @param doc
     * @param message
     * @return
     * @throws Exception
     */
    public static SOAPMessage updateSOAPMessage(Document doc,
                                                SOAPMessage message)
            throws Exception {
        DOMSource domSource = new DOMSource(doc);
        message.getSOAPPart().setContent(domSource);
        return message;
    }
}

Introduce new "toAxisMessage()" to create a Axis message from a DOM
document. Use this new function instead of "toSOAPMessage()". This
resolves a problem in Java 6 which has a built-in xml.SOAPMessage
implementation. This implementation is in conflict with the previous
used Axis implementation. Previously the MessageFactory returned an
Axis message that implements a SOAPMessage interface. The test cases
(TestWS*) used this internal know-how and cast the SOAPMessage into an
Axis message directly. This fails in Java 6 and was bad programming style
anyhow. The TestWS* test cases will be modified to use the new function.

git-svn-id: 10bc45916fe30ae642aa5037c9a4b05727bba413@533031 13f79535-47bb-0310-9956-ffa450edef68


package io.bit3.jsass;

import io.bit3.jsass.importer.Import;
import io.bit3.jsass.importer.Importer;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedList;

public class TestImporter implements Importer {

  @Override
  public Collection<Import> apply(String url, Import previous) {
    if ("functions".equals(url)) {
      return new LinkedList<>();
    }

    if ("include".equals(url)) {
      // Importers does not support SASS syntax, so we enforce scss here
      // String syntax = previous.substring(previous.length() - 4);
      String syntax = "scss";

      String resourcePath = String.format("/%s/src/include.%s", syntax, syntax);
      URL resource = getClass().getResource(resourcePath);

      String basePath = String.format("/%s/src", syntax);
      URL base = getClass().getResource(basePath);

      try {
        String contents = IOUtils.toString(resource);

        Import importSource = new Import(
            new URI(String.format("include.%s", syntax)),
            base.toURI(),
            contents
        );

        Collection<Import> list = new LinkedList<>();
        list.add(importSource);
        return list;
      } catch (IOException | URISyntaxException e) {
        throw new RuntimeException(e);
      }
    }

    return null;
  }
}

package io.bit3.jsass;

import io.bit3.jsass.importer.Import;
import io.bit3.jsass.importer.Importer;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.LinkedList;

public class TestImporter implements Importer {

  @Override
  public Collection<Import> apply(String url, Import previous) {
    if ("functions".equals(url)) {
      return new LinkedList<>();
    }

    if ("include".equals(url)) {
      // Importers does not support SASS syntax, so we enforce scss here
      // String syntax = previous.substring(previous.length() - 4);
      String syntax = "scss";

      String resourcePath = String.format("/%s/src/include.%s", syntax, syntax);
      URL resource = getClass().getResource(resourcePath);

      String basePath = String.format("/%s/src", syntax);
      URL base = getClass().getResource(basePath);

      try {
        String contents = IOUtils.toString(resource);

        Import importSource = new Import(
            new URI(String.format("include.%s", syntax)),
            base.toURI(),
            contents
        );

        Collection<Import> list = new LinkedList<>();
        list.add(importSource);
        return list;
      } catch (IOException | URISyntaxException e) {
        throw new RuntimeException(e);
      }
    }

    throw new IllegalArgumentException("Cannot handle import \"" + url + "\"");
  }
}

Throw an exception if the test importer cannot handle an import.


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that creates a new class Datastore. */
@WebServlet("/newclass")
public final class NewClass extends HttpServlet {
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Get the input from the form.
    // navigate to /_ah/admin to view Datastore

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    System.setProperty(
        DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString());

    String className = request.getParameter("className");
    List<String> emptyQueue = Collections.emptyList();

    Entity classEntity = new Entity("Class");
    classEntity.setProperty("owner", "");
    classEntity.setProperty("name", className);
    classEntity.setProperty("beingHelped", "");
    classEntity.setProperty("studentQueue", emptyQueue);

    datastore.put(classEntity);
  }
}

package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import java.io.IOException;
import java.util.Collections;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that creates a new class Datastore. */
@WebServlet("/newclass")
public final class NewClass extends HttpServlet {
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Get the input from the form.
    // navigate to /_ah/admin to view Datastore

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    System.setProperty(
        DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString());

    String className = request.getParameter("className");

    Entity classEntity = new Entity("Class");
    classEntity.setProperty("owner", "");
    classEntity.setProperty("name", className);
    classEntity.setProperty("beingHelped", "");
    classEntity.setProperty("studentQueue", Collections.emptyList());

    datastore.put(classEntity);
  }
}

Refactor variable to inline creation

Refactor variable to inline creation


import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
import org.slf4j.MDC;

import java.util.UUID;

public class RequestTrackerClientFilter extends ClientFilter {

    @Override
    public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException {
        // As getNext() is final in ClientFilter and cannot be stubbed in test classes, all work is
        // performed in the protected doWork method which can be unit tested.
        // That the filter hands off to the next in the chain can only be tested in an integration test
        return getNext().handle(doWork(clientRequest));
    }

    protected ClientRequest doWork(ClientRequest clientRequest) {
        String logId= MDC.get("Request-Tracker");

        if(logId == null) {
            logId = UUID.randomUUID().toString();
        }

        clientRequest.getHeaders().add("X-Request-Tracker", logId);

        return clientRequest;
    }
}

import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;
import org.slf4j.MDC;

import java.util.UUID;

public class RequestTrackerClientFilter extends ClientFilter {
    private static final Supplier<String> ID_SUPPLIER = new Supplier<String>() {
        @Override
        public String get() {
            return UUID.randomUUID().toString();
        }
    };

    @Override
    public ClientResponse handle(ClientRequest clientRequest) throws ClientHandlerException {
        // As getNext() is final in ClientFilter and cannot be stubbed in test classes, all work is
        // performed in the protected doWork method which can be unit tested.
        // That the filter hands off to the next in the chain can only be tested in an integration test
        return getNext().handle(doWork(clientRequest));
    }

    protected ClientRequest doWork(ClientRequest clientRequest) {
        Optional<String> requestId = Optional.fromNullable(MDC.get("Request-Tracker"));

        clientRequest.getHeaders().add("X-Request-Tracker", requestId.or(ID_SUPPLIER));

        return clientRequest;
    }
}

Use Optional and supplier to match the servlet filter


/*******************************************************************************
 * Copyright 2014, 2020 gwt-ol
 *
 * 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 ol;

import com.github.desjardins.gwt.junit.client.BaseTestCase;

import java.util.Arrays;

/**
 *
 * @author Tino Desjardins
 *
 */
public abstract class GwtOLBaseTestCase extends BaseTestCase {

    public GwtOLBaseTestCase() {

        super(Arrays.asList(
                "//polyfill.io/v3/polyfill.js?features=Blob,URL,Symbol&flags=always",
                "//cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.0/build/ol.js"),
                "ol.GwtOLTest",
                10000);
    }

}

/*******************************************************************************
 * Copyright 2014, 2020 gwt-ol
 *
 * 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 ol;

import com.github.desjardins.gwt.junit.client.BaseTestCase;

import java.util.Arrays;

/**
 *
 * @author Tino Desjardins
 *
 */
public abstract class GwtOLBaseTestCase extends BaseTestCase {

    public GwtOLBaseTestCase() {

        super(Arrays.asList(
                "//polyfill.io/v3/polyfill.js?features=Blob,URL,Symbol&flags=always&version=3.46.0",
                "//cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.2.0/build/ol.js"),
                "ol.GwtOLTest",
                10000);
    }

}

Set explicit polyfill version for tests

Set explicit polyfill version for tests


package io.core9.proxy;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.TreeMap;

import org.littleshoot.proxy.HostResolver;

public class Core9HostResolver implements HostResolver {

	private final Map<String,Proxy> HOSTS = new TreeMap<String,Proxy>();

	@Override
	public InetSocketAddress resolve(String host, int port) throws UnknownHostException {
		if(HOSTS.containsKey(host)) {
			return new InetSocketAddress(HOSTS.get(host).getOrigin(), port);
		} else {
			return null;
		}
	}

	public Core9HostResolver addHost(Proxy proxy) {
		HOSTS.put(proxy.getHostname(), proxy);
		return this;
	}

	public Core9HostResolver removeHost(String address) {
		HOSTS.remove(address);
		return this;
	}

	public Proxy getProxySpecification(String hostname) {
		return HOSTS.get(hostname);
	}

	public Core9HostResolver removeAllHosts() {
		HOSTS.clear();
		return this;
	}

}

package io.core9.proxy;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.TreeMap;

import org.littleshoot.proxy.HostResolver;

public class Core9HostResolver implements HostResolver {

	private final Map<String,Proxy> HOSTS = new TreeMap<String,Proxy>();

	@Override
	public InetSocketAddress resolve(String host, int port) throws UnknownHostException {
		if(HOSTS.containsKey(host)) {
			String origin = HOSTS.get(host).getOrigin();
			if(origin.contains(":")) {
				String [] temp = origin.split(":");
				origin = temp[0];
				port = Integer.parseInt(temp[1]);
			}
			return new InetSocketAddress(origin, port);
		} else {
			return null;
		}
	}

	public Core9HostResolver addHost(Proxy proxy) {
		HOSTS.put(proxy.getHostname(), proxy);
		return this;
	}

	public Core9HostResolver removeHost(String address) {
		HOSTS.remove(address);
		return this;
	}

	public Proxy getProxySpecification(String hostname) {
		return HOSTS.get(hostname);
	}

	public Core9HostResolver removeAllHosts() {
		HOSTS.clear();
		return this;
	}

}

Support port mappings from origin

Support port mappings from origin


/*
Copyright 2011 Frederic Langlet
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 kanzi.entropy;

import kanzi.EntropyDecoder;
import kanzi.BitStream;
import kanzi.BitStreamException;

public abstract class AbstractDecoder implements EntropyDecoder
{
   @Override
   public abstract byte decodeByte();

   @Override
   public abstract BitStream getBitStream();

   // Default implementation: fallback to decodeByte
   @Override
   public int decode(byte[] array, int blkptr, int len)
   {
      if ((array == null) || (blkptr + len > array.length) || (blkptr < 0) || (len < 0))
         return -1;

      int end = blkptr + len;
      int i = blkptr;

      try
      {
         while (i < end)
            array[i++] = this.decodeByte();
      }
      catch (BitStreamException e)
      {
         return i;
      }

      return len;
   }

   @Override
   public void dispose()
   {
   }

}

/*
Copyright 2011 Frederic Langlet
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 kanzi.entropy;

import kanzi.EntropyDecoder;
import kanzi.BitStream;
import kanzi.BitStreamException;

public abstract class AbstractDecoder implements EntropyDecoder
{
   @Override
   public abstract byte decodeByte();

   @Override
   public abstract BitStream getBitStream();

   // Default implementation: fallback to decodeByte
   @Override
   public int decode(byte[] array, int blkptr, int len)
   {
      if ((array == null) || (blkptr + len > array.length) || (blkptr < 0) || (len < 0))
         return -1;

      int end = blkptr + len;
      int i = blkptr;

      try
      {
         while (i < end)
            array[i++] = this.decodeByte();
      }
      catch (BitStreamException e)
      {
         return i - blkptr;
      }

      return len;
   }

   @Override
   public void dispose()
   {
   }

}

Fix length calculation in the exception path


package org.stevewinfield.suja.idk.storage;

import org.stevewinfield.suja.idk.Bootloader;

public class HSQLDBStorageDriver implements StorageDriver {
    @Override
    public String getDriverName() {
        return "hsqldb";
    }

    @Override
    public String getDriverClass() {
        return "org.hsqldb.jdbc.JDBCDriver";
    }

    @Override
    public String getConnectionString() {
        return "jdbc:hsqldb:file:" + Bootloader.getSettings().getProperty("idk.hsqldb.path");
    }

    @Override
    public String getUsername() {
        return "sa";
    }

    @Override
    public String getPassword() {
        return "";
    }
}

package org.stevewinfield.suja.idk.storage;

import org.stevewinfield.suja.idk.Bootloader;

public class HSQLDBStorageDriver implements StorageDriver {
    @Override
    public String getDriverName() {
        return "hsqldb";
    }

    @Override
    public String getDriverClass() {
        return "org.hsqldb.jdbc.JDBCDriver";
    }

    @Override
    public String getConnectionString() {
        return "jdbc:hsqldb:file:" + Bootloader.getSettings().getProperty("idk.hsqldb.path", "database");
    }

    @Override
    public String getUsername() {
        return Bootloader.getSettings().getProperty("idk.hsqldb.user", "");
    }

    @Override
    public String getPassword() {
        return Bootloader.getSettings().getProperty("idk.hsqldb.password", "");
    }
}

Allow specifying username and password for HSQLDB


/*
 * Copyright 2011 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
 *
 *      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.gradle.os.jna;

import org.gradle.os.OperatingSystem;
import org.gradle.os.ProcessEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Uses jna to update the environment variables
 *
 * @author: Szczepan Faber, created at: 9/7/11
 */
public class NativeEnvironment {
    private static final Logger LOGGER = LoggerFactory.getLogger(NativeEnvironment.class);

    public static ProcessEnvironment current() {
        if (OperatingSystem.current().isUnix()) {
            return new Unix();
        } else if (OperatingSystem.current().isWindows()) {
            return new Windows();
        } else {
            LOGGER.warn(String.format("Unable to initialize native environment. Updating env variables and working directory will not be possible. Operating system: %s.", OperatingSystem.current()));
            return new UnsupportedEnvironment();
        }
    }
}

/*
 * Copyright 2011 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
 *
 *      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.gradle.os.jna;

import org.gradle.os.OperatingSystem;
import org.gradle.os.ProcessEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Uses jna to update the environment variables
 *
 * @author: Szczepan Faber, created at: 9/7/11
 */
public class NativeEnvironment {
    private static final Logger LOGGER = LoggerFactory.getLogger(NativeEnvironment.class);

    public static ProcessEnvironment current() {
        try {
            if (OperatingSystem.current().isUnix()) {
                return new Unix();
            } else if (OperatingSystem.current().isWindows()) {
                return new Windows();
            } else {
                LOGGER.warn("Unable to initialize native environment. Updating env variables and working directory will not be possible. Operating system: {}", OperatingSystem.current());
                return new UnsupportedEnvironment();
            }
        } catch (NoClassDefFoundError e) {
            // Thrown when jna cannot initialise the native stuff
            return new UnsupportedEnvironment();
        }
    }
}

Handle the case where jna cannot be loaded because it is in use by another classloader.


package com.netflix.exhibitor.core.config;

import java.util.concurrent.TimeUnit;

public class AutoManageLockArguments
{
    private final String prefix;
    private final int timeoutMs;
    private final int pollingMs;

    public AutoManageLockArguments(String prefix)
    {
        // TODO get defaults right
        this(prefix, (int)TimeUnit.MINUTES.toMillis(1), 250);
    }

    public AutoManageLockArguments(String prefix, int timeoutMs, int pollingMs)
    {
        this.prefix = prefix;
        this.timeoutMs = timeoutMs;
        this.pollingMs = pollingMs;
    }

    public String getPrefix()
    {
        return prefix;
    }

    public int getTimeoutMs()
    {
        return timeoutMs;
    }

    public int getPollingMs()
    {
        return pollingMs;
    }
}

package com.netflix.exhibitor.core.config;

import java.util.concurrent.TimeUnit;

public class AutoManageLockArguments
{
    private final String prefix;
    private final int timeoutMs;
    private final int pollingMs;

    public AutoManageLockArguments(String prefix)
    {
        // TODO get defaults right
        this(prefix, (int)TimeUnit.MINUTES.toMillis(5), 250);
    }

    public AutoManageLockArguments(String prefix, int timeoutMs, int pollingMs)
    {
        this.prefix = prefix;
        this.timeoutMs = timeoutMs;
        this.pollingMs = pollingMs;
    }

    public String getPrefix()
    {
        return prefix;
    }

    public int getTimeoutMs()
    {
        return timeoutMs;
    }

    public int getPollingMs()
    {
        return pollingMs;
    }
}

Increase lock timeout to 5 min

Increase lock timeout to 5 min


/*
 * Copyright 2010-2013 Ning, Inc.
 *
 * Ning licenses this file to you 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.ning.billing.notification.plugin.api;

/**
 * The enum {@code ExtBusEventType} represents the user visible bus event types.
 */

public enum ExtBusEventType {
    ACCOUNT_CREATION,
    ACCOUNT_CHANGE,
    SUBSCRIPTION_CREATION,
    SUBSCRIPTION_PHASE,
    SUBSCRIPTION_CHANGE,
    SUBSCRIPTION_CANCEL,
    SUBSCRIPTION_UNCANCEL,
    OVERDUE_CHANGE,
    INVOICE_CREATION,
    INVOICE_ADJUSTMENT,
    PAYMENT_SUCCESS,
    PAYMENT_FAILED,
    TAG_CREATION,
    TAG_DELETION,
    CUSTOM_FIELD_CREATION,
    CUSTOM_FIELD_DELETION;
}

/*
 * Copyright 2010-2013 Ning, Inc.
 *
 * Ning licenses this file to you 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.ning.billing.notification.plugin.api;

/**
 * The enum {@code ExtBusEventType} represents the user visible bus event types.
 */

public enum ExtBusEventType {
    ACCOUNT_CREATION,
    ACCOUNT_CHANGE,
    SUBSCRIPTION_CREATION,
    SUBSCRIPTION_PHASE,
    SUBSCRIPTION_CHANGE,
    SUBSCRIPTION_CANCEL,
    SUBSCRIPTION_UNCANCEL,
    BUNDLE_PAUSE,
    BUNDLE_RESUME,
    OVERDUE_CHANGE,
    INVOICE_CREATION,
    INVOICE_ADJUSTMENT,
    PAYMENT_SUCCESS,
    PAYMENT_FAILED,
    TAG_CREATION,
    TAG_DELETION,
    CUSTOM_FIELD_CREATION,
    CUSTOM_FIELD_DELETION;
}

Add new external event for pause/resume bundle


package org.adridadou.ethereum.propeller.solidity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.adridadou.ethereum.propeller.solidity.abi.AbiEntry;
import org.adridadou.ethereum.propeller.values.EthData;

import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
public class TruffleSolidityContractDetails implements SolidityContractDetails {

  private final List<AbiEntry> abi;
  private final String bytecode;
  private final String metadata;

  public TruffleSolidityContractDetails() {
    this(null, null, null);
  }

  public TruffleSolidityContractDetails(List<AbiEntry> abi, String bytecode, String metadata) {
    this.abi = abi;
    this.bytecode = bytecode;
    this.metadata = metadata;
  }

  @Override
  public List<AbiEntry> getAbi() {
    return abi;
  }

  @Override
  public String getMetadata() {
    return metadata;
  }

  @Override
  public EthData getBinary() {
    return EthData.of(bytecode);
  }
}

package org.adridadou.ethereum.propeller.solidity;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.adridadou.ethereum.propeller.solidity.abi.AbiEntry;
import org.adridadou.ethereum.propeller.values.EthData;

@JsonIgnoreProperties(ignoreUnknown = true)
public class TruffleSolidityContractDetails implements SolidityContractDetails {

  private final List<AbiEntry> abi;
  private final String bytecode;
  private final String metadata;

  public TruffleSolidityContractDetails() {
    this(null, null, null);
  }

  public TruffleSolidityContractDetails(List<AbiEntry> abi, String bytecode, String metadata) {
    this.abi = abi;
    this.bytecode = bytecode;
    this.metadata = metadata;
  }

  @Override
  public List<AbiEntry> getAbi() {
    return abi;
  }

  @Override
  public String getMetadata() {
    return metadata;
  }

  @Override
  public EthData getBinary() {
    return EthData.of(bytecode);
  }

  public String getBytecode() {
    return bytecode;
  }
}

Fix the missing getter for proper Jackson desserialization of truffle compilation result


package org.roklib.webapps.uridispatching.parameter.annotation;

import java.lang.annotation.*;

/**
 * @author Roland Krüger
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CapturedParameter {
    String name();
}

package org.roklib.webapps.uridispatching.parameter.annotation;

import java.lang.annotation.*;

/**
 * @author Roland Krüger
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CapturedParameter {
    String mapperName();
    String parameterName();
}

Add two properties to annotation

Add two properties to annotation


package org.beanmaker;

/**
 * This class gives information about the VERSION of this library.
 */
public class Version {
    private static final String  PREFIX  = "";
    private static final int     MAJOR   = 0;
    private static final int     MINOR   = 9;
    private static final int     PATCH   = 10;
    private static final String  POSTFIX = "-beta";

    private static final String VERSION = PREFIX + MAJOR + "." + MINOR + "." + PATCH + POSTFIX;

    /**
     * @return the version number of this library
     */
    public static String get() {
        return VERSION;
    }

    /**
     * To be used in build scripts.
     */
    public static void main (String[] args) {
        System.out.println(get());
    }
}

package org.beanmaker;

/**
 * This class gives information about the VERSION of this library.
 */
public class Version {
    private static final String  PREFIX  = "";
    private static final int     MAJOR   = 0;
    private static final int     MINOR   = 9;
    private static final int     PATCH   = 11;
    private static final String  POSTFIX = "-beta";

    private static final String VERSION = PREFIX + MAJOR + "." + MINOR + "." + PATCH + POSTFIX;

    /**
     * @return the version number of this library
     */
    public static String get() {
        return VERSION;
    }

    /**
     * To be used in build scripts.
     */
    public static void main (String[] args) {
        System.out.println(get());
    }
}

Create version 0.9.11 before integrating file upload functionality


package io.quarkus.runtime.logging;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;

import org.jboss.logging.Logger;

public class LogCleanupFilter implements Filter {

    private Map<String, LogCleanupFilterElement> filterElements = new HashMap<>();

    public LogCleanupFilter(List<LogCleanupFilterElement> filterElements) {
        for (LogCleanupFilterElement element : filterElements) {
            this.filterElements.put(element.getLoggerName(), element);
        }
    }

    @Override
    public boolean isLoggable(LogRecord record) {
        if (record.getLevel().intValue() != Level.INFO.intValue()
                && record.getLevel().intValue() != Level.WARNING.intValue()) {
            return true;
        }
        LogCleanupFilterElement filterElement = filterElements.get(record.getLoggerName());
        if (filterElement != null) {
            for (String messageStart : filterElement.getMessageStarts()) {
                if (record.getMessage().startsWith(messageStart)) {
                    record.setLevel(org.jboss.logmanager.Level.DEBUG);
                    return Logger.getLogger(record.getLoggerName()).isDebugEnabled();
                }
            }
        }
        //            System.err.println("isLoggable: "+record.getLoggerName());
        //            System.err.println("isLoggable: "+record.getMessage());
        return true;
    }

}

package io.quarkus.runtime.logging;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;

import org.jboss.logging.Logger;

public class LogCleanupFilter implements Filter {

    private Map<String, LogCleanupFilterElement> filterElements = new HashMap<>();

    public LogCleanupFilter(List<LogCleanupFilterElement> filterElements) {
        for (LogCleanupFilterElement element : filterElements) {
            this.filterElements.put(element.getLoggerName(), element);
        }
    }

    @Override
    public boolean isLoggable(LogRecord record) {
        // Only allow filtering messages of warning level and lower
        if (record.getLevel().intValue() > Level.WARNING.intValue()) {
            return true;
        }
        LogCleanupFilterElement filterElement = filterElements.get(record.getLoggerName());
        if (filterElement != null) {
            for (String messageStart : filterElement.getMessageStarts()) {
                if (record.getMessage().startsWith(messageStart)) {
                    record.setLevel(org.jboss.logmanager.Level.DEBUG);
                    return Logger.getLogger(record.getLoggerName()).isDebugEnabled();
                }
            }
        }
        return true;
    }

}

Adjust which log messages can be filtered out


package se.arbetsformedlingen.venice.probe;

import java.util.Objects;

public class Application {
    private String application;

    Application(String application) {
        this.application = application;
    }

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

    @Override
    public int hashCode() {
        return Objects.hash(application);
    }

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

package se.arbetsformedlingen.venice.probe;

import java.util.Objects;

public class Application {
    private String application;

    Application(String application) {
        this.application = application;
    }

    String getApplicationName() {
        return application;
    }

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

    @Override
    public int hashCode() {
        return Objects.hash(application);
    }

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

Allow users to read the name

Allow users to read the name


package com.tempoiq;

import java.io.IOException;
import org.junit.*;
import static org.junit.Assert.*;

public class DataPointReadTest {

  @Test
  public void smokeTest() throws IOException {
    // Selection sel = new Selection().
    //   addSelector(Selector.Type.DEVICE, Selector.or(
    // 		    Selector.key("building-1234"), Selector.key("building-4321"))).
    //   addSelector(Selector.Type.SENSOR, Selector.key("temp-1"));
  }
}

package com.tempoiq;

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

import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Interval;
import org.junit.*;
import static org.junit.Assert.*;

public class DataPointReadTest {
  private static final DateTimeZone timezone = DateTimeZone.UTC;
  private static final Device device = new Device("device1");
  private static final String json1 = "{" +
    "\"data\":[" +
       "{\"t\":\"2012-01-01T01:00:00.000Z\",\"data\":{" +
         "\"device1\":{" +
           "\"sensor1\":1.23," +
           "\"sensor2\":1.677}}}]}";

  @Test
  public void smokeTest() throws IOException {
    HttpResponse response = Util.getResponse(200, json1);
    Client client = Util.getClient(response);
    DateTime start = new DateTime(2012, 1, 1, 0, 0, 0, 0, timezone);
    DateTime stop = new DateTime(2012, 1, 2, 0, 0, 0, 0, timezone);

    Map<String, Number> points = new HashMap<String, Number>();
    points.put("sensor1", 1.23);
    points.put("sensor2", 1.677);
    MultiDataPoint mp = new MultiDataPoint(new DateTime(2012, 1, 1, 1, 0, 0, 0, timezone), points);
    Result<Void> result = client.writeDataPoints(device, mp);
    assertEquals(State.SUCCESS, result.getState());

    Selection sel = new Selection().
      addSelector(Selector.Type.DEVICES, Selector.key(device.getKey()));
    Cursor<Row> cursor = client.read(sel, start, stop);
    assert(cursor.iterator().hasNext());
    for (Row row : cursor) {
      assertEquals(1.23, row.getValue(device.getKey(), "sensor1"));
      assertEquals(1.677, row.getValue(device.getKey(), "sensor2"));
    }
  }
}

Add simple client test with stubbed result


package arez.doc.examples.at_component_dependency;

import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

@ArezComponent
public abstract class PersonViewModel
{
  @Nonnull
  private final Person _person;
  //DOC ELIDE START

  public PersonViewModel( @Nonnull final Person person )
  {
    _person = person;
  }

  //DOC ELIDE END

  // Let imagine there is a lot more logic and state on the view model
  // to justify it's existence rather than just having view layer directly
  // accessing underlying entities

  @ComponentDependency
  @Nonnull
  public final Person getPerson()
  {
    // This reference is immutable and the network replication
    // layer is responsible for managing the lifecycle of person
    // component and may dispose it when the Person entity is deleted
    // on the server which should trigger this view model being disposed.
    return _person;
  }

  /**
   * The Job entity is likewise controlled by the server
   * and can be updated, removed on the server and replicated to the web
   * browser. In this scenario the current job is just removed from the
   * person view model.
   */
  @ComponentDependency( action = ComponentDependency.Action.SET_NULL )
  @Observable
  @Nullable
  public abstract Job getCurrentJob();
  //DOC ELIDE START

  public abstract void setCurrentJob( @Nullable final Job currentJob );
  //DOC ELIDE END
}

package arez.doc.examples.at_component_dependency;

import arez.annotations.ArezComponent;
import arez.annotations.ComponentDependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

@ArezComponent
public abstract class PersonViewModel
{
  // This reference is immutable and the network replication
  // layer is responsible for managing the lifecycle of person
  // component and may dispose it when the Person entity is deleted
  // on the server which should trigger this view model being disposed.
  @ComponentDependency
  @Nonnull
  final Person _person;
  //DOC ELIDE START

  public PersonViewModel( @Nonnull final Person person )
  {
    _person = person;
  }

  //DOC ELIDE END

  // Let imagine there is a lot more logic and state on the view model
  // to justify it's existence rather than just having view layer directly
  // accessing underlying entities

  @Nonnull
  public final Person getPerson()
  {
    return _person;
  }

  /**
   * The Job entity is likewise controlled by the server
   * and can be updated, removed on the server and replicated to the web
   * browser. In this scenario the current job is just removed from the
   * person view model.
   */
  @ComponentDependency( action = ComponentDependency.Action.SET_NULL )
  @Observable
  @Nullable
  public abstract Job getCurrentJob();
  //DOC ELIDE START

  public abstract void setCurrentJob( @Nullable final Job currentJob );
  //DOC ELIDE END
}

Move @ComponentDependency to the field as that is the latest recomendation


/**
 * Created with IntelliJ IDEA.
 * User: jhasmanyquiroz
 * Date: 11/10/15
 * Time: 11:00 AM
 * To change this template use File | Settings | File Templates.
 */
package steps;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import ui.PageTransporter;

public class LoginSteps {
    public PageTransporter page = PageTransporter.getInstance();

    @Given("^I navigate to Login page$")
    public void navigateLoginPage(){
        page.navigateToMainPage();
    }

    @When("^I login as \"(.*?)\" with password \"(.*?)\"$")
    public void loginAs(String userName, String userPassword){
        page.navigateToLoginPage();
    }

    @Then("^I should login successfully$")
    public void should_login_successfully(){
    }
}

/**
 * Created with IntelliJ IDEA.
 * User: jhasmanyquiroz
 * Date: 11/10/15
 * Time: 11:00 AM
 * To change this template use File | Settings | File Templates.
 */
package steps;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import ui.PageTransporter;
import ui.pages.HomePage;
import ui.pages.LoginPage;
import ui.pages.MainPage;

import static org.testng.Assert.assertTrue;

public class LoginSteps {
    private static PageTransporter page = PageTransporter.getInstance();
    private HomePage homePage;
    private LoginPage loginPage;
    private MainPage mainPage;

    @Given("^I navigate to Login page$")
    public void navigateLoginPage(){
        mainPage = page.navigateToMainPage();
        loginPage = mainPage.clickLogInButton();
        //loginPage = page.navigateToLoginPage();
    }

    @When("^I login as \"(.*?)\" with password \"(.*?)\"$")
    public void loginAs(String userName, String userPassword){
        homePage = loginPage.loginSuccessful(userName, userPassword);
    }

    @Then("^I should login successfully.$")
    public void shouldLoginSuccessfully(){
        assertTrue(homePage.isPartnersDisplayed(), "User Name displayed");
    }
}

Implement the methods for the asserts

Implement the methods for the asserts


package j2048.jgamegui;

import java.awt.Color;

import jgame.GContainer;
import jgame.GRootContainer;
import jgame.Game;

/**
 * The driver class for a 2048 game.
 *
 * @author William Chargin
 *
 */
public class J2048 extends Game {

	public static final Color MAIN_COLOR = new Color(187, 173, 160);
	public static final Color TEXT_COLOR = new Color(119, 110, 101);
	public static final Color LIGHT_COLOR = new Color(250, 248, 239);
	public static final Color LIGHT_TEXT = new Color(238, 228, 218);

	public J2048() {
		setTargetFPS(60);

		GRootContainer root = new GRootContainer(LIGHT_COLOR);
		setRootContainer(root);

		GContainer container = new GContainer();
		GamePanel game = new GamePanel();
		container.setSize(game.getWidth() + 50, game.getHeight() + 50);
		container.addAtCenter(game);
		root.add(container);
	}

	public static void main(String[] args) {
		new J2048().startGame("2048");
	}

}

package j2048.jgamegui;

import java.awt.Color;

import jgame.GContainer;
import jgame.GRootContainer;
import jgame.GameApplet;

/**
 * The driver class for a 2048 game.
 *
 * @author William Chargin
 *
 */
public class J2048 extends GameApplet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public static final Color MAIN_COLOR = new Color(187, 173, 160);
	public static final Color TEXT_COLOR = new Color(119, 110, 101);
	public static final Color LIGHT_COLOR = new Color(250, 248, 239);
	public static final Color LIGHT_TEXT = new Color(238, 228, 218);

	public J2048() {
		core.setTargetFPS(60);

		GRootContainer root = new GRootContainer(LIGHT_COLOR);
		core.setRootContainer(root);

		GContainer container = new GContainer();
		GamePanel game = new GamePanel();
		container.setSize(game.getWidth() + 50, game.getHeight() + 50);
		container.addAtCenter(game);
		root.add(container);
	}

}

Switch to applet (Game -> GameApplet extension)


package io.collap.bryg.environment;

import io.collap.bryg.Template;

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

public class StandardEnvironment implements Environment {

    private Map<String, Template> templateMap = new HashMap<> ();
    private ClassLoader templateClassLoader;

    public StandardEnvironment (ClassLoader templateClassLoader) {
        this.templateClassLoader = templateClassLoader;
    }

    @Override
    public Template getTemplate (String name) {
        Template template = templateMap.get (name);

        if (template == null) {
            template = loadTemplate (name);
        }

        return template;
    }

    /**
     * Also adds the loaded template to the cache.
     */
    private synchronized Template loadTemplate (String name) {
        Template template = null;
        try {
            System.out.println ();
            System.out.println ("Template: " + name);
            long start = System.nanoTime ();
            Class<? extends Template> cl = (Class<? extends Template>) templateClassLoader.loadClass (name);
            template = cl.newInstance ();
            templateMap.put (name, template);
            System.out.println ("Loading took " + ((System.nanoTime () - start) / 1.0e9) + "s.");
            System.out.println ();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace ();
        }

        return template;
    }

}

package io.collap.bryg.environment;

import io.collap.bryg.Template;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class StandardEnvironment implements Environment {

    private Map<String, Template> templateMap = Collections.synchronizedMap (new HashMap<String, Template> ());
    private ClassLoader templateClassLoader;

    public StandardEnvironment (ClassLoader templateClassLoader) {
        this.templateClassLoader = templateClassLoader;
    }

    @Override
    public Template getTemplate (String name) {
        Template template = templateMap.get (name);

        if (template == null) {
            template = loadTemplate (name);
        }

        return template;
    }

    /**
     * Also adds the loaded template to the cache.
     */
    private synchronized Template loadTemplate (String name) {
        Template template = templateMap.get (name);

        /* There could be a case where getTemplate is called with the same name two or more times,
           which would result in the following scenario:
             1. The first call reaches loadTemplate and calls it. loadTemplate is then locked on this object.
             2. The second call reaches loadTemplate and calls it.
             3. The first call finishes.
             4. The second call can now enter loadTemplate and *loads the template again*.
           The check ensures that the template is not loaded again. */
        if (template == null) {
            try {
                System.out.println ();
                System.out.println ("Template: " + name);
                long start = System.nanoTime ();
                Class<? extends Template> cl = (Class<? extends Template>) templateClassLoader.loadClass (name);
                template = cl.newInstance ();
                templateMap.put (name, template);
                System.out.println ("Loading took " + ((System.nanoTime () - start) / 1.0e9) + "s.");
                System.out.println ();
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                e.printStackTrace ();
            }
        }

        return template;
    }

}

Improve thread safety with additional checks and a synchronized map.


/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.devtools.cdbg.debuglets.java;

/**
 * Defines the version of the Java Cloud Debugger agent.
 */
public final class GcpDebugletVersion {
  /**
   * Major version of the debugger.

   * All agents of the same major version are compatible with each other. In other words an
   * application can mix different agents with the same major version within the same debuggee.
   */
  public static final int MAJOR_VERSION = 2;

  /**
   * Minor version of the agent.
   */
  public static final int MINOR_VERSION = 8;

  /**
   * Debugger agent version string in the format of MAJOR.MINOR.
   */
  public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION);

  /**
   * Main function to print the version string.
   */
  public static void main(String[] args) {
    System.out.println(VERSION);
  }
}

/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.devtools.cdbg.debuglets.java;

/**
 * Defines the version of the Java Cloud Debugger agent.
 */
public final class GcpDebugletVersion {
  /**
   * Major version of the debugger.

   * All agents of the same major version are compatible with each other. In other words an
   * application can mix different agents with the same major version within the same debuggee.
   */
  public static final int MAJOR_VERSION = 2;

  /**
   * Minor version of the agent.
   */
  public static final int MINOR_VERSION = 9;

  /**
   * Debugger agent version string in the format of MAJOR.MINOR.
   */
  public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION);

  /**
   * Main function to print the version string.
   */
  public static void main(String[] args) {
    System.out.println(VERSION);
  }
}

Increment minor version to 2.9 to prepare for a new release.

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