text:
package com.appnet.app.monitors;

import android.content.Context;
import android.net.Uri;

import com.appnet.app.operations.PostListOperation;
import io.pivotal.arca.dispatcher.Query;
import io.pivotal.arca.dispatcher.QueryResult;
import io.pivotal.arca.monitor.RequestMonitor.AbstractRequestMonitor;
import io.pivotal.arca.service.OperationService;

public class PostListMonitor extends AbstractRequestMonitor {

	@Override
	public int onPostExecute(final Context context, final Query request, final QueryResult result) {
		final int count = result.getResult().getCount();
		if (count == 0 && syncDataFromNetwork(context, request.getUri())) {
			return Flags.DATA_SYNCING;
		} else {
			return 0;
		}
	}

	public boolean syncDataFromNetwork(final Context context, final Uri uri) {
		final boolean isSyncing = OperationService.start(context, new PostListOperation(uri));
		return isSyncing;
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { lsof } from "list-open-files";

import { makeMakeServer } from "../lib/server-helpers";

import {
	context,
} from "../../index";
import { ensureStatusSuccess } from "../lib/utils";

const itSkipCi = process.env.CI ? it.skip : it;

describe( `http1`, ( ) =>
{
	const { cycleOpts, makeServer } =
		makeMakeServer( { proto: "http:", version: "http1" } );

	describe( "keep-alive", ( ) =>
	{
		describe( "http1.keelAlive === true (default)", ( ) =>
		{
			it( "should not send 'connection: close'", async ( ) =>
			{
				const { server, port } = await makeServer( );
				const { disconnectAll, fetch } = context( { ...cycleOpts } );

				const response1 = ensureStatusSuccess(
					await fetch( `http://localhost:${port}/headers` )
				);

				const headers = await response1.json( );

				expect( headers.connection ).not.toBe( "close" );

				disconnectAll( );

				await server.shutdown( );
			} );

			itSkipCi( "should re-use socket", async ( ) =>
			{
				const { server, port } = await makeServer( );
				const { disconnectAll, fetch } = context( { ...cycleOpts } );

				const [ { files: openFilesA } ] = await lsof( { } );

				const response1 = ensureStatusSuccess(
					await fetch( `http://localhost:${port}/headers` )
				);
				await response1.json( );

				const [ { files: openFilesB } ] = await lsof( { } );

				const response2 = ensureStatusSuccess(
					await fetch( `http://localhost:${port}/headers` )
				);
				await response2.json( );

				const [ { files: openFilesC } ] = await lsof( { } );

				const ipA = openFilesA.filter( fd => fd.type === 'IP' );
				const ipB = openFilesB.filter( fd => fd.type === 'IP' );
				const ipC = openFilesC.filter( fd => fd.type === 'IP' );

				// 2 less because client+server
				expect( ipA.length ).toEqual( ipB.length - 2 );
				expect( ipB.length ).toEqual( ipC.length );
				expect( ipB ).toEqual( ipC );

				disconnectAll( );

				await server.shutdown( );
			} );
		} );

		describe( "http1.keelAlive === false", ( ) =>
		{
			it( "should send 'connection: close'",
				async ( ) =>
			{
				const { server, port } = await makeServer( );
				const { disconnectAll, fetch } = context( {
					...cycleOpts,
					http1: {
						keepAlive: false,
					},
				} );

				const response1 = ensureStatusSuccess(
					await fetch( `http://localhost:${port}/headers` )
				);

				const headers = await response1.json( );

				expect( headers.connection ).toBe( "close" );

				disconnectAll( );

				await server.shutdown( );
			} );
		} );
	} );
} );


text:
<?php
namespace Neos\Flow\ObjectManagement\DependencyInjection;

use Neos\Flow\Annotations as Flow;

/**
 * A Proxy Class Builder which integrates Dependency Injection.
 *
 * @Flow\Proxy(false)
 * @api
 */
class DependencyProxy
{
    /**
     * @var string
     */
    protected $className;

    /**
     * @var \Closure
     */
    protected $builder;

    /**
     * @var array
     */
    protected $propertyVariables = [];

    /**
     * Constructs this proxy
     *
     * @param string $className Implementation class name of the dependency to proxy
     * @param \Closure $builder The closure which eventually builds the dependency
     */
    public function __construct($className, \Closure $builder)
    {
        $this->className = $className;
        $this->builder = $builder;
    }

    /**
     * Activate the dependency and set it in the object.
     *
     * @return object The real dependency object
     * @api
     */
    public function _activateDependency()
    {
        $realDependency = $this->builder->__invoke();
        foreach ($this->propertyVariables as &$propertyVariable) {
            $propertyVariable = $realDependency;
        }
        return $realDependency;
    }

    /**
     * Returns the class name of the proxied dependency
     *
     * @return string Fully qualified class name of the proxied object
     * @api
     */
    public function _getClassName()
    {
        return $this->className;
    }

    /**
     * Adds another variable by reference where the actual dependency object should
     * be injected into once this proxy is activated.
     *
     * @param mixed &$propertyVariable The variable to replace
     * @return void
     */
    public function _addPropertyVariable(&$propertyVariable)
    {
        $this->propertyVariables[] = &$propertyVariable;
    }

    /**
     * Proxy magic call method which triggers the injection of the real dependency
     * and returns the result of a call to the original method in the dependency
     *
     * @param string $methodName Name of the method to be called
     * @param array $arguments An array of arguments to be passed to the method
     * @return mixed
     */
    public function __call($methodName, array $arguments)
    {
        return call_user_func_array([$this->_activateDependency(), $methodName], $arguments);
    }
}


text:
var fs = require('fs');
var buffer = new Buffer(1024);

//fs.read(fd, buffer, offset, length, position, callback)

fs.open('input.text','r+',function(err, fd){
	if(err){
		console.log('Error:'+err);
		return;
	}
	console.log(fd);
	fs.read(fd, buffer, 0, buffer.length, 0, function(err, byte, buff){
		if(err){
			console.log('Error:'+err);
			return;
		}
		console.log('byte:'+byte);
		console.log(buff.toString());
	})
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 * Copyright 2014 Maxim Dominichenko
 *
 * Licensed under The MIT License (MIT) (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * https://github.com/domax/gwt-dynamic-plugins/blob/master/LICENSE
 *
 * 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.
-->
<!DOCTYPE module PUBLIC
	"-//Google Inc.//DTD Google Web Toolkit 2.5.1//EN"
	"http://google-web-toolkit.googlecode.com/svn/tags/2.5.1/distro-source/core/src/gwt-module.dtd">

<module>
	<source path="client" />
	<source path="shared" />
	<public path="export" />

	<add-linker name="xsiframe" />

	<!-- Important! This prefix must be unique across all the modules and host app -->
	<set-configuration-property name="CssResource.obfuscationPrefix" value="DMS" />
</module>


text:
package io.gravitee.am.identityprovider.oauth2.jwt.algo;

import io.gravitee.am.common.jwt.SignatureAlgorithm;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public enum Signature {
    RSA_RS256(SignatureAlgorithm.RS256),
    RSA_RS384(SignatureAlgorithm.RS384),
    RSA_RS512(SignatureAlgorithm.RS512),
    HMAC_HS256(SignatureAlgorithm.HS256),
    HMAC_HS384(SignatureAlgorithm.HS384),
    HMAC_HS512(SignatureAlgorithm.HS512);

    private SignatureAlgorithm alg;

    Signature(SignatureAlgorithm alg) {
        this.alg = alg;
    }

    public SignatureAlgorithm getAlg() {
        return alg;
    }
}


text:
<?php

namespace Drupal\Tests\language\Unit\process;

use Drupal\language\Plugin\migrate\process\LanguageDomains;
use Drupal\Tests\migrate\Unit\process\MigrateProcessTestCase;

/**
 * @coversDefaultClass \Drupal\language\Plugin\migrate\process\LanguageDomains
 * @group language
 */
class LanguageDomainsTest extends MigrateProcessTestCase {

  /**
   * {@inheritdoc}
   */
  protected $backupGlobalsBlacklist = ['base_url'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    $configuration = [
      'key' => 'language',
      'value' => 'domain',
    ];
    $this->plugin = new LanguageDomains($configuration, 'map', []);
    parent::setUp();

    // The language_domains plugin calls getSourceProperty() to check if domain
    // negotiation is used. If it is the values will be processed so we need it
    // to return TRUE to be able to test the process.
    $this->row->expects($this->once())
      ->method('getSourceProperty')
      ->will($this->returnValue(TRUE));

    // The language_domains plugin use $base_url to fill empty domains.
    global $base_url;
    $base_url = 'http://example.com';
  }

  /**
   * @covers ::transform
   */
  public function testTransform() {
    $source = [
      ['language' => 'en', 'domain' => ''],
      ['language' => 'fr', 'domain' => 'fr.example.com'],
      ['language' => 'es', 'domain' => 'http://es.example.com'],
      ['language' => 'hu', 'domain' => 'https://hu.example.com'],
    ];
    $expected = [
      'en' => 'example.com',
      'fr' => 'fr.example.com',
      'es' => 'es.example.com',
      'hu' => 'hu.example.com',
    ];
    $value = $this->plugin->transform($source, $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame($value, $expected);
  }

}


text:
function getFormattedValue(meta, value) {
    switch (meta.type) {
        case 'float': return parseFloat(value);
        case 'int': return parseInt(value);
        case 'string': return value + '';
    }
}

function buildLabel(label) {
    return `<label class="famous-ui__config-panel__group-label">${label}</label>`;
}

function buildField(group, field) {
    if (field.range) {
        if (field.type === 'int') {
            return `
                <input class="famous-ui__config-panel__control"
                    type="number"
                    value="${field.value}"
                    data-group="${group.label}"
                    data-field="${field.name}"
                    data-key="${field.key}"
                    data-type="int"
                    data-uid="${field.uid}">
                ${field.name}
            `;
        }
        else {
            return `
                <input class="famous-ui__config-panel__control"
                    type="range"
                    min="${field.range[0]}"
                    max="${field.range[1]}"
                    step="${field.step || '1'}"
                    value="${field.value}"
                    data-group="${group.label}"
                    data-field="${field.name}"
                    data-key="${field.key}"
                    data-type="float"
                    data-uid="${field.uid}">
                ${field.name}
            `;
        }
    }
    else {
        return `
            <input class="famous-ui__config-panel__control"
                type="text"
                value="${field.value}"
                data-group="${group.label}"
                data-field="${field.name}"
                data-key="${field.key}"
                data-type="string"
                data-uid="${field.uid}">
            ${field.name}
        `;
    }
}

function buildStyle(gutterSize, panelWidth) {
    return `

    `;
}

FamousFramework.component('famous:ui:config-panel', {
    behaviors: {
        '#panel-container': {
            'position': function(offsetPosition) { return offsetPosition; }
        },

        '#panel': {
            'opacity': function(panelOpenness, panelFullOpacity, isPanelHovered) { return panelFullOpacity * panelOpenness; },
            'position': function(panelOpenness, panelWidth) { return [-panelWidth + (panelWidth * panelOpenness), 0]; },
            'style': {
                'background-color': 'black',
                'overflow-y': 'scroll',
                'overflow-x': 'hidden',
                'z-index': 2 // Just to be a jerk
            },
            'size': function(panelWidth) {
                return [panelWidth, undefined];
            }
        },

        '#gradient': {
            'position': function(panelOpenness, panelWidth) { return [-panelWidth + (panelWidth * panelOpenness), 0]; },
            'size': function(panelWidth, gutterSize, buttonSize) { return [panelWidth, buttonSize * 1.5 + gutterSize * 2] },
            'style': {
                'z-index': 3,
                'background': 'linear-gradient(to bottom, rgba(0, 0, 0, 1),  rgba(0, 0, 0, 0))'
            }
        },

        '#panel-content': {
            'position-y': function(buttonSize, gutterSize) { return buttonSize + (gutterSize * 2); },
            'style': function(gutterSize) {
                return {
                    'color': 'white',
                    'padding-left': gutterSize + 'px',
                    'padding-right': gutterSize + 'px'
                };
            },
            'size': [undefined, undefined],
            'content': function(statesData, gutterSize, panelWidth) {
                var out = buildStyle(gutterSize, panelWidth);
                if (statesData.groups) {
                    for (var i = 0; i < statesData.groups.length; i++) {
                        var group = statesData.groups[i];
                        out = out.concat('
');
                        out = out.concat(buildLabel(group.label));
                        for (var j = 0; j < group.fields.length; j++) {
                            out = out.concat(buildField(group, group.fields[j]));
                        }
                        out = out.concat('
');
                    }
                }
                return out;
            }
        },

        '#toggle-button': {
            'origin': [0.5, 0.5],
            'rotation-z': function(buttonRotation) { return buttonRotation; },
            'opacity': function(panelOpenness) { return 0.5 + (panelOpenness / 2); },
            'position-y': function(gutterSize) { return gutterSize; },
            'position-x': function(gutterSize) { return gutterSize; },
            'size-absolute': function(buttonSize) { return [buttonSize, buttonSize]; },
            'style': { 'z-index': 4, 'cursor': 'pointer' },
            'unselectable': true
        }
    },

    events: {
        '$public': {
            'open': function($state) {
                $state.set('isOpen', true);
                $state.set('buttonRotation', $state.get('buttonOpenRotation'), {
                    duration: $state.get('openCloseDuration'),
                    curve: $state.get('openCloseCurve')
                });
                $state.set('panelOpenness', 1.0, {
                    duration: $state.get('openCloseDuration'),
                    curve: $state.get('openCloseCurve')
                });
            },

            'close': function($state) {
                $state.set('isOpen', false);
                // Give the button some extra spin on the way back
                $state.set('buttonRotation', $state.get('buttonRotation') + Math.PI * 2);
                $state.set('buttonRotation', $state.get('buttonClosedRotation'), {
                    duration: $state.get('openCloseDuration'),
                    curve: $state.get('openCloseCurve')
                });
                $state.set('panelOpenness', 0.0, {
                    duration: $state.get('openCloseDuration'),
                    curve: $state.get('openCloseCurve')
                });
            }
        },

        '#toggle-button': {
            'click': function($state, $dispatcher) {
                if ($state.get('isOpen')) {
                    $dispatcher.trigger('close');
                }
                else {
                    $dispatcher.trigger('open');
                }
            }
        },

        '#panel-content': {
            'input': function($event, $dispatcher) {
                var out = {};
                var target = $event.target;
                if (target) {
                    out.field = target.getAttribute('data-field');
                    out.key = target.getAttribute('data-key');
                    out.group = target.getAttribute('data-group');
                    out.type = target.getAttribute('data-type');
                    out.uid = target.getAttribute('data-uid');
                }
                out.value = getFormattedValue(out, $event.value);
                $dispatcher.publish('$states-configured', out);
            }
        },

        '$lifecycle': {
            'post-load': function($state, $dispatcher) {
                var statesData = $state.get('statesData');
                if (!statesData.groups) { statesData.groups = []; }
                $dispatcher.subscribe('$states-exposed', function(key, payload) {
                    for (var i = 0; i < payload.fields.length; i++) {
                        payload.fields[i].uid = payload.uid;
                    }
                    statesData.groups.push({
                        uid: payload.uid,
                        label: payload.name,
                        fields: payload.fields
                    });
                    $state.set('statesData', statesData);
                });
            }
        }
    },

    states: {
        buttonClosedRotation: 0,
        buttonOpenRotation: Math.PI / 4,
        buttonRotation: 0,
        buttonSize: 40,
        gutterSize: 20,
        statesData: {},
        isOpen: false,
        openCloseCurve: 'inOutBack',
        openCloseDuration: 1000,
        offsetPosition: [0, 0],
        panelFullOpacity: 0.8,
        panelOpenness: 0.0,
        panelWidth: 300
    },

    tree: `
        <node id="panel-container">
            <node id="gradient"></node>
            <node id="toggle-button">

            </node>
            <node id="panel">
                <node id="panel-content"></node>
            </node>
        </node>
    `
});


text:
package us.dot.its.jpo.ode.plugin.j2735.builders;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;

import org.junit.Test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class LongitudeBuilderTest {

   @Test
   public void testConversion() throws JsonProcessingException, IOException {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode testInput = mapper.readTree("251234567");
      BigDecimal expectedValue = BigDecimal.valueOf(25.1234567);

      assertEquals(expectedValue, LongitudeBuilder.genericLongitude(testInput));
   }

   @Test
   public void testConversionDeticatedNullValue() throws JsonProcessingException, IOException {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode testInput = mapper.readTree("1800000001");
      BigDecimal expectedValue = null;

      assertEquals(expectedValue, LongitudeBuilder.genericLongitude(testInput));
   }

   @Test
   public void testBigDecimal() throws JsonProcessingException, IOException {

      BigDecimal testInput = new BigDecimal(1.0);

      assertEquals(10000000, LongitudeBuilder.j2735Longitude(testInput));

   }

   @Test
   public void testConstructorIsPrivate()
         throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
      Constructor<LongitudeBuilder> constructor = LongitudeBuilder.class.getDeclaredConstructor();
      assertTrue(Modifier.isPrivate(constructor.getModifiers()));
      constructor.setAccessible(true);
      try {
         constructor.newInstance();
         fail("Expected IllegalAccessException.class");
      } catch (Exception e) {
         assertEquals(InvocationTargetException.class, e.getClass());
      }
   }

}


text:
""" java.utils.Random utility functions.

These methods simulate the Random object 'next' function, and
are used to implement the other Random functions (nextInt, nextDouble, etc.)

Note that it is an error to pass a value for 'bits' that is larger than 32.
"""

from foresight import lcg
from ctypes import c_uint32

MULTIPLIER = 25214903917
INCREMENT = 11
MODULUS = 2**48
SHIFT_BITS = 16

def predict_state(values):
    return lcg.predict_state(values,
                             MULTIPLIER,
                             INCREMENT,
                             MODULUS,
                             SHIFT_BITS)

def generate_values(state, bits):
    gen = lcg.generate_values(state,
                              MULTIPLIER,
                              INCREMENT,
                              MODULUS,
                              0)
    for prediction in gen:
        yield prediction >> (48 - bits)

def from_seed(seed, bits):
    seed = (seed ^ 0x5DEECE66D) & ((1 << 48) - 1)
    gen = lcg.from_seed(seed, MULTIPLIER,
                        INCREMENT, MODULUS, 0)
    for prediction in gen:
        yield prediction >> (48 - bits)

def from_outputs(outputs, bits):
    outputs = [c_uint32(o).value for o in outputs]
    gen = lcg.from_outputs(outputs, MULTIPLIER,
                           INCREMENT, MODULUS,
                           48-bits)
    for prediction in gen:
        yield prediction & ((1 << bits) - 1)


text:
package org.apache.camel.component.box;

import com.box.sdk.BoxAPIConnection;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.component.box.internal.BoxApiCollection;
import org.apache.camel.component.box.internal.BoxApiName;
import org.apache.camel.component.box.internal.BoxConnectionHelper;
import org.apache.camel.spi.Metadata;
import org.apache.camel.support.component.AbstractApiComponent;

public class BoxComponent extends AbstractApiComponent<BoxApiName, BoxConfiguration, BoxApiCollection> {

    @Metadata(label = "advanced")
    BoxAPIConnection boxConnection;

    public BoxComponent() {
        super(BoxEndpoint.class, BoxApiName.class, BoxApiCollection.getCollection());
    }

    public BoxComponent(CamelContext context) {
        super(context, BoxEndpoint.class, BoxApiName.class, BoxApiCollection.getCollection());
    }

    @Override
    protected BoxApiName getApiName(String apiNameStr) throws IllegalArgumentException {
        return BoxApiName.fromValue(apiNameStr);
    }

    /**
     * To use the shared configuration
     */
    @Override
    public void setConfiguration(BoxConfiguration configuration) {
        super.setConfiguration(configuration);
    }

    /**
     * To use the shared configuration
     */
    @Override
    public BoxConfiguration getConfiguration() {
        return super.getConfiguration();
    }

    /**
     * To use a shared connection
     *
     * @return the shared connection
     */
    public BoxAPIConnection getBoxConnection() {
        return boxConnection;
    }

    @Override
    protected Endpoint createEndpoint(String uri, String methodName, BoxApiName apiName,
            BoxConfiguration endpointConfiguration) {
        endpointConfiguration.setApiName(apiName);
        endpointConfiguration.setMethodName(methodName);
        return new BoxEndpoint(uri, this, apiName, methodName, endpointConfiguration);
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();

        if (boxConnection == null) {
            if (configuration != null) {
                boxConnection = BoxConnectionHelper.createConnection(configuration);
            } else {
                throw new IllegalArgumentException("Unable to connect, Box component configuration is missing");
            }
        }
    }

    @Override
    protected void doStop() throws Exception {
        if (boxConnection != null) {
            boxConnection = null;
        }
    }

    @Override
    public void doShutdown() throws Exception {
        if (boxConnection != null) {
            boxConnection = null;
        }
        super.doShutdown();
    }
}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/apps/app_service/webapk/webapk_install_task.h"

#include <memory>

#include "ash/components/arc/mojom/webapk.mojom.h"
#include "ash/components/arc/session/arc_bridge_service.h"
#include "ash/components/arc/session/arc_service_manager.h"
#include "ash/components/arc/test/fake_webapk_instance.h"
#include "ash/constants/ash_features.h"
#include "base/bind.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "chrome/browser/apps/app_service/app_service_test.h"
#include "chrome/browser/apps/app_service/webapk/webapk_metrics.h"
#include "chrome/browser/apps/app_service/webapk/webapk_prefs.h"
#include "chrome/browser/apps/app_service/webapk/webapk_test_server.h"
#include "chrome/browser/ui/app_list/arc/arc_app_test.h"
#include "chrome/browser/web_applications/test/fake_web_app_provider.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/browser/web_applications/web_app_install_info.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/testing_profile.h"
#include "components/prefs/pref_service.h"
#include "components/webapk/webapk.pb.h"
#include "content/public/test/browser_task_environment.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

constexpr char kTestAppUrl[] = "https://www.example.com/";
constexpr char kTestAppActionUrl[] = "https://www.example.com/share";
constexpr char kTestAppIcon[] = "https://www.example.com/icon.png";
constexpr char kTestManifestUrl[] = "https://www.example.com/manifest.json";
constexpr char kTestShareTextParam[] = "share_text";
const std::u16string kTestAppTitle = u"Test App";

std::unique_ptr<WebAppInstallInfo> BuildDefaultWebAppInfo() {
  auto app_info = std::make_unique<WebAppInstallInfo>();
  app_info->start_url = GURL(kTestAppUrl);
  app_info->scope = GURL(kTestAppUrl);
  app_info->title = kTestAppTitle;
  app_info->manifest_url = GURL(kTestManifestUrl);
  apps::IconInfo icon;
  icon.square_size_px = 64;
  icon.purpose = apps::IconInfo::Purpose::kAny;
  icon.url = GURL(kTestAppIcon);
  app_info->manifest_icons.push_back(icon);

  apps::ShareTarget target;
  target.action = GURL(kTestAppActionUrl);
  target.method = apps::ShareTarget::Method::kPost;
  target.enctype = apps::ShareTarget::Enctype::kMultipartFormData;
  target.params.text = kTestShareTextParam;
  app_info->share_target = target;

  return app_info;
}

arc::mojom::WebApkInfoPtr BuildDefaultWebApkInfo(
    const std::string& package_name,
    const std::string& icon_hash) {
  auto webapk_info = arc::mojom::WebApkInfo::New();
  webapk_info->package_name = package_name;
  webapk_info->apk_version = "1";
  webapk_info->shell_apk_version = "1";
  webapk_info->manifest_url = kTestManifestUrl;
  webapk_info->name = "Test App";
  webapk_info->start_url = kTestAppUrl;
  webapk_info->scope = kTestAppUrl;
  webapk_info->icon_hash = icon_hash;
  auto target_info = arc::mojom::WebShareTargetInfo::New();
  target_info->action = kTestAppActionUrl;
  target_info->method = "POST";
  target_info->enctype = "multipart/form-data";
  target_info->param_text = kTestShareTextParam;
  webapk_info->share_info = std::move(target_info);
  return webapk_info;
}

absl::optional<arc::ArcFeatures> GetArcFeaturesWithAbiList(
    const std::string& abi_list) {
  arc::ArcFeatures arc_features;
  arc_features.build_props["ro.product.cpu.abilist"] = abi_list;
  return arc_features;
}

}  // namespace

class WebApkInstallTaskTest : public testing::Test {
  using WebApkResponseBuilder =
      base::RepeatingCallback<std::unique_ptr<net::test_server::HttpResponse>(
          void)>;

 public:
  WebApkInstallTaskTest()
      : task_environment_(content::BrowserTaskEnvironment::MainThreadType::IO) {
  }
  WebApkInstallTaskTest(const WebApkInstallTaskTest&) = delete;
  WebApkInstallTaskTest& operator=(const WebApkInstallTaskTest&) = delete;

  void SetUp() override {
    testing::Test::SetUp();
    app_service_test_.SetUp(&profile_);

    auto* const provider = web_app::FakeWebAppProvider::Get(&profile_);
    provider->SkipAwaitingExtensionSystem();
    web_app::test::AwaitStartWebAppProviderAndSubsystems(profile());

    // Disable WebApkManager by policy. This allows us to unit test
    // WebApkInstallTask without interference from the WebApkManager started by
    // ArcApps.
    profile()->GetPrefs()->SetBoolean(
        apps::webapk_prefs::kGeneratedWebApksEnabled, false);

    arc_test_.SetUp(&profile_);
    auto* arc_bridge_service =
        arc_test_.arc_service_manager()->arc_bridge_service();
    fake_webapk_instance_ = std::make_unique<arc::FakeWebApkInstance>();
    arc_bridge_service->webapk()->SetInstance(fake_webapk_instance_.get());

    app_service_test_.FlushMojoCalls();

    net::test_server::RegisterDefaultHandlers(&test_server_);
    webapk_test_server_ = std::make_unique<apps::WebApkTestServer>();
    ASSERT_TRUE(webapk_test_server_->SetUpAndStartServer(&test_server_));

    arc_features_getter_ =
        base::BindRepeating(&GetArcFeaturesWithAbiList, "x86_64");
    arc::ArcFeaturesParser::SetArcFeaturesGetterForTesting(
        &arc_features_getter_);
  }

  void TearDown() override { arc_test_.TearDown(); }

  bool InstallWebApk(std::string app_id) {
    bool install_success;
    apps::WebApkInstallTask install_task(profile(), app_id);
    base::RunLoop run_loop;
    install_task.Start(base::BindLambdaForTesting([&](bool success) {
      install_success = success;
      run_loop.Quit();
    }));
    run_loop.Run();
    return install_success;
  }

  bool UpdateWebApk(const std::string& app_id) {
    // This is normally set by WebApkManager when an update is queued.
    apps::webapk_prefs::SetUpdateNeededForApp(profile(), app_id,
                                              /* update_needed= */ true);
    return InstallWebApk(app_id);
  }

  TestingProfile* profile() { return &profile_; }

  apps::AppServiceTest* app_service_test() { return &app_service_test_; }

  arc::FakeWebApkInstance* fake_webapk_instance() {
    return fake_webapk_instance_.get();
  }

  webapk::WebApk* last_webapk_request() {
    return webapk_test_server_->last_webapk_request();
  }

  apps::WebApkTestServer* webapk_test_server() {
    return webapk_test_server_.get();
  }

  net::EmbeddedTestServer* test_server() { return &test_server_; }

 private:
  content::BrowserTaskEnvironment task_environment_;
  TestingProfile profile_;
  apps::AppServiceTest app_service_test_;
  ArcAppTest arc_test_;

  net::EmbeddedTestServer test_server_;

  std::unique_ptr<arc::FakeWebApkInstance> fake_webapk_instance_;
  std::unique_ptr<apps::WebApkTestServer> webapk_test_server_;
  base::RepeatingCallback<absl::optional<arc::ArcFeatures>()>
      arc_features_getter_;
};

TEST_F(WebApkInstallTaskTest, SuccessfulInstall) {
  auto arc_features_getter =
      base::BindRepeating(&GetArcFeaturesWithAbiList, "arm64-v8a,armeabi-v7a");
  arc::ArcFeaturesParser::SetArcFeaturesGetterForTesting(&arc_features_getter);

  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());

  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");
  base::HistogramTester histograms;

  EXPECT_TRUE(InstallWebApk(app_id));

  ASSERT_EQ(last_webapk_request()->manifest_url(), kTestManifestUrl);
  ASSERT_EQ(last_webapk_request()->android_abi(), "arm64-v8a");
  const webapk::WebAppManifest& manifest = last_webapk_request()->manifest();
  EXPECT_EQ(manifest.short_name(), "Test App");
  EXPECT_EQ(manifest.start_url(), kTestAppUrl);
  EXPECT_EQ(manifest.icons(0).src(), kTestAppIcon);

  ASSERT_EQ(fake_webapk_instance()->handled_packages().size(), 1u);
  ASSERT_EQ(fake_webapk_instance()->handled_packages().count(
                "org.chromium.webapk.some_package"),
            1u);

  ASSERT_THAT(apps::webapk_prefs::GetWebApkAppIds(profile()),
              testing::ElementsAre(app_id));
  ASSERT_EQ(*apps::webapk_prefs::GetWebApkPackageName(profile(), app_id),
            "org.chromium.webapk.some_package");
  histograms.ExpectBucketCount(apps::kWebApkInstallResultHistogram,
                               apps::WebApkInstallStatus::kSuccess, 1);
  histograms.ExpectBucketCount(apps::kWebApkArcInstallResultHistogram,
                               arc::mojom::WebApkInstallResult::kSuccess, 1);
}

TEST_F(WebApkInstallTaskTest, ShareTarget) {
  auto web_app_info = BuildDefaultWebAppInfo();

  apps::ShareTarget share_target;
  share_target.action = GURL("https://www.example.com/new");
  share_target.method = apps::ShareTarget::Method::kPost;
  share_target.enctype = apps::ShareTarget::Enctype::kFormUrlEncoded;
  share_target.params.text = "share_text";
  share_target.params.url = "share_url";
  apps::ShareTarget::Files files1;
  files1.name = "images";
  files1.accept = {"image/*"};
  apps::ShareTarget::Files files2;
  files2.name = "videos";
  files2.accept = {"video/mp4", "video/quicktime"};
  share_target.params.files = {files1, files2};
  web_app_info->share_target = share_target;

  auto app_id =
      web_app::test::InstallWebApp(profile(), std::move(web_app_info));

  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");

  EXPECT_TRUE(InstallWebApk(app_id));

  const webapk::WebAppManifest& manifest = last_webapk_request()->manifest();
  EXPECT_EQ(manifest.share_targets(0).action(), "https://www.example.com/new");
  EXPECT_EQ(manifest.share_targets(0).params().text(), "share_text");
  EXPECT_EQ(manifest.share_targets(0).params().url(), "share_url");
  EXPECT_FALSE(manifest.share_targets(0).params().has_title());
  EXPECT_EQ(manifest.share_targets(0).params().files(0).name(), "images");
  EXPECT_EQ(manifest.share_targets(0).params().files(0).accept_size(), 1);
  EXPECT_EQ(manifest.share_targets(0).params().files(0).accept(0), "image/*");
  EXPECT_EQ(manifest.share_targets(0).params().files(1).accept_size(), 2);
}

TEST_F(WebApkInstallTaskTest, NoIconInManifest) {
  auto app_info = std::make_unique<WebAppInstallInfo>();
  app_info->start_url = GURL(kTestAppUrl);
  app_info->scope = GURL(kTestAppUrl);
  app_info->title = kTestAppTitle;
  app_info->manifest_url = GURL(kTestManifestUrl);
  auto app_id = web_app::test::InstallWebApp(profile(), std::move(app_info));
  base::HistogramTester histograms;

  ASSERT_FALSE(InstallWebApk(app_id));
  ASSERT_EQ(apps::webapk_prefs::GetWebApkAppIds(profile()).size(), 0u);
  histograms.ExpectBucketCount(apps::kWebApkInstallResultHistogram,
                               apps::WebApkInstallStatus::kAppInvalid, 1);
}

TEST_F(WebApkInstallTaskTest, FailedServerCall) {
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());

  webapk_test_server()->RespondWithError();
  base::HistogramTester histograms;

  ASSERT_FALSE(InstallWebApk(app_id));

  ASSERT_EQ(fake_webapk_instance()->handled_packages().size(), 0u);
  ASSERT_EQ(apps::webapk_prefs::GetWebApkAppIds(profile()).size(), 0u);
  histograms.ExpectBucketCount(apps::kWebApkInstallResultHistogram,
                               apps::WebApkInstallStatus::kNetworkError, 1);
}

TEST_F(WebApkInstallTaskTest, FailedArcInstall) {
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());

  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");
  fake_webapk_instance()->set_install_result(
      arc::mojom::WebApkInstallResult::kErrorResolveNetworkError);
  base::HistogramTester histograms;

  ASSERT_FALSE(InstallWebApk(app_id));
  ASSERT_EQ(fake_webapk_instance()->handled_packages().count(
                "org.chromium.webapk.some_package"),
            1u);
  ASSERT_EQ(apps::webapk_prefs::GetWebApkAppIds(profile()).size(), 0u);
  histograms.ExpectBucketCount(apps::kWebApkInstallResultHistogram,
                               apps::WebApkInstallStatus::kGooglePlayError, 1);
  histograms.ExpectBucketCount(
      apps::kWebApkArcInstallResultHistogram,
      arc::mojom::WebApkInstallResult::kErrorResolveNetworkError, 1);
}

TEST_F(WebApkInstallTaskTest, MinterTimeout) {
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kWebApkServerUrl, test_server()->GetURL("/slow?1000").spec());
  base::HistogramTester histograms;

  bool install_success;
  apps::WebApkInstallTask install_task(profile(), app_id);
  install_task.SetTimeoutForTesting(base::Milliseconds(100));
  base::RunLoop run_loop;
  install_task.Start(base::BindLambdaForTesting([&](bool success) {
    install_success = success;
    run_loop.Quit();
  }));
  run_loop.Run();

  ASSERT_FALSE(install_success);
  histograms.ExpectBucketCount(apps::kWebApkInstallResultHistogram,
                               apps::WebApkInstallStatus::kNetworkTimeout, 1);
}

TEST_F(WebApkInstallTaskTest, NoManifestUrl) {
  auto info = BuildDefaultWebAppInfo();
  info->manifest_url = GURL();
  auto app_id = web_app::test::InstallWebApp(profile(), std::move(info));
  base::HistogramTester histograms;

  ASSERT_FALSE(InstallWebApk(app_id));
  histograms.ExpectBucketCount(apps::kWebApkInstallResultHistogram,
                               apps::WebApkInstallStatus::kAppInvalid, 1);
}

TEST_F(WebApkInstallTaskTest, SuccessfulUpdateShortName) {
  // Install an initial app.
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");

  EXPECT_TRUE(InstallWebApk(app_id));

  fake_webapk_instance()->set_web_apk_info(BuildDefaultWebApkInfo(
      "org.chromium.webapk.some_package",
      last_webapk_request()->manifest().icons(0).hash()));

  // Install the same app with |short_name| changed. This should trigger an
  // update.
  auto web_app_info = BuildDefaultWebAppInfo();
  web_app_info->title = u"Testy test App";
  web_app::test::InstallWebApp(profile(), std::move(web_app_info),
                               /*overwrite_existing_manifest_fields=*/true);
  EXPECT_TRUE(UpdateWebApk(app_id));

  // Check that the update worked.
  ASSERT_THAT(last_webapk_request()->update_reasons(),
              ::testing::ElementsAre(webapk::WebApk::SHORT_NAME_DIFFERS));
  ASSERT_EQ(last_webapk_request()->package_name(),
            "org.chromium.webapk.some_package");
  ASSERT_EQ(last_webapk_request()->version(), "1");

  webapk::WebAppManifest manifest = last_webapk_request()->manifest();
  EXPECT_EQ(manifest.short_name(), "Testy test App");

  // Check we still only have 1 version of |app_id| installed.
  ASSERT_THAT(apps::webapk_prefs::GetWebApkAppIds(profile()),
              testing::ElementsAre(app_id));
}

TEST_F(WebApkInstallTaskTest, SuccessfulUpdateScope) {
  // Install an initial app.
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");

  EXPECT_TRUE(InstallWebApk(app_id));

  fake_webapk_instance()->set_web_apk_info(BuildDefaultWebApkInfo(
      "org.chromium.webapk.some_package",
      last_webapk_request()->manifest().icons(0).hash()));

  // Install the same app with |scope| changed. This should trigger an
  // update.
  auto web_app_info = BuildDefaultWebAppInfo();
  web_app_info->scope = GURL("https://www.differentexample.com/");
  web_app::test::InstallWebApp(profile(), std::move(web_app_info),
                               /*overwrite_existing_manifest_fields=*/true);
  EXPECT_TRUE(UpdateWebApk(app_id));

  // Check that the update worked.
  ASSERT_THAT(last_webapk_request()->update_reasons(),
              ::testing::ElementsAre(webapk::WebApk::SCOPE_DIFFERS));

  webapk::WebAppManifest manifest = last_webapk_request()->manifest();
  EXPECT_EQ(last_webapk_request()->manifest().scopes_size(), 1u);
  EXPECT_EQ(last_webapk_request()->manifest().scopes(0),
            "https://www.differentexample.com/");

  // Check we still only have 1 version of |app_id| installed.
  ASSERT_THAT(apps::webapk_prefs::GetWebApkAppIds(profile()),
              testing::ElementsAre(app_id));
}

TEST_F(WebApkInstallTaskTest, SuccessfulUpdateIconHash) {
  // Install an initial app.
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");

  EXPECT_TRUE(InstallWebApk(app_id));

  // Change icon hash.
  fake_webapk_instance()->set_web_apk_info(BuildDefaultWebApkInfo(
      "org.chromium.webapk.some_package", "fakeiconhash123456789"));

  auto web_app_info = BuildDefaultWebAppInfo();
  web_app::test::InstallWebApp(profile(), std::move(web_app_info));
  EXPECT_TRUE(UpdateWebApk(app_id));

  // Check that the update worked.
  ASSERT_THAT(
      last_webapk_request()->update_reasons(),
      ::testing::ElementsAre(webapk::WebApk::PRIMARY_ICON_HASH_DIFFERS));

  // Check we still only have 1 version of |app_id| installed.
  ASSERT_THAT(apps::webapk_prefs::GetWebApkAppIds(profile()),
              testing::ElementsAre(app_id));
}

TEST_F(WebApkInstallTaskTest, SuccessfulUpdateShareTarget) {
  // Install an initial app.
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");

  EXPECT_TRUE(InstallWebApk(app_id));
  fake_webapk_instance()->set_web_apk_info(BuildDefaultWebApkInfo(
      "org.chromium.webapk.some_package",
      last_webapk_request()->manifest().icons(0).hash()));

  // Install the same app with |share_target| changed. This should trigger an
  // update.
  auto web_app_info = BuildDefaultWebAppInfo();
  web_app_info->share_target->action =
      GURL("https://www.differentexample.com/");
  web_app::test::InstallWebApp(profile(), std::move(web_app_info),
                               /*overwrite_existing_manifest_fields=*/true);
  EXPECT_TRUE(UpdateWebApk(app_id));

  // Check that the update worked.
  ASSERT_THAT(last_webapk_request()->update_reasons(),
              ::testing::ElementsAre(webapk::WebApk::WEB_SHARE_TARGET_DIFFERS));

  webapk::WebAppManifest manifest = last_webapk_request()->manifest();
  EXPECT_EQ(manifest.share_targets(0).action(),
            "https://www.differentexample.com/");

  // Check we still only have 1 version of |app_id| installed.
  ASSERT_THAT(apps::webapk_prefs::GetWebApkAppIds(profile()),
              testing::ElementsAre(app_id));
}

TEST_F(WebApkInstallTaskTest, SuccessfulUpdateMultipleChanges) {
  // Install an initial app.
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");

  EXPECT_TRUE(InstallWebApk(app_id));

  fake_webapk_instance()->set_web_apk_info(BuildDefaultWebApkInfo(
      "org.chromium.webapk.some_package",
      last_webapk_request()->manifest().icons(0).hash()));

  auto web_app_info = BuildDefaultWebAppInfo();
  web_app_info->title = u"Testy test App";
  web_app_info->share_target->action =
      GURL("https://www.differentexample.com/");
  web_app::test::InstallWebApp(profile(), std::move(web_app_info),
                               /*overwrite_existing_manifest_fields=*/true);
  base::HistogramTester histograms;
  EXPECT_TRUE(UpdateWebApk(app_id));

  ASSERT_THAT(last_webapk_request()->update_reasons(),
              ::testing::UnorderedElementsAre(
                  webapk::WebApk::SHORT_NAME_DIFFERS,
                  webapk::WebApk::WEB_SHARE_TARGET_DIFFERS));

  webapk::WebAppManifest manifest = last_webapk_request()->manifest();
  EXPECT_EQ(manifest.short_name(), "Testy test App");
  EXPECT_EQ(manifest.share_targets(0).action(),
            "https://www.differentexample.com/");

  // Check we still only have 1 version of |app_id| installed.
  ASSERT_THAT(apps::webapk_prefs::GetWebApkAppIds(profile()),
              testing::ElementsAre(app_id));
  ASSERT_THAT(apps::webapk_prefs::GetUpdateNeededAppIds(profile()),
              testing::IsEmpty());
  histograms.ExpectBucketCount(apps::kWebApkUpdateResultHistogram,
                               apps::WebApkInstallStatus::kSuccess, 1);
  histograms.ExpectBucketCount(apps::kWebApkArcUpdateResultHistogram,
                               arc::mojom::WebApkInstallResult::kSuccess, 1);
}

TEST_F(WebApkInstallTaskTest, AbandonedUpdateNoChanges) {
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");
  EXPECT_TRUE(InstallWebApk(app_id));
  fake_webapk_instance()->set_web_apk_info(BuildDefaultWebApkInfo(
      "org.chromium.webapk.some_package",
      last_webapk_request()->manifest().icons(0).hash()));

  // Install the same app with no changes. This should fail.
  base::HistogramTester histograms;
  EXPECT_FALSE(UpdateWebApk(app_id));
  histograms.ExpectBucketCount(
      apps::kWebApkUpdateResultHistogram,
      apps::WebApkInstallStatus::kUpdateCancelledWebApkUpToDate, 1);
  // Update should no longer be needed.
  ASSERT_THAT(apps::webapk_prefs::GetUpdateNeededAppIds(profile()),
              testing::IsEmpty());
}

TEST_F(WebApkInstallTaskTest, FailedUpdateWebApkInfoInvalid) {
  // Install an initial app.
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");

  EXPECT_TRUE(InstallWebApk(app_id));

  // Install the same app without setting web apk info. Install should fail.
  base::HistogramTester histograms;
  EXPECT_FALSE(UpdateWebApk(app_id));
  histograms.ExpectBucketCount(
      apps::kWebApkUpdateResultHistogram,
      apps::WebApkInstallStatus::kUpdateGetWebApkInfoError, 1);
}

TEST_F(WebApkInstallTaskTest, FailedUpdateNetworkError) {
  // Install an initial app.
  auto app_id =
      web_app::test::InstallWebApp(profile(), BuildDefaultWebAppInfo());
  webapk_test_server()->RespondWithSuccess("org.chromium.webapk.some_package");

  EXPECT_TRUE(InstallWebApk(app_id));

  fake_webapk_instance()->set_web_apk_info(BuildDefaultWebApkInfo(
      "org.chromium.webapk.some_package",
      last_webapk_request()->manifest().icons(0).hash()));

  // Install the same app with |short_name| changed. This should trigger an
  // update.
  auto web_app_info = BuildDefaultWebAppInfo();
  web_app_info->title = u"Testy test App";
  web_app::test::InstallWebApp(profile(), std::move(web_app_info),
                               /*overwrite_existing_manifest_fields=*/true);

  base::HistogramTester histograms;
  webapk_test_server()->RespondWithError();

  ASSERT_FALSE(UpdateWebApk(app_id));

  histograms.ExpectBucketCount(apps::kWebApkUpdateResultHistogram,
                               apps::WebApkInstallStatus::kNetworkError, 1);
  // Check that the app is still installed and still needs an update.
  ASSERT_THAT(apps::webapk_prefs::GetWebApkAppIds(profile()),
              testing::ElementsAre(app_id));
  ASSERT_THAT(apps::webapk_prefs::GetUpdateNeededAppIds(profile()),
              testing::ElementsAre(app_id));
}


text:
package cz.helmisek.evtademo.api;

public final class ApiConfig
{

	public static final String BASE_URL = "http://jsonplaceholder.typicode.com/";

	public static final String USERS = "users";

}