text:
///*
// * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.carbon.identity.mgt.connector;
//
//import org.wso2.carbon.identity.mgt.Action;
//import org.wso2.carbon.identity.mgt.Group;
//import org.wso2.carbon.identity.mgt.Permission;
//import org.wso2.carbon.identity.mgt.Resource;
//import org.wso2.carbon.identity.mgt.Role;
//import org.wso2.carbon.identity.mgt.User;
//import org.wso2.carbon.identity.mgt.connector.config.AuthorizationStoreConnectorConfig;
//import org.wso2.carbon.identity.mgt.exception.AuthorizationStoreException;
//import org.wso2.carbon.identity.mgt.exception.PermissionNotFoundException;
//import org.wso2.carbon.identity.mgt.exception.RoleNotFoundException;
//
//import java.util.List;
//
///**
// * Authorization store.
// */
//public interface AuthorizationStoreConnector {
//
//    /**
//     * Initialize the authorization store.
//     * @param storeId Id of this store.
//     * @param authorizationStoreConnectorConfig Authorization store configurations for this connector.
//     * @throws AuthorizationStoreException Authorization store exception.
//     */
//    void init(String storeId, AuthorizationStoreConnectorConfig authorizationStoreConnectorConfig)
//            throws AuthorizationStoreException;
//
//    /**
//     * Get the role of from role id.
//     * @param roleId Id of the Role
//     * @return Role.RoleBuilder.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    Role.RoleBuilder getRole(String roleId) throws RoleNotFoundException, AuthorizationStoreException;
//
//    /**
//     * Get the count of the roles available in the authorization store.
//     * @return Number of roles.
//     * @throws AuthorizationStoreException Authorization Store Exception
//     */
//    int getRoleCount() throws AuthorizationStoreException;
//
//    /**
//     * List the roles according to the filter pattern.
//     * @param filterPattern Filter pattern to be used.
//     * @param offset Offset to be used.
//     * @param length Number of roles from the offset.
//     * @return List of roles.
//     * @throws AuthorizationStoreException Authorization Store Exception
//     */
//    List<Role.RoleBuilder> listRoles(String filterPattern, int offset, int length) throws AuthorizationStoreException;
//
//    /**
//     * Get permission from the resource id and action.
//     * @param resource Resource of this permission.
//     * @param action Action of the permission.
//     * @return Permission.PermissionBuilder.
//     * @throws AuthorizationStoreException Authorization Store Exception
//     */
//    Permission.PermissionBuilder getPermission(Resource resource, Action action) throws PermissionNotFoundException,
//                                                                                AuthorizationStoreException;
//
//    /**
//     * Get the count of the permissions available in the authorization store.
//     * @return Number of permissions.
//     */
//    int getPermissionCount() throws AuthorizationStoreException;
//
//    /**
//     * List the permissions according to the filter pattern.
//     * @param resourcePattern Resource pattern to be used.
//     * @param actionPattern Action pattern to be used.
//     * @param offset Offset to be used.
//     * @param length Number of permissions from the offset.
//     * @return List of permissions.
//     * @throws AuthorizationStoreException Authorization Store Exception
//     */
//    List<Permission.PermissionBuilder> listPermissions(String resourcePattern, String actionPattern, int offset,
//                                                       int length) throws AuthorizationStoreException;
//
//    /**
//     * Get a list of resources matched for given resource id pattern.
//     * @param resourcePattern Resource id pattern.
//     * @return List of resources.
//     * @throws AuthorizationStoreException Authorization Store Exception
//     */
//    List<Resource.ResourceBuilder> getResources(String resourcePattern) throws AuthorizationStoreException;
//
//    /**
//     * Get a list of actions matched for give action name pattern.
//     * @param actionPattern Action name pattern.
//     * @return List of actions.
//     * @throws AuthorizationStoreException Authorization Store Exception
//     */
//    List<Action.ActionBuilder> getActions(String actionPattern) throws AuthorizationStoreException;
//
//    /**
//     * Get roles for the user id.
//     * @param userId User id of the user.
//     * @return Roles associated to the user.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    List<Role.RoleBuilder> getRolesForUser(String userId) throws AuthorizationStoreException;
//
//    /**
//     * Get roles associated to the group.
//     * @param groupId Unique id of the group.
//     * @return Roles associated to the group.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    List<Role.RoleBuilder> getRolesForGroup(String groupId) throws AuthorizationStoreException;
//
//    /**
//     * Get permissions associated to the role.
//     * @param roleId Role id of the required role.
//     * @param resource Resource which the permissions should take.
//     * @return List of permissions associated to the Role.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    List<Permission.PermissionBuilder> getPermissionsForRole(String roleId, Resource resource)
//            throws AuthorizationStoreException;
//
//    /**
//     * Get permissions associated to the role.
//     * @param roleId Role id of the required role.
//     * @param action Action which the permissions should take.
//     * @return List of permissions associated to the Role.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    List<Permission.PermissionBuilder> getPermissionsForRole(String roleId, Action action)
//            throws AuthorizationStoreException;
//
//    /**
//     * Add new resource.
//     * @param resourceNamespace Namespace of the resource.
//     * @param resourceId Id of the resource.
//     * @param userId User id of the owner.
//     * @return New Resource.
//     * @throws AuthorizationStoreException
//     */
//    Resource.ResourceBuilder addResource(String resourceNamespace, String resourceId, String userId)
//            throws AuthorizationStoreException;
//
//    /**
//     * Add new action.
//     * @param actionNamespace Namespace of the action.
//     * @param actionName Name of the action.
//     * @return New action.
//     * @throws AuthorizationStoreException
//     */
//    Action addAction(String actionNamespace, String actionName) throws AuthorizationStoreException;
//
//    /**
//     * Add new permission.
//     * @param resource Resource.
//     * @param action Action.
//     * @return New permission.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    Permission.PermissionBuilder addPermission(Resource resource, Action action) throws AuthorizationStoreException;
//
//    /**
//     * Add new role.
//     * @param roleName Name of the new role.
//     * @param permissions List of permissions to be assign.
//     * @return New Role.RoleBuilder.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    Role.RoleBuilder addRole(String roleName, List<Permission> permissions) throws AuthorizationStoreException;
//
//    /**
//     * Checks whether the users is in the role.
//     * @param userId Id of the user.
//     * @param roleName Name of the role.
//     * @return True if user is in the role.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    boolean isUserInRole(String userId, String roleName) throws AuthorizationStoreException;
//
//    /**
//     * Checks whether the group is in the role.
//     * @param groupId Id of the group.
//     * @param roleName Name of the role.
//     * @return True if the group is in the role.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    boolean isGroupInRole(String groupId, String roleName) throws AuthorizationStoreException;
//
//    /**
//     * Get the users of the role.
//     * @param roleId Id of the role.
//     * @return List of @see User.UserBuilder.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    List<User.UserBuilder> getUsersOfRole(String roleId) throws AuthorizationStoreException;
//
//    /**
//     * Get the groups of the role.
//     * @param roleId Id of the role.
//     * @return List of @see Group.GroupBuilder.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    List<Group.GroupBuilder> getGroupsOfRole(String roleId) throws AuthorizationStoreException;
//
//    /**
//     * Delete the specified role.
//     * @param roleId Id of the role.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void deleteRole(String roleId) throws AuthorizationStoreException;
//
//    /**
//     * Delete the specified permission.
//     * @param permissionId Id of the permission.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void deletePermission(String permissionId) throws AuthorizationStoreException;
//
//    /**
//     * Deletes the given resource.
//     * @param resource Resource to be deleted.
//     * @throws AuthorizationStoreException
//     */
//    void deleteResource(Resource resource) throws AuthorizationStoreException;
//
//    /**
//     * Delete the given action.
//     * @param action Action to be deleted.
//     * @throws AuthorizationStoreException
//     */
//    void deleteAction(Action action) throws AuthorizationStoreException;
//
//    /**
//     * Update the roles of the user by replacing existing roles. (PUT)
//     * @param userId Id of the user.
//     * @param newRoleList Role list to replace the existing.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updateRolesInUser(String userId, List<Role> newRoleList) throws AuthorizationStoreException;
//
//    /**
//     * Add a new User list by replacing the existing User list. (PUT)
//     * @param roleId Id of the role.
//     * @param newUserList New user list.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updateUsersInRole(String roleId, List<User> newUserList) throws AuthorizationStoreException;
//
//    /**
//     * Add a new Role list by replacing the existing Role list. (PUT)
//     * @param groupId Id of the group.
//     * @param newRoleList List
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updateRolesInGroup(String groupId, List<Role> newRoleList) throws AuthorizationStoreException;
//
//    /**
//     * Add a new Group list by replacing the existing Group list. (PUT)
//     * @param roleId Id of the role.
//     * @param newGroupList New group list.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updateGroupsInRole(String roleId, List<Group> newGroupList) throws AuthorizationStoreException;
//
//    /**
//     * Add a new Permission list by replacing the existing Permission list. (PUT)
//     * @param roleId Id of the role.
//     * @param newPermissionList New permissions list.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updatePermissionsInRole(String roleId, List<Permission> newPermissionList) throws
// AuthorizationStoreException;
//
//    /**
//     * Assign a new list of Permissions to existing list and/or un-assign Permission from existing Permission. (PATCH)
//     * @param roleId Id of the role.
//     * @param permissionsToBeAssign List of permissions to be assign.
//     * @param permissionsToBeUnassign List of permissions to be un assign.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updatePermissionsInRole(String roleId, List<Permission> permissionsToBeAssign,
//                                 List<Permission> permissionsToBeUnassign) throws AuthorizationStoreException;
//
//    /**
//     * Assign a new list of Roles to existing list and/or un-assign Roles from existing list. (PATCH)
//     * @param userId Id of the user.
//     * @param rolesToBeAssign List of roles to be assign.
//     * @param rolesToBeUnassign List of roles to be un assign.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updateRolesInUser(String userId, List<Role> rolesToBeAssign, List<Role> rolesToBeUnassign)
//            throws AuthorizationStoreException;
//
//    /**
//     * Assign a new list of User to existing list and/or un-assign Permission from existing User. (PATCH)
//     * @param roleId Id of the role.
//     * @param usersToBeAssign List of users to be assign.
//     * @param usersToBeUnassign List of users to un assign.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updateUsersInRole(String roleId, List<User> usersToBeAssign, List<User> usersToBeUnassign)
//            throws AuthorizationStoreException;
//
//    /**
//     * Assign a new list of Group to existing list and/or un-assign Group from existing Group. (PATCH)
//     * @param roleId Id of the role.
//     * @param groupToBeAssign List of groups to be assign.
//     * @param groupToBeUnassign List of groups to be un assign.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updateGroupsInRole(String roleId, List<Group> groupToBeAssign, List<Group> groupToBeUnassign)
//            throws AuthorizationStoreException;
//
//    /**
//     * Assign a new list of Roles to existing list and/or un-assign Roles from existing list. (PATCH)
//     * @param groupId Id of the group.
//     * @param rolesToBeAssign List of roles to be assign.
//     * @param rolesToBeUnassigned List of roles to be un assign.
//     * @throws AuthorizationStoreException Authorization Store Exception.
//     */
//    void updateRolesInGroup(String groupId, List<Role> rolesToBeAssign, List<Role> rolesToBeUnassigned)
//            throws AuthorizationStoreException;
//
//    /**
//     * Get the authorization store config.
//     * @return AuthorizationStoreConnectorConfig.
//     */
//    AuthorizationStoreConnectorConfig getAuthorizationStoreConfig();
//
//    /**
//     * Get the id of this authorization store.
//     * @return Id of the authorization store.
//     */
//    String getAuthorizationStoreId();
//}


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF 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 org.apache.beam.runners.dataflow.worker;

import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.io.Closeable;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.beam.runners.dataflow.worker.StateFetcher.SideInputState;
import org.apache.beam.runners.dataflow.worker.windmill.Windmill;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.ListCoder;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.coders.VarLongCoder;
import org.apache.beam.sdk.coders.VoidCoder;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.Sum;
import org.apache.beam.sdk.transforms.View;
import org.apache.beam.sdk.transforms.windowing.GlobalWindow;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.vendor.grpc.v1p13p1.com.google.protobuf.ByteString;
import org.apache.beam.vendor.guava.v20_0.com.google.common.base.Supplier;
import org.apache.beam.vendor.guava.v20_0.com.google.common.cache.Cache;
import org.apache.beam.vendor.guava.v20_0.com.google.common.cache.CacheBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

/** Unit tests for {@link StateFetcher}. */
@RunWith(JUnit4.class)
public class StateFetcherTest {
  private static final String STATE_FAMILY = "state";

  @Mock MetricTrackingWindmillServerStub server;

  @Mock Supplier<Closeable> readStateSupplier;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testFetchGlobalDataBasic() throws Exception {
    StateFetcher fetcher = new StateFetcher(server);

    ByteString.Output stream = ByteString.newOutput();
    ListCoder.of(StringUtf8Coder.of()).encode(Arrays.asList("data"), stream, Coder.Context.OUTER);
    ByteString encodedIterable = stream.toByteString();

    PCollectionView<String> view =
        TestPipeline.create()
            .apply(Create.empty(StringUtf8Coder.of()))
            .apply(View.<String>asSingleton());

    String tag = view.getTagInternal().getId();

    // Test three calls in a row. First, data is not ready, then data is ready,
    // then the data is already cached.
    when(server.getSideInputData(any(Windmill.GlobalDataRequest.class)))
        .thenReturn(
            buildGlobalDataResponse(tag, ByteString.EMPTY, false, null),
            buildGlobalDataResponse(tag, ByteString.EMPTY, true, encodedIterable));

    assertEquals(
        null,
        fetcher.fetchSideInput(
            view, GlobalWindow.INSTANCE, STATE_FAMILY, SideInputState.UNKNOWN, readStateSupplier));
    assertEquals(
        null,
        fetcher.fetchSideInput(
            view, GlobalWindow.INSTANCE, STATE_FAMILY, SideInputState.UNKNOWN, readStateSupplier));
    assertEquals(
        "data",
        fetcher
            .fetchSideInput(
                view,
                GlobalWindow.INSTANCE,
                STATE_FAMILY,
                SideInputState.KNOWN_READY,
                readStateSupplier)
            .orNull());
    assertEquals(
        "data",
        fetcher
            .fetchSideInput(
                view,
                GlobalWindow.INSTANCE,
                STATE_FAMILY,
                SideInputState.KNOWN_READY,
                readStateSupplier)
            .orNull());

    verify(server, times(2)).getSideInputData(buildGlobalDataRequest(tag, ByteString.EMPTY));
    verifyNoMoreInteractions(server);
  }

  @Test
  public void testFetchGlobalDataNull() throws Exception {
    StateFetcher fetcher = new StateFetcher(server);

    ByteString.Output stream = ByteString.newOutput();
    ListCoder.of(VoidCoder.of()).encode(Arrays.asList((Void) null), stream, Coder.Context.OUTER);
    ByteString encodedIterable = stream.toByteString();

    PCollectionView<Void> view =
        TestPipeline.create().apply(Create.empty(VoidCoder.of())).apply(View.<Void>asSingleton());

    String tag = view.getTagInternal().getId();

    // Test three calls in a row. First, data is not ready, then data is ready,
    // then the data is already cached.
    when(server.getSideInputData(any(Windmill.GlobalDataRequest.class)))
        .thenReturn(
            buildGlobalDataResponse(tag, ByteString.EMPTY, false, null),
            buildGlobalDataResponse(tag, ByteString.EMPTY, true, encodedIterable));

    assertEquals(
        null,
        fetcher.fetchSideInput(
            view, GlobalWindow.INSTANCE, STATE_FAMILY, SideInputState.UNKNOWN, readStateSupplier));
    assertEquals(
        null,
        fetcher.fetchSideInput(
            view, GlobalWindow.INSTANCE, STATE_FAMILY, SideInputState.UNKNOWN, readStateSupplier));
    assertEquals(
        null,
        fetcher
            .fetchSideInput(
                view,
                GlobalWindow.INSTANCE,
                STATE_FAMILY,
                SideInputState.KNOWN_READY,
                readStateSupplier)
            .orNull());
    assertEquals(
        null,
        fetcher
            .fetchSideInput(
                view,
                GlobalWindow.INSTANCE,
                STATE_FAMILY,
                SideInputState.KNOWN_READY,
                readStateSupplier)
            .orNull());

    verify(server, times(2)).getSideInputData(buildGlobalDataRequest(tag, ByteString.EMPTY));
    verifyNoMoreInteractions(server);
  }

  @Test
  public void testFetchGlobalDataCacheOverflow() throws Exception {
    Coder<List<String>> coder = ListCoder.of(StringUtf8Coder.of());

    ByteString.Output stream = ByteString.newOutput();
    coder.encode(Arrays.asList("data1"), stream, Coder.Context.OUTER);
    ByteString encodedIterable1 = stream.toByteString();
    stream = ByteString.newOutput();
    coder.encode(Arrays.asList("data2"), stream, Coder.Context.OUTER);
    ByteString encodedIterable2 = stream.toByteString();

    Cache<StateFetcher.SideInputId, StateFetcher.SideInputCacheEntry> cache =
        CacheBuilder.newBuilder().build();

    StateFetcher fetcher = new StateFetcher(server, cache);

    PCollectionView<String> view1 =
        TestPipeline.create()
            .apply(Create.empty(StringUtf8Coder.of()))
            .apply(View.<String>asSingleton());

    PCollectionView<String> view2 =
        TestPipeline.create()
            .apply(Create.empty(StringUtf8Coder.of()))
            .apply(View.<String>asSingleton());

    String tag1 = view1.getTagInternal().getId();
    String tag2 = view2.getTagInternal().getId();

    // Test four calls in a row. First, fetch view1, then view2 (which evicts view1 from the cache),
    // then view 1 again twice.
    when(server.getSideInputData(any(Windmill.GlobalDataRequest.class)))
        .thenReturn(
            buildGlobalDataResponse(tag1, ByteString.EMPTY, true, encodedIterable1),
            buildGlobalDataResponse(tag2, ByteString.EMPTY, true, encodedIterable2),
            buildGlobalDataResponse(tag1, ByteString.EMPTY, true, encodedIterable1));

    assertEquals(
        "data1",
        fetcher
            .fetchSideInput(
                view1,
                GlobalWindow.INSTANCE,
                STATE_FAMILY,
                SideInputState.UNKNOWN,
                readStateSupplier)
            .orNull());
    assertEquals(
        "data2",
        fetcher
            .fetchSideInput(
                view2,
                GlobalWindow.INSTANCE,
                STATE_FAMILY,
                SideInputState.UNKNOWN,
                readStateSupplier)
            .orNull());
    cache.invalidateAll();
    assertEquals(
        "data1",
        fetcher
            .fetchSideInput(
                view1,
                GlobalWindow.INSTANCE,
                STATE_FAMILY,
                SideInputState.UNKNOWN,
                readStateSupplier)
            .orNull());
    assertEquals(
        "data1",
        fetcher
            .fetchSideInput(
                view1,
                GlobalWindow.INSTANCE,
                STATE_FAMILY,
                SideInputState.UNKNOWN,
                readStateSupplier)
            .orNull());

    ArgumentCaptor<Windmill.GlobalDataRequest> captor =
        ArgumentCaptor.forClass(Windmill.GlobalDataRequest.class);

    verify(server, times(3)).getSideInputData(captor.capture());
    verifyNoMoreInteractions(server);

    assertThat(
        captor.getAllValues(),
        contains(
            buildGlobalDataRequest(tag1, ByteString.EMPTY),
            buildGlobalDataRequest(tag2, ByteString.EMPTY),
            buildGlobalDataRequest(tag1, ByteString.EMPTY)));
  }

  @Test
  public void testEmptyFetchGlobalData() throws Exception {
    StateFetcher fetcher = new StateFetcher(server);

    ByteString encodedIterable = ByteString.EMPTY;

    PCollectionView<Long> view =
        TestPipeline.create()
            .apply(Create.empty(VarLongCoder.of()))
            .apply(Sum.longsGlobally().asSingletonView());

    String tag = view.getTagInternal().getId();

    // Test three calls in a row. First, data is not ready, then data is ready,
    // then the data is already cached.
    when(server.getSideInputData(any(Windmill.GlobalDataRequest.class)))
        .thenReturn(buildGlobalDataResponse(tag, ByteString.EMPTY, true, encodedIterable));

    assertEquals(
        0L,
        (long)
            fetcher
                .fetchSideInput(
                    view,
                    GlobalWindow.INSTANCE,
                    STATE_FAMILY,
                    SideInputState.UNKNOWN,
                    readStateSupplier)
                .orNull());

    verify(server).getSideInputData(buildGlobalDataRequest(tag, ByteString.EMPTY));
    verifyNoMoreInteractions(server);
  }

  private Windmill.GlobalData buildGlobalDataResponse(
      String tag, ByteString version, boolean isReady, ByteString data) {
    Windmill.GlobalData.Builder builder =
        Windmill.GlobalData.newBuilder()
            .setDataId(Windmill.GlobalDataId.newBuilder().setTag(tag).setVersion(version).build());

    if (isReady) {
      builder.setIsReady(true).setData(data);
    } else {
      builder.setIsReady(false);
    }
    return builder.build();
  }

  private Windmill.GlobalDataRequest buildGlobalDataRequest(String tag, ByteString version) {
    Windmill.GlobalDataId id =
        Windmill.GlobalDataId.newBuilder().setTag(tag).setVersion(version).build();

    return Windmill.GlobalDataRequest.newBuilder()
        .setDataId(id)
        .setStateFamily(STATE_FAMILY)
        .setExistenceWatermarkDeadline(
            TimeUnit.MILLISECONDS.toMicros(GlobalWindow.INSTANCE.maxTimestamp().getMillis()))
        .build();
  }
}

domain: java


text:
package com.sbhachu.audioplayer.listener;

import com.sbhachu.audioplayer.data.model.media.Album;
import com.sbhachu.audioplayer.data.model.media.Artist;
import com.sbhachu.audioplayer.data.model.media.Genre;
import com.sbhachu.audioplayer.data.model.media.Playlist;
import com.sbhachu.audioplayer.data.model.media.Track;

import java.util.List;

/**
 * Created by sbhachu on 25/12/2014.
 */
public interface GlobalFragmentInteractionListener {

    public void onNoMusicFound();
    public void onTrackSelected(List<Track> tracks);
    public void onAlbumSelected(Album album);
    public void onArtistSelected(Artist artist);
    public void onGenreSelected(Genre genre);
    public void onPlaylistSelected(Playlist playlist);
    public void onPlaylistsChanged();
    public void onTrackLongPressed(Track track);
    public void onPlaylistDialogSelection(Playlist playlist, Track track);
}


text:
package hyoja.server.board.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import hyoja.server.board.domain.PitchermainVO;
import hyoja.server.board.service.PitchermainService;

@Controller
public class PitchermainController {

  @Resource(name = "hyoja.server.board.service.PitchermainService")
  PitchermainService mPitchermainService;

  @RequestMapping(value = "/pitchermain", method = RequestMethod.GET)
  @ResponseBody
  private List<PitchermainVO> pitchermainList(Model model) throws Exception {

    List<PitchermainVO> pitchermainList = mPitchermainService.pitchermainListService();

    return pitchermainList;
  }

  @RequestMapping(value = "/pitchermain/{pmno}", method = RequestMethod.GET)
  @ResponseBody
  private PitchermainVO pitchermainDetail(@PathVariable int pmno, Model model) throws Exception {

    PitchermainVO pitchermainDetail = mPitchermainService.pitchermainDetailService(pmno);

    return pitchermainDetail;
  }

  @RequestMapping(value = "/pitchermain/{team}/{season}", method = RequestMethod.GET)
  @ResponseBody
  private List<PitchermainVO> pitchermainList_team_season(@PathVariable String team, @PathVariable String season,
      Model model) throws Exception {

    List<PitchermainVO> pitchermainList_team_season = mPitchermainService.pitchermainList_team_seasonService(team,
        season);

    return pitchermainList_team_season;
  }

  @RequestMapping(value = "/pitchermain/{team}/{season}/{pmid}", method = RequestMethod.GET)
  @ResponseBody
  private PitchermainVO pitchermain_team_season_pmid(@PathVariable String team, @PathVariable String season,
      @PathVariable int pmid, Model model) throws Exception {

    PitchermainVO pitchermain_team_season_pmid = mPitchermainService.pitchermain_team_season_pmidService(team, season,
        pmid);

    return pitchermain_team_season_pmid;
  }

}


text:
// Copyright 2021 The Bazel Authors. 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.build.lib.analysis.config;

import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.buildtool.BuildRequestOptions;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.vfs.Path;
import java.util.Set;
import java.util.function.Function;

/** Represents a single kind of convenience symlink ({@code bazel-bin}, etc.). */
public interface SymlinkDefinition {

  /**
   * Returns the name for this symlink in the workspace.
   *
   *
Note that this is independent of the target configuration(s) that may help determine the
   * symlink's destination.
   */
  String getLinkName(String symlinkPrefix, String productName, String workspaceBaseName);

  /**
   * Returns a set of candidate destination paths for the symlink.
   *
   *
The symlink should only be created if there is exactly one candidate. Zero candidates is a
   * no-op, and more than one candidate means a warning about ambiguous symlink destinations should
   * be emitted.
   *
   * @param buildRequestOptions options that may control which symlinks get created and what they
   *     point to.
   * @param targetConfigs the configurations for which symlinks should be created. If these have
   *     conflicting requirements, multiple candidates are returned.
   * @param configGetter used to compute derived configurations, if needed. This is used for
   *     symlinks that link to the output directories of configs that are related to, but not
   *     included in, {@code targetConfigs}.
   * @param repositoryName the repository name.
   * @param outputPath the output path.
   * @param execRoot the exec root.
   */
  ImmutableSet<Path> getLinkPaths(
      BuildRequestOptions buildRequestOptions,
      Set<BuildConfiguration> targetConfigs,
      Function<BuildOptions, BuildConfiguration> configGetter,
      RepositoryName repositoryName,
      Path outputPath,
      Path execRoot);
}


text:
/*
Copyright 2011-2016 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.security.zynamics.reil.translators.arm;

import com.google.security.zynamics.reil.OperandSize;
import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.translators.ITranslationEnvironment;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.TranslationHelpers;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.disassembly.IOperandTreeNode;

import java.util.List;

public class ARMUhsub8Translator extends ARMBaseTranslator {
  @Override
  protected void translateCore(final ITranslationEnvironment environment,
      final IInstruction instruction, final List<ReilInstruction> instructions) {
    final IOperandTreeNode registerOperand1 =
        instruction.getOperands().get(0).getRootNode().getChildren().get(0);
    final IOperandTreeNode registerOperand2 =
        instruction.getOperands().get(1).getRootNode().getChildren().get(0);
    final IOperandTreeNode registerOperand3 =
        instruction.getOperands().get(2).getRootNode().getChildren().get(0);

    final String targetRegister = (registerOperand1.getValue());
    final String sourceRegister1 = (registerOperand2.getValue());
    final String sourceRegister2 = (registerOperand3.getValue());

    final OperandSize wd = OperandSize.WORD;

    final long baseOffset = (instruction.getAddress().toLong() * 0x100) + instructions.size();

    new Processor() {
      @Override
      protected int getResultShiftDelta() {
        return -1;
      }

      @Override
      protected String[] process(final long offset, final String[] firstFour,
          final String[] secondFour) {
        final String diff1 = environment.getNextVariableString();
        final String diff2 = environment.getNextVariableString();
        final String diff3 = environment.getNextVariableString();
        final String diff4 = environment.getNextVariableString();

        long baseOffset = offset;

        instructions.add(ReilHelpers.createSub(baseOffset++, wd, firstFour[0], wd, secondFour[0],
            dw, diff1));
        instructions.add(ReilHelpers.createSub(baseOffset++, wd, firstFour[1], wd, secondFour[1],
            dw, diff2));
        instructions.add(ReilHelpers.createSub(baseOffset++, wd, firstFour[2], wd, secondFour[2],
            dw, diff3));
        instructions.add(ReilHelpers.createSub(baseOffset++, wd, firstFour[3], wd, secondFour[3],
            dw, diff4));

        return new String[] {diff1, diff2, diff3, diff4};
      }
    }.generate(environment, baseOffset, 8, sourceRegister1, sourceRegister2, targetRegister,
        instructions);
  }

  /**
   * UHSUB8{<cond>} <Rd>, <Rn>, <Rm>
   *
   * Operation:
   *
   * if ConditionPassed(cond) then diff = Rn[7:0] - Rm[7:0] // Unsigned subtraction Rd[7:0] =
   * diff[8:1] diff = Rn[15:8] - Rm[15:8] // Unsigned subtraction Rd[15:8] = diff[8:1] diff =
   * Rn[23:16] - Rm[23:16] // Unsigned subtraction Rd[23:16] = diff[8:1] diff = Rn[31:24] -
   * Rm[31:24] // Unsigned subtraction Rd[31:24] = diff[8:1]
   *
   */
  @Override
  public void translate(final ITranslationEnvironment environment, final IInstruction instruction,
      final List<ReilInstruction> instructions) throws InternalTranslationException {
    TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "UHSUB8");
    translateAll(environment, instruction, "UHSUB8", instructions);
  }
}


text:
package pl.backlog.green;

import picocli.CommandLine;

import java.nio.file.Path;
import java.util.concurrent.Callable;

@CommandLine.Command(
        name = "Test04",
        mixinStandardHelpOptions = true,
        version = "1.0",
        description = "Simple program to show capabilities of picocli library"
)
public class Test04 implements Callable<Integer> {
    @CommandLine.Option(names = "-a", required = true, description = "first option without value, mandatory")
    boolean simpleClusteredOption;

    @CommandLine.Option(names = "-b", description = "second option with value, not mandatory")
    String value01;

    @CommandLine.Option(names = "-c", required = true, paramLabel = "INT", description = "second option with value, mandatory")
    String value02;

    @CommandLine.Option(names = {"-p", "--path"}, required = true, paramLabel = "PATH", description = "second option with value, not mandatory")
    Path path;

    @Override
    public Integer call() {
        if (simpleClusteredOption) {
            System.out.println("Podałeś opcję 'a'");
        } else {
            System.out.println("Nie podałeś opcji 'a'");
        }
        System.out.println("Wartość 'b': " + value01);
        System.out.println("Wartość 'c': " + value02);
        System.out.println("Wartość 'p': " + path.toString());
        return 0;
    }

    public static void main(String[] args) {
        int exitCode = new CommandLine(new Test04()).execute(args);
        System.exit(exitCode);
    }
}


text:
package plugin;

import com.google.common.base.Strings;
import stub.weaver.internal.log.Log;

import java.io.File;
import java.util.Objects;

public class LancetExtension {
    private Log.Level level = Log.Level.INFO;
    private String fileName = null;
    private boolean incremental = true;

    public void logLevel(Log.Level level) {
        this.level = Objects.requireNonNull(level, "Log.Level is null");
    }

    public void logLevel(int level) {
        this.level = Log.Level.values()[level];
    }

    public void logLevel(String logStr) {
        logLevel(strToLog(logStr));
    }

    private static Log.Level strToLog(String logStr) {
        logStr = logStr.toLowerCase();
        switch (logStr) {
            case "d":
            case "debug":
                return Log.Level.DEBUG;
            case "i":
            case "info":
                return Log.Level.INFO;
            case "w":
            case "warn":
                return Log.Level.WARN;
            case "e":
            case "error":
                return Log.Level.ERROR;
            default:
                throw new IllegalArgumentException("wrong log string: " + logStr);
        }
    }

    public void useFileLog(String fileName) {
        if (Strings.isNullOrEmpty(fileName) || fileName.contains(File.separator)) {
            throw new IllegalArgumentException("File name is illegal: " + fileName);
        }
        this.fileName = fileName;
    }

    public void setIncremental(boolean incremental) {
        this.incremental = incremental;
    }

    public boolean getIncremental() {
        return this.incremental;
    }

    public void incremental(boolean incremental) {
        this.incremental = incremental;
    }

    public Log.Level getLogLevel() {
        return level;
    }

    public String getFileName() {
        return fileName;
    }
}


text:
package com.lbs.re.ui.components.combobox;

import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.spring.annotation.PrototypeScope;

import com.lbs.re.localization.ResourceEditorLocalizerWrapper;
import com.lbs.re.util.EnumsV2.SearchFilter;
import com.vaadin.spring.annotation.SpringComponent;

@SpringComponent
@PrototypeScope
public class SearchFilterComboBox extends REComboBox<SearchFilter> implements ResourceEditorLocalizerWrapper {

	private static final long serialVersionUID = 1L;

	@Autowired
	public SearchFilterComboBox(SearchFilterComboBoxDataProvider dataProvider) {
		super();
		setId("component.SearchFilterComboBox");
		setCaption(getLocaleValue("component.searchfilter.caption"));
		setStyleName("full");
		setEnabled(true);
		setDataProvider(dataProvider.getListDataProvider());
		setSelectedItem(SearchFilter.CONTAINS);
	}

}


text:
package com.andyadc.codeblocks.common.event;

import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;

/**
 * Parallel {@link EventDispatcher} implementation uses {@link ForkJoinPool#commonPool() JDK common thread pool}
 *
 * @see ForkJoinPool#commonPool()
 */
public class ParallelEventDispatcher extends AbstractEventDispatcher {

	public static final String NAME = "parallel";

	public ParallelEventDispatcher(Executor executor) {
		super(executor);
	}

	public ParallelEventDispatcher() {
		this(ForkJoinPool.commonPool());
	}
}


text:
package com.alibaba.oneagent;

import static org.assertj.core.api.Assertions.assertThat;

import java.lang.instrument.Instrumentation;

import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.test.rule.OutputCapture;

import net.bytebuddy.agent.ByteBuddyAgent;

/**
 *
 * @author hengyunabc 2020-09-17
 *
 */
public class BootstrapAgentTest {
    @Rule
    public OutputCapture capture = new OutputCapture();

    //@Test
    public void test() {
        Instrumentation instrumentation = ByteBuddyAgent.install();
        String args = AgentArgsUtils.agentArgs();

        System.err.println("args: " + args);
        BootstrapAgent.agentmain(args, instrumentation);

        BootstrapAgent.destory();

        assertThat(capture.toString()).contains("enabled TestActivator").contains("init TestActivator")
                .contains("start TestActivator").contains("start DubboDemoActivator").contains("DemoAgent started.")
                .contains("stop TestActivator");
    }

}


text:
/*
 * Copyright 2002-2014 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 com.baidu.jprotobuf.pbrpc.spring;

import org.junit.Ignore;
import org.junit.Test;

import com.baidu.jprotobuf.pbrpc.EchoService;

/**
 * Test class for {@link RpcServiceExporter} and {@link RpcProxyFactoryBean} by XML configuration.
 *
 * @author xiemalin
 * @since 2.17
 */

public class RpcXmlConfigurationTest extends RpcXmlConfigurationTestBase {

    /*
     * (non-Javadoc)
     *
     * @see com.baidu.jprotobuf.pbrpc.spring.RpcXmlConfigurationTestBase#getConfigurationPath()
     */
    @Override
    protected String getConfigurationPath() {
        return "classpath:" + RpcXmlConfigurationTest.class.getName().replace('.', '/') + ".xml";
    }

    @Test
    public void testRpcRequestAndResponse() {
        EchoService echoService = (EchoService) context.getBean("echoServiceProxy", EchoService.class);
        super.internalRpcRequestAndResponse(echoService);
    }
}


text:
package gov.va.escreening.controller.dashboard;

import gov.va.escreening.domain.UserStatusEnum;
import gov.va.escreening.dto.DataTableResponse;
import gov.va.escreening.dto.DropDownObject;
import gov.va.escreening.dto.SearchAttributes;
import gov.va.escreening.dto.SortDirection;
import gov.va.escreening.dto.dashboard.AssessmentSearchResult;
import gov.va.escreening.dto.dashboard.SearchResult;
import gov.va.escreening.form.AssessmentReportFormBean;
import gov.va.escreening.security.CurrentUser;
import gov.va.escreening.security.EscreenUser;
import gov.va.escreening.service.ProgramService;
import gov.va.escreening.service.UserService;
import gov.va.escreening.service.VeteranAssessmentService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/dashboard")
public class AssessmentReportRestController extends BaseDashboardRestController {

	private static final Logger logger = LoggerFactory.getLogger(AssessmentReportRestController.class);

	@Autowired
	private ProgramService programService;

	@Autowired
	private UserService userService;

	@Autowired
	private VeteranAssessmentService veteranAssessmentService;

	@RequestMapping(value = "/assessmentReport/services/assessments/search/init", method = RequestMethod.GET)
	@ResponseBody
	public AssessmentReportFormBean getFormBean(HttpServletRequest request) {

		AssessmentReportFormBean assessmentReportFormBean = new AssessmentReportFormBean();

		Integer veteranId = null;

		if (request.getSession().getAttribute("veteranId") != null) {
			String veteranIdString = request.getSession().getAttribute("veteranId").toString();
			request.getSession().removeAttribute("veteranId");

			if (StringUtils.isNotBlank(veteranIdString) && StringUtils.isNumeric(veteranIdString)) {
				veteranId = Integer.valueOf(veteranIdString);
			}
		}

		if (veteranId != null) {
			assessmentReportFormBean.setVeteranId(veteranId);
		}

		return assessmentReportFormBean;
	}

	@RequestMapping(value = "/assessmentReport/services/assessments/search", method = RequestMethod.POST)
	@ResponseBody
	public DataTableResponse<AssessmentSearchResult> searchAssessments(
			HttpServletRequest request, @CurrentUser EscreenUser escreenUser) {

		displaySearchParms(request);

		return getDataTableResponse(request, escreenUser, false);
	}

	@RequestMapping(value = "/assessmentReport/services/user/clinicians", method = RequestMethod.POST)
	@ResponseBody
	public List<DropDownObject> getClinician(@RequestParam Boolean includeAll,
			@CurrentUser EscreenUser escreenUser) {

		List<Integer> userStatusIdList = new ArrayList<Integer>();
		userStatusIdList.add(UserStatusEnum.ACTIVE.getUserStatusId());
		userStatusIdList.add(UserStatusEnum.INACTIVE.getUserStatusId());

		if (includeAll) {
			userStatusIdList.add(UserStatusEnum.DELETED.getUserStatusId());
		}

		List<DropDownObject> dropDownObjectList = userService.getAssessmentClinicianDropDownObjects(userStatusIdList, escreenUser.getProgramIdList());

		return dropDownObjectList;
	}

	@RequestMapping(value = "/assessmentReport/services/user/assessmentCreators", method = RequestMethod.POST)
	@ResponseBody
	public List<DropDownObject> getAssessmentCreators(
			@RequestParam Boolean includeAll,
			@CurrentUser EscreenUser escreenUser) {

		List<Integer> userStatusIdList = new ArrayList<Integer>();
		userStatusIdList.add(UserStatusEnum.ACTIVE.getUserStatusId());
		userStatusIdList.add(UserStatusEnum.INACTIVE.getUserStatusId());

		if (includeAll) {
			userStatusIdList.add(UserStatusEnum.DELETED.getUserStatusId());
		}

		List<DropDownObject> dropDownObjectList = userService.getAssessmentCreatorDropDownObjects(userStatusIdList, escreenUser.getProgramIdList());

		return dropDownObjectList;
	}

	@RequestMapping(value = "/assessmentReport/services/user/programs", method = RequestMethod.POST)
	@ResponseBody
	public List<DropDownObject> getPrograms(@CurrentUser EscreenUser escreenUser) {

		List<DropDownObject> dropDownObjectList = programService.getProgramDropDownObjects(escreenUser.getProgramIdList());

		return dropDownObjectList;
	}

	@RequestMapping(value = "/assessmentReport/services/assessments/search/pdf", method = RequestMethod.GET)
	public ModelAndView generateAssessmentSearchPdfReport(
			HttpServletRequest request, ModelAndView modelAndView,
			@CurrentUser EscreenUser escreenUser) {

		Map<String, Object> parameterMap = new HashMap<String, Object>();

		DataTableResponse<AssessmentSearchResult> dataTableResponse = getDataTableResponse(request, escreenUser, true);

		JRDataSource JRdataSource = new JRBeanCollectionDataSource(dataTableResponse.getData());
		parameterMap.put("datasource", JRdataSource);

		// assessmentSearchPdfReport bean has been declared in the
		// jasper-views.xml file
		modelAndView = new ModelAndView("assessmentSearchPdfReport", parameterMap);
		return modelAndView;
	}

	@RequestMapping(value = "/assessmentReport/services/assessments/search/xls", method = RequestMethod.GET)
	public ModelAndView generateAssessmentSearchXlsReport(
			HttpServletRequest request, ModelAndView modelAndView,
			@CurrentUser EscreenUser escreenUser) {

		Map<String, Object> parameterMap = new HashMap<String, Object>();

		DataTableResponse<AssessmentSearchResult> dataTableResponse = getDataTableResponse(request, escreenUser, true);

		JRDataSource JRdataSource = new JRBeanCollectionDataSource(dataTableResponse.getData());
		parameterMap.put("datasource", JRdataSource);

		// assessmentSearchPdfReport bean has been declared in the
		// jasper-views.xml file
		modelAndView = new ModelAndView("assessmentSearchXlsReport", parameterMap);
		return modelAndView;
	}

	@RequestMapping(value = "/assessmentReport/services/assessments/search/csv", method = RequestMethod.GET)
	public ModelAndView generateAssessmentSearchCsvReport(
			HttpServletRequest request, ModelAndView modelAndView,
			@CurrentUser EscreenUser escreenUser) {

		Map<String, Object> parameterMap = new HashMap<String, Object>();

		DataTableResponse<AssessmentSearchResult> dataTableResponse = getDataTableResponse(request, escreenUser, true);

		JRDataSource JRdataSource = new JRBeanCollectionDataSource(dataTableResponse.getData());
		parameterMap.put("datasource", JRdataSource);

		// assessmentSearchPdfReport bean has been declared in the
		// jasper-views.xml file
		modelAndView = new ModelAndView("assessmentSearchCsvReport", parameterMap);
		return modelAndView;
	}

	private DataTableResponse<AssessmentSearchResult> getDataTableResponse(
			HttpServletRequest request, EscreenUser escreenUser,
			boolean useMaxPageSize) {

		String echo = request.getParameter("sEcho");

		SearchAttributes searchAttributes = getSearchAttributes(request);

		if (useMaxPageSize) {
			searchAttributes.setPageSize(MAX_PAGE_SIZE);
		}

		AssessmentReportFormBean assessmentReportFormBean = getSearchFormBean(request, escreenUser);

		SearchResult<AssessmentSearchResult> assessmentSearchResult = null;

		if (assessmentReportFormBean.getHasParameter()) {
			// Get the data.
			assessmentSearchResult = veteranAssessmentService.searchVeteranAssessment(assessmentReportFormBean, searchAttributes);
		} else {
			assessmentSearchResult = new SearchResult<AssessmentSearchResult>();
			assessmentSearchResult.setResultList(new ArrayList<AssessmentSearchResult>());
			assessmentSearchResult.setTotalNumRowsFound(0);
		}

		// Populate the DataTableResponse for the data table.
		DataTableResponse<AssessmentSearchResult> dataTableResponse = new DataTableResponse<AssessmentSearchResult>();
		dataTableResponse.setEcho(echo);
		dataTableResponse.setTotalRecords(assessmentSearchResult.getTotalNumRowsFound());
		dataTableResponse.setTotalDisplayRecords(assessmentSearchResult.getTotalNumRowsFound());
		dataTableResponse.setData(assessmentSearchResult.getResultList());

		return dataTableResponse;
	}

	/**
	 * Inspects the request parameters and populates the searchAttributes.
	 *
	 * @param request
	 * @return
	 */
	private SearchAttributes getSearchAttributes(HttpServletRequest request) {

		SearchAttributes searchAttributes = new SearchAttributes();

		// Sort direction.
		String sortDirection = request.getParameter("sSortDir_0");

		if (StringUtils.isNotBlank(sortDirection) && "desc".equalsIgnoreCase(sortDirection)) {
			searchAttributes.setSortDirection(SortDirection.SORT_DESCENDING);
		} else {
			searchAttributes.setSortDirection(SortDirection.SORT_ASCENDING);
		}

		// Start index
		if (StringUtils.isNotBlank(request.getParameter("iDisplayStart")) && StringUtils.isNumeric(request.getParameter("iDisplayStart"))) {
			searchAttributes.setRowStartIndex(Integer.parseInt(request.getParameter("iDisplayStart")));
		} else {
			searchAttributes.setRowStartIndex(0);
		}

		// Page size
		if (StringUtils.isNotBlank(request.getParameter("iDisplayLength")) && StringUtils.isNumeric(request.getParameter("iDisplayLength"))) {
			searchAttributes.setPageSize(Integer.parseInt(request.getParameter("iDisplayLength")));
		} else {
			searchAttributes.setPageSize(10);
		}

		// Sort column
		int sortColumnIndex = 0;
		String sortColumn;

		if (StringUtils.isNotBlank(request.getParameter("iSortCol_0")) && StringUtils.isNumeric(request.getParameter("iSortCol_0"))) {
			sortColumnIndex = Integer.parseInt(request.getParameter("iSortCol_0"));
		}

		switch (sortColumnIndex) {
//		case 0:
//			sortColumn = "veteranAssessmentId";
//			break;

		case 0:
			sortColumn = "programName";
			break;
		case 1:
			sortColumn = "clinicianName";
			break;
		case 2:
			sortColumn = "createdBy";
			break;
		case 3:
			sortColumn = "createDate";
			break;
		case 4:
			sortColumn = "assessmentDate";
			break;
		case 5:
			sortColumn = "veteranId";
			break;
		case 6:
			sortColumn = "veteranName";
			break;
		case 7:
			sortColumn = "assessmentStatusName";
			break;
		default:
			sortColumn = "veteranAssessmentId";
			break;
		}

		searchAttributes.setSortColumn(sortColumn);

		return searchAttributes;
	}

	/**
	 * Inspects the request parameters and populates the
	 * assessmentReportFormBean.
	 *
	 * @param request
	 * @return
	 */
	private AssessmentReportFormBean getSearchFormBean(
			HttpServletRequest request, EscreenUser escreenUser) {

		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

		AssessmentReportFormBean assessmentReportFormBean = new AssessmentReportFormBean();
		assessmentReportFormBean.setHasParameter(false);

		if (StringUtils.isNotBlank(request.getParameter("assessmentReportFormBean.clinicianId")) && StringUtils.isNumeric(request.getParameter("assessmentReportFormBean.clinicianId"))) {
			assessmentReportFormBean.setClinicianId(Integer.parseInt(request.getParameter("assessmentReportFormBean.clinicianId")));
			assessmentReportFormBean.setHasParameter(true);
		}

		if (StringUtils.isNotBlank(request.getParameter("assessmentReportFormBean.createdByUserId")) && StringUtils.isNumeric(request.getParameter("assessmentReportFormBean.createdByUserId"))) {
			assessmentReportFormBean.setCreatedByUserId(Integer.parseInt(request.getParameter("assessmentReportFormBean.createdByUserId")));
			assessmentReportFormBean.setHasParameter(true);
		}

		if (StringUtils.isNotBlank(request.getParameter("assessmentReportFormBean.programId")) && StringUtils.isNumeric(request.getParameter("assessmentReportFormBean.programId"))) {
			assessmentReportFormBean.setProgramId(Integer.parseInt(request.getParameter("assessmentReportFormBean.programId")));
			assessmentReportFormBean.setHasParameter(true);
		}

		if (StringUtils.isNotBlank(request.getParameter("assessmentReportFormBean.veteranAssessmentId")) && StringUtils.isNumeric(request.getParameter("assessmentReportFormBean.veteranAssessmentId"))) {
			assessmentReportFormBean.setVeteranAssessmentId(Integer.parseInt(request.getParameter("assessmentReportFormBean.veteranAssessmentId")));
			assessmentReportFormBean.setHasParameter(true);
		}

		if (StringUtils.isNotBlank(request.getParameter("assessmentReportFormBean.veteranId")) && StringUtils.isNumeric(request.getParameter("assessmentReportFormBean.veteranId"))) {
			assessmentReportFormBean.setVeteranId(Integer.parseInt(request.getParameter("assessmentReportFormBean.veteranId")));
			assessmentReportFormBean.setHasParameter(true);
		}

		if (StringUtils.isNotBlank(request.getParameter("assessmentReportFormBean.fromAssessmentDate"))) {

			try {
				assessmentReportFormBean.setFromAssessmentDate(sdf.parse(request.getParameter("assessmentReportFormBean.fromAssessmentDate")));

				assessmentReportFormBean.setHasParameter(true);
			} catch (ParseException e) {
			}
		}

		if (StringUtils.isNotBlank(request.getParameter("assessmentReportFormBean.toAssessmentDate"))) {

			try {
				assessmentReportFormBean.setToAssessmentDate(sdf.parse(request.getParameter("assessmentReportFormBean.toAssessmentDate")));
				assessmentReportFormBean.setHasParameter(true);
			} catch (ParseException e) {
			}

		}

		// Populate the program id list from the logged in user.
		assessmentReportFormBean.setProgramIdList(escreenUser.getProgramIdList());

		return assessmentReportFormBean;
	}

}


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

package com.google.gapid.perfetto.models;

import static com.google.gapid.perfetto.models.QueryEngine.createSpan;
import static com.google.gapid.perfetto.models.QueryEngine.createView;
import static com.google.gapid.perfetto.models.QueryEngine.createWindow;
import static com.google.gapid.perfetto.models.QueryEngine.dropTable;
import static com.google.gapid.perfetto.models.QueryEngine.dropView;
import static com.google.gapid.perfetto.models.QueryEngine.expectOneRow;
import static com.google.gapid.util.MoreFutures.transform;
import static com.google.gapid.util.MoreFutures.transformAsync;
import static java.lang.String.format;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gapid.perfetto.TimeSpan;
import com.google.gapid.perfetto.views.FrameEventsMultiSelectionView;
import com.google.gapid.perfetto.views.FrameEventsSelectionView;
import com.google.gapid.perfetto.views.State;

import java.util.Arrays;
import org.eclipse.swt.widgets.Composite;

import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Consumer;

/**
 * Data about a Surface Flinger Frame Events in the trace.
 */
// TODO: dedupe code with SliceTrack.
public class FrameEventsTrack extends Track.WithQueryEngine<FrameEventsTrack.Data>{
  private static final String BASE_COLUMNS =
      "id, ts, dur, category, name, depth, stack_id, parent_stack_id, arg_set_id";
  private static final String SLICES_VIEW =
      "select " + BASE_COLUMNS + " from gpu_slice where track_id = %d";
  private static final String SLICE_SQL =
      "select " + BASE_COLUMNS + " from gpu_slice where id = %d";
  private static final String SLICES_SQL =
       "select " + BASE_COLUMNS + " from %s " +
       "where ts >= %d - dur and ts <= %d order by ts";
  private static final String SUMMARY_SQL =
      "select group_concat(id) ids, quantum_ts, count(*) from %s " +
      "where name = 'PresentFenceSignaled' or name GLOB '*[0-9]*'" +
      "group by quantum_ts";
  private static final String RANGE_SQL =
      "select " + BASE_COLUMNS + " from %s " +
      "where ts < %d and ts + dur >= %d and depth >= %d and depth <= %d";
  private static final String RANGE_FOR_IDS_SQL =
      "select " + BASE_COLUMNS + " from %s where id in (%s)";

  private static final long SIGNAL_MARGIN_NS = 10000;

  private final long trackId;

  public FrameEventsTrack(QueryEngine qe, long trackId) {
    super(qe, "sfevents_" + trackId);
    this.trackId = trackId;
  }

  public static FrameEventsTrack forBuffer(QueryEngine qe, GpuInfo.Buffer buffer) {
    return new FrameEventsTrack(qe, buffer.trackId);
  }

  @Override
  protected ListenableFuture<?> initialize() {
    String slices = tableName("slices");
    String window = tableName("window");
    String span = tableName("span");
    return qe.queries(
        dropTable(span),
        dropView(slices),
        dropTable(window),
        createWindow(window),
        createView(slices, format(SLICES_VIEW, trackId)),
        createSpan(span, window + ", " + slices + " PARTITIONED depth"));
  }

  @Override
  public ListenableFuture<Data> computeData(DataRequest req) {
    Window window = Window.compute(req, 5);
    return transformAsync(window.update(qe, tableName("window")),
        $ -> window.quantized ? computeSummary(req, window) : computeSlices(req));
  }

  private ListenableFuture<Data> computeSlices(DataRequest req) {
    return transformAsync(qe.query(slicesSql(req)), res ->
    transform(qe.getAllArgs(res.stream().mapToLong(r -> r.getLong(8))), args -> {
      int rows = res.getNumRows();
      Data data = new Data(req, new long[rows], new long[rows], new long[rows], new int[rows],
          new String[rows], new String[rows], new ArgSet[rows]);
      res.forEachRow((i, row) -> {
        long start = row.getLong(1);
        data.ids[i] = row.getLong(0);
        data.starts[i] = start;
        data.ends[i] = start + row.getLong(2);
        data.categories[i] = row.getString(3);
        data.titles[i] = row.getString(4);
        data.depths[i] = row.getInt(5);
        data.args[i] = args.getOrDefault(row.getLong(8), ArgSet.EMPTY);
      });
      return data;
    }));
  }

  private String slicesSql(DataRequest req) {
    return format(SLICES_SQL, tableName("slices"), req.range.start, req.range.end);
  }

  private ListenableFuture<Data> computeSummary(DataRequest req, Window w) {
    return transform(qe.query(summarySql()), result -> {
      int len = w.getNumberOfBuckets();
      String[] concatedIds = new String[len];
      Arrays.fill(concatedIds, "");
      Data data = new Data(req, w.bucketSize, concatedIds, new long[len]);
      result.forEachRow(($, r) -> {
        data.concatedIds[r.getInt(1)] = r.getString(0);
        data.numEvents[r.getInt(1)] = r.getLong(2);
      });
      return data;
    });
  }

  private String summarySql() {
    return format(SUMMARY_SQL, tableName("span"));
  }

  public ListenableFuture<Slice> getSlice(long id) {
    return transformAsync(expectOneRow(qe.query(sliceSql(id))), r ->
        transform(qe.getArgs(r.getLong(8)), args -> buildSlice(r, args)));
  }

  protected Slice buildSlice(QueryEngine.Row row, ArgSet args) {
    return new Slice(row, args, trackId);
  }

  private static String sliceSql(long id) {
    return format(SLICE_SQL, id);
  }

  public ListenableFuture<List<Slice>> getSlices(TimeSpan ts, int minDepth, int maxDepth) {
    return transform(qe.query(sliceRangeSql(ts, minDepth, maxDepth)),
        res -> res.list(($, row) -> buildSlice(row, ArgSet.EMPTY)));
  }

  private String sliceRangeSql(TimeSpan ts, int minDepth, int maxDepth) {
    return format(RANGE_SQL, tableName("slices"), ts.end, ts.start, minDepth, maxDepth);
  }

  public ListenableFuture<List<Slice>> getSlices(String ids) {
    return transform(qe.query(sliceRangeForIdsSql(ids)),
        res -> res.list(($, row) -> buildSlice(row, ArgSet.EMPTY)));
  }

  private String sliceRangeForIdsSql(String ids) {
    return format(RANGE_FOR_IDS_SQL, tableName("slices"), ids);
  }

  public static class Data extends Track.Data {
    public final Kind kind;
    // Summary.
    public final long bucketSize;
    public final String[] concatedIds;
    public final long[] numEvents;
    // slices
    public final long[] ids;
    public final long[] starts;
    public final long[] ends;
    public final int[] depths;
    public final String[] titles;
    public final String[] categories;
    public final ArgSet[] args;

    public static enum Kind {
      slices,
      summary,
    }

    public Data(DataRequest request, long bucketSize, String[] concatedIds, long[] numEvents) {
      super(request);
      this.kind = Kind.summary;
      this.bucketSize = bucketSize;
      this.concatedIds = concatedIds;
      this.numEvents = numEvents;
      this.ids = null;
      this.starts = null;
      this.ends = null;
      this.depths = null;
      this.titles = null;
      this.categories = null;
      this.args = null;
    }

    public Data(DataRequest request, long[] ids, long[] starts, long[] ends, int[] depths,
        String[] titles, String[] categories, ArgSet[] args) {
      super(request);
      this.kind = Kind.slices;
      this.bucketSize = 0;
      this.concatedIds = null;
      this.numEvents = null;
      this.ids = ids;
      this.starts = starts;
      this.ends = ends;
      this.depths = depths;
      this.titles = titles;
      this.categories = categories;
      this.args = args;
    }
  }

  public static class Slice implements Selection {
    public final long id;
    public final long time;
    public final long dur;
    public final String name;
    public final ArgSet args;
    public final long trackId;

    public Slice(long id, long time, long dur, String name, long trackId) {
      this.id = id;
      this.time = time;
      this.dur = dur;
      this.name = name;
      this.args = ArgSet.EMPTY;
      this.trackId = trackId;
    }

    public Slice(long id, long time, long dur, String name, ArgSet args, long trackId) {
      this.id = id;
      this.time = time;
      this.dur = dur;
      this.name = name;
      this.args = args;
      this.trackId = trackId;
    }

    public Slice(QueryEngine.Row row, ArgSet args, long trackId) {
      this(row.getLong(0), row.getLong(1), row.getLong(2), row.getString(4), args, trackId);
    }

    public Slice(QueryEngine.Row row, long trackId) {
      this(row.getLong(0), row.getLong(1), row.getLong(2), row.getString(4), trackId);
    }

    @Override
    public String getTitle() {
      return "Frame Events";
    }

    @Override
    public boolean contains(Long key) {
      return id == key;
    }

    @Override
    public Composite buildUi(Composite parent, State state) {
      return new FrameEventsSelectionView(parent, state, this);
    }

    @Override
    public Selection.Builder<SlicesBuilder> getBuilder() {
      return new SlicesBuilder(Lists.newArrayList(this));
    }

    @Override
    public void getRange(Consumer<TimeSpan> span) {
      if (dur > 0) {
        span.accept(new TimeSpan(time, time + dur));
      } else { // Expand the zoom/highlight time range for signal selections whose dur is 0.
        span.accept(new TimeSpan(time, time + dur).expand(SIGNAL_MARGIN_NS));
      }
    }

  }

  public static class Slices implements Selection {
    private final List<Slice> slices;
    private final String title;
    public final ImmutableList<Node> nodes;
    public final ImmutableSet<Long> sliceKeys;

    public Slices(List<Slice> slices, String title, ImmutableList<Node> nodes,
        ImmutableSet<Long> sliceKeys) {
      this.slices = slices;
      this.title = title;
      this.nodes = nodes;
      this.sliceKeys = sliceKeys;
    }

    @Override
    public String getTitle() {
      return title;
    }

    @Override
    public boolean contains(Long key) {
      return sliceKeys.contains(key);
    }

    @Override
    public Composite buildUi(Composite parent, State state) {
      return new FrameEventsMultiSelectionView(parent, this);
    }

    @Override
    public Selection.Builder<SlicesBuilder> getBuilder() {
      return new SlicesBuilder(slices);
    }

    @Override
    public void getRange(Consumer<TimeSpan> span) {
      for (Slice slice : slices) {
        slice.getRange(span);
      }
    }
  }

  public static class SlicesBuilder implements Selection.Builder<SlicesBuilder> {
    private final List<Slice> slices;
    private final String title;
    private final TreeMap<Long, Node> roots = Maps.newTreeMap();
    private final Set<Long> sliceKeys = Sets.newHashSet();

    public SlicesBuilder(List<Slice> slices) {
      this.slices = slices;
      String ti = "";
      for (Slice slice : slices) {
        ti = slice.getTitle();
        roots.put(slice.id, new Node(slice.name, slice.dur, slice.dur, slice.trackId));
        sliceKeys.add(slice.id);
      }
      this.title = ti;
    }

    @Override
    public SlicesBuilder combine(SlicesBuilder other) {
      for (Slice s : other.slices) {
        if (!this.sliceKeys.contains(s.id)) {
          this.slices.add(s);
          this.roots.put(s.id, other.roots.get(s.id));
          this.sliceKeys.add(s.id);
        }
      }
      return this;
    }

    @Override
    public Selection build() {
      return new Slices(slices, title, ImmutableList.copyOf(roots.values()),
          ImmutableSet.copyOf(sliceKeys));
    }
  }

  public static class Node {
    public final String name;
    public final long dur;
    public final long self;
    public final long trackId;

    public Node(String name, long dur, long self, long id) {
      this.name = name;
      this.dur = dur;
      this.self = self;
      this.trackId = id;
    }
  }
}


text:
package moe.minori.pgpclipper.activities;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import org.openintents.openpgp.util.OpenPgpApi;
import org.openintents.openpgp.util.OpenPgpServiceConnection;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import moe.minori.pgpclipper.R;

/**
 * Created by Minori on 2015-09-26.
 */
public class PGPClipperQuickReplyActivity extends Activity {

    OpenPgpServiceConnection serviceConnection;

    public static final int REQUEST_CODE_ENCRYPT = 9911;
    public static final int REQUEST_CODE_SIGN_AND_ENCRYPT = 9912;

    public static final String DATA = "DATA";

    private Intent intent;

    CheckBox sigCheckBox;
    EditText replyTextField;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String currentTheme = sharedPreferences.getString("themeSelection", "dark");

        switch (currentTheme)
        {
            case "dark":
                setTheme(R.style.PseudoDialogDarkTheme);
                break;
            case "light":
                setTheme(R.style.PseudoDialogLightTheme);
                break;
        }
        super.onCreate(savedInstanceState);

        intent = getIntent();

        setContentView(R.layout.quickreplyactivitylayout);

        sigCheckBox = (CheckBox) findViewById(R.id.signatureCheck);
        replyTextField = (EditText) findViewById(R.id.replyText);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        String currentPgpProvider = preferences.getString("pgpServiceProviderApp", null);

        if ( currentPgpProvider == null )
        {
            // Default security provider is not set
            Log.e("PGPClipperService", "Security provider is not set!");
        }
        else
        {
            Log.d("PGPClipperService", "Current security provider: " + currentPgpProvider );

            serviceConnection = new OpenPgpServiceConnection(this, currentPgpProvider);
            serviceConnection.bindToService();

        }
    }

    private void tryEncryption ()
    {
        if ( serviceConnection.isBound() )
        {
            if ( intent != null )
            {
                attemptPgpApiAccess(replyTextField.getText().toString());
            }
        }
        else
        {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    tryEncryption();
                }
            }, 500);
        }
    }

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

        overridePendingTransition(0, 0);
    }

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

        if ( serviceConnection != null )
            serviceConnection.unbindFromService();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if ( resultCode == RESULT_OK )
        {
            switch (requestCode)
            {
                case 5298:
                {
                    String[] keyIDs = intent.getStringArrayExtra("KEY_ID");
                    if ( keyIDs != null )
                        data.putExtra(OpenPgpApi.EXTRA_USER_IDS, keyIDs);
                    data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
                    if ( sigCheckBox.isChecked() )
                    {
                        // signature + encryption

                        data.setAction(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT);
                    }
                    else
                    {
                        // only encryption

                        data.setAction(OpenPgpApi.ACTION_ENCRYPT);

                    }

                    InputStream is;
                    ByteArrayOutputStream os = new ByteArrayOutputStream();

                    try
                    {
                        is = new ByteArrayInputStream(replyTextField.getText().toString().getBytes("UTF-8"));
                    }
                    catch (UnsupportedEncodingException e)
                    {
                        e.printStackTrace();
                        return;
                    }

                    OpenPgpApi api = new OpenPgpApi(this, serviceConnection.getService());

                    if ( sigCheckBox.isChecked() )
                    {
                        api.executeApiAsync(data, is, os, new CallBack(os, REQUEST_CODE_SIGN_AND_ENCRYPT));
                    }
                    else
                    {
                        api.executeApiAsync(data, is, os, new CallBack(os, REQUEST_CODE_ENCRYPT));
                    }
                }
            }
        }
    }

    private void attemptPgpApiAccess (String input)
    {
        // try encryption (optionally signature) and copy data into clipboard

        Intent data = new Intent();
        data.putExtra(OpenPgpApi.EXTRA_USER_IDS, intent.getStringArrayExtra("KEY_ID"));
        data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
        if ( sigCheckBox.isChecked() )
        {
            // signature + encryption

            data.setAction(OpenPgpApi.ACTION_SIGN_AND_ENCRYPT);
        }
        else
        {
            // only encryption

            data.setAction(OpenPgpApi.ACTION_ENCRYPT);

        }

        InputStream is;
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        try
        {
            is = new ByteArrayInputStream(input.getBytes("UTF-8"));
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return;
        }

        OpenPgpApi api = new OpenPgpApi(this, serviceConnection.getService());

        if ( sigCheckBox.isChecked() )
        {
            api.executeApiAsync(data, is, os, new CallBack(os, REQUEST_CODE_SIGN_AND_ENCRYPT));
        }
        else
        {
            api.executeApiAsync(data, is, os, new CallBack(os, REQUEST_CODE_ENCRYPT));
        }

    }

    public void onClick (View v)
    {
        tryEncryption();
    }

    private class CallBack implements OpenPgpApi.IOpenPgpCallback
    {

        ByteArrayOutputStream os;
        int requestCode;

        private CallBack(ByteArrayOutputStream os, int requestCode)
        {
            this.os = os;
            this.requestCode = requestCode;
        }

        @Override
        public void onReturn(Intent result) {
            switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR) )
            {
                case OpenPgpApi.RESULT_CODE_SUCCESS:
                {
                    try
                    {
                        //TODO: Use this somewhere!
                        String finalResult = os.toString("UTF-8");

                        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("label", finalResult);
                        clipboardManager.setPrimaryClip(clip);

                        finish();

                    }
                    catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    break;
                }
                case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
                {
                    PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);

                    try
                    {
                        PGPClipperQuickReplyActivity.this.startIntentSenderFromChild(PGPClipperQuickReplyActivity.this, pi.getIntentSender(), 5298, null, 0, 0, 0);
                    }
                    catch (IntentSender.SendIntentException e)
                    {
                        e.printStackTrace();
                    }
                    break;
                }
                case OpenPgpApi.RESULT_CODE_ERROR:
                {
                    //TODO: Show user error dialog

                    replyTextField.setText("Error, cannot continue. Send bug report to author.");

                    break;
                }
            }
        }
    }
}


text:
/**
 *
 */
package com.d2h.application.subscription.decorator.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiPredicate;

import com.d2h.application.subscription.decorator.Subscription;
import com.d2h.application.subscription.model.Bill;
import com.d2h.application.subscription.model.Channel;
import com.d2h.application.subscription.utils.SubscriptionUtils;

/**
 * @author pravt
 *
 */
public class BaseSubscription extends Subscription implements SubscriptionUtils {
	public final static int monthlyCharges = 00;

	private final String SUBSCRIPTION_NAME = "BASE";
	private List<Channel> channels = Arrays.asList(new Channel("DD National", 0), new Channel("DD Sahyandri", 0),
			new Channel("DD Sport", 0), new Channel("DD News", 0), new Channel("DD Bharti", 0));
	private Set<Channel> defaultChannels = new HashSet<>(channels);

	private int discount;
	private int duration;
	private int subscriptionAmount;
	private int amountAfterDiscountApply;

	public BaseSubscription() {
		super.subscriptionName = SUBSCRIPTION_NAME;
		super.note = note;
		// initialiseSubscription();
	}

	@Override
	public void getinfo() {
		super.getinfo();
	}

	@Override
	public Integer calaculateCharges() {
		return defaultChannels.stream().mapToInt(x -> x.getBaseCharges()).sum();
	}

	@Override
	public Integer getMonthlyCharges() {
		return monthlyCharges;
	}

	@Override
	public void setTotalFair(int fair) {
		this.totalFair = fair;

	}

	@Override
	public void initialiseSubscription() {

		super.addChannels(defaultChannels);
		super.getBills().getBills().push(generateBill());
		System.out.println(SUBSCRIPTION_NAME + " subscription initialise successfully");
	}

	@Override
	public BiPredicate<Integer, Integer> isEligiableToSubscribe() throws Exception {
		return (duration, userBalance) -> {
			this.duration = duration;

			discount = SubscriptionUtils.calculateDiscount(monthlyCharges, duration);
			subscriptionAmount = monthlyCharges * duration;
			amountAfterDiscountApply = SubscriptionUtils.applyDiscount(subscriptionAmount, discount);
			setTotalFair(amountAfterDiscountApply);
			if (isEligiableToSubscribe.test(amountAfterDiscountApply, userBalance)) {
				return false;
			}
			return true;
		};
	}

	BiPredicate<Integer, Integer> isEligiableToSubscribe = (x, y) -> x > y ? true : false;

	@Override
	protected Bill generateBill() {

		return new Bill.Builder().packageName(this.subscriptionName).setChannelList(this.defaultChannels)
				.accountBalance(amountAfterDiscountApply).monthlyPrice(monthlyCharges).discountApplied(discount)
				.noOfMonthsFor(duration).finalPriceAfterDiscount(amountAfterDiscountApply).buyAt(LocalDateTime.now())
				.validTill(LocalDateTime.now().plusMonths(duration)).subscriptionAmount(subscriptionAmount).build();

	}
}


text:
/*
 * Copyright 2021 Root101 (jhernandezb96@gmail.com, +53-5-426-8660).
 *
 * 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
 *
 * Or read it directly from LICENCE.txt file at the root of this project.
 * 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.root101.module.util.rest_config.core.module;

import com.root101.clean.core.app.modules.AbstractModule;
import com.root101.clean.core.app.modules.DefaultAbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.root101.clean.core.domain.services.ResourceHandler;
import com.root101.clean.core.exceptions.AlreadyInitModule;
import com.root101.clean.core.exceptions.NotInitModule;
import com.root101.module.util.rest_config.repo.module.RestConfigRepoModule;
import static com.root101.module.util.rest_config.services.ResourceKeys.*;

/**
 *
 * @author Root101 (jhernandezb96@gmail.com, +53-5-426-8660)
 * @author JesusHdezWaterloo@Github
 */
public class RestConfigCoreModule extends DefaultAbstractModule {

    private final Injector inj = Guice.createInjector(new RestConfigCoreInjectionConfig());

    private static RestConfigCoreModule INSTANCE;

    public static RestConfigCoreModule getInstance() {
        if (INSTANCE == null) {
            throw new NotInitModule(ResourceHandler.getString(KEY_MODULE_NAME_REST_CONFIG));
        }
        return INSTANCE;
    }

    public static RestConfigCoreModule init() {
        if (INSTANCE != null) {
            throw new AlreadyInitModule(ResourceHandler.getString(KEY_MODULE_NAME_REST_CONFIG));
        }
        INSTANCE = new RestConfigCoreModule();
        INSTANCE.registerModule(RestConfigRepoModule.init());
        return getInstance();
    }

    /**
     * Usar init() sin repo por parametro para usar el repo por defecto
     *
     * @param repoModule
     * @return
     * @deprecated
     */
    @Deprecated
    public static RestConfigCoreModule init(AbstractModule repoModule) {
        INSTANCE = new RestConfigCoreModule();
        INSTANCE.registerModule(repoModule);
        return getInstance();
    }

    @Override
    protected <T> T getOwnImplementation(Class<T> type) {
        return inj.getInstance(type);
    }

    @Override
    public String getModuleName() {
        return "REST-Config Core Module";
    }

}


text:
package com.ssm.maven.core.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ssm.maven.core.dao.UserDao;
import com.ssm.maven.core.entity.User;
import com.ssm.maven.core.service.UserService;

/**
 * @author 1034683568@qq.com
 * @project_name ssm-maven
 * @date 2017-3-1
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public User login(User user) {
        return userDao.login(user);
    }

    @Override
    public List<User> findUser(Map<String, Object> map) {
        return userDao.findUsers(map);
    }

    @Override
    public int updateUser(User user) {
        //防止有人胡乱修改导致其他人无法正常登陆
        if ("admin".equals(user.getUserName())) {
            return 0;
        }
        return userDao.updateUser(user);
    }

    @Override
    public Long getTotalUser(Map<String, Object> map) {
        return userDao.getTotalUser(map);
    }

    @Override
    public int addUser(User user) {
        if (user.getUserName() == null || user.getPassword() == null || getTotalUser(null) > 90) {
            return 0;
        }
        return userDao.addUser(user);
    }

    @Override
    public int deleteUser(Integer id) {
        //防止有人胡乱修改导致其他人无法正常登陆
        if (2 == id) {
            return 0;
        }
        return userDao.deleteUser(id);
    }

}


text:
/*
 * Copyright 2017 Apereo
 *
 * 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.tle.upgrademanager.handlers;

import com.sun.net.httpserver.HttpExchange;
import com.tle.upgrademanager.ManagerConfig;
import com.tle.upgrademanager.helpers.ServiceWrapper;

public class ServerHandler extends UrlDispatchHandler {
  private final ServiceWrapper serviceWrapper;

  public ServerHandler(ManagerConfig config) {
    serviceWrapper = new ServiceWrapper(config);
  }

  public void stop(HttpExchange exchange) throws Exception {
    serviceWrapper.stop();
    HttpExchangeUtils.respondRedirect(exchange, "/pages/"); // $NON-NLS-1$
  }

  public void start(HttpExchange exchange) throws Exception {
    serviceWrapper.start();
    HttpExchangeUtils.respondRedirect(exchange, "/pages/"); // $NON-NLS-1$
  }
}


text:
package com.janson.flinkdemo.datastream;

import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

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

/**
 * @Description:
 * @Author: shanjian
 * @Date: 2022/2/8 1:58 下午
 */
public class StreamMaxJob {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        List data = new ArrayList<Tuple3<Integer,Integer,Integer>>();
        data.add(new Tuple3<>(0,1,0));
        data.add(new Tuple3<>(0,1,1));
        data.add(new Tuple3<>(0,2,2));
        data.add(new Tuple3<>(0,1,3));
        data.add(new Tuple3<>(1,2,5));
        data.add(new Tuple3<>(1,2,9));
        data.add(new Tuple3<>(1,2,11));
        data.add(new Tuple3<>(1,2,13));

        DataStreamSource<MyStreamingSource.Item> items = env.fromCollection(data);
        items.keyBy(0).max(2).printToErr();

        String jobName = "user defined streaming source";
        env.execute(jobName);
    }
}


text:
package de.selbi.spotify.api;

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

import org.apache.hc.core5.http.ParseException;

import com.wrapper.spotify.exceptions.detailed.TooManyRequestsException;
import com.wrapper.spotify.exceptions.detailed.UnauthorizedException;
import com.wrapper.spotify.model_objects.specification.Paging;
import com.wrapper.spotify.model_objects.specification.PagingCursorbased;
import com.wrapper.spotify.requests.IRequest;
import com.wrapper.spotify.requests.IRequest.Builder;
import com.wrapper.spotify.requests.data.IPagingCursorbasedRequestBuilder;
import com.wrapper.spotify.requests.data.IPagingRequestBuilder;

import de.selbi.spotify.util.BotUtils;

public class SpotifyCall {

  static SpotifyApiAuthorization spotifyApiAuthorization;

  private final static long RETRY_TIMEOUT_429 = 1000;
  private final static long RETRY_TIMEOUT_GENERIC_ERROR = 60 * 1000;
  private final static int MAX_ATTEMPTS = 10;

  /**
   * Utility class
   */
  private SpotifyCall() {
  }

  /**
   * Executes a single "greedy" Spotify Web API request, meaning that on potential
   * 429 Too many requests errors the request will be retried up to 10
   * times until it succeeds. Any attempts will be delayed by the response body's
   * given retryAfter parameter in seconds (with an extra second due
   * to occasional inaccuracies with that value). Generic errors will be retried
   * too.
   *
   * @param <T>            return type (e.g. Album, Playlist...)
   * @param <BT>           Builder (e.g. Album.Builder, Playlist.Builder...)
   * @param requestBuilder the basic, unbuilt request builder
   * @return the result item
   * @throws BotException if request didn't complete within 10 attempts
   */
  public static <T, BT extends Builder<T, ?>> T execute(IRequest.Builder<T, BT> requestBuilder) throws BotException {
    Exception finalException = null;

    for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
      try {
        IRequest<T> builtRequest = requestBuilder.build();
        return builtRequest.execute();
      } catch (Exception ex) {
        try {
          finalException = ex;
          throw ex;
        } catch (ParseException | IOException e) {
          throw new BotException(e);
        } catch (UnauthorizedException e) {
          String newAccessToken = spotifyApiAuthorization.refresh();
          requestBuilder.setHeader("Authorization", "Bearer " + newAccessToken);
        } catch (TooManyRequestsException e) {
          int timeout = e.getRetryAfter();
          long sleepMs = (timeout * RETRY_TIMEOUT_429 * attempt) + RETRY_TIMEOUT_429;
          BotUtils.sneakySleep(sleepMs);
        } catch (Exception e) {
          BotUtils.sneakySleep(RETRY_TIMEOUT_GENERIC_ERROR);
        }
      }
    }

    finalException.printStackTrace();
    throw new BotException(finalException);
  }

  /**
   * Executes a paging-based Spotify Web API request. This process is done
   * greedily, see {@link SpotifyCall#execute}.
   *
   * @param <T>                  the injected return type
   * @param <BT>                 the injected Builder
   * @param pagingRequestBuilder the basic, unbuilt request paging builder
   * @return the fully exhausted list of result items
   */
  public static <T, BT extends Builder<Paging<T>, ?>> List<T> executePaging(IPagingRequestBuilder<T, BT> pagingRequestBuilder)
      throws BotException {
    List<T> resultList = new ArrayList<>();
    Paging<T> paging = null;
    do {
      if (paging != null && paging.getNext() != null) {
        pagingRequestBuilder.offset(paging.getOffset() + paging.getLimit());
      }
      paging = execute(pagingRequestBuilder);
      BotUtils.addToListIfNotBlank(paging.getItems(), resultList);
    } while (paging.getNext() != null);
    return resultList;
  }

  /**
   * Executes a PagingCursor-based Spotify Web API request. This process is done
   * greedily, see {@link SpotifyCall#execute}.
   *
   * @param <T>                  the injected return type
   * @param <BT>                 the injected Builder
   * @param                   the After type (currently only String is
   *                             supported)
   * @param pagingRequestBuilder the basic, unbuilt request PagingCursor builder
   * @return the fully exhausted list of result items
   */
  @SuppressWarnings("unchecked")
  public static <T, A, BT extends Builder<PagingCursorbased<T>, ?>> List<T> executePaging(IPagingCursorbasedRequestBuilder<T, A, BT> pagingRequestBuilder)
      throws BotException {
    List<T> resultList = new ArrayList<>();
    PagingCursorbased<T> paging = null;
    do {
      if (paging != null && paging.getNext() != null) {
        String after = paging.getCursors()[0].getAfter();
        try {
          pagingRequestBuilder.after((A) after);
        } catch (ClassCastException e) {
          throw new UnsupportedOperationException("Cursor-based paging is currently only supported for String-based cursors!");
        }
      }
      paging = execute(pagingRequestBuilder);
      BotUtils.addToListIfNotBlank(paging.getItems(), resultList);
    } while (paging.getNext() != null);
    return resultList;
  }
}


text:
package com.mycrawler.tutorial.akka.stm;

import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.transactor.Coordinated;
import scala.concurrent.stm.Ref;
import scala.concurrent.stm.japi.STM;

/**
 *
* @ClassName: EmployeeActor
* @Description:
* @author yangrenjiang
* @date 2017年7月3日 下午11:44:00
*
 */
public class EmployeeActor extends UntypedActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);

    private Ref.View<Integer> count = STM.newRef(20);//员工账户

    @Override
    public void onReceive(Object o) throws Throwable {
        if(o instanceof Coordinated){
            Coordinated coordinated = (Coordinated) o;
            int downCount = (int) coordinated.getMessage();//员工增加的工资

            try {//注意这里异常要及时处理，否则异常会一直扩散，导致回退到系统刚启动时的初始状态！
                coordinated.atomic(() -> STM.increment(count, downCount));//Employee增加工资
            }catch (Exception e){
                e.printStackTrace();
            }

        }else if("getCount".equals(o)){
            getSender().tell(count.get(), getSelf());
        }else{
            unhandled(o);
        }
    }

}


text:
/*
 * Copyright © 2013-2021, The SeedStack authors <http://seedstack.org>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package org.seedstack.business.assembler;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.seedstack.business.assembler.dsl.FluentAssembler;

/**
 * When {@link FluentAssembler} DSL needs to create an aggregate (i.e. when the {@code
 * fromFactory()} method is used), this annotation allows to specify a matching between a DTO getter
 * and an argument of an aggregate factory method by position.
 *
 *
Example 1: single aggregate

 *

 * public class CustomerDto {
 *    {@literal @}FactoryArgument(index = 0)
 *     public String getName() {...}
 *
 *    {@literal @}FactoryArgument(index = 1)
 *     public Date getBirthDate() {...}
 *
 *     // No need for annotation here as the address is not part of the factory method
 *     public Address getAddress() {...}
 * }
 *
 * {@literal @}Factory
 *  public class CustomerFactory {
 *      public Customer createCustomer(String name, Date birthDate);
 *  }
 *

 *
 *
Example 2: tuple of aggregates

 *

 * public class RecipeDto {
 *    {@literal @}FactoryArgument(aggregateIndex = 0, index = 0)
 *     public String getCustomerName() {...}
 *
 *    {@literal @}FactoryArgument(aggregateIndex = 0, index = 1)
 *     public Date getCustomerBirthDate() {...}
 *
 *    {@literal @}FactoryArgument(aggregateIndex = 1, index = 0)
 *     public int getOrderId() {...}
 * }
 *
 * {@literal @}Factory
 *  public class CustomerFactory {
 *      Customer createCustomer(String name, Date birthDate);
 *  }
 *
 * {@literal @}Factory
 *  public class OrderFactory {
 *      Customer createOrder(int orderId);
 *  }
 *

 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
public @interface FactoryArgument {

    /**
     * Only used when assembling a tuple of aggregates. This specifies which aggregate in the tuple
     * (by position) is concerned by the {@link #index()} value.
     *
     * @return the concerned aggregate index in the tuple.
     */
    int aggregateIndex() default -1;

    /**
     * Specifies the position of the aggregate factory method argument the getter will match. The
     * return value of the getter will be used as the value of the corresponding factory method
     * argument.
     *
     * @return the index of the argument to match in the factory method.
     */
    int index() default -1;

}