hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e19ff04855b2a4f220fc78cb5170fd4ead3221c | 2,803 | java | Java | src/commons/components/Move.java | ODaynes/ProjectRPG | 104ed7d1db586525a9c104691068d13bd0809514 | [
"MIT"
] | null | null | null | src/commons/components/Move.java | ODaynes/ProjectRPG | 104ed7d1db586525a9c104691068d13bd0809514 | [
"MIT"
] | null | null | null | src/commons/components/Move.java | ODaynes/ProjectRPG | 104ed7d1db586525a9c104691068d13bd0809514 | [
"MIT"
] | null | null | null | 27.480392 | 161 | 0.629326 | 11,041 | package commons.components;
import com.sun.istack.internal.NotNull;
/**
* Created by Owen Daynes on 11/07/2019.
*/
public enum Move {
TACKLE("Tackle", "The fighter tackles the opponent with their full force.", 50, Type.NORMAL, Effect.NONE, 0),
VINE_WHIP("Vine Whip", "The fighter whips the opponent with a vine.", 40, Type.GRASS, Effect.NONE, 0),
EMBER("Ember", "The fighter burns the opponent with a small flame.", 40, Type.FIRE, Effect.BURN, 5),
WATER_GUN("Water Gun", "The fighter hits the opponent with a small jet of water.", 40, Type.WATER, Effect.NONE, 0);
private String name;
private String desc;
private Integer power;
private Type type;
private Effect effect;
private Integer effectChance; // 0 - 100, representing 0% - 100%
private Move(@NotNull String name, @NotNull String desc, @NotNull Integer power, @NotNull Type type, @NotNull Effect effect, @NotNull Integer effectChance) {
this.name = name;
this.desc = desc;
this.power = power;
this.type = type;
this.effect = effect;
// If there is no effect, no point in calculating whether effect occurs
if(effect != Effect.NONE) {
this.effectChance = effectChance;
} else {
this.effectChance = 0;
}
}
/**
* Retrieve a Move object by providing a matching string name
*
* @param name The name of the effect to return
* @return The move matching the input string.
* @throws IllegalArgumentException If input string does not match existing Move name
*/
public Effect getMoveByNameIgnoreCase(String name) throws IllegalArgumentException {
for(Effect effect: Effect.values()) {
if(effect.getName().equalsIgnoreCase(name)) return effect;
}
throw new IllegalArgumentException(String.format("Move with the name '%s' cannot be found.", name));
}
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Integer getPower() {
return power;
}
public void setPower(Integer power) {
this.power = power;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Effect getEffect() {
return effect;
}
public void setEffect(Effect effect) {
this.effect = effect;
}
public Integer getEffectChance() {
return effectChance;
}
public void setEffectChance(Integer effectChance) {
this.effectChance = effectChance;
}
}
|
3e19ff0f8ccb56bd155d0d446624d843b5efbf0e | 208 | java | Java | core/remoting/src/main/java/org/nakedobjects/remoting/protocol/Marshaller.java | Corpus-2021/nakedobjects-4.0.0 | 37ee250d4c8da969eac76749420064ca4c918e8e | [
"Apache-2.0"
] | null | null | null | core/remoting/src/main/java/org/nakedobjects/remoting/protocol/Marshaller.java | Corpus-2021/nakedobjects-4.0.0 | 37ee250d4c8da969eac76749420064ca4c918e8e | [
"Apache-2.0"
] | null | null | null | core/remoting/src/main/java/org/nakedobjects/remoting/protocol/Marshaller.java | Corpus-2021/nakedobjects-4.0.0 | 37ee250d4c8da969eac76749420064ca4c918e8e | [
"Apache-2.0"
] | 1 | 2021-02-22T15:40:05.000Z | 2021-02-22T15:40:05.000Z | 20.8 | 80 | 0.807692 | 11,042 | package org.nakedobjects.remoting.protocol;
import org.nakedobjects.metamodel.commons.component.ApplicationScopedComponent;
public interface Marshaller extends ApplicationScopedComponent{
}
|
3e19ff2d3601df679d350c9ca1f69bfebed6dfe7 | 1,319 | java | Java | gous/src/main/java/com/meyoustu/amuse/gous/lang/FileWrapper.java | LiangchengJ/amuse | 4573ca40f00bec02abbea251852e325582de6021 | [
"Apache-2.0"
] | 1 | 2020-12-23T08:13:02.000Z | 2020-12-23T08:13:02.000Z | gous/src/main/java/com/meyoustu/amuse/gous/lang/FileWrapper.java | LiangchengJ/amuse | 4573ca40f00bec02abbea251852e325582de6021 | [
"Apache-2.0"
] | null | null | null | gous/src/main/java/com/meyoustu/amuse/gous/lang/FileWrapper.java | LiangchengJ/amuse | 4573ca40f00bec02abbea251852e325582de6021 | [
"Apache-2.0"
] | null | null | null | 23.140351 | 93 | 0.576194 | 11,043 | package com.meyoustu.amuse.gous.lang;
import com.meyoustu.amuse.gous.listen.TraverseDirListener;
import com.meyoustu.amuse.gous.mey.Share;
import java.io.File;
import java.net.URI;
/**
* @author Liangcheng Juves
* Created at 2020/05/23 11:39
*/
public class FileWrapper extends File {
public FileWrapper(String pathname) {
super(pathname);
}
public FileWrapper(String parent, String child) {
super(parent, child);
}
public FileWrapper(File parent, String child) {
super(parent, child);
}
public FileWrapper(URI uri) {
super(uri);
}
FileWrapper(File file) {
super(file.getAbsolutePath());
}
public String getExtension() {
if (isDirectory()) {
return null;
} else {
return Share.subWithLastIndex(getName(), ".");
}
}
public final void traverseDir(TraverseDirListener traverseDirListener) {
if (isDirectory()) {
for (File file : listFiles()) {
if (file.isDirectory()) {
new FileWrapper(file.getAbsolutePath()).traverseDir(traverseDirListener);
System.gc();
} else {
traverseDirListener.onTraversing(file);
}
}
}
}
}
|
3e1a00d6aa587a4d3f291ab698573e2633bcc9e5 | 158 | java | Java | src/main/java/dan200/computercraft/core/computer/IComputerOwned.java | Vexatos/CC-Tweaked | 33fad2da15029d8d251a40dba2ba5a349653cdba | [
"MIT"
] | null | null | null | src/main/java/dan200/computercraft/core/computer/IComputerOwned.java | Vexatos/CC-Tweaked | 33fad2da15029d8d251a40dba2ba5a349653cdba | [
"MIT"
] | null | null | null | src/main/java/dan200/computercraft/core/computer/IComputerOwned.java | Vexatos/CC-Tweaked | 33fad2da15029d8d251a40dba2ba5a349653cdba | [
"MIT"
] | null | null | null | 15.8 | 43 | 0.778481 | 11,044 | package dan200.computercraft.core.computer;
import javax.annotation.Nullable;
public interface IComputerOwned
{
@Nullable
Computer getComputer();
}
|
3e1a00e9c3dee219f2e1a7b298ccd15f6ed7deb4 | 2,864 | java | Java | src/main/java/com/github/mjdetullio/jenkins/plugins/multibranch/TemplateStaplerResponseWrapper.java | Rajasekharreddygv/multi-branch-project-plugin | 9a5d6ea4df159fbbc8512a25bbca545b6c7c26b0 | [
"MIT"
] | 42 | 2015-01-12T11:24:13.000Z | 2015-12-28T11:03:36.000Z | src/main/java/com/github/mjdetullio/jenkins/plugins/multibranch/TemplateStaplerResponseWrapper.java | Rajasekharreddygv/multi-branch-project-plugin | 9a5d6ea4df159fbbc8512a25bbca545b6c7c26b0 | [
"MIT"
] | 126 | 2015-01-16T01:34:24.000Z | 2015-12-30T05:21:19.000Z | src/main/java/com/github/mjdetullio/jenkins/plugins/multibranch/TemplateStaplerResponseWrapper.java | jenkinsci-transfer/multi-branch-project-plugin | a98828f6b5ea4e0f69a83f3d274fe05063caad52 | [
"MIT"
] | 41 | 2015-12-31T13:48:40.000Z | 2022-01-14T00:53:24.000Z | 33.302326 | 108 | 0.709846 | 11,045 | /*
* The MIT License
*
* Copyright (c) 2014, Matthew DeTullio
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.mjdetullio.jenkins.plugins.multibranch;
import org.kohsuke.stapler.ResponseImpl;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.annotation.Nonnull;
import java.io.IOException;
/**
* Prevents the template project from committing a redirect when it finishes handling the request in
* {@link hudson.model.AbstractProject#doConfigSubmit(StaplerRequest, StaplerResponse)}.
*
* @author Matthew DeTullio
*/
public final class TemplateStaplerResponseWrapper extends ResponseImpl {
/**
* Constructs this extension of {@link ResponseImpl} using the provided {@link Stapler} instance and the
* {@link StaplerResponse} you want to wrap.
*
* @param stapler the Stapler instance, which you can get from {@link StaplerRequest#getStapler()}
* @param response the response you want to wrap
*/
TemplateStaplerResponseWrapper(Stapler stapler, StaplerResponse response) {
super(stapler, response);
}
/**
* No-op.
*
* @param url ignored
* @throws IOException impossible
*/
@Override
public void sendRedirect(@Nonnull String url) throws IOException {
// No-op
}
/**
* No-op.
*
* @param var1 ignored
* @param var2 ignored
* @throws IOException impossible
*/
@Override
public void sendRedirect(int var1, @Nonnull String var2) throws IOException {
// No-op
}
/**
* No-op.
*
* @param var1 ignored
* @throws IOException impossible
*/
@Override
public void sendRedirect2(@Nonnull String var1) throws IOException {
// No-op
}
}
|
3e1a010672d408b52d867e17fcf528fcc4907ead | 2,889 | java | Java | modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMetadata.java | gridgain/apache-ignite-3 | 4760f677f8c2eeaeb34321216ef8bf4a796898de | [
"CC0-1.0"
] | 61 | 2020-12-02T06:43:04.000Z | 2022-03-24T09:28:41.000Z | modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMetadata.java | apache/ignite-3 | c2b800084375c38e89263228cbe82153bb7bb083 | [
"CC0-1.0"
] | 73 | 2020-11-24T02:31:56.000Z | 2022-03-30T09:40:57.000Z | modules/calcite/src/main/java/org/apache/ignite/internal/processors/query/calcite/metadata/IgniteMetadata.java | apache/ignite-3 | c2b800084375c38e89263228cbe82153bb7bb083 | [
"CC0-1.0"
] | 27 | 2020-11-23T23:52:20.000Z | 2022-03-20T12:40:17.000Z | 40.690141 | 96 | 0.717203 | 11,046 | /*
* 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.ignite.internal.processors.query.calcite.metadata;
import java.util.List;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.metadata.ChainedRelMetadataProvider;
import org.apache.calcite.rel.metadata.DefaultRelMetadataProvider;
import org.apache.calcite.rel.metadata.Metadata;
import org.apache.calcite.rel.metadata.MetadataDef;
import org.apache.calcite.rel.metadata.MetadataHandler;
import org.apache.calcite.rel.metadata.RelMetadataProvider;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.ignite.internal.processors.query.calcite.util.IgniteMethod;
/**
* Utility class, holding metadata related interfaces and metadata providers.
*/
public class IgniteMetadata {
/** */
public static final RelMetadataProvider METADATA_PROVIDER =
ChainedRelMetadataProvider.of(
List.of(
// Ignite specific providers
IgniteMdFragmentMapping.SOURCE,
// Ignite overriden providers
IgniteMdDistribution.SOURCE,
IgniteMdPercentageOriginalRows.SOURCE,
IgniteMdCumulativeCost.SOURCE,
IgniteMdNonCumulativeCost.SOURCE,
IgniteMdRowCount.SOURCE,
IgniteMdPredicates.SOURCE,
IgniteMdCollation.SOURCE,
IgniteMdSelectivity.SOURCE,
IgniteMdDistinctRowCount.SOURCE,
// Basic providers
DefaultRelMetadataProvider.INSTANCE));
/** */
public interface FragmentMappingMetadata extends Metadata {
MetadataDef<FragmentMappingMetadata> DEF = MetadataDef.of(FragmentMappingMetadata.class,
FragmentMappingMetadata.Handler.class, IgniteMethod.FRAGMENT_MAPPING.method());
/** Determines how the rows are distributed. */
FragmentMapping fragmentMapping();
/** Handler API. */
interface Handler extends MetadataHandler<FragmentMappingMetadata> {
FragmentMapping fragmentMapping(RelNode r, RelMetadataQuery mq);
}
}
}
|
3e1a012291cb45c2aae06efca3e684bb3670495f | 2,440 | java | Java | src/main/java/graphics/renderer/Renderer.java | GitWither/Azurite | 6a1941458178ece4887664ff05efb73b6d76f1f3 | [
"MIT"
] | 1 | 2022-01-18T19:43:55.000Z | 2022-01-18T19:43:55.000Z | src/main/java/graphics/renderer/Renderer.java | goldspark/Azurite | 062a68ddbc100b43ecd89d3ba15cf7a071f2365e | [
"MIT"
] | null | null | null | src/main/java/graphics/renderer/Renderer.java | goldspark/Azurite | 062a68ddbc100b43ecd89d3ba15cf7a071f2365e | [
"MIT"
] | null | null | null | 23.68932 | 146 | 0.703279 | 11,047 | package graphics.renderer;
import ecs.GameObject;
import graphics.Framebuffer;
import graphics.Shader;
import java.util.ArrayList;
import java.util.List;
import static org.lwjgl.opengl.GL11.*;
public abstract class Renderer<T extends RenderBatch> {
/** Texture slots to be uploaded to the shader. You don't have to upload them in your custom renderer. */
protected final int[] textureSlots = {0, 1, 2, 3, 4, 5, 6, 7};
/** A list of batches */
protected final List<T> batches;
/** Shader to be used for rendering */
private Shader shader;
/** Framebuffer to which this renderer will render */
public Framebuffer framebuffer;
public Renderer () {
this.batches = new ArrayList<>();
}
/**
* Create a shader
*
* @return the created shader
*/
protected abstract Shader createShader();
/**
* Create a framebuffer
*
* @return the created fbo
*/
protected abstract Framebuffer createFramebuffer();
/**
* Upload the required uniforms
*
* @param shader the shader
*/
protected abstract void uploadUniforms(Shader shader);
/**
* Add a gameObject to the renderer, and if it contains a component that affects rendering, like a sprite or light, those are added to the batch.
* @param gameObject the GameObject with renderable components
*/
public void add(GameObject gameObject) {}
/**
* Creates the renderer's shader and framebuffer
*/
public void init() {
shader = createShader();
framebuffer = createFramebuffer();
}
/**
* Get a color attachment texture from the framebuffer
*
* @param index index of the required color attachment texture. Will return -1 if there is no attachment at that index.
* @return the texture ID of the attachment
*/
public int fetchColorAttachment(int index) {
return framebuffer.fetchColorAttachment(index);
}
/**
* Loop through all render batches and render them
*/
public void render () {
framebuffer.bind();
prepare();
shader.attach();
uploadUniforms(shader);
for (T batch : batches) {
batch.updateBuffer();
batch.bind();
glDrawElements(batch.primitive.openglPrimitive, batch.getVertexCount(), GL_UNSIGNED_INT, 0);
batch.unbind();
}
shader.detach();
Framebuffer.unbind();
}
/**
* Prepare for rendering. Do anything like setting background here.
*/
protected abstract void prepare();
/**
* Delete all the Batches.
*/
public void clean() {
batches.forEach(RenderBatch::delete);
}
}
|
3e1a0170319591740bed779c54d74df95ce63218 | 2,822 | java | Java | src/main/java/alipsa/sieparser/SiePeriodValue.java | ig-neetesh/poc | 9cfb431ee410f5284714d521564919921017f3a4 | [
"MIT"
] | 1 | 2016-12-14T16:22:38.000Z | 2016-12-14T16:22:38.000Z | src/main/java/alipsa/sieparser/SiePeriodValue.java | perNyfelt/SIEParser | 6d3abf43ef37a649069c544c0e03afa06baa9cb3 | [
"MIT"
] | null | null | null | src/main/java/alipsa/sieparser/SiePeriodValue.java | perNyfelt/SIEParser | 6d3abf43ef37a649069c544c0e03afa06baa9cb3 | [
"MIT"
] | null | null | null | 25.423423 | 78 | 0.689582 | 11,048 | /*
MIT License
Copyright (c) 2015 Johan Idstam
Modifications by Per Nyfelt Copyright (c) 2016 Alipsa HB
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package alipsa.sieparser;
import java.math.BigDecimal;
import java.util.List;
public class SiePeriodValue {
private SieAccount account;
private int yearNr;
private int period;
private BigDecimal amount;
private BigDecimal quantity;
private List<SieObject> objects;
private String token;
public SieAccount getAccount() {
return account;
}
public void setAccount(SieAccount account) {
this.account = account;
}
public int getYearNr() {
return yearNr;
}
public void setYearNr(int yearNr) {
this.yearNr = yearNr;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public List<SieObject> getObjects() {
return objects;
}
public void setObjects(List<SieObject> objects) {
this.objects = objects;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
/*
public SieVoucherRow toVoucherRow() throws Exception {
SieVoucherRow vr = new SieVoucherRow();
return vr;
}
public SieVoucherRow toInvertedVoucherRow() throws Exception {
SieVoucherRow vr = toVoucherRow();
vr.setAmount(vr.getAmount() * -1);
return vr;
}
*/
}
|
3e1a01bf957bf024f29374acfc04bee0db4affae | 18,125 | java | Java | LIBS/BGXNode/server/main/modules/query/src/java/net/digitalxpert/quicklink/query/ejb/QueryServiceImplBean.java | ValKhv/BGX | e3d57c3a0d6e542d99f6c2828d6d787544d63f50 | [
"Apache-2.0"
] | 2 | 2018-09-27T04:43:33.000Z | 2019-10-23T14:32:31.000Z | LIBS/BGXNode/server/main/modules/query/src/java/net/digitalxpert/quicklink/query/ejb/QueryServiceImplBean.java | ValKhv/BGX | e3d57c3a0d6e542d99f6c2828d6d787544d63f50 | [
"Apache-2.0"
] | null | null | null | LIBS/BGXNode/server/main/modules/query/src/java/net/digitalxpert/quicklink/query/ejb/QueryServiceImplBean.java | ValKhv/BGX | e3d57c3a0d6e542d99f6c2828d6d787544d63f50 | [
"Apache-2.0"
] | 1 | 2018-04-25T00:44:42.000Z | 2018-04-25T00:44:42.000Z | 39.574236 | 139 | 0.606014 | 11,049 | package net.bgx.bgxnetwork.query.ejb;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.LinkedList;
import java.util.logging.Logger;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import net.bgx.bgxnetwork.persistence.query.GraphAnnotation;
import net.bgx.bgxnetwork.persistence.query.LayoutCoordinates;
import net.bgx.bgxnetwork.persistence.query.ParameterTypeEntity;
import net.bgx.bgxnetwork.persistence.query.ParameterValueEntity;
import net.bgx.bgxnetwork.persistence.query.QueryEntity;
import net.bgx.bgxnetwork.persistence.query.QueryTypeEntity;
import net.bgx.bgxnetwork.persistence.metadata.PropertyTypeView;
import net.bgx.bgxnetwork.persistence.metadata.ObjectType;
import net.bgx.bgxnetwork.persistence.metadata.PropertyType;
import net.bgx.bgxnetwork.query.interfaces.ExecuteServiceRemote;
import net.bgx.bgxnetwork.query.interfaces.QueryServiceImplLocal;
import net.bgx.bgxnetwork.system.SystemSetting;
import net.bgx.bgxnetwork.transfer.query.Query;
import net.bgx.bgxnetwork.transfer.query.QueryData;
import net.bgx.bgxnetwork.transfer.query.QueryParameterDataType;
import net.bgx.bgxnetwork.transfer.query.QueryParameterType;
import net.bgx.bgxnetwork.transfer.query.QueryStatus;
import net.bgx.bgxnetwork.transfer.query.QueryType;
import net.bgx.bgxnetwork.transfer.tt.TDPair;
import net.bgx.bgxnetwork.transfer.tt.TimedDiagrammDataSnapshot;
import net.bgx.bgxnetwork.transfer.tt.TransferControlObjectPair;
import net.bgx.bgxnetwork.exception.query.QueryDataException;
import net.bgx.bgxnetwork.exception.query.QueryBusinesException;
import net.bgx.bgxnetwork.exception.query.ErrorList;
import net.bgx.bgxnetwork.exception.query.QueryEJBException;
import org.jboss.annotation.security.SecurityDomain;
import org.jboss.resource.adapter.jdbc.WrappedCallableStatement;
import org.jboss.util.Base64;
import oracle.jdbc.driver.OracleTypes;
import oracle.jdbc.driver.OracleCallableStatement;
/**
* Class QueryServiceBean
*
* @author Yerokhin Yuri copyright by Zsoft Company
* @version 1.0
*/
@Stateless
@SecurityDomain(SystemSetting.SECURITY_DOMAIN)
public class QueryServiceImplBean implements QueryServiceImplLocal {
private static Logger log = Logger.getLogger(QueryServiceImplBean.class.getName());
public static final String netName = "pln";
@PersistenceContext(unitName = "business_manager")
private EntityManager manager;
@EJB
ExecuteServiceRemote executeService;
@Resource(mappedName = "java:/bgxnetworkDS_CORE")
private javax.sql.DataSource ds;
@RolesAllowed( { "LVSystem" })
public List<QueryType> getQueryTypeList() throws QueryDataException, QueryBusinesException {
List<QueryTypeEntity> res = null;
try{
javax.persistence.Query query = manager.createQuery("from QueryTypeEntity qte");
res = query.getResultList();
}catch (Exception e){
throwExecuteException(e);
}
List<QueryType> out = new ArrayList<QueryType>();
QueryType qt;
Boolean collection, optional;
QueryParameterDataType dt;
QueryParameterType pt;
for(QueryTypeEntity entity : res){
qt = new QueryType();
qt.setId(entity.getId());
qt.setName(entity.getName());
qt.setDescription(entity.getDescription());
qt.setDialogClassName(entity.getDialogClassName());
qt.setRoleName(entity.getRoleName());
for(ParameterTypeEntity param : entity.getParameters()){
if(param.getParameterId() == null || (pt = QueryParameterType.getByValue(param.getParameterId())) == null){
String message = "Parameter type id is invalid or missed.";
throw new QueryBusinesException(ErrorList.BUSINES_PARAMETERS_NOT_SET, new Object[] { message });
}
collection = param.getCollection();
if(collection != null && collection)
dt = QueryParameterDataType.Array;
else
dt = QueryParameterDataType.String;
optional = param.getOptional();
qt.addParameter(pt, dt, (optional != null && optional));
}
out.add(qt);
}
return out;
}
@RolesAllowed( { "LVSystem" })
public List<Query> getQueryList(Long accountId) throws QueryBusinesException, QueryDataException{
List<QueryEntity> res = null;
try{
javax.persistence.Query query =
manager.createQuery("from QueryEntity qe where ownerId=" + accountId+ " and qe.parent is null order by name");
res = query.getResultList();
}catch (Exception e){
throwExecuteException(e);
}
List<QueryType> types = getQueryTypeList();
List<Query> out = new ArrayList<Query>();
Query query;
for(QueryEntity qe : res){
if (qe.getParent() == null){
query = createTransfer(qe, types);
addChilds(query, qe);
out.add(query);
}
}
return out;
}
public List<Query> getQueryListByUser(Long accountId) throws QueryBusinesException, QueryDataException{
List<QueryEntity> res = null;
try{
javax.persistence.Query query =
manager.createQuery("from QueryEntity qe where ownerId=" + accountId+ " order by name");
res = query.getResultList();
}catch (Exception e){
throwExecuteException(e);
}
List<QueryType> types = getQueryTypeList();
List<Query> out = new ArrayList<Query>();
Query query;
for(QueryEntity qe : res){
query = createTransfer(qe, types);
out.add(query);
}
return out;
}
private void addChilds(Query parentQuery, QueryEntity parentQueryEntity) throws QueryBusinesException, QueryDataException {
List<QueryType> types = getQueryTypeList();
for (QueryEntity childEntity : parentQueryEntity.getChilds()){
Query childQuery = createTransfer(childEntity, types);
parentQuery.addChild(childQuery);
addChilds(childQuery, childEntity);
}
}
public static Query createTransfer(QueryEntity qe, List<QueryType> types) throws QueryBusinesException{
Query q;
QueryTypeEntity qte;
QueryParameterType pt = null;
Integer pti;
q = new Query();
q.setId(qe.getId());
q.setName(qe.getName());
qte = qe.getQueryType();
for(QueryType qt : types)
if(qt.getId() == qte.getId())
q.setQueryType(qt);
if(q.getQueryType() == null){
log.warning("Query " + qe.getName() + " is of unknown type.");
return null;
}
q.setDescription(qe.getDescription());
q.setCreatedDate(qe.getCreatedDate());
q.setCompletedDate(qe.getCompletedDate());
q.setStartedDate(qe.getStartedDate());
q.setNetworkName(qe.getNetworkName());
if (qe.getParent() == null)
q.setParent(null);
else q.setParent(qe.getParent().getId());
if(qe.getPercent() == null)
q.setPercent(0);
else
q.setPercent(qe.getPercent());
if(qe.getLimited() != null)
q.setObjectsLimit(qe.getLimited());
try{
QueryStatus qs = QueryStatus.getByValue(qe.getQueryStatus());
if(qs != null)
q.setQueryStatus(qs);
}catch (Exception e){
}
for(ParameterValueEntity param : qe.getParameterValues()){
pti = param.getParameterTypeId();
if(pti == null || (pt = QueryParameterType.getByValue(pti)) == null){
String message = "Unknown parameter type " + pti;
log.severe(message);
throw new QueryBusinesException(ErrorList.BUSINES_PARAMETERS_NOT_SET, new Object[] { message });
}
switch (q.getQueryType().getParameterDataType(pt)) {
case String:
q.addParameter(pt, param.getParameterValue());
break;
case Array:
List<String> list = (List<String>) q.getParameter(pt);
if(list == null){
list = new ArrayList<String>();
q.addParameter(pt, list);
}
list.add(param.getParameterValue());
}
}
//set Visible PropertyType
for(PropertyTypeView ptv : qe.getPropertyViews()){
if (ptv != null){
ObjectType objectType = ptv.getObjectType();
PropertyType propertyType = ptv.getPropertyType();
if (objectType != null && propertyType != null){
q.addViewAttribute((long)objectType.getIdObjectType(), propertyType);
}
}
}
return q;
}
@RolesAllowed( { "LVSystem" })
public QueryData getQueryData(long queryId, Locale clientLocale) throws QueryDataException, QueryBusinesException{
QueryEntity qe = findQueryEntityByID(queryId);
// try to instantiate executor
IExecutor executor = null;
try{
executor = (IExecutor) Class.forName(qe.getQueryType().getExecutorClassName()).newInstance();
executor.setDataSource(ds);
executor.setEntityManager(manager);
executor.setClientLocale(clientLocale);
}catch (Exception e){
throwInstantientExcecutorException("Cannot instantiate executor '" + qe.getQueryType().getExecutorClassName() + "' for query "
+ queryId);
}
QueryData data = executor.readQueryData(qe);
executor.doClose();
return data;
}
@RolesAllowed( { "LVSystem" })
public QueryData getNodeList(long queryId, int vxId, Locale clientLocale) throws QueryDataException, QueryBusinesException{
QueryEntity qe = findQueryEntityByID(queryId);
return executeService.getNodeList(qe, vxId, clientLocale);
}
@RolesAllowed( { "LVSystem" })
public boolean saveLayout(long queryId, LayoutCoordinates layout) throws QueryDataException{
QueryEntity qe = findQueryEntityByID(queryId);
try{
if(qe == null)
return false;
qe.getLob().setLayout(layout);
manager.merge(qe);
}catch (EJBException e){
throw new QueryEJBException(ErrorList.EJB_CANNOT_UPDATE_DATA);
}
return true;
}
@RolesAllowed( { "LVSystem" })
public LayoutCoordinates getLayout(long queryId) throws QueryDataException{
QueryEntity qe = findQueryEntityByID(queryId);
if(qe == null)
return null;
return qe.getLob().getLayout();
}
@RolesAllowed( { "LVSystem" })
public boolean saveAnnotation(long queryId, GraphAnnotation annotation){
log.warning("Not implemented.");
return false;
}
@RolesAllowed( { "LVSystem" })
public GraphAnnotation getAnnotation(long queryId){
log.warning("Not implemented.");
return null;
}
@RolesAllowed( { "LVSystem" })
public Query getQueryById(long queryId){
//for audit module (InfoAspect.java)
QueryEntity qe = null;
try{
qe = findQueryEntityByID(queryId);
}catch (QueryDataException ex){
ex.printStackTrace();
}
if(qe == null)
return null;
try{
List<QueryType> types = getQueryTypeList();
return createTransfer(qe, types);
}catch (Exception e){
return null;
}
}
@RolesAllowed( { "LVSystem" })
public String getExecutorNameByQuery(long queryId){
QueryEntity qe = null;
try{
qe = findQueryEntityByID(queryId);
return qe.getQueryType().getExecutorClassName();
}
catch (QueryDataException ex){
ex.printStackTrace();
return null;
}
}
private QueryEntity findQueryEntityByID(Long id) throws QueryDataException{
QueryEntity qe = null;
try{
qe = manager.find(QueryEntity.class, id);
}catch (Exception e){
throwExecuteException(e);
}
return qe;
}
private void throwInstantientExcecutorException(String message) throws QueryBusinesException{
log.severe(message);
throw new QueryBusinesException(ErrorList.BUSINES_CANNOT_INSTANTIATE_EXECUTOR, new Object[] { message });
}
private void throwExecuteException(Exception e) throws QueryDataException{
if(e instanceof IllegalArgumentException){
throw new QueryDataException(ErrorList.DATA_ILLEGAL_ARGUMENT_EXCEPTION);
}else{
throw new QueryDataException(ErrorList.DATA_CANNOT_FIND_DATA);
}
}
@RolesAllowed( { "LVSystem" })
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public List<String> getInnDictionary() throws QueryBusinesException, QueryDataException{
Connection con = null;
CallableStatement cstmt = null;
ArrayList<String> innMaskList = new ArrayList<String>();
try{
con = ds.getConnection();
String pctName = System.getProperty("QLDS.PACKET.SP_MAIN");
cstmt = con.prepareCall("{call QLDS." + pctName + ".GET_INN_MASK_LIST (?)}");
cstmt.registerOutParameter(1, OracleTypes.CURSOR);
cstmt.execute();
OracleCallableStatement ostmt = (OracleCallableStatement) ((WrappedCallableStatement) cstmt).getUnderlyingStatement();
ResultSet rs = ostmt.getCursor(1);
while (rs.next()){
innMaskList.add(rs.getString(1));
}
rs.close();
}
catch (SQLException e){
throw new QueryDataException(ErrorList.DATA_CONNECTION_ERROR);
}
finally{
try{
if(cstmt != null){
cstmt.close();
}
}catch (SQLException ex){
System.out.println(ex.toString());
}
try {
if(con != null && !con.isClosed()){
con.close();
}
}
catch (SQLException e) {
System.out.println(""+e);
}
}
return innMaskList;
}
@RolesAllowed( { "LVSystem" })
public boolean saveTTPairs(long queryId, LinkedList<TDPair> pairs) throws QueryDataException{
QueryEntity qe = findQueryEntityByID(queryId);
try{
if(qe == null)
return false;
LinkedList<Object> obj = new LinkedList<Object>();
for (TDPair pair : pairs){
obj.add(pair);
}
qe.getLob().setTimetablePairs(obj);
manager.merge(qe);
}catch (EJBException e){
throw new QueryEJBException(ErrorList.EJB_CANNOT_UPDATE_DATA);
}
return true;
}
@RolesAllowed( { "LVSystem" })
public LinkedList<TDPair> getTTPairs(long queryId) throws QueryDataException{
QueryEntity qe = findQueryEntityByID(queryId);
if(qe == null)
return null;
LinkedList<Object> objs = qe.getLob().getTimetablePairs();
LinkedList<TDPair> ret = new LinkedList<TDPair>();
if (objs != null)
for (Object obj : objs)
ret.add((TDPair)obj);
return ret;
}
// public boolean saveTTParameters(long queryId, Object data) throws QueryDataException {
// QueryEntity qe = findQueryEntityByID(queryId);
// try{
// if(qe == null)
// return false;
//
// qe.getLob().setTimetableParameters((TimedDiagrammDataSnapshot)data);
// manager.merge(qe);
// }catch (EJBException e){
// throw new QueryEJBException(ErrorList.EJB_CANNOT_UPDATE_DATA);
// }
// return true;
// }
@RolesAllowed( { "LVSystem" })
public boolean saveTTParameters(long queryId, TimedDiagrammDataSnapshot data) throws QueryDataException {
QueryEntity qe = findQueryEntityByID(queryId);
try{
if(qe == null)
return false;
ArrayList<Object> objs = new ArrayList<Object>();
objs.add(data);
qe.getLob().setTimetableParameters(objs);
manager.merge(qe);
}catch (EJBException e){
throw new QueryEJBException(ErrorList.EJB_CANNOT_UPDATE_DATA);
}
return true;
}
@RolesAllowed( { "LVSystem" })
public TimedDiagrammDataSnapshot getTTParameters(long queryId) throws QueryDataException {
QueryEntity qe = findQueryEntityByID(queryId);
if(qe == null)
return null;
ArrayList<Object> objs = qe.getLob().getTimetableParameters();
if (objs.size() >0){
TimedDiagrammDataSnapshot ret = (TimedDiagrammDataSnapshot)objs.get(0);
return ret;
}
return null;
}
}
|
3e1a0268c495914f5759e85814d5bd63e2ecf61a | 803 | java | Java | ExercicioContagem.java | Carlos-MCV/LogicaDeProgramacaoJAVA | 8a879a5adaef63865c4226a244c69492fee34fec | [
"MIT"
] | null | null | null | ExercicioContagem.java | Carlos-MCV/LogicaDeProgramacaoJAVA | 8a879a5adaef63865c4226a244c69492fee34fec | [
"MIT"
] | null | null | null | ExercicioContagem.java | Carlos-MCV/LogicaDeProgramacaoJAVA | 8a879a5adaef63865c4226a244c69492fee34fec | [
"MIT"
] | null | null | null | 22.942857 | 79 | 0.603985 | 11,050 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package exerciciocontagem;
import java.util.Scanner;
/**
*
* @author carli
*/
public class ExercicioContagem {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner teclado=new Scanner(System.in);
System.out.println("Digite um número:");
int numero=teclado.nextInt();
int contador=0;
if (numero==0){
System.out.println(0);
}
while(contador!=numero){
contador++;
System.out.println(contador);
}
}
}
|
3e1a0391269e2ef7397ae1144b5e3854da947956 | 4,459 | java | Java | src/main/java/com/sangupta/jerry/security/SecurityContext.java | sangupta/jerry-core | 1d5439dea73b81cb8dea0c9138a2db757029f65d | [
"Apache-2.0"
] | 5 | 2016-01-28T11:11:21.000Z | 2019-11-25T09:56:48.000Z | src/main/java/com/sangupta/jerry/security/SecurityContext.java | sangupta/jerry-core | 1d5439dea73b81cb8dea0c9138a2db757029f65d | [
"Apache-2.0"
] | 16 | 2015-03-23T11:24:17.000Z | 2021-08-25T15:34:37.000Z | src/main/java/com/sangupta/jerry/security/SecurityContext.java | sangupta/jerry-core | 1d5439dea73b81cb8dea0c9138a2db757029f65d | [
"Apache-2.0"
] | 2 | 2016-06-21T23:12:34.000Z | 2017-10-15T06:18:24.000Z | 24.5 | 103 | 0.682889 | 11,051 | /**
*
* jerry - Common Java Functionality
* Copyright (c) 2012-present, Sandeep Gupta
*
* https://sangupta.com/projects/jerry-core
*
* 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.sangupta.jerry.security;
import java.security.Principal;
import com.sangupta.jerry.entity.UserAwarePrincipal;
import com.sangupta.jerry.util.AssertUtils;
/**
* A simple context that holds the currently valid {@link Principal} for proper
* authentication and authorization.
*
* @author sangupta
*
* @since 1.0.0
*
*/
public class SecurityContext {
/**
* Thread local instance to store the principal per thread
*/
private static final ThreadLocal<UserAwarePrincipal> PRINCIPAL_HOLDER = new ThreadLocal<>();
/**
* Thread local instance to store the auth token if provided by the header
*/
private static final ThreadLocal<String> TOKEN_HOLDER = new ThreadLocal<>();
/**
* Thread local instance to store the tenant per thread
*/
private static final ThreadLocal<String> TENANT_HOLDER = new ThreadLocal<>();
/**
*
*/
private static Class<? extends UserAwarePrincipal> userClass = null;
/**
* Setup a principal in this context.
*
* @param principal the {@link Principal} instance of use for the currently
* signed-in user
*/
public static void setPrincipal(UserAwarePrincipal principal) {
PRINCIPAL_HOLDER.set(principal);
}
/**
* Setup a tenant in this context.
*
* @param tenant the {@link String} based id for the tenant for which this
* request is flowing.
*/
public static void setTenant(String tenant) {
TENANT_HOLDER.set(tenant);
}
public static void setUserClass(Class<? extends UserAwarePrincipal> userClass) {
SecurityContext.userClass = userClass;
}
/**
* Return the currently set principal
*
* @return the current principal, or the anonymous principal object if set
*
*/
public static UserAwarePrincipal getPrincipal() {
return PRINCIPAL_HOLDER.get();
}
@SuppressWarnings("unchecked")
public static <T> T getUser() {
if(SecurityContext.userClass == null) {
throw new IllegalStateException("Must set the user class via SecurityContext.setUserClass()");
}
UserAwarePrincipal principal = getPrincipal();
if(principal == null) {
return null;
}
return (T) SecurityContext.userClass.cast(principal);
}
public static String getUserToken() {
return TOKEN_HOLDER.get();
}
public static void setUserToken(String token) {
TOKEN_HOLDER.set(token);
}
/**
* Returns the user ID for the currently set {@link Principal}.
*
* @since 4.0.0
*
* @return
*/
public static String getUserID() {
UserAwarePrincipal principal = getPrincipal();
if(principal == null) {
return null;
}
return principal.getUserID();
}
/**
* Check if the current user is anonymous or not.
*
* @return <code>true</code> if no principal is set, or if the currently set
* principal is the anonymous identified principal; <code>false</code>
* otherwise
*/
public static boolean isAnonymousUser() {
Principal principal = PRINCIPAL_HOLDER.get();
if (principal == null) {
return true;
}
return false;
}
/**
* Check if the tenant ID provided is the same as the tenant
* in the {@link SecurityContext}.
*
* @param tenant
* @return
*/
public static boolean isSameTenant(String tenant) {
String current = TENANT_HOLDER.get();
if(AssertUtils.isEmpty(current)) {
if(AssertUtils.isEmpty(tenant)) {
return true;
}
return false;
}
return current.equals(tenant);
}
public static void clearPrincipal() {
PRINCIPAL_HOLDER.remove();
}
/**
* Clear the security context of the set principal and tenant values.
*
*/
public static void clear() {
PRINCIPAL_HOLDER.remove();
TENANT_HOLDER.remove();
TOKEN_HOLDER.remove();
}
}
|
3e1a039716a303d8886aa20de61b4174bd68f37f | 604 | java | Java | JedaApi/src/main/java/fr/ippon/tlse/domain/DictionnaryDomain.java | KaratsuFr/Jeda | 6008218c07e45373cb03f4c62b6069ef6b51616a | [
"MIT"
] | null | null | null | JedaApi/src/main/java/fr/ippon/tlse/domain/DictionnaryDomain.java | KaratsuFr/Jeda | 6008218c07e45373cb03f4c62b6069ef6b51616a | [
"MIT"
] | null | null | null | JedaApi/src/main/java/fr/ippon/tlse/domain/DictionnaryDomain.java | KaratsuFr/Jeda | 6008218c07e45373cb03f4c62b6069ef6b51616a | [
"MIT"
] | null | null | null | 22.37037 | 88 | 0.745033 | 11,052 | package fr.ippon.tlse.domain;
import lombok.Data;
import fr.ippon.tlse.annotation.Description;
import fr.ippon.tlse.annotation.Id;
/**
* Dictonnary Domain are abstract class to have special domain value : key / value <br/>
* Usefull for selectbox, constant.... <br/>
*
* @author mpages
*
*/
@Data
public abstract class DictionnaryDomain {
@Id
@Description("Key of dictionnary to get corresponding key")
private String key;
@Description("Value of dictionnary for corresponding key")
private String value;
@Description("Long description of dictionnary Key value")
String description;
}
|
3e1a043316943fe861f32e8601c67534940fb163 | 14,274 | java | Java | common/src/main/java/com/tencent/angel/serving/apis/session/SessionServiceGrpc.java | raohuaming/angel-serving | 75b300d8a6a44f75a6e368be105e2698f60710e3 | [
"Apache-2.0"
] | 63 | 2018-09-28T02:38:43.000Z | 2022-02-23T10:00:14.000Z | common/src/main/java/com/tencent/angel/serving/apis/session/SessionServiceGrpc.java | raohuaming/angel-serving | 75b300d8a6a44f75a6e368be105e2698f60710e3 | [
"Apache-2.0"
] | 6 | 2019-04-10T14:15:37.000Z | 2020-08-14T07:38:39.000Z | common/src/main/java/com/tencent/angel/serving/apis/session/SessionServiceGrpc.java | raohuaming/angel-serving | 75b300d8a6a44f75a6e368be105e2698f60710e3 | [
"Apache-2.0"
] | 29 | 2018-11-13T06:09:30.000Z | 2022-01-29T09:28:42.000Z | 42.106195 | 210 | 0.739036 | 11,053 | /*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. 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
*
* https://opensource.org/licenses/Apache-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.tencent.angel.serving.apis.session;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
* <pre>
* SessionService defines a service with which a client can interact to execute
* Tensorflow model inference. The SessionService::SessionRun method is similar
* to MasterService::RunStep of Tensorflow, except that all sessions are ready
* to run, and you request a specific model/session with ModelSpec.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.17.1)",
comments = "Source: apis/session/session_service.proto")
public final class SessionServiceGrpc {
private SessionServiceGrpc() {}
public static final String SERVICE_NAME = "angel.serving.SessionService";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest,
com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse> getSessionRunMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "SessionRun",
requestType = com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest.class,
responseType = com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest,
com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse> getSessionRunMethod() {
io.grpc.MethodDescriptor<com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest, com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse> getSessionRunMethod;
if ((getSessionRunMethod = SessionServiceGrpc.getSessionRunMethod) == null) {
synchronized (SessionServiceGrpc.class) {
if ((getSessionRunMethod = SessionServiceGrpc.getSessionRunMethod) == null) {
SessionServiceGrpc.getSessionRunMethod = getSessionRunMethod =
io.grpc.MethodDescriptor.<com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest, com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(
"angel.serving.SessionService", "SessionRun"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(
com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse.getDefaultInstance()))
.setSchemaDescriptor(new SessionServiceMethodDescriptorSupplier("SessionRun"))
.build();
}
}
}
return getSessionRunMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static SessionServiceStub newStub(io.grpc.Channel channel) {
return new SessionServiceStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static SessionServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new SessionServiceBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static SessionServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
return new SessionServiceFutureStub(channel);
}
/**
* <pre>
* SessionService defines a service with which a client can interact to execute
* Tensorflow model inference. The SessionService::SessionRun method is similar
* to MasterService::RunStep of Tensorflow, except that all sessions are ready
* to run, and you request a specific model/session with ModelSpec.
* </pre>
*/
public static abstract class SessionServiceImplBase implements io.grpc.BindableService {
/**
* <pre>
* Runs inference of a given model.
* </pre>
*/
public void sessionRun(com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse> responseObserver) {
asyncUnimplementedUnaryCall(getSessionRunMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getSessionRunMethod(),
asyncUnaryCall(
new MethodHandlers<
com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest,
com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse>(
this, METHODID_SESSION_RUN)))
.build();
}
}
/**
* <pre>
* SessionService defines a service with which a client can interact to execute
* Tensorflow model inference. The SessionService::SessionRun method is similar
* to MasterService::RunStep of Tensorflow, except that all sessions are ready
* to run, and you request a specific model/session with ModelSpec.
* </pre>
*/
public static final class SessionServiceStub extends io.grpc.stub.AbstractStub<SessionServiceStub> {
private SessionServiceStub(io.grpc.Channel channel) {
super(channel);
}
private SessionServiceStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected SessionServiceStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new SessionServiceStub(channel, callOptions);
}
/**
* <pre>
* Runs inference of a given model.
* </pre>
*/
public void sessionRun(com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(getSessionRunMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* <pre>
* SessionService defines a service with which a client can interact to execute
* Tensorflow model inference. The SessionService::SessionRun method is similar
* to MasterService::RunStep of Tensorflow, except that all sessions are ready
* to run, and you request a specific model/session with ModelSpec.
* </pre>
*/
public static final class SessionServiceBlockingStub extends io.grpc.stub.AbstractStub<SessionServiceBlockingStub> {
private SessionServiceBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private SessionServiceBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected SessionServiceBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new SessionServiceBlockingStub(channel, callOptions);
}
/**
* <pre>
* Runs inference of a given model.
* </pre>
*/
public com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse sessionRun(com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest request) {
return blockingUnaryCall(
getChannel(), getSessionRunMethod(), getCallOptions(), request);
}
}
/**
* <pre>
* SessionService defines a service with which a client can interact to execute
* Tensorflow model inference. The SessionService::SessionRun method is similar
* to MasterService::RunStep of Tensorflow, except that all sessions are ready
* to run, and you request a specific model/session with ModelSpec.
* </pre>
*/
public static final class SessionServiceFutureStub extends io.grpc.stub.AbstractStub<SessionServiceFutureStub> {
private SessionServiceFutureStub(io.grpc.Channel channel) {
super(channel);
}
private SessionServiceFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected SessionServiceFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new SessionServiceFutureStub(channel, callOptions);
}
/**
* <pre>
* Runs inference of a given model.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse> sessionRun(
com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest request) {
return futureUnaryCall(
getChannel().newCall(getSessionRunMethod(), getCallOptions()), request);
}
}
private static final int METHODID_SESSION_RUN = 0;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final SessionServiceImplBase serviceImpl;
private final int methodId;
MethodHandlers(SessionServiceImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_SESSION_RUN:
serviceImpl.sessionRun((com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunRequest) request,
(io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.session.SessionServiceProtos.SessionRunResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
private static abstract class SessionServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier {
SessionServiceBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.tencent.angel.serving.apis.session.SessionServiceProtos.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("SessionService");
}
}
private static final class SessionServiceFileDescriptorSupplier
extends SessionServiceBaseDescriptorSupplier {
SessionServiceFileDescriptorSupplier() {}
}
private static final class SessionServiceMethodDescriptorSupplier
extends SessionServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final String methodName;
SessionServiceMethodDescriptorSupplier(String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (SessionServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new SessionServiceFileDescriptorSupplier())
.addMethod(getSessionRunMethod())
.build();
}
}
}
return result;
}
}
|
3e1a043a798556b527b442f491fcc864c88e1881 | 3,358 | java | Java | server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportDeleteStoredScriptAction.java | carl10086/myes7 | 42d597ef3df0c98625715b21504732a075b5dd39 | [
"Apache-2.0"
] | 3 | 2017-05-31T14:46:18.000Z | 2022-02-15T08:04:05.000Z | server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportDeleteStoredScriptAction.java | carl10086/myes7 | 42d597ef3df0c98625715b21504732a075b5dd39 | [
"Apache-2.0"
] | 1 | 2020-09-28T15:52:16.000Z | 2020-09-28T15:52:16.000Z | server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/TransportDeleteStoredScriptAction.java | carl10086/myes7 | 42d597ef3df0c98625715b21504732a075b5dd39 | [
"Apache-2.0"
] | 1 | 2019-03-02T20:28:31.000Z | 2019-03-02T20:28:31.000Z | 42.506329 | 133 | 0.769506 | 11,054 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.action.admin.cluster.storedscripts;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.support.master.TransportMasterNodeAction;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.io.IOException;
public class TransportDeleteStoredScriptAction extends TransportMasterNodeAction<DeleteStoredScriptRequest, AcknowledgedResponse> {
private final ScriptService scriptService;
@Inject
public TransportDeleteStoredScriptAction(TransportService transportService, ClusterService clusterService, ThreadPool threadPool,
ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver,
ScriptService scriptService) {
super(DeleteStoredScriptAction.NAME, transportService, clusterService, threadPool, actionFilters,
indexNameExpressionResolver, DeleteStoredScriptRequest::new);
this.scriptService = scriptService;
}
@Override
protected String executor() {
return ThreadPool.Names.SAME;
}
@Override
protected AcknowledgedResponse read(StreamInput in) throws IOException {
return new AcknowledgedResponse(in);
}
@Override
protected AcknowledgedResponse newResponse() {
throw new UnsupportedOperationException("usage of Streamable is to be replaced by Writeable");
}
@Override
protected void masterOperation(DeleteStoredScriptRequest request, ClusterState state,
ActionListener<AcknowledgedResponse> listener) throws Exception {
scriptService.deleteStoredScript(clusterService, request, listener);
}
@Override
protected ClusterBlockException checkBlock(DeleteStoredScriptRequest request, ClusterState state) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_WRITE);
}
}
|
3e1a05c870de522410674fc68c557ecacc17becf | 11,352 | java | Java | functional/SyntheticGCWorkload/src/net/adoptopenjdk/casa/util/Utilities.java | hangshao0/openjdk-tests | 7e0b74c8931e957c68c953ad798fdd7cc96f329b | [
"Apache-2.0"
] | 96 | 2017-05-23T15:47:36.000Z | 2021-04-25T17:26:02.000Z | functional/SyntheticGCWorkload/src/net/adoptopenjdk/casa/util/Utilities.java | hangshao0/openjdk-tests | 7e0b74c8931e957c68c953ad798fdd7cc96f329b | [
"Apache-2.0"
] | 2,005 | 2017-04-25T13:25:57.000Z | 2021-04-29T07:21:36.000Z | functional/SyntheticGCWorkload/src/net/adoptopenjdk/casa/util/Utilities.java | hangshao0/openjdk-tests | 7e0b74c8931e957c68c953ad798fdd7cc96f329b | [
"Apache-2.0"
] | 173 | 2017-04-21T15:33:50.000Z | 2021-04-28T22:39:50.000Z | 26.900474 | 142 | 0.647111 | 11,055 | /*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package net.adoptopenjdk.casa.util;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Random;
/**
* General utility functions used throughout the benchmark
*
*
*/
public class Utilities
{
protected static final Random randomInstance = new Random();
/**
* Rounds the given double to the given number of decimal places.
*
* @param number
* @param decimalPlaces
* @return
*/
public static double roundDouble(double number, int decimalPlaces)
{
return Math.round((number * Math.pow(10,decimalPlaces)))/Math.pow(10.0,decimalPlaces);
}
/**
* The same functionality as formatDataSize(double), but accepts a long.
*
* @param bytes
* @return
*/
public static String formatDataSize(long bytes)
{
return formatDataSize((double) bytes);
}
/**
* Formats the given proportion as a percent suffixed with the "%" sign.
*
* @param proportion - a number representing a proportion or ratio
* @return the proportion formatted as a percent, including the sign.
*/
public static String formatProportionAsPercent(double proportion, int significantDigits)
{
return String.format("%." + significantDigits + "g", proportion * (double)100.0) + "%";
}
public static String formatTime(double time)
{
return formatTime(time, 3);
}
/**
* Formats the given time (in seconds) using the most appropriate
* units and returns the formatted string including the unit symbol.
*
* @param time - time in seconds, nanosecond precision.
* @return a string with a number rounded to three significant figures, suffixed by a time unit. No unit will be appended if the time is 0.
*/
public static String formatTime(double time, int significantFigures)
{
// Pick a unit that fits the time.
if (time < 1E-9)
return "0";
else if (time < 1E-6)
return String.format("%." + significantFigures + "g", time*1E9) + "ns";
else if (time < 1E-3)
return String.format("%." + significantFigures + "g", time*1E6) + "us";
else if (time < 1)
return String.format("%." + significantFigures + "g", time*1E3) + "ms";
else if (time < 60)
return String.format("%." + significantFigures + "g", time) + "s";
else if (time/60 < 60)
return String.format("%." + significantFigures + "g", time/60) + "m";
else if (time/60/60 < 24)
return String.format("%." + significantFigures + "g", time/60/60) + "h";
else
return String.format("%." + significantFigures + "g", time/60/60/24) + "d";
}
/**
* Formats the given data size (in bytes) in an appropriate binary unit and
* returns it as a string with the proper suffix.
*
* @param bytes - data size to be formatted, in bytes.
*/
public static String formatDataSize(double bytes)
{
StringBuilder builder = new StringBuilder();
Double size = bytes;
/*
* Keep dividing by 1024 until the resulting number is under
* 1000; 1000 rather than 1024 avoids scientific notation.
*
* The number of divisions is capped at 9. The resulting
* number will be a round binary data unit.
*/
int divisions = 0;
while (size >= 1000 && divisions < 9)
{
size /= 1024;
divisions++;
}
builder.append(String.format("%.3g", size));
/*
* Choose the unit based on the number of times we divided
* by 1024.
*/
switch (divisions) {
case 0: break;
case 1: builder.append('k'); break;
case 2: builder.append('M'); break;
case 3: builder.append('G'); break;
case 4: builder.append('T'); break;
case 5: builder.append('P'); break;
case 6: builder.append('E'); break;
case 7: builder.append('Z'); break;
case 8: builder.append('Y'); break;
default: return "[format error]";
}
builder.append('B');
return builder.toString();
}
/**
* Returns the formatted data size followed by "/s"
*
* @param dataRate
* @return
*/
public static String formatDataRate(double dataRate) {
return formatDataSize(dataRate) + "/s";
}
/**
* Gets the current time in seconds as a double down to the nanosecond. This
* is not the system time and can only be used to compute relative times.
*
* @return current time in seconds to the precision of System.nanoTime()
*/
public static double getTime()
{
return (System.nanoTime() / 1E9);
}
/**
* Gets the current absolute system time in seconds, accurate
* to the millisecond.
*
* @return current time in seconds to the precision of System.currentTimeMillis()
*/
public static double getAbsoluteTime()
{
return (System.currentTimeMillis() / 1E3);
}
/**
* Sleep for the given amount of time, rounded to the
* nearest nanosecond.
*
* Throws an InterruptedException if interrupted.
*
* If the sleepTime is less than or equal to zero, this
* method returns immediately.
*
* @param sleepTime - sleep time in seconds.
* @throws InterruptedException - thrown if Thread.sleep is interrupted.
*/
public static void idle(double sleepTime) throws InterruptedException
{
if (sleepTime > 0)
{
// Get the number of whole milliseconds
long millis = getMillis(sleepTime);
// Get the nanoseconds from the remainder.
int nanos = getNanos(sleepTime, millis);
// Both numbers must be nonnegative and one of them must be nonzero.
if (millis >= 0 && nanos >= 0 && (millis > 0 || nanos > 0))
Thread.sleep(millis, nanos);
}
}
/**
* Upon acquiring the monitor, waits the given period of time
* OR until monitor.notify() is called OR until interrupted.
*
* Returns immediately if the time is not greater than zero.
*
* @param monitor
* @param time
* @throws InterruptedException
*/
public static void wait(Object monitor, double time) throws InterruptedException
{
if (time > 0)
{
// Get the number of whole milliseconds
long millis = getMillis(time);
// Get the nanoseconds from the remainder.
int nanos = getNanos(time, millis);
// Both numbers must be nonnegative and one of them must be nonzero.
if(millis >= 0 && nanos >= 0 && (millis > 0 || nanos > 0))
{
synchronized(monitor)
{
monitor.wait(millis, nanos);
}
}
}
}
/**
* Returns the rounded number of nanoseconds remaining when all whole
* milliseconds are subtracted off.
*
* @param time
* @return
*/
public static int getNanos(double time)
{
return getNanos(time, getMillis(time));
}
/**
* Returns the rounded number of nanoseconds when the given number
* of milliseconds are subtracted. The result will be truncated to the
* size of an integer after rounding.
*
* @param time
* @param millis
* @return
*/
public static int getNanos(double time, long millis)
{
// Get the nanoseconds from the remainder after the millis have been removed.
return (int)Math.round((time * 1E9) - (millis * 1E6));
}
/**
* Returns the number of whole milliseconds composing the
* time.
*
* @param time
* @return
*/
public static long getMillis(double time)
{
// Get the number of whole milliseconds.
return (long)Math.floor(time * 1E3);
}
/**
* Generates a Gaussian-distributed random data size according to the given
* variance and radius, between the given min and max and conforming to the
* supplied alignment.
*
* @param mean
* @param variance
* @param radius
* @param min
* @param max
* @param alignment
* @return
*/
public static long generateGaussianDataSize(long mean, double variance, long radius, long min, long max, long alignment)
{
if (variance == 0 || radius == 0)
return mean;
do
{
// Generate a possible size.
long candidateSize = Math.round((randomInstance.nextGaussian() * variance + (double)mean)/(double)alignment) * alignment;
// If it fits the radius, use it. If not, try again.
if (
candidateSize >= min
&& candidateSize <= max
)
{
return candidateSize;
}
} while (true);
}
/**
* Generates a random data size between the given min and max and
* conforming to the given alignment.
*
* @param min
* @param max
* @param alignment
* @return
*/
public static long generateRandomDataSize(long min, long max, long alignment)
{
// Check that the range actually includes room for randomness. If it doesn't, return the min.
if (max - min <= 0)
return min;
do
{
// Generate a size.
long candidateSize = Math.round((randomInstance.nextDouble() * (max - min) + (double)min)/(double)alignment) * alignment;
// If it fits within the min and max, use it. Otherwise, reject it and try again.
if (
candidateSize >= min
&& candidateSize <= max
)
{
return candidateSize;
}
} while (true);
}
/**
* Generates a flat random time around the given mean out to the givne radius and greater than zero.
*
* @param mean
* @param radius
* @return
*/
public static double generateRandomTime(double mean, double radius)
{
if (radius == 0)
return mean;
do
{
// Generate a lifespan
double candidateLifespan = (randomInstance.nextDouble() * (radius * 2)) + (mean - radius);
// If it fits in the radius, return it. Otherwise, try again.
if (
candidateLifespan > 0
&& candidateLifespan >= mean - radius
&& candidateLifespan <= mean + radius
)
{
return candidateLifespan;
}
} while (true);
}
/**
* Generates a Gaussian-distributed random time around the given mean accoring to the given
* variance and out to the given radius. If the radius intersects zero, the
* distribution will no longer be normal or centered around the mean.
*
* @param mean
* @param variance
* @param radius
* @return
*/
public static double generateGaussianTime(double mean, double variance, double radius)
{
if (variance == 0 || radius == 0)
return mean;
do
{
// Generate a lifespan
double candidateLifespan = randomInstance.nextGaussian() * variance + mean;
// If it fits in the radius, return it. Otherwise, try again.
if (
candidateLifespan > 0
&& candidateLifespan >= mean - radius
&& candidateLifespan <= mean + radius
)
{
return candidateLifespan;
}
} while (true);
}
/**
* Gets the VM's command line arguments
*/
public static String printVMArgs()
{
//Print out JVM arguments for reference
List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
return inputArguments.toString();
}
}
|
3e1a0620fdae575b33d12b25a55815300aa9aa6c | 1,511 | java | Java | jaxrs-async/src/main/java/com/hantsylabs/example/ee8/jaxrs/CompletionStageResource.java | hantsy/ee8-sandbox | 60f68cb76d9d441a9600bc48b13c7e2e31f1b591 | [
"Apache-2.0"
] | 57 | 2016-05-16T08:35:58.000Z | 2022-01-18T19:42:12.000Z | jaxrs-async/src/main/java/com/hantsylabs/example/ee8/jaxrs/CompletionStageResource.java | hantsy/ee8-sandbox | 60f68cb76d9d441a9600bc48b13c7e2e31f1b591 | [
"Apache-2.0"
] | 1 | 2018-11-13T16:02:04.000Z | 2018-11-18T10:55:52.000Z | jaxrs-async/src/main/java/com/hantsylabs/example/ee8/jaxrs/CompletionStageResource.java | hantsy/ee8-sandbox | 60f68cb76d9d441a9600bc48b13c7e2e31f1b591 | [
"Apache-2.0"
] | 37 | 2016-03-05T14:21:49.000Z | 2022-01-18T19:41:59.000Z | 28.509434 | 105 | 0.585705 | 11,056 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hantsylabs.example.ee8.jaxrs;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
/**
*
* @author hantsy
*/
@Path("cs")
@Stateless
public class CompletionStageResource {
@Resource
private ManagedExecutorService executor;
@Inject
Logger LOG;
@GET
public CompletionStage<String> getAsync() {
CompletionStage<String> cs = CompletableFuture
.<String>supplyAsync(
() -> {
try {
LOG.log(Level.INFO, " execute long run task in CompletionStageResource");
Thread.sleep(500);
} catch (InterruptedException ex) {
LOG.log(Level.SEVERE, "error :" +ex.getMessage());
}
return "return CompletableFuture instead of @Suspended";
}
// , executor
);
return cs;
}
}
|
3e1a062d9660aab8791d4eda72be70959cbeed67 | 52,277 | java | Java | src/main/java/com/google/devtools/build/lib/analysis/actions/CustomCommandLine.java | sluongng/bazel | c1db56c5c638823c20ad5d0897028074971c64fe | [
"Apache-2.0"
] | 1 | 2022-03-17T05:59:18.000Z | 2022-03-17T05:59:18.000Z | src/main/java/com/google/devtools/build/lib/analysis/actions/CustomCommandLine.java | sgowroji/bazel | b3baae9720653a9c6fa8d97780d59331bd590e23 | [
"Apache-2.0"
] | 3 | 2022-03-23T17:53:44.000Z | 2022-03-23T17:54:01.000Z | src/main/java/com/google/devtools/build/lib/analysis/actions/CustomCommandLine.java | sgowroji/bazel | b3baae9720653a9c6fa8d97780d59331bd590e23 | [
"Apache-2.0"
] | 1 | 2022-01-12T18:08:14.000Z | 2022-01-12T18:08:14.000Z | 37.609353 | 104 | 0.674905 | 11,057 | // Copyright 2014 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.actions;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Interner;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander;
import com.google.devtools.build.lib.actions.Artifact.DerivedArtifact;
import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact;
import com.google.devtools.build.lib.actions.CommandLine;
import com.google.devtools.build.lib.actions.CommandLineExpansionException;
import com.google.devtools.build.lib.actions.CommandLineItem;
import com.google.devtools.build.lib.actions.PathStripper;
import com.google.devtools.build.lib.actions.SingleStringArgFormatter;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.concurrent.BlazeInterners;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.VisibleForSerialization;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.SerializationConstant;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.util.OnDemandString;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.errorprone.annotations.CompileTimeConstant;
import com.google.errorprone.annotations.FormatMethod;
import com.google.errorprone.annotations.FormatString;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.function.Consumer;
import javax.annotation.Nullable;
/** A customizable, serializable class for building memory efficient command lines. */
@Immutable
public class CustomCommandLine extends CommandLine {
private interface ArgvFragment {
/**
* Expands this fragment into the passed command line vector.
*
* @param arguments The command line's argument vector.
* @param argi The index of the next available argument.
* @param builder The command line builder to which we should add arguments.
* @param stripOutputPaths Strip output path config prefixes? See {@link PathStripper}.
* @return The index of the next argument, after the ArgvFragment has consumed its args. If the
* ArgvFragment doesn't have any args, it should return {@code argi} unmodified.
*/
int eval(
List<Object> arguments,
int argi,
ImmutableList.Builder<String> builder,
boolean stripOutputPaths)
throws CommandLineExpansionException, InterruptedException;
int addToFingerprint(
List<Object> arguments,
int argi,
ActionKeyContext actionKeyContext,
Fingerprint fingerprint)
throws CommandLineExpansionException, InterruptedException;
}
/**
* Helper base class for an ArgvFragment that doesn't use the input argument vector.
*
* <p>This can be used for any ArgvFragments that self-contain all the necessary state.
*/
private abstract static class StandardArgvFragment implements ArgvFragment {
@Override
public final int eval(
List<Object> arguments,
int argi,
ImmutableList.Builder<String> builder,
boolean stripOutputPaths) {
eval(builder);
return argi; // Doesn't consume any arguments, so return argi unmodified
}
abstract void eval(ImmutableList.Builder<String> builder);
@Override
public int addToFingerprint(
List<Object> arguments,
int argi,
ActionKeyContext actionKeyContext,
Fingerprint fingerprint) {
addToFingerprint(actionKeyContext, fingerprint);
return argi; // Doesn't consume any arguments, so return argi unmodified
}
abstract void addToFingerprint(ActionKeyContext actionKeyContext, Fingerprint fingerprint);
}
/**
* An ArgvFragment that expands a collection of objects in a user-specified way.
*
* <p>Vector args support formatting, interspersing args (adding strings before each value),
* joining, and mapping custom types. Please use this whenever you need to transform lists or
* nested sets instead of doing it manually, as use of this class is more memory efficient.
*
* <p>The order of evaluation is:
*
* <ul>
* <li>Map the type T to a string using a custom map function, if any, or
* <li>Map any non-string type {PathFragment, Artifact} to their path/exec path
* <li>Format the string using the supplied format string, if any
* <li>Add the arguments each prepended by the before string, if any, or
* <li>Join the arguments with the join string, if any, or
* <li>Simply add all arguments
* </ul>
*
* <pre>{@code
* Examples:
*
* List<String> values = ImmutableList.of("1", "2", "3");
*
* commandBuilder.addAll(VectorArg.format("-l%s").each(values))
* -> ["-l1", "-l2", "-l3"]
*
* commandBuilder.addAll(VectorArg.addBefore("-l").each(values))
* -> ["-l", "1", "-l", "2", "-l", "3"]
*
* commandBuilder.addAll(VectorArg.join(":").each(values))
* -> ["1:2:3"]
* }</pre>
*/
public static class VectorArg<T> {
final boolean isNestedSet;
final boolean isEmpty;
final int count;
final String formatEach;
final String beforeEach;
final String joinWith;
private VectorArg(
boolean isNestedSet,
boolean isEmpty,
int count,
String formatEach,
String beforeEach,
String joinWith) {
this.isNestedSet = isNestedSet;
this.isEmpty = isEmpty;
this.count = count;
this.formatEach = formatEach;
this.beforeEach = beforeEach;
this.joinWith = joinWith;
}
/**
* A vector arg that doesn't map its parameters.
*
* <p>Call {@link SimpleVectorArg#mapped} to produce a vector arg that maps from a given type to
* a string.
*/
public static class SimpleVectorArg<T> extends VectorArg<T> {
private final Object values;
private SimpleVectorArg(Builder builder, @Nullable Collection<T> values) {
this(
/* isNestedSet= */ false,
values == null || values.isEmpty(),
values != null ? values.size() : 0,
builder.formatEach,
builder.beforeEach,
builder.joinWith,
values);
}
private SimpleVectorArg(Builder builder, @Nullable NestedSet<T> values) {
this(
/* isNestedSet= */ true,
values == null || values.isEmpty(),
/* count= */ -1,
builder.formatEach,
builder.beforeEach,
builder.joinWith,
values);
}
private SimpleVectorArg(
boolean isNestedSet,
boolean isEmpty,
int count,
String formatEach,
String beforeEach,
String joinWith,
@Nullable Object values) {
super(isNestedSet, isEmpty, count, formatEach, beforeEach, joinWith);
this.values = values;
}
/** Each argument is mapped using the supplied map function */
public MappedVectorArg<T> mapped(CommandLineItem.MapFn<? super T> mapFn) {
return new MappedVectorArg<>(this, mapFn);
}
}
/** A vector arg that maps some type T to strings. */
static class MappedVectorArg<T> extends VectorArg<String> {
private final Object values;
private final CommandLineItem.MapFn<? super T> mapFn;
private MappedVectorArg(SimpleVectorArg<T> other, CommandLineItem.MapFn<? super T> mapFn) {
super(
other.isNestedSet,
other.isEmpty,
other.count,
other.formatEach,
other.beforeEach,
other.joinWith);
this.values = other.values;
this.mapFn = mapFn;
}
}
public static <T> SimpleVectorArg<T> of(Collection<T> values) {
return new Builder().each(values);
}
public static <T> SimpleVectorArg<T> of(NestedSet<T> values) {
return new Builder().each(values);
}
/** Each argument is formatted via {@link SingleStringArgFormatter#format}. */
public static Builder format(@CompileTimeConstant String formatEach) {
return new Builder().format(formatEach);
}
/** Each argument is prepended by the beforeEach param. */
public static Builder addBefore(@CompileTimeConstant String beforeEach) {
return new Builder().addBefore(beforeEach);
}
/** Once all arguments have been evaluated, they are joined with this delimiter */
public static Builder join(String delimiter) {
return new Builder().join(delimiter);
}
/** Builder for {@link VectorArg}. */
public static class Builder {
private String formatEach;
private String beforeEach;
private String joinWith;
/** Each argument is formatted via {@link SingleStringArgFormatter#format}. */
public Builder format(@CompileTimeConstant String formatEach) {
Preconditions.checkNotNull(formatEach);
this.formatEach = formatEach;
return this;
}
/** Each argument is prepended by the beforeEach param. */
public Builder addBefore(@CompileTimeConstant String beforeEach) {
Preconditions.checkNotNull(beforeEach);
this.beforeEach = beforeEach;
return this;
}
/** Once all arguments have been evaluated, they are joined with this delimiter */
public Builder join(String delimiter) {
Preconditions.checkNotNull(delimiter);
this.joinWith = delimiter;
return this;
}
public <T> SimpleVectorArg<T> each(Collection<T> values) {
return new SimpleVectorArg<>(this, values);
}
public <T> SimpleVectorArg<T> each(NestedSet<T> values) {
return new SimpleVectorArg<>(this, values);
}
}
private static void push(List<Object> arguments, VectorArg<?> vectorArg) {
// This is either a Collection or a NestedSet.
final Object values;
final CommandLineItem.MapFn<?> mapFn;
if (vectorArg instanceof SimpleVectorArg) {
values = ((SimpleVectorArg) vectorArg).values;
mapFn = null;
} else {
values = ((MappedVectorArg) vectorArg).values;
mapFn = ((MappedVectorArg) vectorArg).mapFn;
}
VectorArgFragment vectorArgFragment =
new VectorArgFragment(
vectorArg.isNestedSet,
mapFn != null,
vectorArg.formatEach != null,
vectorArg.beforeEach != null,
vectorArg.joinWith != null);
if (vectorArgFragment.hasBeforeEach && vectorArgFragment.hasJoinWith) {
throw new IllegalArgumentException("Cannot use both 'before' and 'join' in vector arg.");
}
vectorArgFragment = VectorArgFragment.interner.intern(vectorArgFragment);
arguments.add(vectorArgFragment);
if (vectorArgFragment.hasMapEach) {
arguments.add(mapFn);
}
if (vectorArgFragment.isNestedSet) {
arguments.add(values);
} else {
// Simply expand any ordinary collection into the argv
arguments.add(vectorArg.count);
arguments.addAll((Collection<?>) values);
}
if (vectorArgFragment.hasFormatEach) {
arguments.add(vectorArg.formatEach);
}
if (vectorArgFragment.hasBeforeEach) {
arguments.add(vectorArg.beforeEach);
}
if (vectorArgFragment.hasJoinWith) {
arguments.add(vectorArg.joinWith);
}
}
private static final class VectorArgFragment implements ArgvFragment {
private static Interner<VectorArgFragment> interner = BlazeInterners.newStrongInterner();
private static final UUID FORMAT_EACH_UUID =
UUID.fromString("f830781f-2e0d-4e3b-9b99-ece7f249e0f3");
private static final UUID BEFORE_EACH_UUID =
UUID.fromString("07d22a0d-2691-4f1c-9f47-5294de1f94e4");
private static final UUID JOIN_WITH_UUID =
UUID.fromString("c96ed6f0-9220-40f6-9e0c-1c0c5e0b47e4");
private final boolean isNestedSet;
private final boolean hasMapEach;
private final boolean hasFormatEach;
private final boolean hasBeforeEach;
private final boolean hasJoinWith;
VectorArgFragment(
boolean isNestedSet,
boolean hasMapEach,
boolean hasFormatEach,
boolean hasBeforeEach,
boolean hasJoinWith) {
this.isNestedSet = isNestedSet;
this.hasMapEach = hasMapEach;
this.hasFormatEach = hasFormatEach;
this.hasBeforeEach = hasBeforeEach;
this.hasJoinWith = hasJoinWith;
}
@Override
@SuppressWarnings("unchecked")
public int eval(
List<Object> arguments,
int argi,
ImmutableList.Builder<String> builder,
boolean stripOutputPaths)
throws CommandLineExpansionException, InterruptedException {
final List<String> mutatedValues;
CommandLineItem.MapFn<Object> mapFn =
hasMapEach ? (CommandLineItem.MapFn<Object>) arguments.get(argi++) : null;
if (isNestedSet) {
NestedSet<Object> values = (NestedSet<Object>) arguments.get(argi++);
ImmutableList<Object> list = values.toList();
mutatedValues = new ArrayList<>(list.size());
if (mapFn != null) {
Consumer<String> args = mutatedValues::add; // Hoist out of loop to reduce GC
for (Object object : list) {
mapFn.expandToCommandLine(object, args);
}
} else {
for (Object object : list) {
mutatedValues.add(CommandLineItem.expandToCommandLine(object));
}
}
} else {
int count = (Integer) arguments.get(argi++);
mutatedValues = new ArrayList<>(count);
if (mapFn != null) {
Consumer<String> args = mutatedValues::add; // Hoist out of loop to reduce GC
for (int i = 0; i < count; ++i) {
mapFn.expandToCommandLine(arguments.get(argi++), args);
}
} else {
for (int i = 0; i < count; ++i) {
Object arg = arguments.get(argi++);
if (arg instanceof DerivedArtifact && stripOutputPaths) {
// This argument is an output file and the command line creator strips output paths.
mutatedValues.add(PathStripper.strip((DerivedArtifact) arg));
} else {
mutatedValues.add(CommandLineItem.expandToCommandLine(arg));
}
}
}
}
final int count = mutatedValues.size();
if (hasFormatEach) {
String formatStr = (String) arguments.get(argi++);
for (int i = 0; i < count; ++i) {
mutatedValues.set(i, SingleStringArgFormatter.format(formatStr, mutatedValues.get(i)));
}
}
if (hasBeforeEach) {
String beforeEach = (String) arguments.get(argi++);
for (int i = 0; i < count; ++i) {
builder.add(beforeEach);
builder.add(mutatedValues.get(i));
}
} else if (hasJoinWith) {
String joinWith = (String) arguments.get(argi++);
builder.add(Joiner.on(joinWith).join(mutatedValues));
} else {
for (int i = 0; i < count; ++i) {
builder.add(mutatedValues.get(i));
}
}
return argi;
}
@SuppressWarnings("unchecked")
@Override
public int addToFingerprint(
List<Object> arguments,
int argi,
ActionKeyContext actionKeyContext,
Fingerprint fingerprint)
throws CommandLineExpansionException, InterruptedException {
CommandLineItem.MapFn<Object> mapFn =
hasMapEach ? (CommandLineItem.MapFn<Object>) arguments.get(argi++) : null;
if (isNestedSet) {
NestedSet<Object> values = (NestedSet<Object>) arguments.get(argi++);
if (mapFn != null) {
actionKeyContext.addNestedSetToFingerprint(mapFn, fingerprint, values);
} else {
actionKeyContext.addNestedSetToFingerprint(fingerprint, values);
}
} else {
int count = (Integer) arguments.get(argi++);
if (mapFn != null) {
for (int i = 0; i < count; ++i) {
mapFn.expandToCommandLine(arguments.get(argi++), fingerprint::addString);
}
} else {
for (int i = 0; i < count; ++i) {
fingerprint.addString(CommandLineItem.expandToCommandLine(arguments.get(argi++)));
}
}
}
if (hasFormatEach) {
fingerprint.addUUID(FORMAT_EACH_UUID);
fingerprint.addString((String) arguments.get(argi++));
}
if (hasBeforeEach) {
fingerprint.addUUID(BEFORE_EACH_UUID);
fingerprint.addString((String) arguments.get(argi++));
} else if (hasJoinWith) {
fingerprint.addUUID(JOIN_WITH_UUID);
fingerprint.addString((String) arguments.get(argi++));
}
return argi;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VectorArgFragment vectorArgFragment = (VectorArgFragment) o;
return isNestedSet == vectorArgFragment.isNestedSet
&& hasMapEach == vectorArgFragment.hasMapEach
&& hasFormatEach == vectorArgFragment.hasFormatEach
&& hasBeforeEach == vectorArgFragment.hasBeforeEach
&& hasJoinWith == vectorArgFragment.hasJoinWith;
}
@Override
public int hashCode() {
return Objects.hashCode(isNestedSet, hasMapEach, hasFormatEach, hasBeforeEach, hasJoinWith);
}
}
}
@VisibleForSerialization
static class FormatArg implements ArgvFragment {
@SerializationConstant @VisibleForSerialization
static final FormatArg INSTANCE = new FormatArg();
private static final UUID FORMAT_UUID = UUID.fromString("377cee34-e947-49e0-94a2-6ab95b396ec4");
private static void push(List<Object> arguments, String formatStr, Object... args) {
arguments.add(INSTANCE);
arguments.add(args.length);
arguments.add(formatStr);
Collections.addAll(arguments, args);
}
@Override
public int eval(
List<Object> arguments,
int argi,
ImmutableList.Builder<String> builder,
boolean stripOutputPaths) {
int argCount = (Integer) arguments.get(argi++);
String formatStr = (String) arguments.get(argi++);
Object[] args = new Object[argCount];
for (int i = 0; i < argCount; ++i) {
args[i] = CommandLineItem.expandToCommandLine(arguments.get(argi++));
}
builder.add(String.format(formatStr, args));
return argi;
}
@Override
public int addToFingerprint(
List<Object> arguments,
int argi,
ActionKeyContext actionKeyContext,
Fingerprint fingerprint) {
int argCount = (Integer) arguments.get(argi++);
fingerprint.addUUID(FORMAT_UUID);
fingerprint.addString((String) arguments.get(argi++));
for (int i = 0; i < argCount; ++i) {
fingerprint.addString(CommandLineItem.expandToCommandLine(arguments.get(argi++)));
}
return argi;
}
}
@VisibleForSerialization
static class PrefixArg implements ArgvFragment {
@SerializationConstant @VisibleForSerialization
static final PrefixArg INSTANCE = new PrefixArg();
private static final UUID PREFIX_UUID = UUID.fromString("a95eccdf-4f54-46fc-b925-c8c7e1f50c95");
private static void push(List<Object> arguments, String before, Object arg) {
arguments.add(INSTANCE);
arguments.add(before);
arguments.add(arg);
}
@Override
public int eval(
List<Object> arguments,
int argi,
ImmutableList.Builder<String> builder,
boolean stripOutputPaths) {
String before = (String) arguments.get(argi++);
Object arg = arguments.get(argi++);
builder.add(before + CommandLineItem.expandToCommandLine(arg));
return argi;
}
@Override
public int addToFingerprint(
List<Object> arguments,
int argi,
ActionKeyContext actionKeyContext,
Fingerprint fingerprint) {
fingerprint.addUUID(PREFIX_UUID);
fingerprint.addString((String) arguments.get(argi++));
fingerprint.addString(CommandLineItem.expandToCommandLine(arguments.get(argi++)));
return argi;
}
}
/**
* A command line argument for {@link TreeFileArtifact}.
*
* <p>Since {@link TreeFileArtifact} is not known or available at analysis time, subclasses should
* enclose its parent TreeFileArtifact instead at analysis time. This interface provides method
* {@link #substituteTreeArtifact} to generate another argument object that replaces the enclosed
* TreeArtifact with one of its {@link TreeFileArtifact} at execution time.
*/
private abstract static class TreeFileArtifactArgvFragment {
/**
* Substitutes this ArgvFragment with another arg object, with the original TreeArtifacts
* contained in this ArgvFragment replaced by their associated TreeFileArtifacts.
*
* @param substitutionMap A map between TreeArtifacts and their associated TreeFileArtifacts
* used to replace them.
*/
abstract Object substituteTreeArtifact(Map<Artifact, TreeFileArtifact> substitutionMap);
}
/**
* A command line argument that can expand enclosed TreeArtifacts into a list of child {@link
* TreeFileArtifact}s at execution time before argument evaluation.
*
* <p>The main difference between this class and {@link TreeFileArtifactArgvFragment} is that
* {@link TreeFileArtifactArgvFragment} is used in {@link SpawnActionTemplate} to substitutes a
* TreeArtifact with *one* of its child TreeFileArtifacts, while this class expands a TreeArtifact
* into *all* of its child TreeFileArtifacts.
*/
private abstract static class TreeArtifactExpansionArgvFragment extends StandardArgvFragment {
/**
* Evaluates this argument fragment into an argument string and adds it into {@code builder}.
* The enclosed TreeArtifact will be expanded using {@code artifactExpander}.
*/
abstract void eval(ImmutableList.Builder<String> builder, ArtifactExpander artifactExpander);
/**
* Evaluates this argument fragment by serializing it into a string. Note that the returned
* argument is not suitable to be used as part of an actual command line. The purpose of this
* method is to provide a unique command line argument string to be used as part of an action
* key at analysis time.
*
* <p>Internally this method just calls {@link #describe}.
*/
@Override
void eval(ImmutableList.Builder<String> builder) {
builder.add(describe());
}
/**
* Returns a string that describes this argument fragment. The string can be used as part of an
* action key for the command line at analysis time.
*/
abstract String describe();
}
private static final class ExpandedTreeArtifactArg extends TreeArtifactExpansionArgvFragment {
private static final UUID TREE_UUID = UUID.fromString("13b7626b-c77d-4a30-ad56-ff08c06b1cee");
private final Artifact treeArtifact;
ExpandedTreeArtifactArg(Artifact treeArtifact) {
Preconditions.checkArgument(
treeArtifact.isTreeArtifact(), "%s is not a TreeArtifact", treeArtifact);
this.treeArtifact = treeArtifact;
}
@Override
void eval(ImmutableList.Builder<String> builder, ArtifactExpander artifactExpander) {
Set<Artifact> expandedArtifacts = new TreeSet<>();
artifactExpander.expand(treeArtifact, expandedArtifacts);
for (Artifact expandedArtifact : expandedArtifacts) {
builder.add(expandedArtifact.getExecPathString());
}
}
@Override
public String describe() {
return String.format(
"ExpandedTreeArtifactArg{ treeArtifact: %s}", treeArtifact.getExecPathString());
}
@Override
void addToFingerprint(ActionKeyContext actionKeyContext, Fingerprint fingerprint) {
fingerprint.addUUID(TREE_UUID);
fingerprint.addPath(treeArtifact.getExecPath());
}
}
/**
* An argument object that evaluates to the exec path of a {@link TreeFileArtifact}, enclosing the
* associated {@link TreeFileArtifact}.
*/
private static final class TreeFileArtifactExecPathArg extends TreeFileArtifactArgvFragment {
private final Artifact placeHolderTreeArtifact;
private TreeFileArtifactExecPathArg(Artifact artifact) {
Preconditions.checkArgument(artifact.isTreeArtifact(), "%s must be a TreeArtifact", artifact);
placeHolderTreeArtifact = artifact;
}
@Override
Object substituteTreeArtifact(Map<Artifact, TreeFileArtifact> substitutionMap) {
Artifact artifact = substitutionMap.get(placeHolderTreeArtifact);
Preconditions.checkNotNull(artifact, "Artifact to substitute: %s", placeHolderTreeArtifact);
return artifact.getExecPath();
}
}
/**
* A Builder class for CustomCommandLine with the appropriate methods.
*
* <p>{@link Collection} instances passed to {@code add*} methods will copied internally. If you
* have a {@link NestedSet}, these should never be flattened to a collection before being passed
* to the command line.
*
* <p>Try to avoid coercing items to strings unnecessarily. Instead, use a more memory-efficient
* form that defers the string coercion until the last moment. In particular, avoid flattening
* lists and nested sets (see {@link VectorArg}).
*
* <p>Three types are given special consideration:
*
* <ul>
* <li>Any labels added will be added using {@link Label#getCanonicalForm()}
* <li>Path fragments will be added using {@link PathFragment#toString}
* <li>Artifacts will be added using {@link Artifact#getExecPathString()}.
* </ul>
*
* <p>Any other type must be mapped to a string. For collections, please use {@link
* VectorArg.SimpleVectorArg#mapped}.
*/
public static final class Builder {
// In order to avoid unnecessary wrapping, we keep raw objects here, but these objects are
// always either ArgvFragments or objects whose desired string representations are just their
// toString() results.
private final List<Object> arguments = new ArrayList<>();
private boolean stripOutputPaths = false;
private PathFragment outputRoot = null;
public boolean isEmpty() {
return arguments.isEmpty();
}
private final NestedSetBuilder<Artifact> treeArtifactInputs = NestedSetBuilder.stableOrder();
private boolean treeArtifactsRequested = false;
/**
* Strip output path config prefixes from the command line.
*
* <p>This offers better executor caching. But it's only safe for actions that don't vary when
* {@code /x86-fastbuild/} (or equivalent) changes in the executor's action key. This only
* affects {@link #addExecPath} and {@link #addPath(PathFragment)} entries. Output paths
* embedded in larger strings and added via {@link #add(String)} or other variants must be
* handled separately.
*
* <p>See {@link PathStripper} for details.
*
* @param outputRoot the output tree's root fragment (i.e. "bazel-out")
*/
public Builder stripOutputPaths(PathFragment outputRoot) {
Preconditions.checkArgument(!stripOutputPaths);
Preconditions.checkArgument(this.outputRoot == null);
this.stripOutputPaths = true;
this.outputRoot = outputRoot;
return this;
}
/**
* Adds a constant-value string.
*
* <p>Prefer this over its dynamic cousin, as using static strings saves memory.
*/
public Builder add(@CompileTimeConstant String value) {
return addObjectInternal(value);
}
/**
* Adds a string argument to the command line.
*
* <p>If the value is null, neither the arg nor the value is added.
*/
public Builder add(@CompileTimeConstant String arg, @Nullable String value) {
return addObjectInternal(arg, value);
}
/**
* Adds a single argument to the command line, which is lazily converted to string.
*
* <p>If the value is null, neither the arg nor the value is added.
*/
public Builder addObject(@Nullable Object value) {
return addObjectInternal(value);
}
/**
* Adds a dynamically calculated string.
*
* <p>Consider whether using another method could be more efficient. For instance, rather than
* calling this method with an Artifact's exec path, just add the artifact itself. It will
* lazily get converted to its exec path. Same with labels, path fragments, and many other
* objects.
*
* <p>If you are joining some list into a single argument, consider using {@link VectorArg}.
*
* <p>If you are formatting a string, consider using {@link Builder#addFormatted(String,
* Object...)}.
*
* <p>There are many other ways you can try to avoid calling this. In general, try to use
* constants or objects that are already on the heap elsewhere.
*/
public Builder addDynamicString(@Nullable String value) {
return addObjectInternal(value);
}
/**
* Adds a label value by calling {@link Label#getCanonicalForm}.
*
* <p>Prefer this over manually calling {@link Label#getCanonicalForm}, as it avoids a copy of
* the label value.
*/
public Builder addLabel(@Nullable Label value) {
return addObjectInternal(value);
}
/**
* Adds a label value by calling {@link Label#getCanonicalForm}.
*
* <p>Prefer this over manually calling {@link Label#getCanonicalForm}, as it avoids storing a
* copy of the label value.
*
* <p>If the value is null, neither the arg nor the value is added.
*/
public Builder addLabel(@CompileTimeConstant String arg, @Nullable Label value) {
return addObjectInternal(arg, value);
}
/**
* Adds an artifact by calling {@link PathFragment#getPathString}.
*
* <p>Prefer this over manually calling {@link PathFragment#getPathString}, as it avoids storing
* a copy of the path string.
*/
public Builder addPath(@Nullable PathFragment value) {
return addObjectInternal(value);
}
/**
* Adds an artifact by calling {@link PathFragment#getPathString}.
*
* <p>Prefer this over manually calling {@link PathFragment#getPathString}, as it avoids storing
* a copy of the path string.
*
* <p>If the value is null, neither the arg nor the value is added.
*/
public Builder addPath(@CompileTimeConstant String arg, @Nullable PathFragment value) {
return addObjectInternal(arg, value);
}
/**
* Adds an artifact by calling {@link Artifact#getExecPath}.
*
* <p>Prefer this over manually calling {@link Artifact#getExecPath}, as it avoids storing a
* copy of the artifact path string.
*/
public Builder addExecPath(@Nullable Artifact value) {
return addObjectInternal(value);
}
/**
* Adds an artifact by calling {@link Artifact#getExecPath}.
*
* <p>Prefer this over manually calling {@link Artifact#getExecPath}, as it avoids storing a
* copy of the artifact path string.
*
* <p>If the value is null, neither the arg nor the value is added.
*/
public Builder addExecPath(@CompileTimeConstant String arg, @Nullable Artifact value) {
return addObjectInternal(arg, value);
}
/** Adds a lazily expanded string. */
public Builder addLazyString(@Nullable OnDemandString value) {
return addObjectInternal(value);
}
/** Adds a lazily expanded string. */
public Builder addLazyString(@CompileTimeConstant String arg, @Nullable OnDemandString value) {
return addObjectInternal(arg, value);
}
/** Calls {@link String#format} at command line expansion time. */
@FormatMethod
public Builder addFormatted(@FormatString String formatStr, Object... args) {
Preconditions.checkNotNull(formatStr);
FormatArg.push(arguments, formatStr, args);
return this;
}
/** Concatenates the passed prefix string and the string. */
public Builder addPrefixed(@CompileTimeConstant String prefix, @Nullable String arg) {
return addPrefixedInternal(prefix, arg);
}
/** Concatenates the passed prefix string and the label using {@link Label#getCanonicalForm}. */
public Builder addPrefixedLabel(@CompileTimeConstant String prefix, @Nullable Label arg) {
return addPrefixedInternal(prefix, arg);
}
/** Concatenates the passed prefix string and the path. */
public Builder addPrefixedPath(@CompileTimeConstant String prefix, @Nullable PathFragment arg) {
return addPrefixedInternal(prefix, arg);
}
/** Concatenates the passed prefix string and the artifact's exec path. */
public Builder addPrefixedExecPath(@CompileTimeConstant String prefix, @Nullable Artifact arg) {
return addPrefixedInternal(prefix, arg);
}
/**
* Adds the passed strings to the command line.
*
* <p>If you are converting long lists or nested sets of a different type to string lists,
* please try to use a different method that supports what you are trying to do directly.
*/
public Builder addAll(@Nullable Collection<String> values) {
return addCollectionInternal(values);
}
/**
* Adds the passed strings to the command line.
*
* <p>If you are converting long lists or nested sets of a different type to string lists,
* please try to use a different method that supports what you are trying to do directly.
*/
public Builder addAll(@Nullable NestedSet<String> values) {
return addNestedSetInternal(values);
}
/**
* Adds the arg followed by the passed strings.
*
* <p>If you are converting long lists or nested sets of a different type to string lists,
* please try to use a different method that supports what you are trying to do directly.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addAll(@CompileTimeConstant String arg, @Nullable Collection<String> values) {
return addCollectionInternal(arg, values);
}
/**
* Adds the arg followed by the passed strings.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addAll(@CompileTimeConstant String arg, @Nullable NestedSet<String> values) {
return addNestedSetInternal(arg, values);
}
/** Adds the passed vector arg. See {@link VectorArg}. */
public Builder addAll(VectorArg<String> vectorArg) {
return addVectorArgInternal(vectorArg);
}
/**
* Adds the arg followed by the passed vector arg. See {@link VectorArg}.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addAll(@CompileTimeConstant String arg, VectorArg<String> vectorArg) {
return addVectorArgInternal(arg, vectorArg);
}
/** Adds the passed paths to the command line. */
public Builder addPaths(@Nullable Collection<PathFragment> values) {
return addCollectionInternal(values);
}
/** Adds the passed paths to the command line. */
public Builder addPaths(@Nullable NestedSet<PathFragment> values) {
return addNestedSetInternal(values);
}
/**
* Adds the arg followed by the path strings.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addPaths(
@CompileTimeConstant String arg, @Nullable Collection<PathFragment> values) {
return addCollectionInternal(arg, values);
}
/**
* Adds the arg followed by the path fragments.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addPaths(
@CompileTimeConstant String arg, @Nullable NestedSet<PathFragment> values) {
return addNestedSetInternal(arg, values);
}
/** Adds the passed vector arg. See {@link VectorArg}. */
public Builder addPaths(VectorArg<PathFragment> vectorArg) {
return addVectorArgInternal(vectorArg);
}
/**
* Adds the arg followed by the passed vector arg. See {@link VectorArg}.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addPaths(@CompileTimeConstant String arg, VectorArg<PathFragment> vectorArg) {
return addVectorArgInternal(arg, vectorArg);
}
/**
* Adds the artifacts' exec paths to the command line.
*
* <p>Do not use this method if the list is derived from a flattened nested set. Instead, figure
* out how to avoid flattening the set and use {@link
* Builder#addExecPaths(NestedSet<Artifact>)}.
*/
public Builder addExecPaths(@Nullable Collection<Artifact> values) {
return addCollectionInternal(values);
}
/** Adds the artifacts' exec paths to the command line. */
public Builder addExecPaths(@Nullable NestedSet<Artifact> values) {
return addNestedSetInternal(values);
}
/**
* Adds the arg followed by the artifacts' exec paths.
*
* <p>Do not use this method if the list is derived from a flattened nested set. Instead, figure
* out how to avoid flattening the set and use {@link Builder#addExecPaths(String,
* NestedSet<Artifact>)}.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addExecPaths(
@CompileTimeConstant String arg, @Nullable Collection<Artifact> values) {
return addCollectionInternal(arg, values);
}
/**
* Adds the arg followed by the artifacts' exec paths.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addExecPaths(
@CompileTimeConstant String arg, @Nullable NestedSet<Artifact> values) {
return addNestedSetInternal(arg, values);
}
/** Adds the passed vector arg. See {@link VectorArg}. */
public Builder addExecPaths(VectorArg<Artifact> vectorArg) {
return addVectorArgInternal(vectorArg);
}
/**
* Adds the arg followed by the passed vector arg. See {@link VectorArg}.
*
* <p>If values is empty, the arg isn't added.
*/
public Builder addExecPaths(@CompileTimeConstant String arg, VectorArg<Artifact> vectorArg) {
return addVectorArgInternal(arg, vectorArg);
}
/**
* Adds a placeholder TreeArtifact exec path. When the command line is used in an action
* template, the placeholder will be replaced by the exec path of a {@link TreeFileArtifact}
* inside the TreeArtifact at execution time for each expanded action.
*
* @param treeArtifact the TreeArtifact that will be evaluated to one of its child {@link
* TreeFileArtifact} at execution time
*/
public Builder addPlaceholderTreeArtifactExecPath(@Nullable Artifact treeArtifact) {
if (treeArtifact != null) {
Preconditions.checkState(!treeArtifactsRequested);
treeArtifactInputs.add(treeArtifact);
arguments.add(new TreeFileArtifactExecPathArg(treeArtifact));
}
return this;
}
/**
* Adds a flag with the exec path of a placeholder TreeArtifact. When the command line is used
* in an action template, the placeholder will be replaced by the exec path of a {@link
* TreeFileArtifact} inside the TreeArtifact at execution time for each expanded action.
*
* @param arg the name of the argument
* @param treeArtifact the TreeArtifact that will be evaluated to one of its child {@link
* TreeFileArtifact} at execution time
*/
public Builder addPlaceholderTreeArtifactExecPath(String arg, @Nullable Artifact treeArtifact) {
Preconditions.checkNotNull(arg);
if (treeArtifact != null) {
Preconditions.checkState(!treeArtifactsRequested);
treeArtifactInputs.add(treeArtifact);
arguments.add(arg);
arguments.add(new TreeFileArtifactExecPathArg(treeArtifact));
}
return this;
}
/**
* Adds the exec paths (one argument per exec path) of all {@link TreeFileArtifact}s under
* {@code treeArtifact}.
*
* @param treeArtifact the TreeArtifact containing the {@link TreeFileArtifact}s to add.
*/
public Builder addExpandedTreeArtifactExecPaths(Artifact treeArtifact) {
Preconditions.checkState(!treeArtifactsRequested);
treeArtifactInputs.add(treeArtifact);
Preconditions.checkNotNull(treeArtifact);
arguments.add(new ExpandedTreeArtifactArg(treeArtifact));
return this;
}
/** Gets all the tree artifact inputs for command line */
public NestedSet<Artifact> getTreeArtifactInputs() {
treeArtifactsRequested = true;
return treeArtifactInputs.build();
}
public CustomCommandLine build() {
return stripOutputPaths
? new PathStrippingCustomCommandline(
arguments,
/*substitutionMap=*/ null,
Verify.verifyNotNull(
outputRoot,
"path stripping needs an output root ('bazel-out') to identify output paths"))
: new CustomCommandLine(arguments, /*substitutionMap=*/ null);
}
private Builder addObjectInternal(@Nullable Object value) {
if (value != null) {
arguments.add(value);
}
return this;
}
/** Adds the arg and the passed value if the value is non-null. */
private Builder addObjectInternal(@CompileTimeConstant String arg, @Nullable Object value) {
Preconditions.checkNotNull(arg);
if (value != null) {
arguments.add(arg);
addObjectInternal(value);
}
return this;
}
private Builder addPrefixedInternal(String prefix, @Nullable Object arg) {
Preconditions.checkNotNull(prefix);
if (arg != null) {
PrefixArg.push(arguments, prefix, arg);
}
return this;
}
private Builder addCollectionInternal(@Nullable Collection<?> values) {
if (values != null) {
addVectorArgInternal(VectorArg.of(values));
}
return this;
}
private Builder addCollectionInternal(
@CompileTimeConstant String arg, @Nullable Collection<?> values) {
Preconditions.checkNotNull(arg);
if (values != null && !values.isEmpty()) {
arguments.add(arg);
addCollectionInternal(values);
}
return this;
}
private Builder addNestedSetInternal(@Nullable NestedSet<?> values) {
if (values != null) {
arguments.add(values);
}
return this;
}
private Builder addNestedSetInternal(
@CompileTimeConstant String arg, @Nullable NestedSet<?> values) {
Preconditions.checkNotNull(arg);
if (values != null && !values.isEmpty()) {
arguments.add(arg);
addNestedSetInternal(values);
}
return this;
}
private Builder addVectorArgInternal(VectorArg<?> vectorArg) {
if (!vectorArg.isEmpty) {
VectorArg.push(arguments, vectorArg);
}
return this;
}
private Builder addVectorArgInternal(@CompileTimeConstant String arg, VectorArg<?> vectorArg) {
Preconditions.checkNotNull(arg);
if (!vectorArg.isEmpty) {
arguments.add(arg);
addVectorArgInternal(vectorArg);
}
return this;
}
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(Builder other) {
Builder builder = new Builder();
builder.arguments.addAll(other.arguments);
return builder;
}
private final ImmutableList<Object> arguments;
/**
* A map between enclosed TreeArtifacts and their associated {@link TreeFileArtifact}s for
* substitution.
*
* <p>This map is used to support TreeArtifact substitutions in {@link
* TreeFileArtifactArgvFragment}s.
*/
private final Map<Artifact, TreeFileArtifact> substitutionMap;
private CustomCommandLine(
List<Object> arguments, Map<Artifact, TreeFileArtifact> substitutionMap) {
this.arguments = ImmutableList.copyOf(arguments);
this.substitutionMap = substitutionMap == null ? null : ImmutableMap.copyOf(substitutionMap);
}
protected boolean stripOutputPaths() {
return false;
}
protected PathFragment getOutputRoot() {
throw new UnsupportedOperationException(
"This should only be called for PathStrippingCustomCommandLine");
}
/**
* {@link CustomCommandLine} that strips config prefixes from output paths. See {@link
* PathStripper}.
*
* <p>We use inheritance vs. a {@code stripOutputPaths} field in {@link CustomCommandLine} because
* Java-heavy builds keep many {@link CustomCommandLine} objects in memory. So we need to minimize
* each one's memory footprint.
*/
private static final class PathStrippingCustomCommandline extends CustomCommandLine {
// TODO(https://github.com/bazelbuild/bazel/issues/6526): outputRoot is just an indirect
// reference to "bazel-out". Java-heavy builds keep enough CustomCommandLine objects in memory
// such that each additional reference contributes observable extra memory on the host machine.
// Find a way to consolidate this into a single global reference.
private final PathFragment outputRoot;
private PathStrippingCustomCommandline(
List<Object> arguments,
Map<Artifact, TreeFileArtifact> substitutionMap,
@Nullable PathFragment outputRoot) {
super(arguments, substitutionMap);
this.outputRoot = outputRoot;
}
@Override
protected boolean stripOutputPaths() {
return true;
}
@Override
protected PathFragment getOutputRoot() {
return outputRoot;
}
}
/**
* Given the list of {@link TreeFileArtifact}s, returns another CustomCommandLine that replaces
* their parent TreeArtifacts with the TreeFileArtifacts in all {@link
* TreeFileArtifactArgvFragment} argument objects.
*/
@VisibleForTesting
public CustomCommandLine evaluateTreeFileArtifacts(Iterable<TreeFileArtifact> treeFileArtifacts) {
ImmutableMap.Builder<Artifact, TreeFileArtifact> substitutionMap = ImmutableMap.builder();
for (TreeFileArtifact treeFileArtifact : treeFileArtifacts) {
substitutionMap.put(treeFileArtifact.getParent(), treeFileArtifact);
}
return new CustomCommandLine(arguments, substitutionMap.buildOrThrow());
}
@Override
public ImmutableList<String> arguments()
throws CommandLineExpansionException, InterruptedException {
return argumentsInternal(null);
}
@Override
public ImmutableList<String> arguments(ArtifactExpander artifactExpander)
throws CommandLineExpansionException, InterruptedException {
return argumentsInternal(Preconditions.checkNotNull(artifactExpander));
}
private ImmutableList<String> argumentsInternal(@Nullable ArtifactExpander artifactExpander)
throws CommandLineExpansionException, InterruptedException {
ImmutableList.Builder<String> builder = ImmutableList.builder();
int count = arguments.size();
for (int i = 0; i < count; ) {
Object arg = arguments.get(i++);
Object substitutedArg = substituteTreeFileArtifactArgvFragment(arg);
if (substitutedArg instanceof NestedSet) {
evalSimpleVectorArg(((NestedSet<?>) substitutedArg).toList(), builder);
} else if (substitutedArg instanceof Iterable) {
evalSimpleVectorArg((Iterable<?>) substitutedArg, builder);
} else if (substitutedArg instanceof ArgvFragment) {
if (artifactExpander != null
&& substitutedArg instanceof TreeArtifactExpansionArgvFragment) {
TreeArtifactExpansionArgvFragment expansionArg =
(TreeArtifactExpansionArgvFragment) substitutedArg;
expansionArg.eval(builder, artifactExpander);
} else {
i = ((ArgvFragment) substitutedArg).eval(arguments, i, builder, stripOutputPaths());
}
} else if (substitutedArg instanceof DerivedArtifact && stripOutputPaths()) {
builder.add(PathStripper.strip((DerivedArtifact) substitutedArg));
} else if (substitutedArg instanceof PathFragment
&& stripOutputPaths()
&& PathStripper.isOutputPath((PathFragment) substitutedArg, getOutputRoot())) {
builder.add(PathStripper.strip(((PathFragment) substitutedArg)).getPathString());
} else {
builder.add(CommandLineItem.expandToCommandLine(substitutedArg));
}
}
return builder.build();
}
private void evalSimpleVectorArg(Iterable<?> arg, ImmutableList.Builder<String> builder) {
for (Object value : arg) {
builder.add(
value instanceof DerivedArtifact && stripOutputPaths()
? PathStripper.strip((DerivedArtifact) value)
: CommandLineItem.expandToCommandLine(value));
}
}
/**
* If the given arg is a {@link TreeFileArtifactArgvFragment} and we have its associated
* TreeArtifact substitution map, returns another argument object that has its enclosing
* TreeArtifact substituted by one of its {@link TreeFileArtifact}. Otherwise, returns the given
* arg unmodified.
*/
private Object substituteTreeFileArtifactArgvFragment(Object arg) {
if (arg instanceof TreeFileArtifactArgvFragment) {
TreeFileArtifactArgvFragment argvFragment = (TreeFileArtifactArgvFragment) arg;
return argvFragment.substituteTreeArtifact(
Preconditions.checkNotNull(substitutionMap, argvFragment));
} else {
return arg;
}
}
@Override
@SuppressWarnings("unchecked")
public void addToFingerprint(
ActionKeyContext actionKeyContext,
@Nullable ArtifactExpander artifactExpander,
Fingerprint fingerprint)
throws CommandLineExpansionException, InterruptedException {
int count = arguments.size();
for (int i = 0; i < count; ) {
Object arg = arguments.get(i++);
Object substitutedArg = substituteTreeFileArtifactArgvFragment(arg);
if (substitutedArg instanceof NestedSet) {
actionKeyContext.addNestedSetToFingerprint(fingerprint, (NestedSet<Object>) substitutedArg);
} else if (substitutedArg instanceof Iterable) {
for (Object value : (Iterable<Object>) substitutedArg) {
fingerprint.addString(CommandLineItem.expandToCommandLine(value));
}
} else if (substitutedArg instanceof ArgvFragment) {
i =
((ArgvFragment) substitutedArg)
.addToFingerprint(arguments, i, actionKeyContext, fingerprint);
} else {
fingerprint.addString(CommandLineItem.expandToCommandLine(substitutedArg));
}
}
}
}
|
3e1a0751cd9f79b85ef519758223a400261c37dc | 899 | java | Java | src/main/java/com/changqin/fast/config/FireEventHandler.java | DongJigong/spring-boot-starter-disruptor-examples | dab0eaf07296d28c36ea11ce7b7239b699de630b | [
"Apache-2.0"
] | 1 | 2020-04-07T07:52:45.000Z | 2020-04-07T07:52:45.000Z | src/main/java/com/changqin/fast/config/FireEventHandler.java | DongJigong/spring-boot-starter-disruptor-examples | dab0eaf07296d28c36ea11ce7b7239b699de630b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/changqin/fast/config/FireEventHandler.java | DongJigong/spring-boot-starter-disruptor-examples | dab0eaf07296d28c36ea11ce7b7239b699de630b | [
"Apache-2.0"
] | null | null | null | 26.441176 | 67 | 0.746385 | 11,058 | package com.changqin.fast.config;
import com.changqin.fast.domain.message.DomainMessage;
import com.changqin.fast.event.EventFirer;
import com.changqin.fast.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @ProjectName: spring-boot-starter-disruptor
* @Package: com.changqin.fast.config
* @ClassName: FireEventHanlder
* @Description: java类作用描述
* @Author: dongjigong
* @CreateDate: 2019/10/24 11:19
* @UpdateUser:
* @UpdateDate: 2019/10/24 11:19
* @UpdateRemark:
* @Version: 1.0
* @Copyright: 河南昱荣教育科技有限公司
*/
@Component
public class FireEventHandler {
@Autowired
private EventFirer eventFirer;
public DomainMessage getSchoolUser(UserInfo user,String topic){
DomainMessage message = new DomainMessage(user);
eventFirer.fire(message,topic);
return message;
}
}
|
3e1a07b08c7493cd2cd56eebc5dc5eb84783dac3 | 6,726 | java | Java | src/main/java/org/olat/modules/video/ui/VideoDisplayOptions.java | em3ndez/OpenOLAT | 80176e03805b823645eb2878d0d0725fa345f5c6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/olat/modules/video/ui/VideoDisplayOptions.java | em3ndez/OpenOLAT | 80176e03805b823645eb2878d0d0725fa345f5c6 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/olat/modules/video/ui/VideoDisplayOptions.java | em3ndez/OpenOLAT | 80176e03805b823645eb2878d0d0725fa345f5c6 | [
"Apache-2.0"
] | null | null | null | 27.946058 | 189 | 0.773422 | 11,059 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.modules.video.ui;
/**
*
*
* Initial date: 6 déc. 2018<br>
* @author srosse, kenaa@example.com, http://www.frentix.com
*
*/
public class VideoDisplayOptions {
private boolean autoplay;
private boolean showComments;
private boolean showRating;
private boolean useContainerForCommentsAndRatings;
private boolean showTitle;
private boolean showDescription;
private boolean autoWidth;
private boolean readOnly;
private String descriptionText;
private boolean showAnnotations;
private boolean showQuestions;
private boolean showPoster;
private boolean alwaysShowControls;
private boolean dragAnnotations;
private boolean clickToPlayPause;
private boolean authorMode;
private boolean forwardSeekingRestricted;
public static VideoDisplayOptions valueOf(boolean autoplay, boolean showComments, boolean showRating, boolean useContainerForCommentsAndRatings, boolean showTitle, boolean showDescription,
boolean autoWidth, String descriptionText, boolean authorMode, boolean readOnly, boolean forwardSeekingRestricted) {
VideoDisplayOptions options = new VideoDisplayOptions();
options.setAutoplay(autoplay);
options.setAutoWidth(autoWidth);
options.setDescriptionText(descriptionText);
options.setReadOnly(readOnly);
options.setShowComments(showComments);
options.setShowRating(showRating);
options.setUseContainerForCommentsAndRatings(useContainerForCommentsAndRatings);
options.setShowTitle(showTitle);
options.setShowDescription(showDescription);
options.setForwardSeekingRestricted(forwardSeekingRestricted);
options.setShowPoster(true);
options.setShowQuestions(true);
options.setShowAnnotations(true);
options.setAlwaysShowControls(false);
options.setDragAnnotations(false);
options.setClickToPlayPause(true);
options.setAuthorMode(authorMode);
return options;
}
public static VideoDisplayOptions disabled() {
VideoDisplayOptions options = new VideoDisplayOptions();
options.setAutoplay(false);
options.setAutoWidth(false);
options.setDescriptionText(null);
options.setReadOnly(false);
options.setShowComments(false);
options.setShowRating(false);
options.setShowTitle(false);
options.setShowDescription(false);
options.setForwardSeekingRestricted(false);
options.setShowPoster(true);
options.setShowQuestions(false);
options.setShowAnnotations(false);
options.setAlwaysShowControls(false);
options.setDragAnnotations(false);
options.setClickToPlayPause(true);
options.setAuthorMode(false);
return options;
}
public boolean isAutoplay() {
return autoplay;
}
public void setAutoplay(boolean autoplay) {
this.autoplay = autoplay;
}
public boolean isAlwaysShowControls() {
return alwaysShowControls;
}
public void setAlwaysShowControls(boolean alwaysShowControls) {
this.alwaysShowControls = alwaysShowControls;
}
public boolean isClickToPlayPause() {
return clickToPlayPause;
}
public void setClickToPlayPause(boolean clickToPlayPause) {
this.clickToPlayPause = clickToPlayPause;
}
public boolean isShowComments() {
return showComments;
}
public void setShowComments(boolean showComments) {
this.showComments = showComments;
}
public boolean isShowRating() {
return showRating;
}
public void setShowRating(boolean showRating) {
this.showRating = showRating;
}
public boolean isShowAnnotations() {
return showAnnotations;
}
public void setShowAnnotations(boolean showAnnotations) {
this.showAnnotations = showAnnotations;
}
public boolean isDragAnnotations() {
return dragAnnotations;
}
public void setDragAnnotations(boolean dragAnnotations) {
this.dragAnnotations = dragAnnotations;
}
public boolean isShowQuestions() {
return showQuestions;
}
public void setShowQuestions(boolean showQuestions) {
this.showQuestions = showQuestions;
}
public boolean isShowTitle() {
return showTitle;
}
public void setShowTitle(boolean showTitle) {
this.showTitle = showTitle;
}
public boolean isShowDescription() {
return showDescription;
}
public void setShowDescription(boolean showDescription) {
this.showDescription = showDescription;
}
public boolean isAutoWidth() {
return autoWidth;
}
public void setAutoWidth(boolean autoWidth) {
this.autoWidth = autoWidth;
}
public boolean isShowPoster() {
return showPoster;
}
public void setShowPoster(boolean showPoster) {
this.showPoster = showPoster;
}
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public String getDescriptionText() {
return descriptionText;
}
public void setDescriptionText(String descriptionText) {
this.descriptionText = descriptionText;
}
public boolean isAuthorMode() {
return authorMode;
}
public void setAuthorMode(boolean authorMode) {
this.authorMode = authorMode;
}
public boolean isForwardSeekingRestricted() {
return forwardSeekingRestricted;
}
public void setForwardSeekingRestricted(boolean forwardSeekingRestricted) {
this.forwardSeekingRestricted = forwardSeekingRestricted;
}
/**
* @return true: store comments and ratings using the container resource given
* to the VideoDisplayController (e.g. the course resource);
* false: use the video resource to store the comments and ratings
*/
public boolean isUseContainerForCommentsAndRatings() {
return useContainerForCommentsAndRatings;
}
/**
* true: store comments and ratings using the container resource given to the
* VideoDisplayController (e.g. the course resource); false: use the video
* resource to store the comments and ratings
*
* @param useContainerForCommentsAndRatings
*/
public void setUseContainerForCommentsAndRatings(boolean useContainerForCommentsAndRatings) {
this.useContainerForCommentsAndRatings = useContainerForCommentsAndRatings;
}
}
|
3e1a09cfac3d0a31f752f8dbbbdb5d40b7c17986 | 753 | java | Java | rxarch/src/main/java/io/github/mechatronik/rxarch/RxArch.java | mechatronik/rxarch | 9ac793c5d50503a41b517522e85e2434bed396ea | [
"MIT"
] | null | null | null | rxarch/src/main/java/io/github/mechatronik/rxarch/RxArch.java | mechatronik/rxarch | 9ac793c5d50503a41b517522e85e2434bed396ea | [
"MIT"
] | null | null | null | rxarch/src/main/java/io/github/mechatronik/rxarch/RxArch.java | mechatronik/rxarch | 9ac793c5d50503a41b517522e85e2434bed396ea | [
"MIT"
] | null | null | null | 23.53125 | 76 | 0.713147 | 11,060 | /*
* Copyright © 2018 Konrad Kowalewski
*
* This code is licensed under MIT license (see LICENSE for details)
*/
package io.github.mechatronik.rxarch;
import android.arch.lifecycle.LiveData;
import io.reactivex.MaybeSource;
import io.reactivex.ObservableSource;
import io.reactivex.SingleSource;
public final class RxArch {
private RxArch() {}
public static <T> LiveData<T> toLiveData(ObservableSource<T> upstream) {
return new RxObservableLiveData<>(upstream);
}
public static <T> LiveData<T> toLiveData(SingleSource<T> upstream) {
return new RxSingleLiveData<>(upstream);
}
public static <T> LiveData<T> toLiveData(MaybeSource<T> upstream) {
return new RxMaybeLiveData<>(upstream);
}
}
|
3e1a09e74b23fb1f588d1b10f819e4d5a73f9187 | 1,639 | java | Java | aliyun-java-sdk-emr/src/main/java/com/aliyuncs/emr/model/v20160408/DescribeSecurityGroupAttributeRequest.java | ssy352959096/aliyun-openapi-java-sdk | 7decd0e2273445b4311d576202fb6151e2194596 | [
"Apache-2.0"
] | 3 | 2021-01-25T16:15:23.000Z | 2021-01-25T16:15:54.000Z | aliyun-java-sdk-emr/src/main/java/com/aliyuncs/emr/model/v20160408/DescribeSecurityGroupAttributeRequest.java | 03040081/aliyun-openapi-java-sdk | cf7a6bf5355f0dce0a7de21591f22d337377866c | [
"Apache-2.0"
] | null | null | null | aliyun-java-sdk-emr/src/main/java/com/aliyuncs/emr/model/v20160408/DescribeSecurityGroupAttributeRequest.java | 03040081/aliyun-openapi-java-sdk | cf7a6bf5355f0dce0a7de21591f22d337377866c | [
"Apache-2.0"
] | null | null | null | 26.868852 | 114 | 0.751068 | 11,061 | /*
* 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.aliyuncs.emr.model.v20160408;
import com.aliyuncs.RpcAcsRequest;
/**
* @author auto create
* @version
*/
public class DescribeSecurityGroupAttributeRequest extends RpcAcsRequest<DescribeSecurityGroupAttributeResponse> {
public DescribeSecurityGroupAttributeRequest() {
super("Emr", "2016-04-08", "DescribeSecurityGroupAttribute");
}
private Long resourceOwnerId;
private String clusterId;
public Long getResourceOwnerId() {
return this.resourceOwnerId;
}
public void setResourceOwnerId(Long resourceOwnerId) {
this.resourceOwnerId = resourceOwnerId;
if(resourceOwnerId != null){
putQueryParameter("ResourceOwnerId", resourceOwnerId.toString());
}
}
public String getClusterId() {
return this.clusterId;
}
public void setClusterId(String clusterId) {
this.clusterId = clusterId;
if(clusterId != null){
putQueryParameter("ClusterId", clusterId);
}
}
@Override
public Class<DescribeSecurityGroupAttributeResponse> getResponseClass() {
return DescribeSecurityGroupAttributeResponse.class;
}
}
|
3e1a09fc8f42e7ce2da97daad8652af0ca5b2cae | 2,183 | java | Java | Mage.Sets/src/mage/cards/w/WeightOfSpires.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/w/WeightOfSpires.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/w/WeightOfSpires.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 30.319444 | 141 | 0.707284 | 11,062 |
package mage.cards.w;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.DamageTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.filter.StaticFilters;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author TheElk801
*/
public final class WeightOfSpires extends CardImpl {
public WeightOfSpires(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{R}");
// Weight of Spires deals damage to target creature equal to the number of nonbasic lands that creature's controller controls.
this.getSpellAbility().addEffect(new WeightOfSpiresEffect());
this.getSpellAbility().addTarget(new TargetCreaturePermanent());
}
private WeightOfSpires(final WeightOfSpires card) {
super(card);
}
@Override
public WeightOfSpires copy() {
return new WeightOfSpires(this);
}
}
class WeightOfSpiresEffect extends OneShotEffect {
WeightOfSpiresEffect() {
super(Outcome.Benefit);
this.staticText = "{this} deals damage to target creature equal to the number of nonbasic lands that creature's controller controls";
}
WeightOfSpiresEffect(final WeightOfSpiresEffect effect) {
super(effect);
}
@Override
public WeightOfSpiresEffect copy() {
return new WeightOfSpiresEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Permanent creature = game.getPermanent(source.getFirstTarget());
if (creature == null) {
return false;
}
Player player = game.getPlayer(creature.getControllerId());
if (player == null) {
return false;
}
int damage = game.getBattlefield().getAllActivePermanents(StaticFilters.FILTER_LANDS_NONBASIC, player.getId(), game).size();
return new DamageTargetEffect(damage).apply(game, source);
}
}
|
3e1a0bf1e2a02b8401b33e3b937eede609069f98 | 13,958 | java | Java | src/java/org/apache/cassandra/cql3/statements/CreateMaterializedViewStatement.java | Icaruszzc/cassandra | 47886dff3d13534070b2bc6690b807edec3ac567 | [
"Apache-2.0"
] | null | null | null | src/java/org/apache/cassandra/cql3/statements/CreateMaterializedViewStatement.java | Icaruszzc/cassandra | 47886dff3d13534070b2bc6690b807edec3ac567 | [
"Apache-2.0"
] | null | null | null | src/java/org/apache/cassandra/cql3/statements/CreateMaterializedViewStatement.java | Icaruszzc/cassandra | 47886dff3d13534070b2bc6690b807edec3ac567 | [
"Apache-2.0"
] | null | null | null | 49.496454 | 185 | 0.644362 | 11,063 | /*
* 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.cassandra.cql3.statements;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Iterables;
import org.apache.cassandra.auth.Permission;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.config.MaterializedViewDefinition;
import org.apache.cassandra.cql3.CFName;
import org.apache.cassandra.cql3.ColumnIdentifier;
import org.apache.cassandra.cql3.selection.RawSelector;
import org.apache.cassandra.cql3.selection.Selectable;
import org.apache.cassandra.db.view.MaterializedView;
import org.apache.cassandra.exceptions.AlreadyExistsException;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.exceptions.RequestValidationException;
import org.apache.cassandra.exceptions.UnauthorizedException;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.ClientWarn;
import org.apache.cassandra.service.MigrationManager;
import org.apache.cassandra.thrift.ThriftValidation;
import org.apache.cassandra.transport.Event;
public class CreateMaterializedViewStatement extends SchemaAlteringStatement
{
private final CFName baseName;
private final List<RawSelector> selectClause;
private final List<ColumnIdentifier.Raw> notNullWhereClause;
private final List<ColumnIdentifier.Raw> partitionKeys;
private final List<ColumnIdentifier.Raw> clusteringKeys;
public final CFProperties properties = new CFProperties();
private final boolean ifNotExists;
public CreateMaterializedViewStatement(CFName viewName,
CFName baseName,
List<RawSelector> selectClause,
List<ColumnIdentifier.Raw> notNullWhereClause,
List<ColumnIdentifier.Raw> partitionKeys,
List<ColumnIdentifier.Raw> clusteringKeys,
boolean ifNotExists)
{
super(viewName);
this.baseName = baseName;
this.selectClause = selectClause;
this.notNullWhereClause = notNullWhereClause;
this.partitionKeys = partitionKeys;
this.clusteringKeys = clusteringKeys;
this.ifNotExists = ifNotExists;
}
public void checkAccess(ClientState state) throws UnauthorizedException, InvalidRequestException
{
if (!baseName.hasKeyspace())
baseName.setKeyspace(keyspace(), true);
state.hasColumnFamilyAccess(keyspace(), baseName.getColumnFamily(), Permission.ALTER);
}
public void validate(ClientState state) throws RequestValidationException
{
// We do validation in announceMigration to reduce doubling up of work
}
public boolean announceMigration(boolean isLocalOnly) throws RequestValidationException
{
// We need to make sure that:
// - primary key includes all columns in base table's primary key
// - make sure that the select statement does not have anything other than columns
// and their names match the base table's names
// - make sure that primary key does not include any collections
// - make sure there is no where clause in the select statement
// - make sure there is not currently a table or view
// - make sure baseTable gcGraceSeconds > 0
properties.validate();
if (properties.useCompactStorage)
throw new InvalidRequestException("Cannot use 'COMPACT STORAGE' when defining a materialized view");
// We enforce the keyspace because if the RF is different, the logic to wait for a
// specific replica would break
if (!baseName.getKeyspace().equals(keyspace()))
throw new InvalidRequestException("Cannot create a materialized view on a table in a separate keyspace");
CFMetaData cfm = ThriftValidation.validateColumnFamily(baseName.getKeyspace(), baseName.getColumnFamily());
if (cfm.isCounter())
throw new InvalidRequestException("Materialized views are not supported on counter tables");
if (cfm.isMaterializedView())
throw new InvalidRequestException("Materialized views cannot be created against other materialized views");
if (cfm.params.gcGraceSeconds == 0)
{
throw new InvalidRequestException(String.format("Cannot create materialized view '%s' for base table " +
"'%s' with gc_grace_seconds of 0, since this value is " +
"used to TTL undelivered updates. Setting gc_grace_seconds" +
" too low might cause undelivered updates to expire " +
"before being replayed.", cfName.getColumnFamily(),
baseName.getColumnFamily()));
}
Set<ColumnIdentifier> included = new HashSet<>();
for (RawSelector selector : selectClause)
{
Selectable.Raw selectable = selector.selectable;
if (selectable instanceof Selectable.WithFieldSelection.Raw)
throw new InvalidRequestException("Cannot select out a part of type when defining a materialized view");
if (selectable instanceof Selectable.WithFunction.Raw)
throw new InvalidRequestException("Cannot use function when defining a materialized view");
if (selectable instanceof Selectable.WritetimeOrTTL.Raw)
throw new InvalidRequestException("Cannot use function when defining a materialized view");
ColumnIdentifier identifier = (ColumnIdentifier) selectable.prepare(cfm);
if (selector.alias != null)
throw new InvalidRequestException(String.format("Cannot alias column '%s' as '%s' when defining a materialized view", identifier.toString(), selector.alias.toString()));
ColumnDefinition cdef = cfm.getColumnDefinition(identifier);
if (cdef == null)
throw new InvalidRequestException("Unknown column name detected in CREATE MATERIALIZED VIEW statement : "+identifier);
if (cdef.isStatic())
ClientWarn.warn(String.format("Unable to include static column '%s' in Materialized View SELECT statement", identifier));
else
included.add(identifier);
}
Set<ColumnIdentifier.Raw> targetPrimaryKeys = new HashSet<>();
for (ColumnIdentifier.Raw identifier : Iterables.concat(partitionKeys, clusteringKeys))
{
if (!targetPrimaryKeys.add(identifier))
throw new InvalidRequestException("Duplicate entry found in PRIMARY KEY: "+identifier);
ColumnDefinition cdef = cfm.getColumnDefinition(identifier.prepare(cfm));
if (cdef == null)
throw new InvalidRequestException("Unknown column name detected in CREATE MATERIALIZED VIEW statement : "+identifier);
if (cfm.getColumnDefinition(identifier.prepare(cfm)).type.isMultiCell())
throw new InvalidRequestException(String.format("Cannot use MultiCell column '%s' in PRIMARY KEY of materialized view", identifier));
if (cdef.isStatic())
throw new InvalidRequestException(String.format("Cannot use Static column '%s' in PRIMARY KEY of materialized view", identifier));
}
Set<ColumnIdentifier> basePrimaryKeyCols = new HashSet<>();
for (ColumnDefinition definition : Iterables.concat(cfm.partitionKeyColumns(), cfm.clusteringColumns()))
basePrimaryKeyCols.add(definition.name);
List<ColumnIdentifier> targetClusteringColumns = new ArrayList<>();
List<ColumnIdentifier> targetPartitionKeys = new ArrayList<>();
Set<ColumnIdentifier> notNullColumns = new HashSet<>();
if (notNullWhereClause != null)
{
for (ColumnIdentifier.Raw raw : notNullWhereClause)
{
notNullColumns.add(raw.prepare(cfm));
}
}
// This is only used as an intermediate state; this is to catch whether multiple non-PK columns are used
boolean hasNonPKColumn = false;
for (ColumnIdentifier.Raw raw : partitionKeys)
{
hasNonPKColumn = getColumnIdentifier(cfm, basePrimaryKeyCols, hasNonPKColumn, raw, targetPartitionKeys, notNullColumns);
}
for (ColumnIdentifier.Raw raw : clusteringKeys)
{
hasNonPKColumn = getColumnIdentifier(cfm, basePrimaryKeyCols, hasNonPKColumn, raw, targetClusteringColumns, notNullColumns);
}
// We need to include all of the primary key colums from the base table in order to make sure that we do not
// overwrite values in the materialized view. We cannot support "collapsing" the base table into a smaller
// number of rows in the view because if we need to generate a tombstone, we have no way of knowing which value
// is currently being used in the view and whether or not to generate a tombstone.
// In order to not surprise our users, we require that they include all of the columns. We provide them with
// a list of all of the columns left to include.
boolean missingClusteringColumns = false;
StringBuilder columnNames = new StringBuilder();
for (ColumnDefinition def : cfm.allColumns())
{
if (!def.isPrimaryKeyColumn()) continue;
ColumnIdentifier identifier = def.name;
if (!targetClusteringColumns.contains(identifier) && !targetPartitionKeys.contains(identifier))
{
if (missingClusteringColumns)
columnNames.append(',');
else
missingClusteringColumns = true;
columnNames.append(identifier);
}
}
if (missingClusteringColumns)
throw new InvalidRequestException(String.format("Cannot create Materialized View %s without primary key columns from base %s (%s)",
columnFamily(), baseName.getColumnFamily(), columnNames.toString()));
if (targetPartitionKeys.isEmpty())
throw new InvalidRequestException("Must select at least a column for a Materialized View");
if (targetClusteringColumns.isEmpty())
throw new InvalidRequestException("No columns are defined for Materialized View other than primary key");
MaterializedViewDefinition definition = new MaterializedViewDefinition(baseName.getColumnFamily(),
columnFamily(),
targetPartitionKeys,
targetClusteringColumns,
included);
CFMetaData indexCf = MaterializedView.getCFMetaData(definition, cfm, properties);
try
{
MigrationManager.announceNewColumnFamily(indexCf, isLocalOnly);
}
catch (AlreadyExistsException e)
{
if (ifNotExists)
return false;
throw e;
}
CFMetaData newCfm = cfm.copy();
newCfm.materializedViews(newCfm.getMaterializedViews().with(definition));
MigrationManager.announceColumnFamilyUpdate(newCfm, false, isLocalOnly);
return true;
}
private static boolean getColumnIdentifier(CFMetaData cfm,
Set<ColumnIdentifier> basePK,
boolean hasNonPKColumn,
ColumnIdentifier.Raw raw,
List<ColumnIdentifier> columns,
Set<ColumnIdentifier> allowedPKColumns)
{
ColumnIdentifier identifier = raw.prepare(cfm);
boolean isPk = basePK.contains(identifier);
if (!isPk && hasNonPKColumn)
{
throw new InvalidRequestException(String.format("Cannot include more than one non-primary key column '%s' in materialized view partition key", identifier));
}
if (!allowedPKColumns.contains(identifier))
{
throw new InvalidRequestException(String.format("Primary key column '%s' is required to be filtered by 'IS NOT NULL'", identifier));
}
columns.add(identifier);
return !isPk;
}
public Event.SchemaChange changeEvent()
{
return new Event.SchemaChange(Event.SchemaChange.Change.CREATED, Event.SchemaChange.Target.TABLE, keyspace(), columnFamily());
}
}
|
3e1a0d61166b3fdf2e094e2c712ea8bf2387f3d7 | 900 | java | Java | xchange-bitcurex/src/main/java/com/xeiam/xchange/bitcurex/Bitcurex.java | PiotrLadyzynski/XChange | 634c8bc515df57a99ca0fe2adcd7fb361cc338b5 | [
"MIT"
] | 11 | 2015-07-19T00:56:14.000Z | 2021-05-21T20:31:44.000Z | xchange-bitcurex/src/main/java/com/xeiam/xchange/bitcurex/Bitcurex.java | joansmith3/XChange | 83c9f154cfb56ad53e0e5cdff487c67b261fdebf | [
"MIT"
] | null | null | null | xchange-bitcurex/src/main/java/com/xeiam/xchange/bitcurex/Bitcurex.java | joansmith3/XChange | 83c9f154cfb56ad53e0e5cdff487c67b261fdebf | [
"MIT"
] | 5 | 2015-03-13T07:13:35.000Z | 2020-06-22T03:36:22.000Z | 28.125 | 95 | 0.782222 | 11,064 | package com.xeiam.xchange.bitcurex;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.xeiam.xchange.bitcurex.dto.marketdata.BitcurexDepth;
import com.xeiam.xchange.bitcurex.dto.marketdata.BitcurexTicker;
import com.xeiam.xchange.bitcurex.dto.marketdata.BitcurexTrade;
@Path("api")
@Produces(MediaType.APPLICATION_JSON)
public interface Bitcurex {
@GET
@Path("{currency}/ticker.json")
public BitcurexTicker getTicker(@PathParam("currency") String currency) throws IOException;
@GET
@Path("{currency}/orderbook.json")
public BitcurexDepth getFullDepth(@PathParam("currency") String currency) throws IOException;
@GET
@Path("{currency}/trades.json")
public BitcurexTrade[] getTrades(@PathParam("currency") String currency) throws IOException;
}
|
3e1a0d664dd57c24ee9184b23dddbe611021cb66 | 422 | java | Java | ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/entity/RelationStatus.java | FlameYagami/RuoYi-bilibili | a24af1e535969d7aeae417fb4a9a6a80507af1fc | [
"MIT"
] | null | null | null | ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/entity/RelationStatus.java | FlameYagami/RuoYi-bilibili | a24af1e535969d7aeae417fb4a9a6a80507af1fc | [
"MIT"
] | null | null | null | ruoyi-admin/src/main/java/com/ruoyi/web/controller/demo/entity/RelationStatus.java | FlameYagami/RuoYi-bilibili | a24af1e535969d7aeae417fb4a9a6a80507af1fc | [
"MIT"
] | null | null | null | 19.181818 | 53 | 0.755924 | 11,065 | package com.ruoyi.web.controller.demo.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.Date;
/**
* Created by Flame on 2021/02/07.
**/
@Data
@TableName("t_bilibili_relation_status")
public class RelationStatus {
private long id;
private long mid;
private long follower;
private Date createDate;
}
|
3e1a0da63cb01014f4c1931c9c54470b88135f47 | 2,794 | java | Java | stelvio-batch-java/src/main/java/no/stelvio/batch/count/support/CounterEvent.java | navikt/stelvio | a13c081b6fb96425464c3de278b496a6be9d6da4 | [
"MIT"
] | null | null | null | stelvio-batch-java/src/main/java/no/stelvio/batch/count/support/CounterEvent.java | navikt/stelvio | a13c081b6fb96425464c3de278b496a6be9d6da4 | [
"MIT"
] | null | null | null | stelvio-batch-java/src/main/java/no/stelvio/batch/count/support/CounterEvent.java | navikt/stelvio | a13c081b6fb96425464c3de278b496a6be9d6da4 | [
"MIT"
] | null | null | null | 23.090909 | 119 | 0.648533 | 11,066 | package no.stelvio.batch.count.support;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* A batch event that can be counted by a {@link BatchCounter}.
*
*
*/
public final class CounterEvent {
private static ConcurrentHashMap<Class<?>, Set<CounterEvent>> registeredEvents =
new ConcurrentHashMap<>();
/**
* Defines different types of {@link CounterEvent}.
*
*
*/
public enum EventType {
/** */
FUNCTIONAL,
/** */
TECHNICAL
}
private final String name;
private final String description;
private final EventType type;
private CounterEvent(String name, String description, EventType type) {
this.name = name;
this.description = description;
this.type = type;
}
/**
* Creates a new event and registrates it.
*
* @param eventClass
* Class that defines the event
* @param name
* Name of event
* @param description
* Description of event
* @param type
* Type of event
* @return The newly created event
*/
public static CounterEvent createCounterEvent(Class<?> eventClass, String name, String description, EventType type) {
CounterEvent event = new CounterEvent(name, description, type);
Set<CounterEvent> events = registeredEvents.get(eventClass);
if (events == null) {
Set<CounterEvent> newEventSet = new HashSet<>();
events = registeredEvents.putIfAbsent(eventClass, newEventSet);
if (events == null) {
events = newEventSet;
}
}
events.add(event);
return event;
}
/**
* @return the registeredEvents
*/
public static Map<Class<?>, Set<CounterEvent>> getRegisteredEvents() {
return registeredEvents;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CounterEvent)) {
return false;
}
CounterEvent event = (CounterEvent) o;
return new EqualsBuilder().append(name, event.name).append(description, event.description).append(type, event.type)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(7, 13).append(name).append(description).append(type).toHashCode();
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the type
*/
public EventType getType() {
return type;
}
@Override
public String toString() {
return "name=" + name + ", description=" + description + ", type=" + type;
}
}
|
3e1a0dda831a776cdaa8324ab2f0f94d672bbb2d | 2,883 | java | Java | portfolio/src/main/java/com/google/sps/utils/SpeechUtils.java | abbymapes/step43-2020 | c68a045e265f0ac461b9e6c08089dea044354699 | [
"Apache-2.0"
] | 1 | 2020-06-23T03:10:08.000Z | 2020-06-23T03:10:08.000Z | portfolio/src/main/java/com/google/sps/utils/SpeechUtils.java | abbymapes/step43-2020 | c68a045e265f0ac461b9e6c08089dea044354699 | [
"Apache-2.0"
] | 19 | 2020-06-23T17:16:21.000Z | 2020-07-29T14:14:49.000Z | portfolio/src/main/java/com/google/sps/utils/SpeechUtils.java | abbymapes/step43-2020 | c68a045e265f0ac461b9e6c08089dea044354699 | [
"Apache-2.0"
] | 3 | 2020-06-23T01:34:51.000Z | 2020-06-23T16:38:21.000Z | 37.441558 | 96 | 0.721471 | 11,067 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.sps.utils;
// Imports the Google Cloud client library
import com.google.cloud.texttospeech.v1.AudioConfig;
import com.google.cloud.texttospeech.v1.AudioEncoding;
import com.google.cloud.texttospeech.v1.SsmlVoiceGender;
import com.google.cloud.texttospeech.v1.SynthesisInput;
import com.google.cloud.texttospeech.v1.SynthesizeSpeechResponse;
import com.google.cloud.texttospeech.v1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1.VoiceSelectionParams;
import com.google.protobuf.ByteString;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class SpeechUtils {
/**
* Demonstrates using the Text to Speech client to synthesize text or ssml.
*
* @param text the raw text to be synthesized. (e.g., "Hello there!")
* @throws Exception on TextToSpeechClient Errors.
*/
public static ByteString synthesizeText(String text, String languageCode) throws Exception {
languageCode = (languageCode == null) ? "en-US" : languageCode;
// Instantiates a client
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// Set the text input to be synthesized
SynthesisInput input = SynthesisInput.newBuilder().setText(text).build();
// Build the voice request
VoiceSelectionParams voice =
VoiceSelectionParams.newBuilder()
.setLanguageCode(languageCode) // languageCode = "en_us"
.setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
.build();
// Select the type of audio file you want returned
AudioConfig audioConfig =
AudioConfig.newBuilder()
.setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
.build();
// Perform the text-to-speech request
SynthesizeSpeechResponse response =
textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
// Get the audio contents from the response
ByteString audioContents = response.getAudioContent();
// Write the response to the output file.
OutputStream out = new FileOutputStream("output.mp3");
out.write(audioContents.toByteArray());
return audioContents;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
3e1a0e04d1a5f644f8285c5c48b8cdd8e3eee968 | 6,552 | java | Java | vcx/wrappers/java/vcx/src/main/java/com/evernym/sdk/vcx/wallet/WalletApi.java | tplooker/sdk | 8feef310a9867771da24ecdfa67dd69fcb0e2d54 | [
"Apache-2.0"
] | null | null | null | vcx/wrappers/java/vcx/src/main/java/com/evernym/sdk/vcx/wallet/WalletApi.java | tplooker/sdk | 8feef310a9867771da24ecdfa67dd69fcb0e2d54 | [
"Apache-2.0"
] | null | null | null | vcx/wrappers/java/vcx/src/main/java/com/evernym/sdk/vcx/wallet/WalletApi.java | tplooker/sdk | 8feef310a9867771da24ecdfa67dd69fcb0e2d54 | [
"Apache-2.0"
] | null | null | null | 38.315789 | 139 | 0.671551 | 11,068 | package com.evernym.sdk.vcx.wallet;
import android.util.Log;
import com.evernym.sdk.vcx.LibVcx;
import com.evernym.sdk.vcx.ParamGuard;
import com.evernym.sdk.vcx.VcxException;
import com.evernym.sdk.vcx.VcxJava;
import com.sun.jna.Callback;
import java9.util.concurrent.CompletableFuture;
public class WalletApi extends VcxJava.API {
private static String TAG = "JAVA_WRAPPER::API_VCX::WALLET";
private WalletApi(){}
private static Callback vcxExportWalletCB = new Callback() {
public void callback(int command_handle, int err, int export_handle){
CompletableFuture<Integer> future = (CompletableFuture<Integer>) removeFuture(command_handle);
if(!checkCallback(future,err)) return;
Integer result = export_handle;
future.complete(result);
}
};
public static CompletableFuture<Integer> exportWallet(
String exportPath,
String encryptionKey
) throws VcxException {
ParamGuard.notNull(exportPath, "exportPath");
ParamGuard.notNull(encryptionKey, "encryptionKey");
CompletableFuture<Integer> future = new CompletableFuture<Integer>();
int commandHandle = addFuture(future);
int result = LibVcx.api.vcx_wallet_export(commandHandle, exportPath, encryptionKey, vcxExportWalletCB);
checkResult(result);
return future;
}
private static Callback vcxImportWalletCB = new Callback() {
public void callback(int command_handle, int err, int import_handle){
CompletableFuture<Integer> future = (CompletableFuture<Integer>) removeFuture(command_handle);
if(!checkCallback(future,err)) return;
Integer result = import_handle;
future.complete(result);
}
};
public static CompletableFuture<Integer> importWallet(
String config
) throws VcxException {
ParamGuard.notNull(config, "config");
CompletableFuture<Integer> future = new CompletableFuture<Integer>();
int commandHandle = addFuture(future);
int result = LibVcx.api.vcx_wallet_import(commandHandle, config, vcxImportWalletCB);
checkResult(result);
return future;
}
private static Callback vcxAddRecordWalletCB = new Callback() {
public void callback(int command_handle, int err){
CompletableFuture<Integer> future = (CompletableFuture<Integer>) removeFuture(command_handle);
if(!checkCallback(future,err)) return;
Integer result = command_handle;
future.complete(result);
}
};
public static CompletableFuture<Integer> addRecordWallet(
String recordType,
String recordId,
String recordValue
) throws VcxException {
ParamGuard.notNull(recordType, "recordType");
ParamGuard.notNull(recordId, "recordId");
ParamGuard.notNull(recordValue, "recordValue");
CompletableFuture<Integer> future = new CompletableFuture<Integer>();
int commandHandle = addFuture(future);
String recordTag = "{}";
int result = LibVcx.api.vcx_wallet_add_record( commandHandle, recordType, recordId, recordValue, recordTag, vcxAddRecordWalletCB);
checkResult(result);
return future;
}
private static Callback vcxDeleteRecordWalletCB = new Callback() {
public void callback(int command_handle, int err){
CompletableFuture<Integer> future = (CompletableFuture<Integer>) removeFuture(command_handle);
if(!checkCallback(future,err)) return;
Integer result = command_handle;
future.complete(result);
}
};
public static CompletableFuture<Integer> deleteRecordWallet(
String recordType,
String recordId
) throws VcxException {
ParamGuard.notNull(recordType, "recordType");
ParamGuard.notNull(recordId, "recordId");
CompletableFuture<Integer> future = new CompletableFuture<Integer>();
int commandHandle = addFuture(future);
int result = LibVcx.api.vcx_wallet_delete_record( commandHandle, recordType, recordId, vcxDeleteRecordWalletCB);
checkResult(result);
return future;
}
private static Callback vcxGetRecordWalletCB = new Callback() {
public void callback(int command_handle, int err, String wallet_value){
CompletableFuture<String> future = (CompletableFuture<String>) removeFuture(command_handle);
if(!checkCallback(future,err)) return;
String result = wallet_value;
// if nonzero errorcode, ignore wallet_value (null)
// if error fail
// if error = 0 then send the result
future.complete(result);
}
};
public static CompletableFuture<String> getRecordWallet(
String recordType,
String recordId,
String recordValue
) throws VcxException {
ParamGuard.notNull(recordType, "recordType");
ParamGuard.notNull(recordId, "recordId");
ParamGuard.notNull(recordValue, "recordValue");
CompletableFuture<String> future = new CompletableFuture<String>();
int commandHandle = addFuture(future);
String recordTag = "{}";
int result = LibVcx.api.vcx_wallet_get_record( commandHandle, recordType, recordId, recordTag, vcxGetRecordWalletCB);
checkResult(result);
return future;
}
private static Callback vcxUpdateRecordWalletCB = new Callback() {
public void callback(int command_handle, int err){
CompletableFuture<Integer> future = (CompletableFuture<Integer>) removeFuture(command_handle);
if(!checkCallback(future,err)) return;
Integer result = command_handle;
future.complete(result);
}
};
public static CompletableFuture<Integer> updateRecordWallet(
String recordType,
String recordId,
String recordValue
) throws VcxException {
ParamGuard.notNull(recordType, "recordType");
ParamGuard.notNull(recordId, "recordId");
ParamGuard.notNull(recordValue, "recordValue");
CompletableFuture<Integer> future = new CompletableFuture<Integer>();
int commandHandle = addFuture(future);
int result = LibVcx.api.vcx_wallet_update_record_value( commandHandle, recordType, recordId, recordValue, vcxUpdateRecordWalletCB);
checkResult(result);
return future;
}
} |
3e1a0e9f5e6261eb52f4bcab4bc5bb4fc2478d18 | 2,431 | java | Java | domain-api/src/main/java/org/yes/cart/service/order/OrderSplittingStrategy.java | Yulyalu/yes-cart | 611f24daac39a7678400af1bd72e662b6b44c7c2 | [
"Apache-2.0"
] | 122 | 2015-07-15T08:26:40.000Z | 2022-03-14T08:02:29.000Z | domain-api/src/main/java/org/yes/cart/service/order/OrderSplittingStrategy.java | Yulyalu/yes-cart | 611f24daac39a7678400af1bd72e662b6b44c7c2 | [
"Apache-2.0"
] | 42 | 2016-11-13T07:22:55.000Z | 2022-03-31T19:58:11.000Z | domain-api/src/main/java/org/yes/cart/service/order/OrderSplittingStrategy.java | Yulyalu/yes-cart | 611f24daac39a7678400af1bd72e662b6b44c7c2 | [
"Apache-2.0"
] | 88 | 2015-09-04T12:04:45.000Z | 2022-02-08T17:29:40.000Z | 34.728571 | 108 | 0.621144 | 11,069 | /*
* Copyright 2009 Inspire-Software.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yes.cart.service.order;
import org.yes.cart.shoppingcart.CartItem;
import org.yes.cart.shoppingcart.ShoppingCart;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* User: denispavlov
* Date: 18/02/2016
* Time: 08:33
*/
public interface OrderSplittingStrategy {
/**
* Determine delivery buckets for given item at current point in time.
*
* @param item item to determine buckets for
* @param cart cart with items for which buckets are calculated (item has to be one of the cart items)
*
* @return delivery group marker
*/
DeliveryBucket determineDeliveryBucket(CartItem item,
ShoppingCart cart);
/**
* Determine delivery buckets for given items at current point in time.
*
* @param shopId shop PK
* @param items items to determine buckets for
* @param onePhysicalDelivery true if need to create one physical delivery (per supplier).
*
* @return cart items by delivery bucket
*/
Map<DeliveryBucket, List<CartItem>> determineDeliveryBuckets(long shopId,
Collection<CartItem> items,
Map<String, Boolean> onePhysicalDelivery);
/**
* Can order have multiple deliveries by supplier.
*
* @param shopId shop PK
* @param items items to determine buckets for
*
* @return true in case if order can have multiple physical deliveries by supplier.
*/
Map<String, Boolean> isMultipleDeliveriesAllowed(long shopId,
Collection<CartItem> items);
}
|
3e1a0f2539117b5c1792f45ae205aeda910c167b | 328 | java | Java | lib_common/src/main/java/com/guiying/module/common/base/IApplicationDelegate.java | KyrieWangyz/ModulePattern-master | 73cc7ada08ab879dfa2c2e0e868455644ed7cb9d | [
"Apache-2.0"
] | 1 | 2018-12-03T07:32:51.000Z | 2018-12-03T07:32:51.000Z | lib_common/src/main/java/com/guiying/module/common/base/IApplicationDelegate.java | KyrieWangyz/ModulePattern-master | 73cc7ada08ab879dfa2c2e0e868455644ed7cb9d | [
"Apache-2.0"
] | null | null | null | lib_common/src/main/java/com/guiying/module/common/base/IApplicationDelegate.java | KyrieWangyz/ModulePattern-master | 73cc7ada08ab879dfa2c2e0e868455644ed7cb9d | [
"Apache-2.0"
] | null | null | null | 13.666667 | 39 | 0.676829 | 11,070 | package com.guiying.module.common.base;
import android.support.annotation.Keep;
/**
* <p>类说明</p>
*
* @author Kyrie
* @version V2.8.3
* @name ApplicationDelegate
*/
@Keep
public interface IApplicationDelegate {
void onCreate();
void onTerminate();
void onLowMemory();
void onTrimMemory(int level);
}
|
3e1a0f73a1f9762c3a7e23ffb5b21fb5319fd5cb | 1,237 | java | Java | src/main/java/com/urcpo/mstr/beans/Customer.java | Methodo-Stats-Tutor/backend | 9cedccacd1ce11dda495c98e236e1d2c6ae30d62 | [
"MIT"
] | null | null | null | src/main/java/com/urcpo/mstr/beans/Customer.java | Methodo-Stats-Tutor/backend | 9cedccacd1ce11dda495c98e236e1d2c6ae30d62 | [
"MIT"
] | null | null | null | src/main/java/com/urcpo/mstr/beans/Customer.java | Methodo-Stats-Tutor/backend | 9cedccacd1ce11dda495c98e236e1d2c6ae30d62 | [
"MIT"
] | null | null | null | 26.891304 | 62 | 0.701698 | 11,071 | package com.urcpo.mstr.beans;
/**
* 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.
*/
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Customer")
public class Customer {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
3e1a0f79d4fe3850f48faa99736a2b5894a535ea | 403 | java | Java | src/main/java/com/tambunan/handlers/TaxChangedHandler.java | timpamungkas/bootservice | 34e6886dfaa647cc99437968dcddabe49a054364 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tambunan/handlers/TaxChangedHandler.java | timpamungkas/bootservice | 34e6886dfaa647cc99437968dcddabe49a054364 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/tambunan/handlers/TaxChangedHandler.java | timpamungkas/bootservice | 34e6886dfaa647cc99437968dcddabe49a054364 | [
"Apache-2.0"
] | null | null | null | 26.866667 | 67 | 0.771712 | 11,072 | package com.tambunan.handlers;
import com.google.common.eventbus.Subscribe;
import com.tambunan.bus.BuzzHandler;
import com.tambunan.bus.BuzzMessage;
import com.tambunan.messages.TaxChanged;
public class TaxChangedHandler implements BuzzHandler<TaxChanged> {
@Override
@Subscribe
public void handle(TaxChanged message) {
System.out.println("Handling TaxChanged message ");
}
}
|
3e1a0fa885214f1cfb47a5f4689376961a0bad04 | 590 | java | Java | security/buckler_public/src/java/com/internal/pubsector/civilian/buckler/controllers/ControllerInterface.java | joshwarecom/joshwarecom.github.com | 8f7c1be0425b2dcf9d5b8231dd613b4ff7ad9442 | [
"MIT"
] | null | null | null | security/buckler_public/src/java/com/internal/pubsector/civilian/buckler/controllers/ControllerInterface.java | joshwarecom/joshwarecom.github.com | 8f7c1be0425b2dcf9d5b8231dd613b4ff7ad9442 | [
"MIT"
] | null | null | null | security/buckler_public/src/java/com/internal/pubsector/civilian/buckler/controllers/ControllerInterface.java | joshwarecom/joshwarecom.github.com | 8f7c1be0425b2dcf9d5b8231dd613b4ff7ad9442 | [
"MIT"
] | null | null | null | 28.095238 | 72 | 0.779661 | 11,073 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.internal.pubsector.civilian.buckler.controllers;
import com.internal.pubsector.civilian.buckler.managers.TestManager;
import com.internal.pubsector.civilian.buckler.managers.KeyManager;
import java.util.Map;
/**
*
* @author jowilson
*/
public interface ControllerInterface {
public Object go(Map<String, String[]> parameters) throws Exception;
public Boolean exposeTestManagerIfAllowed(TestManager m);
public Boolean exposeKeyManagerIfAllowed(KeyManager k);
}
|
3e1a0fc683bb83da41e6f78a059bc233005aaf53 | 973 | java | Java | clbs/src/main/java/com/zw/api/service/impl/SwaggerMediaServiceImpl.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | 1 | 2021-09-29T02:13:49.000Z | 2021-09-29T02:13:49.000Z | clbs/src/main/java/com/zw/api/service/impl/SwaggerMediaServiceImpl.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | null | null | null | clbs/src/main/java/com/zw/api/service/impl/SwaggerMediaServiceImpl.java | youyouqiu/hybrid-development | 784c5227a73d1e6609b701a42ef4cdfd6400d2b7 | [
"MIT"
] | null | null | null | 32.433333 | 105 | 0.76259 | 11,074 | package com.zw.api.service.impl;
import com.zw.api.domain.MediaInfo;
import com.zw.api.repository.mysql.SwaggerMediaDao;
import com.zw.api.service.SwaggerMediaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class SwaggerMediaServiceImpl implements SwaggerMediaService {
@Autowired
private SwaggerMediaDao swaggerMediaDao;
@Value("${fdfs.webServerUrl}")
private String mediaServerHost;
@Override
public List<MediaInfo> listMonitorMedia(String monitorName, LocalDateTime start, LocalDateTime end) {
final List<MediaInfo> mediaInfos = swaggerMediaDao.listMediaUrls(monitorName, start, end);
for (MediaInfo info : mediaInfos) {
info.setUrl(mediaServerHost + info.getUrl());
}
return mediaInfos;
}
}
|
3e1a0fcece3edaf1498be6916d53d1ce598249f6 | 3,975 | java | Java | clustering/src/main/java/io/hyperfoil/clustering/Run.java | Hyperfoil/Hyperfoil | fc3542f497403c0d23780f9f1de0a4579e01d55e | [
"Apache-2.0"
] | 38 | 2019-01-31T19:08:56.000Z | 2022-03-17T10:48:25.000Z | clustering/src/main/java/io/hyperfoil/clustering/Run.java | Hyperfoil/Hyperfoil | fc3542f497403c0d23780f9f1de0a4579e01d55e | [
"Apache-2.0"
] | 196 | 2019-01-16T15:12:28.000Z | 2022-03-25T07:11:19.000Z | clustering/src/main/java/io/hyperfoil/clustering/Run.java | Hyperfoil/Hyperfoil | fc3542f497403c0d23780f9f1de0a4579e01d55e | [
"Apache-2.0"
] | 20 | 2019-02-01T16:59:18.000Z | 2021-12-02T10:29:56.000Z | 33.686441 | 174 | 0.658113 | 11,075 | package io.hyperfoil.clustering;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import io.hyperfoil.api.config.Benchmark;
import io.hyperfoil.api.config.Phase;
import io.hyperfoil.controller.StatisticsStore;
import io.hyperfoil.core.util.Util;
import io.vertx.core.Promise;
class Run {
final String id;
final Path dir;
Benchmark benchmark;
final Map<String, ControllerPhase> phases = new HashMap<>();
final List<AgentInfo> agents = new ArrayList<>();
final Phase[] phasesById;
final List<Error> errors = new ArrayList<>();
final List<RunHookOutput> hookResults = new ArrayList<>();
long deployTimerId;
String description;
long startTime = Long.MIN_VALUE;
Promise<Long> terminateTime = Promise.promise();
boolean cancelled;
boolean completed;
Supplier<StatisticsStore> statsSupplier;
private StatisticsStore statisticsStore;
Run(String id, Path dir, Benchmark benchmark) {
this.id = id;
this.dir = dir;
this.benchmark = benchmark;
this.phasesById = benchmark.phasesById();
}
void initStore(StatisticsStore store) {
this.statisticsStore = store;
}
long nextTimestamp() {
long nextPhaseStart = phases.values().stream()
.filter(phase -> phase.status() == ControllerPhase.Status.NOT_STARTED && phase.definition().startTime() >= 0)
.mapToLong(phase -> startTime + phase.definition().startTime()).min().orElse(Long.MAX_VALUE);
long nextPhaseFinish = phases.values().stream()
.filter(phase -> phase.status() == ControllerPhase.Status.RUNNING)
.mapToLong(phase -> phase.absoluteStartTime() + phase.definition().duration()).min().orElse(Long.MAX_VALUE);
long nextPhaseTerminate = phases.values().stream()
.filter(phase -> (phase.status() == ControllerPhase.Status.RUNNING || phase.status() == ControllerPhase.Status.FINISHED) && phase.definition().maxDuration() >= 0)
.mapToLong(phase -> phase.absoluteStartTime() + phase.definition().maxDuration()).min().orElse(Long.MAX_VALUE);
return Math.min(Math.min(nextPhaseStart, nextPhaseFinish), nextPhaseTerminate);
}
ControllerPhase[] getAvailablePhases() {
return phases.values().stream().filter(phase -> phase.status() == ControllerPhase.Status.NOT_STARTED &&
startTime + phase.definition().startTime() <= System.currentTimeMillis() &&
phase.definition().startAfter().stream().allMatch(dep -> phases.get(dep).status().isFinished()) &&
phase.definition().startAfterStrict().stream().allMatch(dep -> phases.get(dep).status().isTerminated()))
.toArray(ControllerPhase[]::new);
}
public String phase(int phaseId) {
if (phaseId < phasesById.length) {
return phasesById[phaseId].name();
} else {
return null;
}
}
public StatisticsStore statisticsStore() {
if (statisticsStore != null) {
return statisticsStore;
} else if (statsSupplier != null) {
return statisticsStore = statsSupplier.get();
} else {
return null;
}
}
public boolean isLoaded() {
return statisticsStore != null;
}
public void unload() {
statisticsStore = null;
}
public static class Error {
public final AgentInfo agent;
public final Throwable error;
public Error(AgentInfo agent, Throwable error) {
this.agent = agent;
this.error = error;
}
@Override
public String toString() {
return (agent == null ? "" : agent.name + ": ") + Util.explainCauses(error);
}
}
public static class RunHookOutput {
public final String name;
public final String output;
public RunHookOutput(String name, String output) {
this.name = name;
this.output = output;
}
}
}
|
3e1a101628cb30c987f67a964ac0e022eb7d0a30 | 1,991 | java | Java | container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 4,054 | 2017-08-11T07:58:38.000Z | 2022-03-31T22:32:15.000Z | container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 4,854 | 2017-08-10T20:19:25.000Z | 2022-03-31T19:04:23.000Z | container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java | sagiyaho/vespa | 5865b9bb80b540f6d252312fa6002300b2f1c9ee | [
"Apache-2.0"
] | 541 | 2017-08-10T18:51:18.000Z | 2022-03-11T03:18:56.000Z | 35.553571 | 104 | 0.716223 | 11,076 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.query.profile.test;
import com.yahoo.search.query.profile.DimensionValues;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* @author Tony Vaagenes
*/
public class QueryProfileVariantsCloneTestCase {
@Test
public void test_that_interior_and_leaf_values_on_a_path_are_preserved_when_cloning() {
Map<String, String> dimensionBinding = createDimensionBinding("location", "norway");
QueryProfile profile = new QueryProfile("profile");
profile.setDimensions(keys(dimensionBinding));
DimensionValues dimensionValues = DimensionValues.createFrom(values(dimensionBinding));
profile.set("interior.leaf", "leafValue", dimensionValues, null);
profile.set("interior", "interiorValue", dimensionValues, null);
CompiledQueryProfile clone = profile.compile(null).clone();
assertEquals(profile.get("interior", dimensionBinding, null),
clone.get("interior", dimensionBinding));
assertEquals(profile.get("interior.leaf", dimensionBinding, null),
clone.get("interior.leaf", dimensionBinding));
}
private static Map<String,String> createDimensionBinding(String dimension, String value) {
Map<String, String> dimensionBinding = new HashMap<>();
dimensionBinding.put(dimension, value);
return Collections.unmodifiableMap(dimensionBinding);
}
private static String[] keys(Map<String, String> map) {
return map.keySet().toArray(new String[0]);
}
private static String[] values(Map<String, String> map) {
return map.values().toArray(new String[0]);
}
}
|
3e1a1050ed5fb7603db83d8e3703a86045893e15 | 1,139 | java | Java | gmall-pms/src/main/java/com/atguigu/gmall/pms/entity/SkuSaleAttrValueEntity.java | xujian19961108/gmall | 604aab46ca19a6a73a4a87d31bd83b4fc49fd08c | [
"Apache-2.0"
] | null | null | null | gmall-pms/src/main/java/com/atguigu/gmall/pms/entity/SkuSaleAttrValueEntity.java | xujian19961108/gmall | 604aab46ca19a6a73a4a87d31bd83b4fc49fd08c | [
"Apache-2.0"
] | 1 | 2021-04-22T17:01:37.000Z | 2021-04-22T17:01:37.000Z | gmall-pms/src/main/java/com/atguigu/gmall/pms/entity/SkuSaleAttrValueEntity.java | xujian19961108/gmall | 604aab46ca19a6a73a4a87d31bd83b4fc49fd08c | [
"Apache-2.0"
] | null | null | null | 19.982456 | 61 | 0.702371 | 11,077 | package com.atguigu.gmall.pms.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* sku销售属性&值
*
* @author canjian
* @email
* @date 2021-12-26 00:48:38
*/
@ApiModel
@Data
@TableName("pms_sku_sale_attr_value")
public class SkuSaleAttrValueEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
@ApiModelProperty(name = "id",value = "id")
private Long id;
/**
* sku_id
*/
@ApiModelProperty(name = "skuId",value = "sku_id")
private Long skuId;
/**
* attr_id
*/
@ApiModelProperty(name = "attrId",value = "attr_id")
private Long attrId;
/**
* 销售属性名
*/
@ApiModelProperty(name = "attrName",value = "销售属性名")
private String attrName;
/**
* 销售属性值
*/
@ApiModelProperty(name = "attrValue",value = "销售属性值")
private String attrValue;
/**
* 顺序
*/
@ApiModelProperty(name = "attrSort",value = "顺序")
private Integer attrSort;
}
|
3e1a106111f1877ffe5c53ad1fe9e6bf5313031b | 970 | java | Java | AppStoreTest/app/src/main/java/com/juanocampo/test/appstoretest/api/ProxyApp.java | ingjuanocampo/AppStoreTest | 01e91035f67e9ff3cc7400ec823f42d566064ebe | [
"Apache-2.0"
] | null | null | null | AppStoreTest/app/src/main/java/com/juanocampo/test/appstoretest/api/ProxyApp.java | ingjuanocampo/AppStoreTest | 01e91035f67e9ff3cc7400ec823f42d566064ebe | [
"Apache-2.0"
] | null | null | null | AppStoreTest/app/src/main/java/com/juanocampo/test/appstoretest/api/ProxyApp.java | ingjuanocampo/AppStoreTest | 01e91035f67e9ff3cc7400ec823f42d566064ebe | [
"Apache-2.0"
] | null | null | null | 26.944444 | 95 | 0.693814 | 11,078 | package com.juanocampo.test.appstoretest.api;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by juanocampo
*/
public class ProxyApp {
private final Context context;
private Itunes itunes;
public ProxyApp(Context context) {
this.context = context;
}
public Itunes getItunesInstance() {
if (isNetworkAvailable(context)) {
itunes = new ItunesApiClientImp(context);
} else {
itunes = new ItunesCacheImp(context);
}
return itunes;
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
|
3e1a10788023e9f5c4db853c04cb2cb791b8dd45 | 1,221 | java | Java | java/src/com/google/gxp/compiler/reparent/UnknownContentTypeError.java | xenomachina/gxp | 65acae881b2b43569725d36a0dab17d2ac787cdf | [
"Apache-2.0"
] | null | null | null | java/src/com/google/gxp/compiler/reparent/UnknownContentTypeError.java | xenomachina/gxp | 65acae881b2b43569725d36a0dab17d2ac787cdf | [
"Apache-2.0"
] | null | null | null | java/src/com/google/gxp/compiler/reparent/UnknownContentTypeError.java | xenomachina/gxp | 65acae881b2b43569725d36a0dab17d2ac787cdf | [
"Apache-2.0"
] | null | null | null | 33.916667 | 75 | 0.755938 | 11,079 | /*
* Copyright (C) 2008 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.gxp.compiler.reparent;
import com.google.gxp.compiler.alerts.ErrorAlert;
import com.google.gxp.compiler.alerts.SourcePosition;
import com.google.gxp.compiler.base.Node;
/**
* {@link com.google.gxp.compiler.alerts.Alert} which indicates that a
* unknown content type was encountered.
*/
public class UnknownContentTypeError extends ErrorAlert {
public UnknownContentTypeError(SourcePosition pos, String contentType) {
super(pos, "Unknown content-type: " + contentType);
}
public UnknownContentTypeError(Node node, String contentType) {
this(node.getSourcePosition(), contentType);
}
}
|
3e1a10c4ff0822f7caf3375a17a7c8109fdd59f7 | 3,999 | java | Java | src/main/java/lemon/core/Pair.java | emiruner/lemon | dd26d3457968b94ecdf534fc941a0e355bff3815 | [
"Apache-2.0"
] | null | null | null | src/main/java/lemon/core/Pair.java | emiruner/lemon | dd26d3457968b94ecdf534fc941a0e355bff3815 | [
"Apache-2.0"
] | 1 | 2021-01-17T15:02:35.000Z | 2021-01-17T15:02:35.000Z | src/main/java/lemon/core/Pair.java | emiruner/lemon | dd26d3457968b94ecdf534fc941a0e355bff3815 | [
"Apache-2.0"
] | null | null | null | 23.803571 | 71 | 0.541885 | 11,080 | package lemon.core;
import java.util.Iterator;
public class Pair extends LObjectBase implements Iterable<LObject> {
public static int TYPE = 3;
public Pair(LObject head) {
this(head, Constants.NIL);
}
public Pair(LObject head, LObject tail) {
super(TYPE, 2);
setHead(head);
setTail(tail);
}
public LObject getHead() {
return at(0);
}
public void setHead(LObject head) {
atPut(0, head);
}
public LObject getTail() {
return at(1);
}
public void setTail(LObject tail) {
atPut(1, tail);
}
public void append(LObject o) {
Pair current = this;
while (!(current.getTail() instanceof Undefined)) {
current = (Pair) current.getTail();
}
current.setTail(new Pair(o));
}
@Override
public int getType() {
return TYPE;
}
private static class PairIterator implements Iterator<LObject> {
private Object current;
private PairIterator(LObject start) {
this.current = start;
}
@Override
public boolean hasNext() {
return current instanceof Pair;
}
@Override
public LObject next() {
LObject result = ((Pair) current).getHead();
current = ((Pair) current).getTail();
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public Iterator<LObject> iterator() {
return new PairIterator(this);
}
@Override
public String toString() {
if (getTail() instanceof Undefined) {
return "(" + getHead() + ")";
}
if (!(getTail() instanceof Pair)) {
return "(" + getHead() + " . " + getTail() + ")";
}
String str = "(" + getHead();
LObject currentTail = getTail();
while (!(currentTail instanceof Undefined)) {
if (currentTail instanceof Pair) {
str += " " + ((Pair) currentTail).getHead();
currentTail = ((Pair) currentTail).getTail();
} else {
str += " . " + currentTail;
break;
}
}
return str + ")";
}
public static LObject list(LObject... values) {
LObject current = Constants.NIL;
for (int i = (values.length - 1); i >= 0; --i) {
current = new Pair(values[i], current);
}
return current;
}
public static Iterable<LObject> iterable(final LObject nilOrPair) {
return new Iterable<LObject>() {
public Iterator<LObject> iterator() {
return new PairIterator(nilOrPair);
}
};
}
public static LObject first(LObject nilOrPair) {
if (nilOrPair instanceof Undefined) {
throw new RuntimeException("cannot access element");
}
return ((Pair) nilOrPair).getHead();
}
public static LObject second(LObject nilOrPair) {
if (nilOrPair instanceof Undefined) {
throw new RuntimeException("cannot access element");
}
return first(((Pair) nilOrPair).getTail());
}
public static LObject third(LObject nilOrPair) {
if (nilOrPair instanceof Undefined) {
throw new RuntimeException("cannot access element");
}
return second(((Pair) nilOrPair).getTail());
}
public static LObject rest(LObject nilOrPair) {
if (nilOrPair instanceof Undefined) {
throw new RuntimeException("expecting list found nil");
}
return ((Pair) nilOrPair).getTail();
}
public static int size(LObject nilOrPair) {
int count = 0;
while (!(nilOrPair instanceof Undefined)) {
++count;
nilOrPair = ((Pair) nilOrPair).getTail();
}
return count;
}
}
|
3e1a10de16b81307b2c86b5be0b5b86e8ee70a2c | 1,076 | java | Java | JAVASsty/src/main/java/com/Sysclass/XunliehuaTest.java | endcy/Endcy_Config | 9a5ad08672bd42dfefd8b848d52bce285692cc68 | [
"MIT"
] | null | null | null | JAVASsty/src/main/java/com/Sysclass/XunliehuaTest.java | endcy/Endcy_Config | 9a5ad08672bd42dfefd8b848d52bce285692cc68 | [
"MIT"
] | 6 | 2020-06-15T20:48:17.000Z | 2022-02-09T22:56:45.000Z | JAVASsty/src/main/java/com/Sysclass/XunliehuaTest.java | endcy/Endcy_Projects | 9a5ad08672bd42dfefd8b848d52bce285692cc68 | [
"MIT"
] | null | null | null | 22.893617 | 67 | 0.605019 | 11,081 | package com.Sysclass;
import java.util.*;
public class XunliehuaTest {
ArrayList a1;
public XunliehuaTest(int num,int mod){
a1=new ArrayList(num);
Random rand=new Random();
System.out.println("排序之前");
for(int i=0;i<num;i++){
a1.add(new Integer(Math.abs(rand.nextInt())%mod+1));
System.out.println("a1["+i+"]="+a1.get(i));
}
}
public void Sortit(){
Integer tempint;
int MaxSize=1;
for(int i=1;i<a1.size();i++){
tempint=(Integer)a1.remove(i);
if(tempint.intValue()>=((Integer)a1.get(MaxSize-1)).intValue()){
a1.add(MaxSize, tempint);
MaxSize++;
System.out.println(a1.toString());
}
else{
for(int j=0;j<MaxSize;j++){
if(((Integer)a1.get(j)).intValue()>=tempint.intValue()){
a1.add(j, tempint);
MaxSize++;
System.out.println(a1.toString());
break;
}
}
}
}
System.out.println("排序之后:");
for(int i=0;i<a1.size();i++){
System.out.println("a1["+i+"]="+a1.get(i));
}
}
public static void main(String[] args) {
XunliehuaTest XT=new XunliehuaTest(10,100);
XT.Sortit();
}
}
|
3e1a12e5e9033ce844b4ed7a01a8cb3fc6750307 | 170 | java | Java | services/uaa/src/main/java/com/github/punchat/uaa/events/EventBus.java | punchat/backend | 969f64e12a0ac9357ec693de075c9a928e8a783a | [
"Apache-2.0"
] | 1 | 2018-03-31T19:44:51.000Z | 2018-03-31T19:44:51.000Z | services/uaa/src/main/java/com/github/punchat/uaa/events/EventBus.java | punchat/backend | 969f64e12a0ac9357ec693de075c9a928e8a783a | [
"Apache-2.0"
] | 50 | 2018-04-02T08:53:22.000Z | 2018-06-10T05:35:15.000Z | services/uaa/src/main/java/com/github/punchat/uaa/events/EventBus.java | punchat/punchat | 969f64e12a0ac9357ec693de075c9a928e8a783a | [
"Apache-2.0"
] | null | null | null | 21.25 | 53 | 0.805882 | 11,082 | package com.github.punchat.uaa.events;
import com.github.punchat.events.AccountCreatedEvent;
public interface EventBus {
void publish(AccountCreatedEvent event);
}
|
3e1a13aa94da4782f8954b2cc2fdab2b2c8c5404 | 1,999 | java | Java | src/main/java/com/npn/spring/learning/logger/smallsite/models/factories/SendFilesFactory.java | Novoselov-pavel/small-site-spring-log | 9970b9552de53844298cdde247fd4fca805ecf67 | [
"MIT"
] | 11 | 2020-07-05T19:10:58.000Z | 2021-12-13T19:28:51.000Z | src/main/java/com/npn/spring/learning/logger/smallsite/models/factories/SendFilesFactory.java | Novoselov-pavel/small-site-spring-log | 9970b9552de53844298cdde247fd4fca805ecf67 | [
"MIT"
] | 3 | 2020-07-17T19:33:31.000Z | 2022-03-31T20:54:09.000Z | src/main/java/com/npn/spring/learning/logger/smallsite/models/factories/SendFilesFactory.java | Novoselov-pavel/small-site-spring-log | 9970b9552de53844298cdde247fd4fca805ecf67 | [
"MIT"
] | null | null | null | 35.696429 | 102 | 0.711856 | 11,083 | package com.npn.spring.learning.logger.smallsite.models.factories;
import com.npn.spring.learning.logger.smallsite.models.ProvidedObject;
import com.npn.spring.learning.logger.smallsite.models.driver.GetFilesInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
/**
* Фабрика для получения ProvidedObject из реализаций GetFilesInterface
*/
@Component
public class SendFilesFactory {
private final CopyOnWriteArrayList<GetFilesInterface> filesDrivers = new CopyOnWriteArrayList<>();
@Autowired
public void setFilesDrivers(List<GetFilesInterface> filesDrivers) {
this.filesDrivers.addAll(filesDrivers);
}
/**
* Возвращает список из ProvidedObject соотвествующий переданной папке
*
* @param baseDir папка, среди объектов которой ведется поиск файла
* @return UnmodifiableList
*/
public List<ProvidedObject> getObjectList(String baseDir) {
return filesDrivers.stream()
.filter(x->x.getBaseDir().equals(baseDir))
.flatMap(x->x.getObjectsList().stream())
.sorted(Comparator.comparing(ProvidedObject::getFileName))
.collect(Collectors.toUnmodifiableList());
}
/**
* Возвращает объект ProvidedObject соотвествующий переданной папке и имени файла
*
* @param baseDir папка, среди объектов которой ведется поиск файла
* @param fileName имя файла
* @return ProvidedObject или null, если объект не найден
*/
public ProvidedObject getObject(String baseDir, String fileName){
return filesDrivers.stream()
.filter(x->x.getBaseDir().equals(baseDir))
.flatMap(x->x.getObjectsList().stream())
.filter(x->x.getFileName().equals(fileName)).findFirst().orElse(null);
}
}
|
3e1a13d6beb0ba3d252f17715b8cbe9e3e7f0a31 | 1,587 | java | Java | src/main/java/com/pkran/blockchain/models/Block.java | panakran/spring-boot-blockchain-impl | abc604598dec9f5af1f23fbf3a7944c1cf4b1e7e | [
"MIT"
] | null | null | null | src/main/java/com/pkran/blockchain/models/Block.java | panakran/spring-boot-blockchain-impl | abc604598dec9f5af1f23fbf3a7944c1cf4b1e7e | [
"MIT"
] | null | null | null | src/main/java/com/pkran/blockchain/models/Block.java | panakran/spring-boot-blockchain-impl | abc604598dec9f5af1f23fbf3a7944c1cf4b1e7e | [
"MIT"
] | null | null | null | 20.881579 | 65 | 0.647763 | 11,084 | package com.pkran.blockchain.models;
import com.pkran.blockchain.Utilities.BlockchainUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Block {
private String hash;
private String previousHash;
private String merkleRoot;
private List<Transaction> transactions = new ArrayList<>();
private Long timeStamp;
private Integer nonce;
public Block(String previousHash) {
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.nonce = 0;
this.hash = BlockchainUtil.calculateHash(this);
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getPreviousHash() {
return previousHash;
}
public void setPreviousHash(String previousHash) {
this.previousHash = previousHash;
}
public String getMerkleRoot() {
return merkleRoot;
}
public void setMerkleRoot(String merkleRoot) {
this.merkleRoot = merkleRoot;
}
public List<Transaction> getTransactions() {
return transactions;
}
public void setTransactions(List<Transaction> transactions) {
this.transactions = transactions;
}
public Long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Long timeStamp) {
this.timeStamp = timeStamp;
}
public Integer getNonce() {
return nonce;
}
public void setNonce(Integer nonce) {
this.nonce = nonce;
}
}
|
3e1a1459a8d52b206c219b3681aaedd2c7d4c18e | 1,446 | java | Java | BrickKit/app/src/main/java/com/wayfair/brickkitdemo/FragmentBrickFragment.java | deanshi/brickkit-android | 6151a3e652834687a2cc82d9c4174dd9f333f3c7 | [
"Apache-2.0"
] | null | null | null | BrickKit/app/src/main/java/com/wayfair/brickkitdemo/FragmentBrickFragment.java | deanshi/brickkit-android | 6151a3e652834687a2cc82d9c4174dd9f333f3c7 | [
"Apache-2.0"
] | null | null | null | BrickKit/app/src/main/java/com/wayfair/brickkitdemo/FragmentBrickFragment.java | deanshi/brickkit-android | 6151a3e652834687a2cc82d9c4174dd9f333f3c7 | [
"Apache-2.0"
] | null | null | null | 32.863636 | 99 | 0.58852 | 11,085 | /**
* Copyright © 2017 Wayfair. All rights reserved.
*/
package com.wayfair.brickkitdemo;
import android.os.Bundle;
import com.wayfair.brickkit.BrickFragment;
import com.wayfair.brickkit.size.SimpleBrickSize;
import com.wayfair.brickkitdemo.bricks.FragmentBrick;
/**
* Example of fragment containing {@link FragmentBrick}'s containing {@link SimpleBrickFragment}'s.
*/
public class FragmentBrickFragment extends BrickFragment {
private int[] colors = new int[3];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
colors[0] = getResources().getColor(R.color.colorAccent);
colors[1] = getResources().getColor(R.color.colorPrimary);
colors[2] = getResources().getColor(R.color.colorPrimaryDark);
for (int i = 0; i < colors.length; i++) {
FragmentBrick brick = new FragmentBrick(
getContext(),
new SimpleBrickSize(maxSpans()) {
@Override
protected int size() {
return dataManager.getMaxSpanCount() / 2;
}
},
getChildFragmentManager(),
SimpleBrickFragment.newInstance(i + 1),
"simple" + i
);
brick.setBackgroundColor(colors[i]);
dataManager.addLast(brick);
}
}
}
|
3e1a147b12deea93e2f4dbe9ec15b2dd210f7852 | 2,481 | java | Java | tddl-rule/src/test/java/com/taobao/tddl/rule/utils/AdvancedParameterParserTest.java | hejianzxl/TDDL-1 | 33ab99c37ae8b927f1cd3294d1ec8aa31b71c84b | [
"Apache-2.0"
] | 35 | 2015-09-08T12:46:12.000Z | 2021-09-10T02:17:31.000Z | tddl-rule/src/test/java/com/taobao/tddl/rule/utils/AdvancedParameterParserTest.java | hejianzxl/TDDL-1 | 33ab99c37ae8b927f1cd3294d1ec8aa31b71c84b | [
"Apache-2.0"
] | null | null | null | tddl-rule/src/test/java/com/taobao/tddl/rule/utils/AdvancedParameterParserTest.java | hejianzxl/TDDL-1 | 33ab99c37ae8b927f1cd3294d1ec8aa31b71c84b | [
"Apache-2.0"
] | 63 | 2015-07-24T08:27:19.000Z | 2022-01-17T07:16:25.000Z | 38.765625 | 108 | 0.683595 | 11,086 | package com.taobao.tddl.rule.utils;
import org.junit.Assert;
import org.junit.Test;
import com.taobao.tddl.rule.model.AdvancedParameter;
import com.taobao.tddl.rule.model.AdvancedParameter.AtomIncreaseType;
import com.taobao.tddl.rule.model.AdvancedParameter.Range;
public class AdvancedParameterParserTest {
@Test
public void test_正常() {
String param = "id,1_number,1024";
AdvancedParameter result = AdvancedParameterParser.getAdvancedParamByParamTokenNew(param, false);
testResult(result, AtomIncreaseType.NUMBER, 1, 1024);
param = "id,1024";
result = AdvancedParameterParser.getAdvancedParamByParamTokenNew(param, false);
testResult(result, AtomIncreaseType.NUMBER, 1, 1024);
}
@Test
public void test_范围() {
String param = "id,1_number,0_1024|1m_1g";
AdvancedParameter result = AdvancedParameterParser.getAdvancedParamByParamTokenNew(param, false);
testResult(result,
AtomIncreaseType.NUMBER,
new AdvancedParameter.Range[] { getRange(0, 1024), getRange(1 * 1000000, 1 * 1000000000) },
1);
param = "id,0_1024|1m_1g";
result = AdvancedParameterParser.getAdvancedParamByParamTokenNew(param, false);
testResult(result,
AtomIncreaseType.NUMBER,
new AdvancedParameter.Range[] { getRange(0, 1024), getRange(1 * 1000000, 1 * 1000000000) },
1);
}
private void testResult(AdvancedParameter result, AtomIncreaseType type, Comparable atomicIncreateValue,
Integer cumulativeTimes) {
Assert.assertEquals(result.atomicIncreateType, type);
Assert.assertEquals(result.atomicIncreateValue, atomicIncreateValue);
Assert.assertEquals(result.cumulativeTimes, cumulativeTimes);
}
private void testResult(AdvancedParameter result, AtomIncreaseType type, Range[] rangeValue,
Integer atomicIncreateValue) {
Assert.assertEquals(result.atomicIncreateType, type);
Assert.assertEquals(result.atomicIncreateValue, atomicIncreateValue);
int i = 0;
for (Range range : result.rangeArray) {
Assert.assertEquals(range.start, rangeValue[i].start);
Assert.assertEquals(range.end, rangeValue[i].end);
i++;
}
}
private AdvancedParameter.Range getRange(int start, int end) {
return new AdvancedParameter.Range(start, end);
}
}
|
3e1a14ce31540c2f8c65b316c27c0cfcc2cf4331 | 2,906 | java | Java | train/src/main/java/com/expedia/aquila/train/AquilaTrainerApp.java | Diffblue-benchmarks/aquila | 253515b012a636d19a176dd8b4e639c5bc20fe2e | [
"Apache-2.0"
] | null | null | null | train/src/main/java/com/expedia/aquila/train/AquilaTrainerApp.java | Diffblue-benchmarks/aquila | 253515b012a636d19a176dd8b4e639c5bc20fe2e | [
"Apache-2.0"
] | null | null | null | train/src/main/java/com/expedia/aquila/train/AquilaTrainerApp.java | Diffblue-benchmarks/aquila | 253515b012a636d19a176dd8b4e639c5bc20fe2e | [
"Apache-2.0"
] | null | null | null | 35.012048 | 94 | 0.730902 | 11,087 | /*
* Copyright 2018-2019 Expedia Group, 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.expedia.aquila.train;
import com.expedia.adaptivealerting.core.util.ReflectionUtil;
import com.expedia.aquila.core.repo.AquilaModelRepo;
import com.expedia.aquila.core.repo.s3.S3AquilaModelRepo;
import com.expedia.aquila.train.dataconnect.DataConnector;
import com.expedia.metrics.jackson.MetricsJavaModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @author Willie Wheeler
*/
@SpringBootApplication
@Slf4j
public class AquilaTrainerApp {
public static void main(String[] args) {
log.info("Starting AquilaTrainerApp");
SpringApplication.run(AquilaTrainerApp.class, args);
}
@Bean
public Config connectorsConfig() {
log.trace("Creating connectorsConfig bean");
return ConfigFactory.load("connectors.conf");
}
@Bean
public DataConnector dataConnector() {
log.trace("Creating dataConnector bean");
final Config dataConfig = connectorsConfig().getConfig("data");
final String className = dataConfig.getString("class");
final DataConnector connector = (DataConnector) ReflectionUtil.newInstance(className);
connector.init(dataConfig);
return connector;
}
@Bean
public AquilaModelRepo modelConnector() {
log.trace("Creating modelConnector bean");
final Config modelsConfig = connectorsConfig().getConfig("models");
final AquilaModelRepo connector = new S3AquilaModelRepo();
connector.init(modelsConfig);
return connector;
}
@Bean
public ObjectMapper objectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.registerModule(new MetricsJavaModule());
return objectMapper;
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
|
3e1a1515274caef06b5b509c38369ad1bff7727b | 2,008 | java | Java | src/com/hokumus/schoolmanagement/model/management/Days.java | hokumus86/SchollManagement | 50e38c9a4c36ca39dba4796205e37146965eaee3 | [
"PostgreSQL"
] | null | null | null | src/com/hokumus/schoolmanagement/model/management/Days.java | hokumus86/SchollManagement | 50e38c9a4c36ca39dba4796205e37146965eaee3 | [
"PostgreSQL"
] | null | null | null | src/com/hokumus/schoolmanagement/model/management/Days.java | hokumus86/SchollManagement | 50e38c9a4c36ca39dba4796205e37146965eaee3 | [
"PostgreSQL"
] | null | null | null | 17.614035 | 92 | 0.661355 | 11,088 | package com.hokumus.schoolmanagement.model.management;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "days")
public class Days {
private Long id;
private String name;
private int gun1;
private int gun2;
private int gun3;
private int gun4;
private int gun5;
private int gun6;
private int gun7;
private CourseTimes saat;
@Id
@SequenceGenerator(name = "seq_lessons", allocationSize = 1, sequenceName = "seq_lessons")
@GeneratedValue(generator = "seq_lessons", strategy = GenerationType.SEQUENCE)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGun1() {
return gun1;
}
public void setGun1(int gun1) {
this.gun1 = gun1;
}
public int getGun2() {
return gun2;
}
public void setGun2(int gun2) {
this.gun2 = gun2;
}
public int getGun3() {
return gun3;
}
public void setGun3(int gun3) {
this.gun3 = gun3;
}
public int getGun4() {
return gun4;
}
public void setGun4(int gun4) {
this.gun4 = gun4;
}
public int getGun5() {
return gun5;
}
public void setGun5(int gun5) {
this.gun5 = gun5;
}
public int getGun6() {
return gun6;
}
public void setGun6(int gun6) {
this.gun6 = gun6;
}
public int getGun7() {
return gun7;
}
public void setGun7(int gun7) {
this.gun7 = gun7;
}
@Enumerated
@JoinColumn(name = "clock_id")
@Column(name = "saat")
public CourseTimes getSaat() {
return saat;
}
public void setSaat(CourseTimes saat) {
this.saat = saat;
}
}
|
3e1a17ffd2221fe3d1693000dcb0e50ac31df511 | 1,200 | java | Java | data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/ServiceNotificationChannel.java | taqdirali/Mining-Minds | 048f746199ede78b39f87fe2e253be4814d763a5 | [
"Apache-2.0"
] | 42 | 2017-01-09T09:57:05.000Z | 2021-09-29T15:17:01.000Z | data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/ServiceNotificationChannel.java | taqdirali/Mining-Minds | 048f746199ede78b39f87fe2e253be4814d763a5 | [
"Apache-2.0"
] | 14 | 2016-12-30T06:06:55.000Z | 2020-09-25T02:09:04.000Z | data-curation-layer/lifelog-monitoring-system/src/main/java/org/uclab/mm/dcl/llm/monitoring/ServiceNotificationChannel.java | taqdirali/Mining-Minds | 048f746199ede78b39f87fe2e253be4814d763a5 | [
"Apache-2.0"
] | 27 | 2016-12-30T05:48:33.000Z | 2020-07-25T19:39:55.000Z | 40 | 102 | 0.7675 | 11,089 | /**
*
* Copyright [2016] [Bilal Ali]
* 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.uclab.mm.dcl.llm.monitoring;
import org.uclab.mm.dcl.llm.objectmodel.SituationNotification;
/**
* This is an interface for the service notification channel and
* have an object of class situation notification.
* @author Rizvi
*/
public interface ServiceNotificationChannel{
/**
* The function specification is required to for different kind of implementation with
* respect to the end point address and the notification object.
* @param objSituationNotification
* @param endPoint
*/
public void notifyToRestService(SituationNotification objSituationNotification, String endPoint);
}
|
3e1a18eb979299db649a69e9f70d075ababe35e4 | 575 | java | Java | src/main/java/frc/robot/BooleanSource.java | Programmer3314/2021Code | a9b2ea084779f98d5ee6b2b6094e6432a8b54468 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/BooleanSource.java | Programmer3314/2021Code | a9b2ea084779f98d5ee6b2b6094e6432a8b54468 | [
"BSD-3-Clause"
] | 5 | 2021-10-31T04:42:48.000Z | 2021-11-01T23:44:44.000Z | src/main/java/frc/robot/BooleanSource.java | Programmer3314/2021Code | a9b2ea084779f98d5ee6b2b6094e6432a8b54468 | [
"BSD-3-Clause"
] | null | null | null | 44.230769 | 80 | 0.406957 | 11,090 | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot;
public interface BooleanSource {
public boolean getBoolean();
}
|
3e1a18ee54e7c60bb2a698226b03b2d7efa3a6a1 | 5,951 | java | Java | src/main/java/org/apache/commons/lang3/JavaVersion.java | kinow/commons-lang | a0f58df56871dbc92fc21ed1b1b8b2eac38fa88b | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/commons/lang3/JavaVersion.java | kinow/commons-lang | a0f58df56871dbc92fc21ed1b1b8b2eac38fa88b | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/commons/lang3/JavaVersion.java | kinow/commons-lang | a0f58df56871dbc92fc21ed1b1b8b2eac38fa88b | [
"Apache-2.0"
] | null | null | null | 28.203791 | 98 | 0.549824 | 11,091 | /*
* 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.commons.lang3;
/**
* <p>An enum representing all the versions of the Java specification.
* This is intended to mirror available values from the
* <em>java.specification.version</em> System property. </p>
*
* @since 3.0
* @version $Id$
*/
public enum JavaVersion {
/**
* The Java version reported by Android. This is not an official Java version number.
*/
JAVA_0_9(1.5f, "0.9"),
/**
* Java 1.1.
*/
JAVA_1_1(1.1f, "1.1"),
/**
* Java 1.2.
*/
JAVA_1_2(1.2f, "1.2"),
/**
* Java 1.3.
*/
JAVA_1_3(1.3f, "1.3"),
/**
* Java 1.4.
*/
JAVA_1_4(1.4f, "1.4"),
/**
* Java 1.5.
*/
JAVA_1_5(1.5f, "1.5"),
/**
* Java 1.6.
*/
JAVA_1_6(1.6f, "1.6"),
/**
* Java 1.7.
*/
JAVA_1_7(1.7f, "1.7"),
/**
* Java 1.8.
*/
JAVA_1_8(1.8f, "1.8"),
/**
* Java 1.9.
*/
JAVA_1_9(1.9f, "1.9"),
/**
* Java 1.x, x > 9. Mainly introduced to avoid to break when a new version of Java is used.
*/
JAVA_RECENT(maxVersion(), Float.toString(maxVersion()));
/**
* The float value.
*/
private final float value;
/**
* The standard name.
*/
private final String name;
/**
* Constructor.
*
* @param value the float value
* @param name the standard name, not null
*/
JavaVersion(final float value, final String name) {
this.value = value;
this.name = name;
}
//-----------------------------------------------------------------------
/**
* <p>Whether this version of Java is at least the version of Java passed in.</p>
*
* <p>For example:<br>
* {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}<p>
*
* @param requiredVersion the version to check against, not null
* @return true if this version is equal to or greater than the specified version
*/
public boolean atLeast(final JavaVersion requiredVersion) {
return this.value >= requiredVersion.value;
}
/**
* Transforms the given string with a Java version number to the
* corresponding constant of this enumeration class. This method is used
* internally.
*
* @param nom the Java version as string
* @return the corresponding enumeration constant or <b>null</b> if the
* version is unknown
*/
// helper for static importing
static JavaVersion getJavaVersion(final String nom) {
return get(nom);
}
/**
* Transforms the given string with a Java version number to the
* corresponding constant of this enumeration class. This method is used
* internally.
*
* @param nom the Java version as string
* @return the corresponding enumeration constant or <b>null</b> if the
* version is unknown
*/
static JavaVersion get(final String nom) {
if ("0.9".equals(nom)) {
return JAVA_0_9;
} else if ("1.1".equals(nom)) {
return JAVA_1_1;
} else if ("1.2".equals(nom)) {
return JAVA_1_2;
} else if ("1.3".equals(nom)) {
return JAVA_1_3;
} else if ("1.4".equals(nom)) {
return JAVA_1_4;
} else if ("1.5".equals(nom)) {
return JAVA_1_5;
} else if ("1.6".equals(nom)) {
return JAVA_1_6;
} else if ("1.7".equals(nom)) {
return JAVA_1_7;
} else if ("1.8".equals(nom)) {
return JAVA_1_8;
} else if ("1.9".equals(nom)) {
return JAVA_1_9;
}
if (nom == null) {
return null;
}
final float v = toFloatVersion(nom);
if ((v - 1.) < 1.) { // then we need to check decimals > .9
final int firstComma = Math.max(nom.indexOf('.'), nom.indexOf(','));
final int end = Math.max(nom.length(), nom.indexOf(',', firstComma));
if (Float.parseFloat(nom.substring(firstComma + 1, end)) > .9f) {
return JAVA_RECENT;
}
}
return null;
}
//-----------------------------------------------------------------------
/**
* <p>The string value is overridden to return the standard name.</p>
*
* <p>For example, <code>"1.5"</code>.</p>
*
* @return the name, not null
*/
@Override
public String toString() {
return name;
}
// upper bound of java version considering 2. or current is the higher
private static float maxVersion() {
final float v = toFloatVersion(System.getProperty("java.version", "2.0"));
if (v > 0) {
return v;
}
return 2f;
}
private static float toFloatVersion(final String name) {
final String[] toParse = name.split("\\.");
if (toParse.length >= 2) {
try {
return Float.parseFloat(toParse[0] + '.' + toParse[1]);
} catch (final NumberFormatException nfe) {
// no-op, let use default
}
}
return -1;
}
}
|
3e1a18f7356153d0dfd19e386c40fc4c3958e787 | 266 | java | Java | app/src/main/java/com/yueweather/app/util/HttpCallbackListener.java | yuezhusust/yueweather | 23626b457ad702c6a615894fec60492539e0b4d0 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yueweather/app/util/HttpCallbackListener.java | yuezhusust/yueweather | 23626b457ad702c6a615894fec60492539e0b4d0 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yueweather/app/util/HttpCallbackListener.java | yuezhusust/yueweather | 23626b457ad702c6a615894fec60492539e0b4d0 | [
"Apache-2.0"
] | null | null | null | 15.647059 | 39 | 0.676692 | 11,092 | package com.yueweather.app.util;
/**
* 项目名称:YueWeather
* 类描述:
* 创建人:lenovo
* 创建时间:2016/11/17 15:36
* 修改人:lenovo
* 修改时间:2016/11/17 15:36
* 修改备注:
*/
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
|
3e1a19989b59f1553c7751d47ecd439c038f69e7 | 4,063 | java | Java | app/src/main/java/com/imakancustomer/ui/dashboard/DashboardFragment.java | GangsOfCoder/FoodOrderingCustomeApp | 26e0d9ee5656cd610500b35e89b719aaf0ff5f1e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/imakancustomer/ui/dashboard/DashboardFragment.java | GangsOfCoder/FoodOrderingCustomeApp | 26e0d9ee5656cd610500b35e89b719aaf0ff5f1e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/imakancustomer/ui/dashboard/DashboardFragment.java | GangsOfCoder/FoodOrderingCustomeApp | 26e0d9ee5656cd610500b35e89b719aaf0ff5f1e | [
"Apache-2.0"
] | 1 | 2021-01-07T16:50:21.000Z | 2021-01-07T16:50:21.000Z | 33.858333 | 125 | 0.710313 | 11,093 | package com.imakancustomer.ui.dashboard;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.imakancustomer.R;
import com.imakancustomer.core.listeners.OnItemSelectedListener;
import com.imakancustomer.model.DashboardPojo;
import com.imakancustomer.ui.home.HomeActivity;
import com.imakancustomer.ui.order.OrderFragment;
import com.imakancustomer.utils.Function;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
public class DashboardFragment extends Fragment implements DashboardContract.View, OnItemSelectedListener {
@BindView(R.id.tv_dashboard_total_booking)
TextView tv_dashboard_total_booking;
@BindView(R.id.tv_dashboard_total_fav)
TextView tv_dashboard_total_fav;
@BindView(R.id.rv_recent_booking)
RecyclerView rv_recent_booking;
@BindView(R.id.ll_loader)
LinearLayout ll_loader;
private View mView;
private OrderFragment mDashboardFragment;
private RecyclerView.LayoutManager mLayoutManager;
//private List<DashboardPojo> mDashboardList = new ArrayList<>();
private DashboardAdapter mDashboardAdapter;
private DashboardContract.Action mDashboardPresenter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_dashboard, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.title_dashboard);
ButterKnife.bind(this, mView);
HomeActivity.hideShowLocationOption(false,"");
mDashboardPresenter = new DashboardPresenter(this, getActivity());
init();
checkInternet();
setHasOptionsMenu(true);
return mView;
}
private void checkInternet() {
if (Function.isNetworkConnected(Objects.requireNonNull(getActivity()))) {
mDashboardPresenter.getDashboardlist();
} else {
Function.showMessage(getString(R.string.no_internet), getActivity());
}
}
private void init() {
mLayoutManager = new LinearLayoutManager(getActivity());
rv_recent_booking.setLayoutManager(mLayoutManager);
}
@Override
public void showLoader() {
ll_loader.setVisibility(View.VISIBLE);
}
@Override
public void hideLoader() {
ll_loader.setVisibility(View.GONE);
}
@Override
public void showMessage(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
@SuppressLint("SetTextI18n")
@Override
public void setDataToAdapter(DashboardPojo data) {
try {
Log.d("TEST", "" + data.getData().get(0).getCompleteBookings().get(0).getCompleteRequest());
tv_dashboard_total_booking.setText("" + data.getData().get(0).getCompleteBookings().get(0).getCompleteRequest());
tv_dashboard_total_fav.setText("" + data.getData().get(0).getTotalFavourites().get(0).getTotalFavouriteCount());
if (data.getData().size() > 0) {
//mDashboardList = data;
mDashboardAdapter = new DashboardAdapter(data.getData().get(0).getRecentBooking(), getActivity());
mDashboardAdapter.OnItemSelectedListener(this);
rv_recent_booking.setAdapter(mDashboardAdapter);
mDashboardAdapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onItemClick(int position, String type) {
}
}
|
3e1a19e06bb7f10c09193fb47dd7ec6eacbc9a44 | 1,309 | java | Java | src/tree/PostorderTraversal.java | Joshua-Wei/algorithm | e842092112df4ad132d6d82c64174e87b4b5956f | [
"MIT"
] | null | null | null | src/tree/PostorderTraversal.java | Joshua-Wei/algorithm | e842092112df4ad132d6d82c64174e87b4b5956f | [
"MIT"
] | null | null | null | src/tree/PostorderTraversal.java | Joshua-Wei/algorithm | e842092112df4ad132d6d82c64174e87b4b5956f | [
"MIT"
] | null | null | null | 22.964912 | 76 | 0.528648 | 11,094 | package tree;
import java.util.*;
/**
* Given a binary tree, return the postorder traversal of its nodes' values.
*
* For example:
* Given binary tree {1,#,2,3},
* 1
* \
* 2
* /
* 3
*
* return [3,2,1].
*
* Note: Recursive solution is trivial, could you do it iteratively?
*
* @author Joshua Wei
*/
public class PostorderTraversal {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
// recursive
//recursive(root, list);
// iterative
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<TreeNode> stack2 = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode n = stack.pop();
if (n == null) continue;
stack2.push(n);
stack.push(n.left);
stack.push(n.right);
}
while (!stack2.isEmpty()) {
list.add(stack2.pop().val);
}
return list;
}
@SuppressWarnings("unused")
private void recursive(TreeNode n, List<Integer> list) {
if (n == null) return;
recursive(n.left, list);
recursive(n.right, list);
list.add(n.val);
}
}
|
3e1a1a515d5d45e86d49f52ca17438bf55cd631a | 561 | java | Java | src/main/java/com/garowing/gameexp/game/rts/skill/manager/AttributesPropertyTransformer.java | cool112/game | 61071efa6498825f9cbcc7722420c6cd399bb3ab | [
"MIT"
] | null | null | null | src/main/java/com/garowing/gameexp/game/rts/skill/manager/AttributesPropertyTransformer.java | cool112/game | 61071efa6498825f9cbcc7722420c6cd399bb3ab | [
"MIT"
] | null | null | null | src/main/java/com/garowing/gameexp/game/rts/skill/manager/AttributesPropertyTransformer.java | cool112/game | 61071efa6498825f9cbcc7722420c6cd399bb3ab | [
"MIT"
] | null | null | null | 21.576923 | 86 | 0.805704 | 11,095 | package com.garowing.gameexp.game.rts.skill.manager;
import java.lang.reflect.Field;
import com.yeto.war.fightcore.attr.AttrHelp;
import com.yeto.war.fightcore.attr.entity.AttrEntity;
import commons.configuration.PropertyTransformer;
import commons.configuration.TransformationException;
/**
* 怪物属性转换器
* @author seg
*
*/
public class AttributesPropertyTransformer implements PropertyTransformer<AttrEntity>
{
@Override
public AttrEntity transform(String value, Field field) throws TransformationException
{
return AttrHelp.parseAttr(value);
}
}
|
3e1a1a87c3d4998c5b0f0ee04b0e5525def67548 | 2,807 | java | Java | core/src/test/java/org/apache/druid/common/config/NullHandlingTest.java | tejaswini-imply/druid | a235aca2b3f89d3ce46232461410ae7e07d2d61f | [
"Apache-2.0"
] | 5,813 | 2015-01-01T14:14:54.000Z | 2018-07-06T11:13:03.000Z | core/src/test/java/org/apache/druid/common/config/NullHandlingTest.java | tejaswini-imply/druid | a235aca2b3f89d3ce46232461410ae7e07d2d61f | [
"Apache-2.0"
] | 4,320 | 2015-01-02T18:37:24.000Z | 2018-07-06T14:51:01.000Z | core/src/test/java/org/apache/druid/common/config/NullHandlingTest.java | tejaswini-imply/druid | a235aca2b3f89d3ce46232461410ae7e07d2d61f | [
"Apache-2.0"
] | 1,601 | 2015-01-05T05:37:05.000Z | 2018-07-06T11:13:04.000Z | 25.752294 | 77 | 0.722123 | 11,096 | /*
* 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.druid.common.config;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.apache.druid.common.config.NullHandling.replaceWithDefault;
import static org.junit.Assert.assertEquals;
public class NullHandlingTest
{
@BeforeClass
public static void setUpClass()
{
NullHandling.initializeForTests();
}
@Test
public void test_defaultValueForClass_float()
{
assertEquals(
replaceWithDefault() ? 0f : null,
NullHandling.defaultValueForClass(Float.class)
);
}
@Test
public void test_defaultValueForClass_double()
{
assertEquals(
replaceWithDefault() ? 0d : null,
NullHandling.defaultValueForClass(Double.class)
);
}
@Test
public void test_defaultValueForClass_integer()
{
Assert.assertNull(NullHandling.defaultValueForClass(Integer.class));
}
@Test
public void test_defaultValueForClass_long()
{
assertEquals(
replaceWithDefault() ? 0L : null,
NullHandling.defaultValueForClass(Long.class)
);
}
@Test
public void test_defaultValueForClass_number()
{
assertEquals(
replaceWithDefault() ? 0d : null,
NullHandling.defaultValueForClass(Number.class)
);
}
@Test
public void test_defaultValueForClass_string()
{
assertEquals(
replaceWithDefault() ? "" : null,
NullHandling.defaultValueForClass(String.class)
);
}
@Test
public void test_defaultValueForClass_object()
{
Assert.assertNull(NullHandling.defaultValueForClass(Object.class));
}
@Test
public void test_ignoreNullsStrings()
{
try {
NullHandling.initializeForTestsWithValues(false, true);
Assert.assertFalse(NullHandling.ignoreNullsForStringCardinality());
NullHandling.initializeForTestsWithValues(true, false);
Assert.assertFalse(NullHandling.ignoreNullsForStringCardinality());
}
finally {
NullHandling.initializeForTests();
}
}
}
|
3e1a1a9cc7f5e93084cc1c46867e8aeea2142c87 | 3,820 | java | Java | hudi-common/src/main/java/org/apache/hudi/common/util/StringUtils.java | xushiyan/incubator-hudi | 3343cbb47b75b9d65a73a7a98ed9dae0b5ec58a9 | [
"Apache-2.0"
] | 738 | 2019-02-13T00:25:32.000Z | 2020-05-22T15:49:36.000Z | hudi-common/src/main/java/org/apache/hudi/common/util/StringUtils.java | xushiyan/incubator-hudi | 3343cbb47b75b9d65a73a7a98ed9dae0b5ec58a9 | [
"Apache-2.0"
] | 831 | 2019-02-04T20:03:43.000Z | 2020-05-23T07:17:44.000Z | hudi-common/src/main/java/org/apache/hudi/common/util/StringUtils.java | xushiyan/incubator-hudi | 3343cbb47b75b9d65a73a7a98ed9dae0b5ec58a9 | [
"Apache-2.0"
] | 403 | 2019-02-12T18:42:57.000Z | 2020-05-23T11:43:58.000Z | 32.10084 | 120 | 0.675393 | 11,097 | /*
* 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.hudi.common.util;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Simple utility for operations on strings.
*/
public class StringUtils {
public static final String EMPTY_STRING = "";
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No separator is added to the joined String. Null objects or empty strings within the array are represented by empty
* strings.
* </p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*/
public static <T> String join(final String... elements) {
return join(elements, EMPTY_STRING);
}
public static <T> String joinUsingDelim(String delim, final String... elements) {
return join(elements, delim);
}
public static String join(final String[] array, final String separator) {
if (array == null) {
return null;
}
return org.apache.hadoop.util.StringUtils.join(separator, array);
}
public static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
public static boolean isNullOrEmpty(String str) {
return str == null || str.length() == 0;
}
/**
* Returns the given string if it is non-null; the empty string otherwise.
*
* @param string the string to test and possibly return
* @return {@code string} itself if it is non-null; {@code ""} if it is null
*/
public static String nullToEmpty(@Nullable String string) {
return string == null ? "" : string;
}
public static String objToString(@Nullable Object obj) {
return obj == null ? null : obj.toString();
}
/**
* Returns the given string if it is nonempty; {@code null} otherwise.
*
* @param string the string to test and possibly return
* @return {@code string} itself if it is nonempty; {@code null} if it is empty or null
*/
public static @Nullable String emptyToNull(@Nullable String string) {
return stringIsNullOrEmpty(string) ? null : string;
}
private static boolean stringIsNullOrEmpty(@Nullable String string) {
return string == null || string.isEmpty();
}
/**
* Splits input string, delimited {@code delimiter} into a list of non-empty strings
* (skipping any empty string produced during splitting)
*/
public static List<String> split(@Nullable String input, String delimiter) {
if (isNullOrEmpty(input)) {
return Collections.emptyList();
}
return Stream.of(input.split(delimiter)).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList());
}
}
|
3e1a1adb87f5386800225417074279c791e2d389 | 1,282 | java | Java | aws-java-sdk-kinesisvideo/src/main/java/com/amazonaws/services/kinesisvideo/model/InvalidMediaFrameException.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | 1 | 2020-08-27T17:36:34.000Z | 2020-08-27T17:36:34.000Z | aws-java-sdk-kinesisvideo/src/main/java/com/amazonaws/services/kinesisvideo/model/InvalidMediaFrameException.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-kinesisvideo/src/main/java/com/amazonaws/services/kinesisvideo/model/InvalidMediaFrameException.java | jplippi/aws-sdk-java | 147eefec220e2944dc571283af6552611bc94301 | [
"Apache-2.0"
] | 1 | 2020-10-10T15:59:17.000Z | 2020-10-10T15:59:17.000Z | 34.648649 | 119 | 0.729329 | 11,098 | /*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.kinesisvideo.model;
import javax.annotation.Generated;
/**
* <p>
* One or more frames in the requested clip could not be parsed based on the specified codec.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidMediaFrameException extends com.amazonaws.services.kinesisvideo.model.AmazonKinesisVideoException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new InvalidMediaFrameException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public InvalidMediaFrameException(String message) {
super(message);
}
}
|
3e1a1ae4aec6de8f282e4fd617ff3d0018e1c1cb | 1,199 | java | Java | chapter_004/src/main/java/ru/job4j/generic/Role.java | StanislavEsin/estanislav | b7f2812d6f0b25f2d37716aa22fc5711e3210a9b | [
"Apache-2.0"
] | null | null | null | chapter_004/src/main/java/ru/job4j/generic/Role.java | StanislavEsin/estanislav | b7f2812d6f0b25f2d37716aa22fc5711e3210a9b | [
"Apache-2.0"
] | null | null | null | chapter_004/src/main/java/ru/job4j/generic/Role.java | StanislavEsin/estanislav | b7f2812d6f0b25f2d37716aa22fc5711e3210a9b | [
"Apache-2.0"
] | null | null | null | 16.84507 | 65 | 0.474916 | 11,099 | package ru.job4j.generic;
/**
* Role.
*
* @author Stanislav (anpch@example.com)
* @since 14.09.2017
*/
public class Role extends Base {
/**
*/
private String id;
/**
*/
private String name;
/**
* Constructor.
* @param id - String
* @param name - String
*/
public Role(String id, String name) {
this.id = id;
this.name = name;
}
/**
* getName.
* @return return - String
*/
public String getName() {
return name;
}
/**
* setName.
* @param name - String
*/
public void setName(String name) {
this.name = name;
}
@Override
String getId() {
return id;
}
@Override
void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Role role = (Role) o;
return id != null ? id.equals(role.id) : role.id == null;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
} |
3e1a1b09d33323963fdde77882be4091b2852f02 | 7,511 | java | Java | zsblogs/src/main/java/com/zs/tools/CrawlerNo1.java | ZS1994/zsblogs | 1183385c777d29cfb2e6587924451a9627ecb797 | [
"Apache-2.0"
] | null | null | null | zsblogs/src/main/java/com/zs/tools/CrawlerNo1.java | ZS1994/zsblogs | 1183385c777d29cfb2e6587924451a9627ecb797 | [
"Apache-2.0"
] | 2 | 2020-01-25T10:45:27.000Z | 2020-10-24T19:19:05.000Z | zsblogs/src/main/java/com/zs/tools/CrawlerNo1.java | ZS1994/zsblogs | 1183385c777d29cfb2e6587924451a9627ecb797 | [
"Apache-2.0"
] | 3 | 2017-11-22T02:00:55.000Z | 2022-02-21T13:25:09.000Z | 28.236842 | 173 | 0.647584 | 11,100 | package com.zs.tools;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;
import com.zs.dao.BlogMapper;
import com.zs.dao.TimelineMapper;
import com.zs.entity.Blog;
import com.zs.entity.BlogList;
import com.zs.entity.Timeline;
import com.zs.entity.other.CrawlerData1;
import com.zs.service.BlogListSer;
import com.zs.service.BlogSer;
/**
* 2017-11-12
* @author 张顺
* 爬虫的第一次尝试,爬虫机器人1号
*/
@Component
public class CrawlerNo1{
@Resource
private BlogSer blogSer;
@Resource
private BlogMapper blogMapper;
@Resource
private BlogListSer blogListSer;
@Resource
private DownloadImg downloadImg;
@Resource
private TimelineMapper timelineMapper;
private List<CrawlerData1> list = new ArrayList<>();
private Gson gson=new Gson();
private Logger log=Logger.getLogger(getClass());
// 正则表达式规则
private Pattern pattern = Pattern.compile("^/?http");
//张顺,2019-12-16,减少局部变量,优化内存使用
String urlroot = "https://tech.meituan.com";
Blog blog;
Elements content;
String title;
String summary;
Elements imgs;
String url;
String root;
String str;
Document doc;
Elements summaryE;
String newImgPath;
Timeline tl;
Blog blog2;
String src;
String fileName;
String srctmp;
String ss[];
CrawlerData1 ctmp;
List<BlogList> blist;
List<Integer> urlbloglisttmp;
Elements elements;
Elements tagAll;
BlogList blogList;
public DownloadImg getDownloadImg() {
return downloadImg;
}
public void setDownloadImg(DownloadImg downloadImg) {
this.downloadImg = downloadImg;
}
public BlogSer getBlogSer() {
return blogSer;
}
public void setBlogSer(BlogSer blogSer) {
this.blogSer = blogSer;
}
public BlogListSer getBlogListSer() {
return blogListSer;
}
public void setBlogListSer(BlogListSer blogListSer) {
this.blogListSer = blogListSer;
}
public void work(){
getAllUrlAndList();
for (int i = list.size()-1; i >= 0; i--) {
blog = null;
content = null;
title = "";
summary = null;
imgs = null;
try {
url = list.get(i).getUrl();
url = url.replaceAll(" ", "%20");
root = url.split("//")[0]+"//"+url.split("//")[1].split("/")[0];
str = HttpClientReq.httpGet(url, null,null);
doc = Jsoup.parse(str);
//摘要
summaryE = doc.select("meta[property=og:description]");
summary = summaryE.size()>0?summaryE.get(0).attr("content"):"[未获取到摘要]";
title = doc.select("meta[property=og:title]").attr("content");
title = title.equals("")?"[未获取到标题]":title;
content = doc.select("div .content");
//图片
imgs = content.select("img");
for (Element img : imgs) {
src = img.attr("src");
fileName = "";
srctmp = "";
if (src != null){
src = src.indexOf("/")==0?src:"/"+src;
ss = src.split("/");
fileName = ss[ss.length-1];
//张顺,2019-6-17,因网站改为地址为外部地址,故不可直接拼接,而是应该先判断是否站内
if (pattern.matcher(src).find()) {
//判断第一个字符是否是/,如果是则去掉
src = src.substring(0, 1).equals("/")?src.substring(1, src.length()):src;
srctmp = src;
}else{
for (String s : ss) {
s = URLEncoder.encode(s, "utf-8");
srctmp = srctmp + s + "/";
}
srctmp = srctmp.equals("")?srctmp:srctmp.substring(0, srctmp.lastIndexOf("/"));
srctmp = root + srctmp;
}
newImgPath = downloadImg.download(srctmp, fileName);
img.attr("src", Constans.PATH_TOMCAT_IMGS + newImgPath);
}
}
blog = new Blog(title, content.html(), summary, list.get(i).getUrlBlogList());
blogSer.add(blog);
} catch (Exception e) {
e.printStackTrace();
log.error("【错误参数详情】"+gson.toJson(blog));
try {
//如果出错,这里一般是那个编码问题,而字符过滤又挺耗时,所以仅在出错时使用尝试解决问题
blog = new Blog(EmojiFilterUtils.filterEmoji(title), EmojiFilterUtils.filterEmoji(content.html()), EmojiFilterUtils.filterEmoji(summary), list.get(i).getUrlBlogList());
blogSer.add(blog);
} catch (Exception e2) {
e2.getMessage();
}
}finally {
list.remove(i);
//2019-6-19,张顺,保存日志
tl = new Timeline();
tl.setCreateTime(new Date());
tl.setuId(Constans.CRAWLERNO1);
tl.setpId(13);//操作:博客单条添加
blog2 = new Blog(EmojiFilterUtils.filterEmoji(title), null, EmojiFilterUtils.filterEmoji(summary), null);
tl.setInfo(gson.toJson(blog2));
timelineMapper.insert(tl);
}
}
}
/**自动获取美团点评网的博客,规则如下:
* 1、如果没有这个博客栏目,则先创建再爬取
* 2、如果已经有了这篇博客(标题一样、所属栏目一样),则跳过*/
private void getAllUrlAndList(){
try {
str = HttpClientReq.httpGet("https://tech.meituan.com/archives", null,null);
doc = Jsoup.parse(str);
elements = doc.select(".post-title");
//2019-6-13,张顺,由于点评网结构变化,所以相应修改
tagAll = doc.select(".tag-links");
for (int i = 0; i < elements.size(); i++) {
Element e = elements.get(i);
//得到目标url
url = urlroot+e.select("a").get(0).attr("href");
//得到标题
title = e.select("a").get(0).html();
//得到栏目名称
Elements tags = tagAll.get(i).select("a");
blist = blogListSer.queryAll(Constans.CRAWLERNO1);
urlbloglisttmp = new ArrayList<>();
for (Element tag : tags) {
// String stmp = tag.attr("href");
String stmp = tag.html();
//博客栏目名称
// String stag = stmp.split("/")[stmp.split("/").length-1];
String stag = stmp;
//2019-6-13,现已不用,他的tag结构已经变化了
boolean isHas=false;
for (BlogList bl : blist) {
if (stag.equals(bl.getName())) {
urlbloglisttmp.add(bl.getId());
isHas=true;
break;
}
}
//如果发现新栏目则创建博客栏目
if (isHas == false) {
String id = blogListSer.add(new BlogList(stag, new Date(), 1, Constans.CRAWLERNO1));
urlbloglisttmp.add(Integer.valueOf(id));
//2019-6-19,张顺,保存日志
tl = new Timeline();
tl.setCreateTime(new Date());
tl.setuId(Constans.CRAWLERNO1);
tl.setpId(7);//操作:博客栏目单条添加
blogList=new BlogList(stag, new Date(), 1, Constans.CRAWLERNO1);
blogList.setId(Trans.TransToInteger(id));
tl.setInfo(gson.toJson(blogList));
timelineMapper.insert(tl);
}
}
if (title.equals("美团外卖客户端高可用建设体系 - 美团技术团队")) {
log.error(blogMapper.queryByTitle(title).size());
log.error(blogSer.queryByTitle(title).size());
}
//判断这个博客是否已经创建过?创建过就跳过,否则创建
if(blogMapper.queryByTitle(title).size()>0){
//log.info("【判断这个博客是否已经创建过?创建过就跳过,否则创建】"+title+"("+url+")"+" 【list大小】"+list.size());
}else{
//保存这个博客的栏目id序列到list中
ctmp = new CrawlerData1(url, gson.toJson(urlbloglisttmp));
list.add(ctmp);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public List<CrawlerData1> getList() {
return list;
}
public void setList(List<CrawlerData1> list) {
this.list = list;
}
public static void main(String[] args) {
// 要验证的字符串
String str = "/https://baike.xsoftlab.net";
// 正则表达式规则
String regEx = "^/?http";
// 编译正则表达式
Pattern p = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(str);
// 查找字符串中是否有匹配正则表达式的字符/字符串
boolean rs = matcher.find();
System.out.println(rs);
System.out.println(Pattern.matches("^http", "https://baike.xsoftlab.net"));
}
}
|
3e1a1b3254ec9749da5805c88a306d17f576249d | 588 | java | Java | soln-dynamic-programming-problems/range-sum-query-immutable.java | devakar771/Data-Structures-and-Algorithms | 289edf440926ee9ce66fe596271574a88bce3040 | [
"MIT"
] | 120 | 2021-02-19T07:39:50.000Z | 2022-02-19T14:55:28.000Z | soln-dynamic-programming-problems/range-sum-query-immutable.java | devakar771/Data-Structures-and-Algorithms | 289edf440926ee9ce66fe596271574a88bce3040 | [
"MIT"
] | null | null | null | soln-dynamic-programming-problems/range-sum-query-immutable.java | devakar771/Data-Structures-and-Algorithms | 289edf440926ee9ce66fe596271574a88bce3040 | [
"MIT"
] | 22 | 2021-06-21T17:21:27.000Z | 2021-12-24T01:56:29.000Z | 18.375 | 64 | 0.579932 | 11,101 | /**
@author Farheen Bano
Reference-
https://leetcode.com/problems/range-sum-query-immutable/
*/
import java.util.*;
import java.lang.*;
import java.io.*;
class NumArray {
int[] dp;
public NumArray(int[] nums) {
dp=new int[nums.length+1];
for(int i=1;i<=nums.length;i++){
dp[i]=nums[i-1]+dp[i-1];
}
}
public int sumRange(int i, int j) {
return dp[j+1]-dp[i];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
|
3e1a1cb4ba290c7f7f505798130ca1f2f6da77fc | 10,974 | java | Java | systemtest/src/main/java/io/strimzi/systemtest/utils/specific/CruiseControlUtils.java | ppatierno/barnabas | 414635007ea000689cccbecf7c0327226c37e5db | [
"Apache-2.0"
] | 211 | 2018-01-03T17:55:54.000Z | 2018-06-06T15:47:45.000Z | systemtest/src/main/java/io/strimzi/systemtest/utils/specific/CruiseControlUtils.java | ppatierno/barnabas | 414635007ea000689cccbecf7c0327226c37e5db | [
"Apache-2.0"
] | 250 | 2018-01-02T14:19:00.000Z | 2018-06-06T15:55:56.000Z | systemtest/src/main/java/io/strimzi/systemtest/utils/specific/CruiseControlUtils.java | ppatierno/barnabas | 414635007ea000689cccbecf7c0327226c37e5db | [
"Apache-2.0"
] | 38 | 2018-01-11T15:13:27.000Z | 2018-06-04T21:51:23.000Z | 56.860104 | 182 | 0.73747 | 11,102 | /*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.systemtest.utils.specific;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.strimzi.api.kafka.model.KafkaResources;
import io.strimzi.api.kafka.model.KafkaTopic;
import io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlConfigurationParameters;
import io.strimzi.operator.cluster.operator.resource.cruisecontrol.CruiseControlEndpoints;
import io.strimzi.systemtest.Constants;
import io.strimzi.systemtest.Environment;
import io.strimzi.systemtest.resources.crd.KafkaTopicResource;
import io.strimzi.systemtest.utils.kubeUtils.objects.PodUtils;
import io.strimzi.test.TestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Level;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;
import static io.strimzi.test.k8s.KubeClusterResource.cmdKubeClient;
import static io.strimzi.test.k8s.KubeClusterResource.kubeClient;
public class CruiseControlUtils {
private static final Logger LOGGER = LogManager.getLogger(CruiseControlUtils.class);
public static final String CRUISE_CONTROL_METRICS_TOPIC = "strimzi.cruisecontrol.metrics"; // partitions 1 , rf - 1
public static final String CRUISE_CONTROL_MODEL_TRAINING_SAMPLES_TOPIC = "strimzi.cruisecontrol.modeltrainingsamples"; // partitions 32 , rf - 2
public static final String CRUISE_CONTROL_PARTITION_METRICS_SAMPLES_TOPIC = "strimzi.cruisecontrol.partitionmetricsamples"; // partitions 32 , rf - 2
private static final int CRUISE_CONTROL_DEFAULT_PORT = 9090;
private static final int CRUISE_CONTROL_METRICS_PORT = 9404;
private static final String CONTAINER_NAME = "cruise-control";
private CruiseControlUtils() { }
public enum SupportedHttpMethods {
GET,
POST
}
public enum SupportedSchemes {
HTTP,
HTTPS
}
@SuppressWarnings("Regexp")
@SuppressFBWarnings("DM_CONVERT_CASE")
public static String callApi(String namespaceName, SupportedHttpMethods method, CruiseControlEndpoints endpoint, SupportedSchemes scheme, Boolean withCredentials) {
String ccPodName = PodUtils.getFirstPodNameContaining(namespaceName, CONTAINER_NAME);
String args = " -k ";
if (withCredentials) {
args = " --cacert /etc/cruise-control/cc-certs/cruise-control.crt"
+ " --user admin:$(cat /opt/cruise-control/api-auth-config/cruise-control.apiAdminPassword) ";
}
return cmdKubeClient(namespaceName).execInPodContainer(Level.DEBUG, ccPodName, CONTAINER_NAME, "/bin/bash", "-c",
"curl -X" + method.name() + args + " " + scheme + "://localhost:" + CRUISE_CONTROL_DEFAULT_PORT + endpoint.toString()).out();
}
@SuppressWarnings("Regexp")
@SuppressFBWarnings("DM_CONVERT_CASE")
public static String callApi(String namespaceName, SupportedHttpMethods method, String endpoint) {
String ccPodName = PodUtils.getFirstPodNameContaining(namespaceName, CONTAINER_NAME);
return cmdKubeClient(namespaceName).execInPodContainer(Level.DEBUG, ccPodName, CONTAINER_NAME, "/bin/bash", "-c",
"curl -X" + method.name() + " localhost:" + CRUISE_CONTROL_METRICS_PORT + endpoint).out();
}
@SuppressWarnings("BooleanExpressionComplexity")
public static void verifyCruiseControlMetricReporterConfigurationInKafkaConfigMapIsPresent(Properties kafkaProperties) {
String kafkaClusterName = kafkaProperties.getProperty("cluster-name");
TestUtils.waitFor("Verify that kafka configuration " + kafkaProperties.toString() + " has correct cruise control metric reporter properties",
Constants.GLOBAL_POLL_INTERVAL, Constants.GLOBAL_CRUISE_CONTROL_TIMEOUT, () ->
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_TOPIC_NAME.getValue()).equals("strimzi.cruisecontrol.metrics") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_SSL_ENDPOINT_ID_ALGO.getValue()).equals("HTTPS") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_BOOTSTRAP_SERVERS.getValue()).equals(kafkaClusterName + "-kafka-brokers:9091") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_SECURITY_PROTOCOL.getValue()).equals("SSL") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_SSL_KEYSTORE_TYPE.getValue()).equals("PKCS12") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_SSL_KEYSTORE_LOCATION.getValue()).equals("/tmp/kafka/cluster.keystore.p12") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_SSL_KEYSTORE_PASSWORD.getValue()).equals("${CERTS_STORE_PASSWORD}") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_SSL_TRUSTSTORE_TYPE.getValue()).equals("PKCS12") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_SSL_TRUSTSTORE_LOCATION.getValue()).equals("/tmp/kafka/cluster.truststore.p12") &&
kafkaProperties.getProperty(CruiseControlConfigurationParameters.METRICS_REPORTER_SSL_TRUSTSTORE_PASSWORD.getValue()).equals("${CERTS_STORE_PASSWORD}"));
}
public static void verifyThatCruiseControlSamplesTopicsArePresent(String namespaceName, long timeout) {
final int numberOfPartitionsSamplesTopic = 32;
final int numberOfReplicasSamplesTopic = 2;
TestUtils.waitFor("Verify that kafka contains cruise control topics with related configuration.",
Constants.GLOBAL_POLL_INTERVAL, timeout, () -> {
KafkaTopic modelTrainingSamples = KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(CRUISE_CONTROL_MODEL_TRAINING_SAMPLES_TOPIC).get();
KafkaTopic partitionsMetricsSamples = KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(CRUISE_CONTROL_PARTITION_METRICS_SAMPLES_TOPIC).get();
if (modelTrainingSamples != null && partitionsMetricsSamples != null) {
boolean hasTopicCorrectPartitionsCount =
modelTrainingSamples.getSpec().getPartitions() == numberOfPartitionsSamplesTopic &&
partitionsMetricsSamples.getSpec().getPartitions() == numberOfPartitionsSamplesTopic;
boolean hasTopicCorrectReplicasCount =
modelTrainingSamples.getSpec().getReplicas() == numberOfReplicasSamplesTopic &&
partitionsMetricsSamples.getSpec().getReplicas() == numberOfReplicasSamplesTopic;
return hasTopicCorrectPartitionsCount && hasTopicCorrectReplicasCount;
}
LOGGER.debug("One of the samples {}, {} topics are not present", CRUISE_CONTROL_MODEL_TRAINING_SAMPLES_TOPIC, CRUISE_CONTROL_PARTITION_METRICS_SAMPLES_TOPIC);
return false;
});
}
public static void verifyThatKafkaCruiseControlMetricReporterTopicIsPresent(String namespaceName, long timeout) {
final int numberOfPartitionsMetricTopic = 1;
final int numberOfReplicasMetricTopic = 3;
TestUtils.waitFor("Verify that kafka contains cruise control topics with related configuration.",
Constants.GLOBAL_POLL_INTERVAL, timeout, () -> {
KafkaTopic metrics = KafkaTopicResource.kafkaTopicClient().inNamespace(namespaceName).withName(CRUISE_CONTROL_METRICS_TOPIC).get();
boolean hasTopicCorrectPartitionsCount =
metrics.getSpec().getPartitions() == numberOfPartitionsMetricTopic;
boolean hasTopicCorrectReplicasCount =
metrics.getSpec().getReplicas() == numberOfReplicasMetricTopic;
return hasTopicCorrectPartitionsCount && hasTopicCorrectReplicasCount;
});
}
public static void verifyThatCruiseControlTopicsArePresent(String namespaceName) {
verifyThatKafkaCruiseControlMetricReporterTopicIsPresent(namespaceName, Constants.GLOBAL_CRUISE_CONTROL_TIMEOUT);
verifyThatCruiseControlSamplesTopicsArePresent(namespaceName, Constants.GLOBAL_CRUISE_CONTROL_TIMEOUT);
}
public static Properties getKafkaCruiseControlMetricsReporterConfiguration(String namespaceName, String clusterName) throws IOException {
String cmName;
if (Environment.isStrimziPodSetEnabled()) {
cmName = KafkaResources.kafkaPodName(clusterName, 0);
} else {
cmName = KafkaResources.kafkaMetricsAndLogConfigMapName(clusterName);
}
InputStream configurationFileStream = new ByteArrayInputStream(kubeClient(namespaceName).getConfigMap(namespaceName, cmName)
.getData().get("server.config").getBytes(StandardCharsets.UTF_8));
Properties configurationOfKafka = new Properties();
configurationOfKafka.load(configurationFileStream);
Properties cruiseControlProperties = new Properties();
for (Map.Entry<Object, Object> entry : configurationOfKafka.entrySet()) {
if (entry.getKey().toString().startsWith("cruise.control.metrics")) {
cruiseControlProperties.put(entry.getKey(), entry.getValue());
}
}
cruiseControlProperties.put("cluster-name", clusterName);
return cruiseControlProperties;
}
public static void waitForRebalanceEndpointIsReady(String namespaceName) {
TestUtils.waitFor("Wait for rebalance endpoint is ready",
Constants.API_CRUISE_CONTROL_POLL, Constants.API_CRUISE_CONTROL_TIMEOUT, () -> {
String response = callApi(namespaceName, SupportedHttpMethods.POST, CruiseControlEndpoints.REBALANCE, SupportedSchemes.HTTPS, true);
LOGGER.debug("API response {}", response);
return !response.contains("Error processing POST request '/rebalance' due to: " +
"'com.linkedin.kafka.cruisecontrol.exception.KafkaCruiseControlException: " +
"com.linkedin.cruisecontrol.exception.NotEnoughValidWindowsException: ");
});
}
/**
* Returns user defined network capacity value without KiB/s suffix.
*
* @param userCapacity User defined network capacity with KiB/s suffix.
*
* @return User defined network capacity without KiB/s as a Double.
*/
public static Double removeNetworkCapacityKibSuffix(String userCapacity) {
return Double.valueOf(userCapacity.substring(0, userCapacity.length() - 5));
}
}
|
3e1a1da7c20185458cdf6c2566c3f879174c89f4 | 189 | java | Java | src/core/src/main/java/org/tio/client/DefaultClientAioListener.java | weizai118/t-io | bc3caf0f33a86d10e3a054c6aefdfff8e9df2bf1 | [
"Apache-2.0"
] | 2 | 2019-03-29T02:11:23.000Z | 2020-08-20T08:59:08.000Z | src/core/src/main/java/org/tio/client/DefaultClientAioListener.java | youchangxu1205/t-io | 519bba94e8f0855494697b1cbd2cebd26ba22140 | [
"Apache-2.0"
] | null | null | null | src/core/src/main/java/org/tio/client/DefaultClientAioListener.java | youchangxu1205/t-io | 519bba94e8f0855494697b1cbd2cebd26ba22140 | [
"Apache-2.0"
] | 1 | 2019-05-14T08:50:27.000Z | 2019-05-14T08:50:27.000Z | 15.75 | 66 | 0.756614 | 11,103 | package org.tio.client;
import org.tio.core.DefaultAioListener;
/**
*
* @author tanyaowu
* 2017年4月1日 上午9:32:39
*/
public class DefaultClientAioListener extends DefaultAioListener {
}
|
3e1a1db44839403c777d88401205d81270786b05 | 808 | java | Java | module_text/src/main/java/com/example/module_text/TextFragment.java | xiongzebao/MyMVPArms | f5fc9a4a2788d42e542d530425d21edfadb29591 | [
"Apache-2.0"
] | 1 | 2019-11-27T14:00:39.000Z | 2019-11-27T14:00:39.000Z | module_text/src/main/java/com/example/module_text/TextFragment.java | xiongzebao/MyMVPArms | f5fc9a4a2788d42e542d530425d21edfadb29591 | [
"Apache-2.0"
] | null | null | null | module_text/src/main/java/com/example/module_text/TextFragment.java | xiongzebao/MyMVPArms | f5fc9a4a2788d42e542d530425d21edfadb29591 | [
"Apache-2.0"
] | null | null | null | 23.085714 | 128 | 0.757426 | 11,104 | package com.example.module_text;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
public class TextFragment extends BaseFragment {
@Override
public void setupFragmentComponent(@NonNull AppComponent appComponent) {
}
@Override
public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return null;
}
@Override
public void initData(@Nullable Bundle savedInstanceState) {
}
@Override
public void setData(@Nullable Object data) {
}
}
|
3e1a1e02e6099ad58a462f3475348556c8c9aead | 1,516 | java | Java | src/main/java/avatar/game/entity/NPC/spawn/NPCConcernedCitizen.java | Jimmeh94/AvatarSpigot | 704f4f219963bd3de124beee2c25a4dd29ce52e0 | [
"MIT"
] | null | null | null | src/main/java/avatar/game/entity/NPC/spawn/NPCConcernedCitizen.java | Jimmeh94/AvatarSpigot | 704f4f219963bd3de124beee2c25a4dd29ce52e0 | [
"MIT"
] | null | null | null | src/main/java/avatar/game/entity/NPC/spawn/NPCConcernedCitizen.java | Jimmeh94/AvatarSpigot | 704f4f219963bd3de124beee2c25a4dd29ce52e0 | [
"MIT"
] | null | null | null | 36.095238 | 159 | 0.729551 | 11,105 | package avatar.game.entity.npc.spawn;
import avatar.Avatar;
import avatar.game.entity.npc.NPCVillager;
import avatar.game.quest.quests.test.DemoQuest;
import avatar.game.user.UserPlayer;
import avatar.util.misc.Qualifier;
import avatar.util.text.Messager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import java.util.Optional;
public class NPCConcernedCitizen extends NPCVillager {
private Qualifier qualifier;
public NPCConcernedCitizen() {
this(new Location(Bukkit.getWorlds().get(0), -844.5, 5, 303.5, -90f, 0f));
}
public NPCConcernedCitizen(Location location) {
super(location, Villager.Profession.LIBRARIAN, "Concerned Citizen");
this.qualifier = new Qualifier(Qualifier.What.QUEST, Qualifier.When.BEFORE, DemoQuest.reference.getID());
}
@Override
public void onInteraction(Player player) {
UserPlayer userPlayer = Avatar.INSTANCE.getUserManager().findUserPlayer(player).get();
if(qualifier.valid(userPlayer) && userPlayer.getQuestManager().canTakeQuest(DemoQuest.reference)){
Messager.sendMessage(player, ChatColor.GRAY + "[Concerned Citizen] I heard the old man to my left needs help!", Optional.<Messager.Prefix>empty());
} else {
Messager.sendMessage(player, ChatColor.GRAY + "[Concerned Citizen] It's nice of you to have helped him!", Optional.<Messager.Prefix>empty());
}
}
}
|
3e1a1f46c539d79b8879e4aa205915f136c0cd58 | 1,248 | java | Java | src/main/java/fortifiedid/bankidapi/auth/AuthRequest.java | fortifiedid/bankidapi | a3294b562af43a5861ae25bc9ea4e7cdc4035566 | [
"Apache-2.0"
] | null | null | null | src/main/java/fortifiedid/bankidapi/auth/AuthRequest.java | fortifiedid/bankidapi | a3294b562af43a5861ae25bc9ea4e7cdc4035566 | [
"Apache-2.0"
] | null | null | null | src/main/java/fortifiedid/bankidapi/auth/AuthRequest.java | fortifiedid/bankidapi | a3294b562af43a5861ae25bc9ea4e7cdc4035566 | [
"Apache-2.0"
] | null | null | null | 26.553191 | 85 | 0.722756 | 11,106 | package fortifiedid.bankidapi.auth;
import fortifiedid.bankidapi.entities.EndUserIp;
import fortifiedid.bankidapi.entities.PersonalNumber;
import fortifiedid.bankidapi.entities.Requirement;
import fortifiedid.bankidapi.util.JsonParser;
import fortifiedid.bankidapi.util.JsonParserException;
import java.nio.charset.Charset;
public class AuthRequest {
public String endUserIp;
public String personalNumber;
public Requirement Requirement;
public static final String URI="/auth";
public AuthRequest(EndUserIp ip) {
this.endUserIp = ip.toString();
}
private AuthRequest() {
}
public void personalNumer(PersonalNumber pnr) {
this.personalNumber = pnr.toString();
}
public void requirement(Requirement Requirement) {
this.Requirement = Requirement;
}
public static AuthRequest parseJson(byte[] jsonData) throws JsonParserException {
return new JsonParser().parse(jsonData, AuthRequest.class);
}
public String toJson() throws JsonParserException {
return new JsonParser().toJson(this);
}
public byte[] toByte() throws JsonParserException {
return new JsonParser().toJson(this).getBytes(Charset.forName("UTF-8"));
}
}
|
3e1a1fdb6192b014b03f3221ae945714f4041ee9 | 2,795 | java | Java | src/test/java/org/sanju/ml/plugin/TestMLModuleDeployerMojo.java | sanjuthomas/marklogic-module-deployer | eed9219f5d83804781cf26936964c4399d3edffc | [
"MIT"
] | 2 | 2016-10-25T02:40:30.000Z | 2017-08-18T19:58:33.000Z | src/test/java/org/sanju/ml/plugin/TestMLModuleDeployerMojo.java | sanjuthomas/marklogic-module-deployer | eed9219f5d83804781cf26936964c4399d3edffc | [
"MIT"
] | 3 | 2016-11-17T15:10:42.000Z | 2017-03-22T17:33:48.000Z | src/test/java/org/sanju/ml/plugin/TestMLModuleDeployerMojo.java | sanjuthomas/marklogic-module-deployer | eed9219f5d83804781cf26936964c4399d3edffc | [
"MIT"
] | null | null | null | 41.716418 | 119 | 0.826118 | 11,107 | package org.sanju.ml.plugin;
import static org.junit.Assert.assertNotNull;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.maven.plugin.MojoExecutionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sanju.ml.ConnectionManager;
import org.sanju.ml.deployer.AbstractTest;
import com.marklogic.client.admin.ExtensionLibrariesManager;
import com.marklogic.client.admin.QueryOptionsManager;
import com.marklogic.client.admin.ResourceExtensionsManager;
import com.marklogic.client.admin.TransformExtensionsManager;
import com.marklogic.client.io.StringHandle;
/**
*
* @author Sanju Thomas
*
*/
public class TestMLModuleDeployerMojo extends AbstractTest{
private MLModuleDeployerMojo mlModuleDeployerMojo;
private ExtensionLibrariesManager extensionLibrariesManager;
private QueryOptionsManager queryOptionsManager ;
private ResourceExtensionsManager resourceExtensionsManager;
private TransformExtensionsManager transformExtensionManager;
@Override
@Before
public void setup() throws FileNotFoundException, IOException{
super.setup();
this.mlModuleDeployerMojo = new MLModuleDeployerMojo();
}
@After
public void tearDown(){
ConnectionManager.close(this.databaseClient);
}
@Test
public void shouldDeployAllAssets() throws MojoExecutionException{
this.mlModuleDeployerMojo.setMlConfiguration("src/test/resources/ml-server-config.properties");
this.mlModuleDeployerMojo.execute();
super.databaseClient = ConnectionManager.getClient(this.mlApplicationServer);
this.extensionLibrariesManager = this.databaseClient.newServerConfigManager().newExtensionLibrariesManager();
this.queryOptionsManager = this.databaseClient.newServerConfigManager().newQueryOptionsManager();
this.resourceExtensionsManager = this.databaseClient.newServerConfigManager().newResourceExtensionsManager();
this.transformExtensionManager = this.databaseClient.newServerConfigManager().newTransformExtensionsManager();
assertNotNull(this.resourceExtensionsManager.readServices("js-test-extension", new StringHandle()).get());
assertNotNull(this.resourceExtensionsManager.readServices("xq-test-extension", new StringHandle()).get());
assertNotNull(this.extensionLibrariesManager.read("/ext/test-lib.sjs", new StringHandle()).get());
assertNotNull(this.queryOptionsManager.readOptions("test-query-option", new StringHandle()).get());
assertNotNull(this.transformExtensionManager.readJavascriptTransform("js-test-transform", new StringHandle()).get());
assertNotNull(this.transformExtensionManager.readJavascriptTransform("xq-test-transform", new StringHandle()).get());
assertNotNull(this.transformExtensionManager.readJavascriptTransform("xl-test-transform", new StringHandle()).get());
}
}
|
3e1a20437bec902633454e1cd0095be4e4390ed5 | 5,584 | java | Java | temporal-test-server/src/main/java/io/temporal/internal/testservice/TestService.java | yiminc/sdk-java | 16903942bf7613e00cb652d7782d3fe70274373e | [
"Apache-2.0"
] | 9 | 2020-03-20T21:04:40.000Z | 2020-07-07T12:50:55.000Z | temporal-test-server/src/main/java/io/temporal/internal/testservice/TestService.java | yiminc/sdk-java | 16903942bf7613e00cb652d7782d3fe70274373e | [
"Apache-2.0"
] | 58 | 2020-03-26T19:47:57.000Z | 2020-07-07T13:47:03.000Z | temporal-test-server/src/main/java/io/temporal/internal/testservice/TestService.java | yiminc/sdk-java | 16903942bf7613e00cb652d7782d3fe70274373e | [
"Apache-2.0"
] | 11 | 2020-07-10T07:36:33.000Z | 2020-09-18T01:36:13.000Z | 35.566879 | 99 | 0.735673 | 11,108 | /*
* Copyright (C) 2020 Temporal Technologies, Inc. All Rights Reserved.
*
* Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Modifications copyright (C) 2017 Uber Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. A copy of the License is
* located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.temporal.internal.testservice;
import com.google.protobuf.Empty;
import com.google.protobuf.Timestamp;
import io.grpc.stub.StreamObserver;
import io.temporal.api.testservice.v1.*;
import io.temporal.internal.common.ProtobufTimeUtils;
import java.io.Closeable;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* In memory implementation of the Operator Service. To be used for testing purposes only.
*
* <p>Do not use directly, instead use {@link io.temporal.testing.TestWorkflowEnvironment}.
*/
final class TestService extends TestServiceGrpc.TestServiceImplBase implements Closeable {
private final SelfAdvancingTimer selfAdvancingTimer;
private final TestWorkflowStore workflowStore;
public TestService(
TestWorkflowStore workflowStore,
SelfAdvancingTimer selfAdvancingTimer,
boolean lockTimeSkipping) {
this.workflowStore = workflowStore;
this.selfAdvancingTimer = selfAdvancingTimer;
if (lockTimeSkipping) {
selfAdvancingTimer.lockTimeSkipping("TestService constructor");
}
}
@Override
public void lockTimeSkipping(
LockTimeSkippingRequest request, StreamObserver<LockTimeSkippingResponse> responseObserver) {
selfAdvancingTimer.lockTimeSkipping("External Caller");
responseObserver.onNext(LockTimeSkippingResponse.newBuilder().build());
responseObserver.onCompleted();
}
@Override
public void unlockTimeSkipping(
UnlockTimeSkippingRequest request,
StreamObserver<UnlockTimeSkippingResponse> responseObserver) {
selfAdvancingTimer.unlockTimeSkipping("External Caller");
responseObserver.onNext(UnlockTimeSkippingResponse.newBuilder().build());
responseObserver.onCompleted();
}
@Override
public void sleep(SleepRequest request, StreamObserver<SleepResponse> responseObserver) {
CompletableFuture<Void> result = new CompletableFuture<>();
selfAdvancingTimer.schedule(
ProtobufTimeUtils.toJavaDuration(request.getDuration()),
() -> result.complete(null),
"TestService sleep");
try {
result.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
responseObserver.onNext(SleepResponse.newBuilder().build());
responseObserver.onCompleted();
}
@Override
public void sleepUntil(
SleepUntilRequest request, StreamObserver<SleepResponse> responseObserver) {
CompletableFuture<Void> result = new CompletableFuture<>();
selfAdvancingTimer.scheduleAt(
ProtobufTimeUtils.toJavaInstant(request.getTimestamp()),
() -> result.complete(null),
"TestService sleepUntil");
try {
result.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
responseObserver.onNext(SleepResponse.newBuilder().build());
responseObserver.onCompleted();
}
@Override
public void unlockTimeSkippingWithSleep(
SleepRequest request, StreamObserver<SleepResponse> responseObserver) {
unlockTimeSkippingWhileSleep(ProtobufTimeUtils.toJavaDuration(request.getDuration()));
responseObserver.onNext(SleepResponse.newBuilder().build());
responseObserver.onCompleted();
}
@Override
public void getCurrentTime(
Empty request, StreamObserver<GetCurrentTimeResponse> responseObserver) {
Timestamp timestamp = workflowStore.currentTime();
responseObserver.onNext(GetCurrentTimeResponse.newBuilder().setTime(timestamp).build());
responseObserver.onCompleted();
}
/**
* Unlocks time skipping and blocks the calling thread until internal clock passes the current +
* duration time.<br>
* When the time is reached, locks time skipping and returns.<br>
* Might not block at all due to time skipping. Or might block if the time skipping lock counter
* was more than 1.
*/
private void unlockTimeSkippingWhileSleep(Duration duration) {
CompletableFuture<Void> result = new CompletableFuture<>();
selfAdvancingTimer.schedule(
duration,
() -> {
selfAdvancingTimer.lockTimeSkipping("TestService unlockTimeSkippingWhileSleep");
result.complete(null);
},
"TestService unlockTimeSkippingWhileSleep");
selfAdvancingTimer.unlockTimeSkipping("TestService unlockTimeSkippingWhileSleep");
try {
result.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {}
}
|
3e1a20c54029a5423c7e65a3c49274e6001ed243 | 3,472 | java | Java | hermes/src/main/java/com/gengoai/hermes/annotator/Annotator.java | gengoai/mono-repo | 50e95c16579aaa8a4ee0776582964868b5625415 | [
"Apache-2.0"
] | 2 | 2020-05-15T10:19:13.000Z | 2020-06-06T15:21:33.000Z | hermes/src/main/java/com/gengoai/hermes/annotator/Annotator.java | gengoai/mono-repo | 50e95c16579aaa8a4ee0776582964868b5625415 | [
"Apache-2.0"
] | 5 | 2021-03-31T17:54:38.000Z | 2022-02-10T02:40:07.000Z | hermes/src/main/java/com/gengoai/hermes/annotator/Annotator.java | gengoai/gengoai | 50e95c16579aaa8a4ee0776582964868b5625415 | [
"Apache-2.0"
] | 1 | 2022-01-29T20:02:40.000Z | 2022-01-29T20:02:40.000Z | 35.428571 | 122 | 0.719758 | 11,109 | /*
* (c) 2005 David B. Bracewell
*
* 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 com.gengoai.hermes.annotator;
import com.gengoai.Language;
import com.gengoai.MultithreadedStopwatch;
import com.gengoai.config.Config;
import com.gengoai.hermes.AnnotatableType;
import com.gengoai.hermes.Document;
import lombok.NonNull;
import java.io.Serializable;
import java.util.Collections;
import java.util.Set;
/**
* <p>
* An annotator processes documents adding one or more {@link AnnotatableType}s. An annotator may require specific
* types of annotations to be present on the document before it can process the document (by default it requires none).
* Annotators define a provider name ({@link #getProvider(Language)}) that identifies the model, version, lexicon, etc.
* used by
* the annotator to produce its annotations (by default this is set "SimpleClassName v1.0").
* </p>
* <p><b>Note</b>: Annotator implementations should be implemented in a thread safe manner.</p>
*
* @author David B. Bracewell
*/
public abstract class Annotator implements Serializable {
private static final long serialVersionUID = 1L;
private final MultithreadedStopwatch stopwatch = new MultithreadedStopwatch("Annotator." + getClass().getSimpleName());
/**
* Annotates a document with one or more AnnotatableType defined in <code>satisfies()</code>.
*
* @param document The document to annotate
*/
public final void annotate(@NonNull Document document) {
stopwatch.start();
annotateImpl(document);
stopwatch.stop();
}
/**
* Annotates a document with one or more AnnotatableType defined in <code>satisfies()</code>.
*
* @param document The document to annotate
*/
protected abstract void annotateImpl(Document document);
/**
* Gets the provider information for this annotator.. The provider information should relate to a version number,
* model used, or something else to identify the settings of the annotator.
*
* @param language
* @return the provider
*/
public String getProvider(Language language) {
return Config.get(this.getClass(), "version")
.asString(getClass().getSimpleName() + " v1.0");
}
/**
* The annotation types required to be on a document before this annotator can annotate
*
* @return the set of required annotation types
*/
public Set<AnnotatableType> requires() {
return Collections.emptySet();
}
/**
* The set of annotation types that this annotator satisfies by this annotator
*
* @return the set of satisfied annotation types
*/
public abstract Set<AnnotatableType> satisfies();
}//END OF Annotator
|
3e1a20fa78b21699fcef8ee93bf2fcf402ff743a | 1,188 | java | Java | src/main/java/writeside/application/BookingServiceImpl.java | SystemArchitecture-org/Lab_CQRS | e2da3e467fbba64da66ae5c60cecfeae97ff85a9 | [
"MIT"
] | null | null | null | src/main/java/writeside/application/BookingServiceImpl.java | SystemArchitecture-org/Lab_CQRS | e2da3e467fbba64da66ae5c60cecfeae97ff85a9 | [
"MIT"
] | null | null | null | src/main/java/writeside/application/BookingServiceImpl.java | SystemArchitecture-org/Lab_CQRS | e2da3e467fbba64da66ae5c60cecfeae97ff85a9 | [
"MIT"
] | null | null | null | 32.108108 | 114 | 0.772727 | 11,110 | package writeside.application;
import eventside.domain.CancelBookingEvent;
import eventside.domain.CreateBookingEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import writeside.EventPublisher;
import writeside.application.api.BookingService;
import writeside.domain.Booking;
import writeside.domain.repositories.BookingRepository;
@Service
public class BookingServiceImpl implements BookingService {
@Autowired
private BookingRepository bookingRepository;
@Autowired
private EventPublisher eventPublisher;
public void createBooking(Booking booking){
bookingRepository.addBooking(booking);
if (eventPublisher.publishCreateBookingEvent(new CreateBookingEvent(booking))) {
System.out.println("Create booking event successfully published");
}
}
public void cancelBooking(Booking booking){
bookingRepository.removeBooking(booking);
if (eventPublisher.publishCancelBookingEvent(new CancelBookingEvent(booking.getBookingID().toString()))) {
System.out.println("Cancel booking event successfully published");
}
}
}
|
3e1a21521c6b67fdc10b68eccbb4952c8144d9f9 | 1,523 | java | Java | src/main/java/io/github/cottonmc/libdp/api/driver/Driver.java | CottonMC/LibDP | 7629f5b1e4706631c7bf7c84e76428f4d7d74b5b | [
"MIT"
] | 3 | 2020-08-18T16:06:00.000Z | 2021-12-19T21:03:43.000Z | src/main/java/io/github/cottonmc/libdp/api/driver/Driver.java | CottonMC/LibDP | 7629f5b1e4706631c7bf7c84e76428f4d7d74b5b | [
"MIT"
] | null | null | null | src/main/java/io/github/cottonmc/libdp/api/driver/Driver.java | CottonMC/LibDP | 7629f5b1e4706631c7bf7c84e76428f4d7d74b5b | [
"MIT"
] | 1 | 2021-04-03T19:56:27.000Z | 2021-04-03T19:56:27.000Z | 35.418605 | 121 | 0.753119 | 11,111 | package io.github.cottonmc.libdp.api.driver;
import net.minecraft.resource.ResourceManager;
import java.util.concurrent.Executor;
import com.google.gson.JsonObject;
import io.github.cottonmc.libdp.api.Diskette;
public interface Driver {
/**
* Called whenever the /reload command is run, before scripts are run.
* Use this time to empty out any lists or maps you need to.
* @param manager The ResourceManager reloading tweakers.
*/
void prepareReload(ResourceManager manager);
/**
* Called whenever the /reload command is run, after scripts are run.
* Use this time to apply whatever you need to.
* @param manager The ResourceManager applying tweakers. Should be the same one called in prepareReload.
* @param executor The Executor applying tweakers.
*/
void applyReload(ResourceManager manager, Executor executor);
/**
* Called after all scripts have been run, to log what tweakers have been applied.
* @return The number of applied tweaks and the description of what type of tweak it is, ex. "12 recipes"
*/
String getApplyMessage();
/**
* Prepare anything needed based on the script, like namespaces or other information. Called before each script is run.
* @param bridge The bridge provided for this script, including info like the namespace, script engine, and script text.
*/
default void prepareFor(Diskette bridge) {}
/**
* @return A JsonObject containing information useful for debugging. Called when `/libcd debug export` is run.
*/
JsonObject getDebugInfo();
}
|
3e1a222b7fe068f5a6946823a5b4ebff53c9089e | 1,721 | java | Java | src/main/java/io/renren/modules/app/form/TreasureDetailCommentForm.java | xukaka/chongai | b3eaf1b1cff63d13952e195d3ae7c8a1714dd203 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/renren/modules/app/form/TreasureDetailCommentForm.java | xukaka/chongai | b3eaf1b1cff63d13952e195d3ae7c8a1714dd203 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/renren/modules/app/form/TreasureDetailCommentForm.java | xukaka/chongai | b3eaf1b1cff63d13952e195d3ae7c8a1714dd203 | [
"Apache-2.0"
] | 1 | 2019-03-01T08:41:04.000Z | 2019-03-01T08:41:04.000Z | 15.888889 | 64 | 0.631702 | 11,112 | package io.renren.modules.app.form;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
/**
* 宠物宝典评论表
*
* @author fz
* @email lyhxr@example.com
* @date 2019-03-12 10:30:59
*/
@ApiModel
public class TreasureDetailCommentForm implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 评论ID
*/
@ApiModelProperty(value = "评论ID",example = "")
private Long id;
/**
* 宠物宝典ID
*/
@ApiModelProperty(value = "宠物宝典ID",example = "")
private Long detailId;
/**
* 品论内容
*/
@ApiModelProperty(value = "品论内容",example = "")
private String content;
/**
* 评论者openid
*/
@ApiModelProperty(value = "评论者openid",example = "")
private String fromOpenid;
/**
* 点赞数
*/
@ApiModelProperty(value = "点赞数",example = "")
private Long likeCount;
/**
* 设置:评论ID
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取:评论ID
*/
public Long getId() {
return id;
}
/**
* 设置:宠物宝典ID
*/
public void setDetailId(Long detailId) {
this.detailId = detailId;
}
/**
* 获取:宠物宝典ID
*/
public Long getDetailId() {
return detailId;
}
/**
* 设置:品论内容
*/
public void setContent(String content) {
this.content = content;
}
/**
* 获取:品论内容
*/
public String getContent() {
return content;
}
/**
* 设置:评论者openid
*/
public void setFromOpenid(String fromOpenid) {
this.fromOpenid = fromOpenid;
}
/**
* 获取:评论者openid
*/
public String getFromOpenid() {
return fromOpenid;
}
/**
* 设置:点赞数
*/
public void setLikeCount(Long likeCount) {
this.likeCount = likeCount;
}
/**
* 获取:点赞数
*/
public Long getLikeCount() {
return likeCount;
}
}
|
3e1a2245c87c4345824914c54fde9b68963c27ab | 4,972 | java | Java | AppLockPro/app/src/main/java/com/eeontheway/android/applocker/login/IUserManager.java | lhzheng880828/AndroidApp | c985a5fce654b4f5ea3253edef7641e4ec18b01a | [
"Apache-2.0"
] | 4 | 2017-12-10T08:05:55.000Z | 2021-04-10T10:42:17.000Z | AppLockPro/app/src/main/java/com/eeontheway/android/applocker/login/IUserManager.java | lhzheng880828/AndroidApp | c985a5fce654b4f5ea3253edef7641e4ec18b01a | [
"Apache-2.0"
] | null | null | null | AppLockPro/app/src/main/java/com/eeontheway/android/applocker/login/IUserManager.java | lhzheng880828/AndroidApp | c985a5fce654b4f5ea3253edef7641e4ec18b01a | [
"Apache-2.0"
] | 4 | 2017-12-10T08:05:56.000Z | 2019-12-09T15:58:53.000Z | 19.421875 | 82 | 0.558126 | 11,113 | package com.eeontheway.android.applocker.login;
import android.content.Context;
/**
* 用户管理接口
* @author lishutong
* @version v1.0
* @Time 2016-2-8
*/
public interface IUserManager {
int SMS_SEND_OK = 0; // 短信发送成功
int SMS_SEND_FAIL = 1; // 短信发送失败
int SMS_SEND_SENDING = 2; // 短信正在发送
/**
* 初始化反馈接口
* @return true 成功; false 失败
*/
boolean init (Context context);
/**
* 反初始化反馈接口
*/
void unInit();
/**
* 回调接口
*/
interface OnResultListener {
/**
* 登陆失败
* @param code 错误码
* @param msg 错误原因消息
*/
void onFail (int code, String msg);
/**
* 登陆成功
*/
void onSuccess ();
}
/**
* 短信注册码的回调
*/
interface OnRequestSmsCodeListener {
/**
* 登陆失败
* @param code 错误码
* @param msg 错误原因消息
*/
void onFail (int code, String msg);
/**
* 登陆成功
* @param smsId 注册码的ID
*/
void onSuccess (String smsId);
}
/**
* 回调接口
*/
interface OnQueryResultCodeListener {
/**
* 登陆失败
* @param code 错误码
* @param msg 错误原因消息
*/
void onFail (int code, String msg);
/**
* 登陆成功
*/
void onSuccess (int code);
}
/**
* 查询短信注册码的回调
*/
interface OnQuerySmsCodeListener {
/**
* 查询结果回调
* @param state 短信状态
* @param verified 是否已经验证
*/
void onQueryResult (int state, boolean verified);
}
/**
* 设置注册回调
* @param listener 注册事件监听器
*/
void setOnSignUpListener (OnResultListener listener);
/**
* 使用指定的用户名/密码/邮件/手机号 注册
* @param userName 用户名
* @param password 密码
*/
void signUp (String userName, String password);
/**
* 设置登陆回调
* @param listener
*/
void setOnLoginListener (OnResultListener listener);
/**
* 使用短信验证码一键注册和登陆
* @param phoneNumber 手机号
* @param smsCode 短信验证码
* @param phoneNumber 手机号
*/
void signUpAndLoginBySmsCode(String phoneNumber, String smsCode);
/**
* 使用指定的用户名和密码登陆
* @param userName 用户名
* @param password 密码
*/
void loginByUserName (String userName, String password);
/**
* 使用指定的手机号和密码登陆
* @param phoneNumber 手机号
* @param password 密码
*/
void loginByPhoneNumber (String phoneNumber, String password);
/**
* 获取已登陆的用户信息
* @return 用户信息; 为null表示用户未登陆
*/
UserInfo getMyUserInfo ();
/**
* 设置修改资料回调
* @param listener 注册事件监听器
*/
void setUpdateInfoListener (OnResultListener listener);
/**
* 更新自己的用户信息
* @param userInfo 用户信息
*/
void updateMyUserInfo (UserInfo userInfo);
/**
* 设置退出登陆事件
* @param listener 注册事件监听器
*/
void setOnLogoutListener (OnResultListener listener);
/**
* 退出登陆
*/
void logout ();
/**
* 设置密码修改监听器
* @param listener 注册事件监听器
*/
void setModifyPasswordListener (OnResultListener listener);
/**
* 修改密码
* @param oldPassword 旧密码
* @param newPassword 新密码
*/
void modifyPassword (String oldPassword, String newPassword);
/**
* 设置验证码申请的监听器
* @param listener 注册事件监听器
*/
void setRequestSmsCodeListener(OnRequestSmsCodeListener listener);
/**
* 设置短信注册码的查询回调
* @param listener 注册事件监听器
*/
void setQuerySmsCodeListener(OnQuerySmsCodeListener listener);
/**
* 设置短信注册码的校验回调
* @param listener 注册事件监听器
*/
void setVerifySmsCodeListener(OnResultListener listener);
/**
* 请求发送手机验证码用于登陆
* @param phoneNumber 手机号
* @param msgTemplate 发送消息的模板
*/
void reqeustSmsCode (String phoneNumber, String msgTemplate);
/**
* 检查手机验证码的有效性
* @param phoneNumber 手机号
* @param code 手同验证码
*/
void verifySmsCode (String phoneNumber, String code);
/**
* 查询手机验证码的发送状态
* @param smsId 短信ID
*/
void querySmsCode (String smsId);
/**
* 设置手机号绑定的事件回调
* @param listener 注册事件监听器
*/
void setBindPhoneListener(OnResultListener listener);
/**
* 为当前用户绑定手机号
* @param phoneNumber 待邦定的手机号
*/
void bindPhoneNumer (String phoneNumber);
/**
* 使用短信验证码来修改密码
* @param smsCode 短信验证码
* @param newPassword 新密码
*/
void modifyPasswordBySmsCode (String smsCode, String newPassword);
/**
* 检查手机号是否注册过
* @param listener 注册事件监听器
*/
void setCheckPhoneNumberVerifiedListener (OnQueryResultCodeListener listener);
/**
* 检查手机号是否被验证过
* @param phoneNumber
*/
void checkPhoneNumberVerified (String phoneNumber);
/**
* 获取自己的cid
* @return
*/
String getMyCid ();
/**
* 设置自己的cid
* @return 设置成功或失败。用户未登陆时,失败
*/
boolean setMyCid (String cid);
}
|
3e1a22ebb3bbbfd99ff7a89ee552be7859ab9f65 | 4,660 | java | Java | shardingsphere-features/shardingsphere-sharding/shardingsphere-sharding-distsql/shardingsphere-sharding-distsql-handler/src/test/java/org/apache/shardingsphere/sharding/distsql/update/AlterShardingKeyGeneratorStatementUpdaterTest.java | LeeGuoPing/shardingsphere | adf3ac02b53868b1933d1631ca879f7614478de1 | [
"Apache-2.0"
] | 4,372 | 2019-01-16T03:07:05.000Z | 2020-04-17T11:16:15.000Z | shardingsphere-features/shardingsphere-sharding/shardingsphere-sharding-distsql/shardingsphere-sharding-distsql-handler/src/test/java/org/apache/shardingsphere/sharding/distsql/update/AlterShardingKeyGeneratorStatementUpdaterTest.java | LeeGuoPing/shardingsphere | adf3ac02b53868b1933d1631ca879f7614478de1 | [
"Apache-2.0"
] | 3,040 | 2019-01-16T01:18:40.000Z | 2020-04-17T12:53:05.000Z | shardingsphere-features/shardingsphere-sharding/shardingsphere-sharding-distsql/shardingsphere-sharding-distsql-handler/src/test/java/org/apache/shardingsphere/sharding/distsql/update/AlterShardingKeyGeneratorStatementUpdaterTest.java | LeeGuoPing/shardingsphere | adf3ac02b53868b1933d1631ca879f7614478de1 | [
"Apache-2.0"
] | 1,515 | 2019-01-16T08:44:17.000Z | 2020-04-17T09:07:53.000Z | 54.186047 | 176 | 0.803648 | 11,114 | /*
* 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.shardingsphere.sharding.distsql.update;
import org.apache.shardingsphere.distsql.parser.segment.AlgorithmSegment;
import org.apache.shardingsphere.infra.config.algorithm.ShardingSphereAlgorithmConfiguration;
import org.apache.shardingsphere.infra.distsql.exception.DistSQLException;
import org.apache.shardingsphere.infra.distsql.exception.rule.DuplicateRuleException;
import org.apache.shardingsphere.infra.distsql.exception.rule.InvalidAlgorithmConfigurationException;
import org.apache.shardingsphere.infra.distsql.exception.rule.RequiredAlgorithmMissedException;
import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
import org.apache.shardingsphere.sharding.distsql.handler.update.AlterShardingKeyGeneratorStatementUpdater;
import org.apache.shardingsphere.sharding.distsql.parser.segment.ShardingKeyGeneratorSegment;
import org.apache.shardingsphere.sharding.distsql.parser.statement.AlterShardingKeyGeneratorStatement;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public final class AlterShardingKeyGeneratorStatementUpdaterTest {
private final AlterShardingKeyGeneratorStatementUpdater updater = new AlterShardingKeyGeneratorStatementUpdater();
@Mock
private ShardingSphereMetaData shardingSphereMetaData;
@Before
public void before() {
when(shardingSphereMetaData.getDatabaseName()).thenReturn("test");
}
@Test(expected = DuplicateRuleException.class)
public void assertExecuteWithDuplicate() throws DistSQLException {
ShardingKeyGeneratorSegment keyGeneratorSegment = new ShardingKeyGeneratorSegment("inputAlgorithmName", new AlgorithmSegment("inputAlgorithmName", createProperties()));
updater.checkSQLStatement(shardingSphereMetaData, new AlterShardingKeyGeneratorStatement(Arrays.asList(keyGeneratorSegment, keyGeneratorSegment)), null);
}
@Test(expected = RequiredAlgorithmMissedException.class)
public void assertExecuteWithNotExist() throws DistSQLException {
Properties props = createProperties();
ShardingKeyGeneratorSegment keyGeneratorSegment = new ShardingKeyGeneratorSegment("notExistAlgorithmName", new AlgorithmSegment("inputAlgorithmName", props));
ShardingRuleConfiguration ruleConfig = new ShardingRuleConfiguration();
ruleConfig.getShardingAlgorithms().put("existAlgorithmName", new ShardingSphereAlgorithmConfiguration("hash_mod", props));
updater.checkSQLStatement(shardingSphereMetaData, new AlterShardingKeyGeneratorStatement(Collections.singletonList(keyGeneratorSegment)), ruleConfig);
}
@Test(expected = InvalidAlgorithmConfigurationException.class)
public void assertExecuteWithInvalidAlgorithm() throws DistSQLException {
Properties props = createProperties();
ShardingKeyGeneratorSegment keyGeneratorSegment = new ShardingKeyGeneratorSegment("existAlgorithmName", new AlgorithmSegment("inputAlgorithmName", props));
ShardingRuleConfiguration ruleConfig = new ShardingRuleConfiguration();
ruleConfig.getKeyGenerators().put("existAlgorithmName", new ShardingSphereAlgorithmConfiguration("InvalidAlgorithm", props));
updater.checkSQLStatement(shardingSphereMetaData, new AlterShardingKeyGeneratorStatement(Collections.singletonList(keyGeneratorSegment)), ruleConfig);
}
private Properties createProperties() {
Properties result = new Properties();
result.put("inputKey", "inputValue");
return result;
}
}
|
3e1a234246c9fcd305680552d2f9bc88b63ee195 | 24,373 | java | Java | ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java | WinterBoy-Galois/react-native-swiftui | 93755f22e5e8d5277b4e7c1839bd6b2f478194b2 | [
"CC-BY-4.0",
"MIT"
] | 153 | 2020-08-25T17:16:30.000Z | 2022-03-23T20:06:19.000Z | ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java | WinterBoy-Galois/react-native-swiftui | 93755f22e5e8d5277b4e7c1839bd6b2f478194b2 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/MountingManager.java | WinterBoy-Galois/react-native-swiftui | 93755f22e5e8d5277b4e7c1839bd6b2f478194b2 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2021-12-21T20:04:52.000Z | 2022-01-15T07:44:37.000Z | 35.842647 | 105 | 0.672917 | 11,115 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.fabric.mounting;
import static com.facebook.infer.annotation.ThreadConfined.ANY;
import static com.facebook.infer.annotation.ThreadConfined.UI;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.AnyThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.react.bridge.ReactSoftException;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.bridge.RetryableMountingLayerException;
import com.facebook.react.bridge.SoftAssertions;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.common.build.ReactBuildConfig;
import com.facebook.react.fabric.FabricUIManager;
import com.facebook.react.fabric.events.EventEmitterWrapper;
import com.facebook.react.fabric.mounting.mountitems.MountItem;
import com.facebook.react.touch.JSResponderHandler;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.facebook.react.uimanager.ReactStylesDiffMap;
import com.facebook.react.uimanager.RootView;
import com.facebook.react.uimanager.RootViewManager;
import com.facebook.react.uimanager.StateWrapper;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.uimanager.ViewManagerRegistry;
import com.facebook.yoga.YogaMeasureMode;
import java.util.concurrent.ConcurrentHashMap;
/**
* Class responsible for actually dispatching view updates enqueued via {@link
* FabricUIManager#scheduleMountItems(int, MountItem[])} on the UI thread.
*/
public class MountingManager {
public static final String TAG = MountingManager.class.getSimpleName();
private static final boolean SHOW_CHANGED_VIEW_HIERARCHIES = ReactBuildConfig.DEBUG && false;
@NonNull private final ConcurrentHashMap<Integer, ViewState> mTagToViewState;
@NonNull private final JSResponderHandler mJSResponderHandler = new JSResponderHandler();
@NonNull private final ViewManagerRegistry mViewManagerRegistry;
@NonNull private final RootViewManager mRootViewManager = new RootViewManager();
public MountingManager(@NonNull ViewManagerRegistry viewManagerRegistry) {
mTagToViewState = new ConcurrentHashMap<>();
mViewManagerRegistry = viewManagerRegistry;
}
private static void logViewHierarchy(ViewGroup parent) {
int parentTag = parent.getId();
FLog.e(TAG, " <ViewGroup tag=" + parentTag + ">");
for (int i = 0; i < parent.getChildCount(); i++) {
FLog.e(
TAG,
" <View idx="
+ i
+ " tag="
+ parent.getChildAt(i).getId()
+ " toString="
+ parent.getChildAt(i).toString()
+ ">");
}
FLog.e(TAG, " </ViewGroup tag=" + parentTag + ">");
}
/**
* This mutates the rootView, which is an Android View, so this should only be called on the UI
* thread.
*
* @param reactRootTag
* @param rootView
*/
@ThreadConfined(UI)
public void addRootView(int reactRootTag, @NonNull View rootView) {
if (rootView.getId() != View.NO_ID) {
throw new IllegalViewOperationException(
"Trying to add a root view with an explicit id already set. React Native uses "
+ "the id field to track react tags and will overwrite this field. If that is fine, "
+ "explicitly overwrite the id field to View.NO_ID before calling addRootView.");
}
mTagToViewState.put(
reactRootTag, new ViewState(reactRootTag, rootView, mRootViewManager, true));
rootView.setId(reactRootTag);
}
/** Releases all references to given native View. */
@UiThread
private void dropView(@NonNull View view) {
UiThreadUtil.assertOnUiThread();
int reactTag = view.getId();
ViewState state = getViewState(reactTag);
ViewManager viewManager = state.mViewManager;
if (!state.mIsRoot && viewManager != null) {
// For non-root views we notify viewmanager with {@link ViewManager#onDropInstance}
viewManager.onDropViewInstance(view);
}
if (view instanceof ViewGroup && viewManager instanceof ViewGroupManager) {
ViewGroup viewGroup = (ViewGroup) view;
ViewGroupManager<ViewGroup> viewGroupManager = getViewGroupManager(state);
for (int i = viewGroupManager.getChildCount(viewGroup) - 1; i >= 0; i--) {
View child = viewGroupManager.getChildAt(viewGroup, i);
if (getNullableViewState(child.getId()) != null) {
if (SHOW_CHANGED_VIEW_HIERARCHIES) {
FLog.e(
TAG,
"Automatically dropping view that is still attached to a parent being dropped. Parent: ["
+ reactTag
+ "] child: ["
+ child.getId()
+ "]");
}
dropView(child);
}
viewGroupManager.removeViewAt(viewGroup, i);
}
}
mTagToViewState.remove(reactTag);
}
@UiThread
public void addViewAt(final int parentTag, final int tag, final int index) {
UiThreadUtil.assertOnUiThread();
ViewState parentViewState = getViewState(parentTag);
if (!(parentViewState.mView instanceof ViewGroup)) {
String message =
"Unable to add a view into a view that is not a ViewGroup. ParentTag: "
+ parentTag
+ " - Tag: "
+ tag
+ " - Index: "
+ index;
FLog.e(TAG, message);
throw new IllegalStateException(message);
}
final ViewGroup parentView = (ViewGroup) parentViewState.mView;
ViewState viewState = getViewState(tag);
final View view = viewState.mView;
if (view == null) {
throw new IllegalStateException(
"Unable to find view for viewState " + viewState + " and tag " + tag);
}
// Display children before inserting
if (SHOW_CHANGED_VIEW_HIERARCHIES) {
FLog.e(TAG, "addViewAt: [" + tag + "] -> [" + parentTag + "] idx: " + index + " BEFORE");
logViewHierarchy(parentView);
}
try {
getViewGroupManager(parentViewState).addView(parentView, view, index);
} catch (IllegalStateException e) {
// Wrap error with more context for debugging
throw new IllegalStateException(
"addViewAt: failed to insert view ["
+ tag
+ "] into parent ["
+ parentTag
+ "] at index "
+ index,
e);
}
// Display children after inserting
if (SHOW_CHANGED_VIEW_HIERARCHIES) {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
FLog.e(
TAG, "addViewAt: [" + tag + "] -> [" + parentTag + "] idx: " + index + " AFTER");
logViewHierarchy(parentView);
}
});
}
}
private @NonNull ViewState getViewState(int tag) {
ViewState viewState = mTagToViewState.get(tag);
if (viewState == null) {
throw new RetryableMountingLayerException("Unable to find viewState view for tag " + tag);
}
return viewState;
}
private @Nullable ViewState getNullableViewState(int tag) {
return mTagToViewState.get(tag);
}
@Deprecated
public void receiveCommand(int reactTag, int commandId, @Nullable ReadableArray commandArgs) {
ViewState viewState = getNullableViewState(reactTag);
// It's not uncommon for JS to send events as/after a component is being removed from the
// view hierarchy. For example, TextInput may send a "blur" command in response to the view
// disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev
// for now.
if (viewState == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId);
}
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException("Unable to find viewManager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs);
}
public void receiveCommand(
int reactTag, @NonNull String commandId, @Nullable ReadableArray commandArgs) {
ViewState viewState = getNullableViewState(reactTag);
// It's not uncommon for JS to send events as/after a component is being removed from the
// view hierarchy. For example, TextInput may send a "blur" command in response to the view
// disappearing. Throw `ReactNoCrashSoftException` so they're logged but don't crash in dev
// for now.
if (viewState == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState for tag: " + reactTag + " for commandId: " + commandId);
}
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState manager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mViewManager.receiveCommand(viewState.mView, commandId, commandArgs);
}
public void sendAccessibilityEvent(int reactTag, int eventType) {
ViewState viewState = getViewState(reactTag);
if (viewState.mViewManager == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState manager for tag " + reactTag);
}
if (viewState.mView == null) {
throw new RetryableMountingLayerException(
"Unable to find viewState view for tag " + reactTag);
}
viewState.mView.sendAccessibilityEvent(eventType);
}
@SuppressWarnings("unchecked") // prevents unchecked conversion warn of the <ViewGroup> type
private static @NonNull ViewGroupManager<ViewGroup> getViewGroupManager(
@NonNull ViewState viewState) {
if (viewState.mViewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for view: " + viewState);
}
return (ViewGroupManager<ViewGroup>) viewState.mViewManager;
}
@UiThread
public void removeViewAt(final int tag, final int parentTag, final int index) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getNullableViewState(parentTag);
if (viewState == null) {
ReactSoftException.logSoftException(
MountingManager.TAG,
new IllegalStateException(
"Unable to find viewState for tag: " + parentTag + " for removeViewAt"));
return;
}
final ViewGroup parentView = (ViewGroup) viewState.mView;
if (parentView == null) {
throw new IllegalStateException("Unable to find view for tag " + parentTag);
}
if (SHOW_CHANGED_VIEW_HIERARCHIES) {
// Display children before deleting any
FLog.e(TAG, "removeViewAt: [" + tag + "] -> [" + parentTag + "] idx: " + index + " BEFORE");
logViewHierarchy(parentView);
}
ViewGroupManager<ViewGroup> viewGroupManager = getViewGroupManager(viewState);
// Verify that the view we're about to remove has the same tag we expect
View view = viewGroupManager.getChildAt(parentView, index);
if (view != null && view.getId() != tag) {
throw new IllegalStateException(
"Tried to delete view ["
+ tag
+ "] of parent ["
+ parentTag
+ "] at index "
+ index
+ ", but got view tag "
+ view.getId());
}
try {
viewGroupManager.removeViewAt(parentView, index);
} catch (RuntimeException e) {
// Note: `getChildCount` may not always be accurate!
// We don't currently have a good explanation other than, in situations where you
// would empirically expect to see childCount > 0, the childCount is reported as 0.
// This is likely due to a ViewManager overriding getChildCount or some other methods
// in a way that is strictly incorrect, but potentially only visible here.
// The failure mode is actually that in `removeViewAt`, a NullPointerException is
// thrown when we try to perform an operation on a View that doesn't exist, and
// is therefore null.
// We try to add some extra diagnostics here, but we always try to remove the View
// from the hierarchy first because detecting by looking at childCount will not work.
//
// Note that the lesson here is that `getChildCount` is not /required/ to adhere to
// any invariants. If you add 9 children to a parent, the `getChildCount` of the parent
// may not be equal to 9. This apparently causes no issues with Android and is common
// enough that we shouldn't try to change this invariant, without a lot of thought.
int childCount = viewGroupManager.getChildCount(parentView);
throw new IllegalStateException(
"Cannot remove child at index "
+ index
+ " from parent ViewGroup ["
+ parentView.getId()
+ "], only "
+ childCount
+ " children in parent. Warning: childCount may be incorrect!",
e);
}
// Display children after deleting any
if (SHOW_CHANGED_VIEW_HIERARCHIES) {
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
FLog.e(TAG, "removeViewAt: [" + parentTag + "] idx: " + index + " AFTER");
logViewHierarchy(parentView);
}
});
}
}
@UiThread
public void createView(
@NonNull ThemedReactContext themedReactContext,
@NonNull String componentName,
int reactTag,
@Nullable ReadableMap props,
@Nullable StateWrapper stateWrapper,
boolean isLayoutable) {
if (getNullableViewState(reactTag) != null) {
return;
}
View view = null;
ViewManager viewManager = null;
ReactStylesDiffMap propsDiffMap = null;
if (props != null) {
propsDiffMap = new ReactStylesDiffMap(props);
}
if (isLayoutable) {
viewManager = mViewManagerRegistry.get(componentName);
// View Managers are responsible for dealing with initial state and props.
view =
viewManager.createView(
themedReactContext, propsDiffMap, stateWrapper, mJSResponderHandler);
view.setId(reactTag);
}
ViewState viewState = new ViewState(reactTag, view, viewManager);
viewState.mCurrentProps = propsDiffMap;
viewState.mCurrentState = (stateWrapper != null ? stateWrapper.getState() : null);
mTagToViewState.put(reactTag, viewState);
}
@UiThread
public void updateProps(int reactTag, @Nullable ReadableMap props) {
if (props == null) {
return;
}
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
viewState.mCurrentProps = new ReactStylesDiffMap(props);
View view = viewState.mView;
if (view == null) {
throw new IllegalStateException("Unable to find view for tag " + reactTag);
}
Assertions.assertNotNull(viewState.mViewManager)
.updateProperties(view, viewState.mCurrentProps);
}
@UiThread
public void updateLayout(int reactTag, int x, int y, int width, int height) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
// Do not layout Root Views
if (viewState.mIsRoot) {
return;
}
View viewToUpdate = viewState.mView;
if (viewToUpdate == null) {
throw new IllegalStateException("Unable to find View for tag: " + reactTag);
}
viewToUpdate.measure(
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
ViewParent parent = viewToUpdate.getParent();
if (parent instanceof RootView) {
parent.requestLayout();
}
// TODO: T31905686 Check if the parent of the view has to layout the view, or the child has
// to lay itself out. see NativeViewHierarchyManager.updateLayout
viewToUpdate.layout(x, y, x + width, y + height);
}
@UiThread
public void updatePadding(int reactTag, int left, int top, int right, int bottom) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
// Do not layout Root Views
if (viewState.mIsRoot) {
return;
}
View viewToUpdate = viewState.mView;
if (viewToUpdate == null) {
throw new IllegalStateException("Unable to find View for tag: " + reactTag);
}
ViewManager viewManager = viewState.mViewManager;
if (viewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for view: " + viewState);
}
//noinspection unchecked
viewManager.setPadding(viewToUpdate, left, top, right, bottom);
}
@UiThread
public void deleteView(int reactTag) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getNullableViewState(reactTag);
if (viewState == null) {
ReactSoftException.logSoftException(
MountingManager.TAG,
new IllegalStateException(
"Unable to find viewState for tag: " + reactTag + " for deleteView"));
return;
}
View view = viewState.mView;
if (view != null) {
dropView(view);
} else {
mTagToViewState.remove(reactTag);
}
}
@UiThread
public void updateState(final int reactTag, @Nullable StateWrapper stateWrapper) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = getViewState(reactTag);
@Nullable ReadableNativeMap newState = stateWrapper == null ? null : stateWrapper.getState();
viewState.mCurrentState = newState;
ViewManager viewManager = viewState.mViewManager;
if (viewManager == null) {
throw new IllegalStateException("Unable to find ViewManager for tag: " + reactTag);
}
Object extraData =
viewManager.updateState(viewState.mView, viewState.mCurrentProps, stateWrapper);
if (extraData != null) {
viewManager.updateExtraData(viewState.mView, extraData);
}
}
@UiThread
public void preallocateView(
@NonNull ThemedReactContext reactContext,
String componentName,
int reactTag,
@Nullable ReadableMap props,
@Nullable StateWrapper stateWrapper,
boolean isLayoutable) {
if (getNullableViewState(reactTag) != null) {
throw new IllegalStateException(
"View for component " + componentName + " with tag " + reactTag + " already exists.");
}
createView(reactContext, componentName, reactTag, props, stateWrapper, isLayoutable);
}
@UiThread
public void updateEventEmitter(int reactTag, @NonNull EventEmitterWrapper eventEmitter) {
UiThreadUtil.assertOnUiThread();
ViewState viewState = mTagToViewState.get(reactTag);
if (viewState == null) {
// TODO T62717437 - Use a flag to determine that these event emitters belong to virtual nodes
// only.
viewState = new ViewState(reactTag, null, null);
mTagToViewState.put(reactTag, viewState);
}
viewState.mEventEmitter = eventEmitter;
}
/**
* Set the JS responder for the view associated with the tags received as a parameter.
*
* <p>The JSResponder coordinates the return values of the onInterceptTouch method in Android
* Views. This allows JS to coordinate when a touch should be handled by JS or by the Android
* native views. See {@link JSResponderHandler} for more details.
*
* <p>This method is going to be executed on the UIThread as soon as it is delivered from JS to
* RN.
*
* <p>Currently, there is no warranty that the view associated with the react tag exists, because
* this method is not handled by the react commit process.
*
* @param reactTag React tag of the first parent of the view that is NOT virtual
* @param initialReactTag React tag of the JS view that initiated the touch operation
* @param blockNativeResponder If native responder should be blocked or not
*/
@UiThread
public synchronized void setJSResponder(
int reactTag, int initialReactTag, boolean blockNativeResponder) {
if (!blockNativeResponder) {
mJSResponderHandler.setJSResponder(initialReactTag, null);
return;
}
ViewState viewState = getViewState(reactTag);
View view = viewState.mView;
if (initialReactTag != reactTag && view instanceof ViewParent) {
// In this case, initialReactTag corresponds to a virtual/layout-only View, and we already
// have a parent of that View in reactTag, so we can use it.
mJSResponderHandler.setJSResponder(initialReactTag, (ViewParent) view);
return;
} else if (view == null) {
SoftAssertions.assertUnreachable("Cannot find view for tag " + reactTag + ".");
return;
}
if (viewState.mIsRoot) {
SoftAssertions.assertUnreachable(
"Cannot block native responder on " + reactTag + " that is a root view");
}
mJSResponderHandler.setJSResponder(initialReactTag, view.getParent());
}
/**
* Clears the JS Responder specified by {@link #setJSResponder(int, int, boolean)}. After this
* method is called, all the touch events are going to be handled by JS.
*/
@UiThread
public void clearJSResponder() {
mJSResponderHandler.clearJSResponder();
}
@AnyThread
public long measure(
@NonNull Context context,
@NonNull String componentName,
@NonNull ReadableMap localData,
@NonNull ReadableMap props,
@NonNull ReadableMap state,
float width,
@NonNull YogaMeasureMode widthMode,
float height,
@NonNull YogaMeasureMode heightMode,
@Nullable float[] attachmentsPositions) {
return mViewManagerRegistry
.get(componentName)
.measure(
context,
localData,
props,
state,
width,
widthMode,
height,
heightMode,
attachmentsPositions);
}
@AnyThread
@ThreadConfined(ANY)
public @Nullable EventEmitterWrapper getEventEmitter(int reactTag) {
ViewState viewState = getNullableViewState(reactTag);
return viewState == null ? null : viewState.mEventEmitter;
}
/**
* This class holds view state for react tags. Objects of this class are stored into the {@link
* #mTagToViewState}, and they should be updated in the same thread.
*/
private static class ViewState {
@Nullable final View mView;
final int mReactTag;
final boolean mIsRoot;
@Nullable final ViewManager mViewManager;
@Nullable public ReactStylesDiffMap mCurrentProps = null;
@Nullable public ReadableMap mCurrentLocalData = null;
@Nullable public ReadableMap mCurrentState = null;
@Nullable public EventEmitterWrapper mEventEmitter = null;
private ViewState(int reactTag, @Nullable View view, @Nullable ViewManager viewManager) {
this(reactTag, view, viewManager, false);
}
private ViewState(int reactTag, @Nullable View view, ViewManager viewManager, boolean isRoot) {
mReactTag = reactTag;
mView = view;
mIsRoot = isRoot;
mViewManager = viewManager;
}
@Override
public String toString() {
boolean isLayoutOnly = mViewManager == null;
return "ViewState ["
+ mReactTag
+ "] - isRoot: "
+ mIsRoot
+ " - props: "
+ mCurrentProps
+ " - localData: "
+ mCurrentLocalData
+ " - viewManager: "
+ mViewManager
+ " - isLayoutOnly: "
+ isLayoutOnly;
}
}
}
|
3e1a23a968fd2159c584b93d2dfc49de54beba1f | 545 | java | Java | src/main/java/org/kyojo/schemaOrg/m3n3/doma/core/clazz/AutoWashConverter.java | covernorgedi/nagoyakaICT | b375db53216eaa54f9797549a36e7c79f66b44c0 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/kyojo/schemaOrg/m3n3/doma/core/clazz/AutoWashConverter.java | covernorgedi/nagoyakaICT | b375db53216eaa54f9797549a36e7c79f66b44c0 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/kyojo/schemaOrg/m3n3/doma/core/clazz/AutoWashConverter.java | covernorgedi/nagoyakaICT | b375db53216eaa54f9797549a36e7c79f66b44c0 | [
"Apache-2.0"
] | null | null | null | 23.695652 | 77 | 0.801835 | 11,116 | package org.kyojo.schemaOrg.m3n3.doma.core.clazz;
import org.seasar.doma.ExternalDomain;
import org.seasar.doma.jdbc.domain.DomainConverter;
import org.kyojo.schemaOrg.m3n3.core.impl.AUTO_WASH;
import org.kyojo.schemaOrg.m3n3.core.Clazz.AutoWash;
@ExternalDomain
public class AutoWashConverter implements DomainConverter<AutoWash, String> {
@Override
public String fromDomainToValue(AutoWash domain) {
return domain.getNativeValue();
}
@Override
public AutoWash fromValueToDomain(String value) {
return new AUTO_WASH(value);
}
}
|
3e1a24a31bb7cc8faddd104817b09e1e94446523 | 6,851 | java | Java | airbyte-integrations/bases/base-java/src/main/java/io/airbyte/integrations/base/IntegrationCliParser.java | AryeoHQ/airbyte | e396f01a2c2420bd810a57265d4cc9e6bab1f5c8 | [
"MIT"
] | 6,215 | 2020-09-21T13:45:56.000Z | 2022-03-31T21:21:45.000Z | airbyte-integrations/bases/base-java/src/main/java/io/airbyte/integrations/base/IntegrationCliParser.java | AryeoHQ/airbyte | e396f01a2c2420bd810a57265d4cc9e6bab1f5c8 | [
"MIT"
] | 8,448 | 2020-09-21T00:43:50.000Z | 2022-03-31T23:56:06.000Z | airbyte-integrations/bases/base-java/src/main/java/io/airbyte/integrations/base/IntegrationCliParser.java | AryeoHQ/airbyte | e396f01a2c2420bd810a57265d4cc9e6bab1f5c8 | [
"MIT"
] | 1,251 | 2020-09-20T05:48:47.000Z | 2022-03-31T10:41:29.000Z | 39.373563 | 144 | 0.695957 | 11,117 | /*
* Copyright (c) 2021 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.integrations.base;
import com.google.common.base.Preconditions;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// todo (cgardens) - use argparse4j.github.io instead of org.apache.commons.cli to leverage better
// sub-parser support.
/**
* Parses command line args to a type safe config object for each command type.
*/
public class IntegrationCliParser {
private static final Logger LOGGER = LoggerFactory.getLogger(IntegrationCliParser.class);
private static final OptionGroup COMMAND_GROUP = new OptionGroup();
static {
COMMAND_GROUP.setRequired(true);
COMMAND_GROUP.addOption(Option.builder()
.longOpt(Command.SPEC.toString().toLowerCase())
.desc("outputs the json configuration specification")
.build());
COMMAND_GROUP.addOption(Option.builder()
.longOpt(Command.CHECK.toString().toLowerCase())
.desc("checks the config can be used to connect")
.build());
COMMAND_GROUP.addOption(Option.builder()
.longOpt(Command.DISCOVER.toString().toLowerCase())
.desc("outputs a catalog describing the source's catalog")
.build());
COMMAND_GROUP.addOption(Option.builder()
.longOpt(Command.READ.toString().toLowerCase())
.desc("reads the source and outputs messages to STDOUT")
.build());
COMMAND_GROUP.addOption(Option.builder()
.longOpt(Command.WRITE.toString().toLowerCase())
.desc("writes messages from STDIN to the integration")
.build());
}
public IntegrationConfig parse(final String[] args) {
final Command command = parseCommand(args);
return parseOptions(args, command);
}
private static Command parseCommand(final String[] args) {
final CommandLineParser parser = new RelaxedParser();
final HelpFormatter helpFormatter = new HelpFormatter();
final Options options = new Options();
options.addOptionGroup(COMMAND_GROUP);
try {
final CommandLine parsed = parser.parse(options, args);
return Command.valueOf(parsed.getOptions()[0].getLongOpt().toUpperCase());
// if discover, then validate, etc...
} catch (final ParseException e) {
helpFormatter.printHelp("java-base", options);
throw new IllegalArgumentException(e);
}
}
private static IntegrationConfig parseOptions(final String[] args, final Command command) {
final Options options = new Options();
options.addOptionGroup(COMMAND_GROUP); // so that the parser does not throw an exception when encounter command args.
switch (command) {
case SPEC -> {
// no args.
}
case CHECK, DISCOVER -> options.addOption(Option
.builder().longOpt(JavaBaseConstants.ARGS_CONFIG_KEY).desc(JavaBaseConstants.ARGS_CONFIG_DESC).hasArg(true).required(true).build());
case READ -> {
options.addOption(Option
.builder().longOpt(JavaBaseConstants.ARGS_CONFIG_KEY).desc(JavaBaseConstants.ARGS_CONFIG_DESC).hasArg(true).required(true).build());
options.addOption(Option
.builder().longOpt(JavaBaseConstants.ARGS_CATALOG_KEY).desc(JavaBaseConstants.ARGS_CATALOG_DESC).hasArg(true).build());
options.addOption(Option
.builder().longOpt(JavaBaseConstants.ARGS_STATE_KEY).desc(JavaBaseConstants.ARGS_PATH_DESC).hasArg(true).build());
}
case WRITE -> {
options.addOption(Option
.builder().longOpt(JavaBaseConstants.ARGS_CONFIG_KEY).desc(JavaBaseConstants.ARGS_CONFIG_DESC).hasArg(true).required(true).build());
options.addOption(Option
.builder().longOpt(JavaBaseConstants.ARGS_CATALOG_KEY).desc(JavaBaseConstants.ARGS_CATALOG_DESC).hasArg(true).build());
}
default -> throw new IllegalStateException("Unexpected value: " + command);
}
final CommandLine parsed = runParse(options, args, command);
Preconditions.checkNotNull(parsed);
final Map<String, String> argsMap = new HashMap<>();
for (final Option option : parsed.getOptions()) {
argsMap.put(option.getLongOpt(), option.getValue());
}
LOGGER.info("integration args: {}", argsMap);
switch (command) {
case SPEC -> {
return IntegrationConfig.spec();
}
case CHECK -> {
return IntegrationConfig.check(Path.of(argsMap.get(JavaBaseConstants.ARGS_CONFIG_KEY)));
}
case DISCOVER -> {
return IntegrationConfig.discover(Path.of(argsMap.get(JavaBaseConstants.ARGS_CONFIG_KEY)));
}
case READ -> {
return IntegrationConfig.read(
Path.of(argsMap.get(JavaBaseConstants.ARGS_CONFIG_KEY)),
Path.of(argsMap.get(JavaBaseConstants.ARGS_CATALOG_KEY)),
argsMap.containsKey(JavaBaseConstants.ARGS_STATE_KEY) ? Path.of(argsMap.get(JavaBaseConstants.ARGS_STATE_KEY)) : null);
}
case WRITE -> {
return IntegrationConfig.write(
Path.of(argsMap.get(JavaBaseConstants.ARGS_CONFIG_KEY)),
Path.of(argsMap.get(JavaBaseConstants.ARGS_CATALOG_KEY)));
}
default -> throw new IllegalStateException("Unexpected value: " + command);
}
}
private static CommandLine runParse(final Options options, final String[] args, final Command command) {
final CommandLineParser parser = new DefaultParser();
final HelpFormatter helpFormatter = new HelpFormatter();
try {
return parser.parse(options, args);
} catch (final ParseException e) {
helpFormatter.printHelp(command.toString().toLowerCase(), options);
throw new IllegalArgumentException(e);
}
}
// https://stackoverflow.com/questions/33874902/apache-commons-cli-1-3-1-how-to-ignore-unknown-arguments
private static class RelaxedParser extends DefaultParser {
@Override
public CommandLine parse(final Options options, final String[] arguments) throws ParseException {
final List<String> knownArgs = new ArrayList<>();
for (int i = 0; i < arguments.length; i++) {
if (options.hasOption(arguments[i])) {
knownArgs.add(arguments[i]);
if (i + 1 < arguments.length && options.getOption(arguments[i]).hasArg()) {
knownArgs.add(arguments[i + 1]);
}
}
}
return super.parse(options, knownArgs.toArray(new String[0]));
}
}
}
|
3e1a2503441df60f8f5f55f4bfc278527e21a1a9 | 4,388 | java | Java | QueryTranslator/S2RDF_QueryTranslator/src/queryTranslator/sql/SimpleTriple.java | h4ck3rm1k3/S2RDF | 4560afed7427dcf79e5f05089cdd5172252b8afb | [
"Apache-2.0"
] | 11 | 2017-09-21T09:09:06.000Z | 2021-03-21T06:05:15.000Z | QueryTranslator/S2RDF_QueryTranslator/src/queryTranslator/sql/SimpleTriple.java | tf-dbis-uni-freiburg/S2RDF | 4560afed7427dcf79e5f05089cdd5172252b8afb | [
"Apache-2.0"
] | 2 | 2019-12-03T08:25:27.000Z | 2020-01-21T13:32:38.000Z | QueryTranslator/S2RDF_QueryTranslator/src/queryTranslator/sql/SimpleTriple.java | tf-dbis-uni-freiburg/S2RDF | 4560afed7427dcf79e5f05089cdd5172252b8afb | [
"Apache-2.0"
] | 8 | 2017-12-29T16:56:14.000Z | 2021-09-29T15:19:28.000Z | 27.254658 | 146 | 0.698952 | 11,118 | package queryTranslator.sql;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.print.attribute.standard.SheetCollate;
//import queryTranslator.ScalaGenerator;
import queryTranslator.Tags;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.shared.PrefixMapping;
import com.hp.hpl.jena.sparql.util.FmtUtils;
public class SimpleTriple implements SqlTriple{
public Triple _t1;
private String _tableName;
public boolean verticalPartitioning = false;
private int _tabs;
private PrefixMapping _prefixMapping;
private boolean _isDistinct = false;
public SimpleTriple(Triple a) {
// TODO Auto-generated constructor stub
this._t1 = a;
}
@Override
public void setDistinct() {
// TODO Auto-generated method stub
_isDistinct = true;
}
@Override
public String getType() {
// TODO Auto-generated method stub
return "simple";
}
@Override
public Triple getFirstTriple() {
// TODO Auto-generated method stub
return _t1;
}
@Override
public Triple getSecondTriple() {
// TODO Auto-generated method stub
return null;
}
@Override
public SqlStatement translate() {
Select select = new Select(this._tableName);
select.setTabs(_tabs);
Map<String, String> vars = new HashMap<String, String>();
ArrayList<String> whereConditions = new ArrayList<String>();
boolean first = true;
Node subject = _t1.getSubject();
Node predicate = _t1.getPredicate();
Node object = _t1.getObject();
if (subject.isURI() || subject.isBlank()) {
whereConditions.add(Tags.SUBJECT_COLUMN_NAME + " = '"+ FmtUtils.stringForNode(subject,
this._prefixMapping).replace("http://yago-knowledge.org/resource/", "") + "'");
} else {
vars.put(Tags.SUBJECT_COLUMN_NAME, subject.getName());
}
if (predicate.isURI()) {
this._tableName = FmtUtils.stringForNode(predicate, this._prefixMapping).replace("http://yago-knowledge.org/resource/", "").replace(":", "__");
this.verticalPartitioning = true;
} else {
vars.put(Tags.PREDICATE_COLUMN_NAME, predicate.getName());
}
if (object.isURI() || object.isLiteral() || object.isBlank()) {
String string = FmtUtils.stringForNode(object,
this._prefixMapping).replace("http://yago-knowledge.org/resource/", "");
//if (object.isLiteral()) {
// string = "" + object.getLiteral().toString();
//}
whereConditions.add(Tags.OBJECT_COLUMN_NAME + " = '" + string + "'");
} else {
vars.put(Tags.OBJECT_COLUMN_NAME, object.getName());
}
ArrayList<String> varSet = new ArrayList<String>();
for (String var : vars.keySet()) {
select.addSelector(vars.get(var), new String[] { var });
varSet.add(vars.get(var));
}
select.setVariables(varSet);
// FROM
select.setFrom(this._tableName);
// WHERE
for (String where : whereConditions) {
select.addConjunction(where);
}
select.setDistinct(_isDistinct);
return select;
}
@Override
public void setTableName(String tName) {
// TODO Auto-generated method stub
_tableName = tName;
}
@Override
public String getTableName() {
// TODO Auto-generated method stub
return _tableName;
}
@Override
public void setPrefixMapping(PrefixMapping pMapping) {
// TODO Auto-generated method stub
_prefixMapping = pMapping;
}
public ArrayList<String> getVariables() {
// TODO Auto-generated method stub
ArrayList<String> res = new ArrayList<String>();
if (_t1.getSubject().isVariable())
res.add(_t1.getSubject().getName());
if (_t1.getObject().isVariable())
res.add(_t1.getObject().getName());
if (_t1.getPredicate().isVariable())
res.add(_t1.getPredicate().getName());
return res;
}
@Override
public Map<String, String[]> getMappings() {
ArrayList<String> original = getVariables();
HashMap<String, String[]> result = new HashMap<String, String[]>();
for (String key : original) {
result.put(key, new String[] { _tableName, key });
}
return result;
}
@Override
public int getTabs() {
// TODO Auto-generated method stub
return _tabs;
}
@Override
public void setTabs(int tabs) {
this._tabs = tabs;
}
@Override
public int getNumberOfValues() {
// TODO Auto-generated method stub
int result=0;
if (!_t1.getSubject().isVariable())
result++;
if (!_t1.getPredicate().isVariable())
result++;
if (!_t1.getObject().isVariable())
result++;
return result;
}
}
|
3e1a2671c0ccfd29a9962386cf38bf1870c3c6ad | 1,427 | java | Java | is-lnu-converter/src/test/java/org/lnu/is/converter/paper/usage/PaperUsageResourceConverterTest.java | JLLeitschuh/ums-backend | 363213ff0f8d6a350a3ce559940c5707ad71bfd6 | [
"Apache-2.0"
] | 14 | 2015-05-26T11:16:30.000Z | 2019-08-16T08:21:24.000Z | is-lnu-converter/src/test/java/org/lnu/is/converter/paper/usage/PaperUsageResourceConverterTest.java | JLLeitschuh/ums-backend | 363213ff0f8d6a350a3ce559940c5707ad71bfd6 | [
"Apache-2.0"
] | 16 | 2015-05-26T18:29:05.000Z | 2016-04-21T19:11:55.000Z | is-lnu-converter/src/test/java/org/lnu/is/converter/paper/usage/PaperUsageResourceConverterTest.java | JLLeitschuh/ums-backend | 363213ff0f8d6a350a3ce559940c5707ad71bfd6 | [
"Apache-2.0"
] | 12 | 2015-07-09T16:11:18.000Z | 2020-02-11T05:42:27.000Z | 22.296875 | 78 | 0.740014 | 11,119 | package org.lnu.is.converter.paper.usage;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.lnu.is.domain.paper.usage.PaperUsage;
import org.lnu.is.resource.paper.usage.PaperUsageResource;
public class PaperUsageResourceConverterTest {
private PaperUsageResourceConverter unit = new PaperUsageResourceConverter();
@Test
public void testConvert() throws Exception {
// Given
String name = "first blood";
String abbrName = "fb";
PaperUsage expected = new PaperUsage();
expected.setName(name);
expected.setAbbrName(abbrName);
PaperUsageResource source = new PaperUsageResource();
source.setName(name);
source.setAbbrName(abbrName);
// When
PaperUsage actual = unit.convert(source);
// Then
assertEquals(expected, actual);
}
@Test
public void testConvertAll() throws Exception {
// Given
String name = "first blood";
String abbrName = "fb";
PaperUsage expected = new PaperUsage();
expected.setName(name);
expected.setAbbrName(abbrName);
PaperUsageResource source = new PaperUsageResource();
source.setName(name);
source.setAbbrName(abbrName);
List<PaperUsageResource> sources = Arrays.asList(source);
List<PaperUsage> expecteds = Arrays.asList(expected);
// When
List<PaperUsage> actuals = unit.convertAll(sources);
// Then
assertEquals(expecteds, actuals);
}
}
|
3e1a2672d6b0271d03063dcb92a2253e6786bfa9 | 14,174 | java | Java | ide/mercurial/test/unit/src/org/netbeans/modules/mercurial/IgnoresTest.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | ide/mercurial/test/unit/src/org/netbeans/modules/mercurial/IgnoresTest.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | ide/mercurial/test/unit/src/org/netbeans/modules/mercurial/IgnoresTest.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 39.814607 | 172 | 0.65091 | 11,120 | /*
* 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.netbeans.modules.mercurial;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.netbeans.modules.mercurial.ui.ignore.IgnoreAction;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.actions.SystemAction;
import org.openide.util.lookup.Lookups;
import org.openide.util.test.MockLookup;
/**
*
* @author tomas
*/
public class IgnoresTest extends AbstractHgTestCase {
public IgnoresTest(String arg0) {
super(arg0);
}
@Override
protected void setUp() throws Exception {
System.setProperty("netbeans.user", new File(new File(getWorkDirPath()).getParentFile(), "userdir").getAbsolutePath());
super.setUp();
MockLookup.setLayersAndInstances();
// create
FileObject fo = FileUtil.toFileObject(getWorkTreeDir());
}
// ignore patterns - issue 171378 - should pass
public void testIgnores () throws IOException {
File workDir = getWorkTreeDir();
File ignoreFile = new File(getDataDir().getAbsolutePath() + "/ignore/hgignore");
File toFile = new File(workDir, ".hgignore");
ignoreFile.renameTo(toFile);
File ignoredFolder = new File(workDir, "ignoredFolderLevel1");
ignoredFolder.mkdirs();
FileInformation info = getCache().getCachedStatus(ignoredFolder);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
File ignoredFile = new File(ignoredFolder, "file");
ignoredFile.createNewFile();
info = getCache().getCachedStatus(ignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
File unignoredFile = new File(workDir, "file");
unignoredFile.createNewFile();
info = getCache().getCachedStatus(unignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) == 0);
File unignoredFolder = new File(workDir, "unignoredFolderLevel1");
unignoredFolder.mkdirs();
info = getCache().getCachedStatus(unignoredFolder);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) == 0);
ignoredFolder = new File(unignoredFolder, "ignoredFolderLevel2");
ignoredFolder.mkdirs();
info = getCache().getCachedStatus(ignoredFolder);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
ignoredFolder = new File(unignoredFolder, "ignoredFolderLevel2_2");
ignoredFolder.mkdirs();
info = getCache().getCachedStatus(ignoredFolder);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
ignoredFile = new File(ignoredFolder, "ignoredFile");
ignoredFile.createNewFile();
info = getCache().getCachedStatus(ignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
ignoredFile = new File(workDir, "file.ignore");
ignoredFile.createNewFile();
info = getCache().getCachedStatus(ignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
ignoredFile = new File(unignoredFolder, "file.ignore");
ignoredFile.createNewFile();
info = getCache().getCachedStatus(ignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
unignoredFolder = new File(unignoredFolder, "project");
unignoredFolder.mkdirs();
info = getCache().getCachedStatus(unignoredFolder);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) == 0);
unignoredFile = new File(unignoredFolder, "project");
unignoredFile.createNewFile();
info = getCache().getCachedStatus(unignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) == 0);
ignoredFile = new File(workDir, ".project");
ignoredFile.createNewFile();
info = getCache().getCachedStatus(ignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
ignoredFile = new File(unignoredFolder, ".project");
ignoredFile.createNewFile();
info = getCache().getCachedStatus(ignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) != 0);
unignoredFile = new File(workDir, "file.ignore2");
unignoredFile.createNewFile();
info = getCache().getCachedStatus(unignoredFile);
assertTrue((info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED) == 0);
}
public void testIgnoreAction () throws Exception {
File workDir = getWorkTreeDir();
new File(workDir, ".hgignore").delete();
File folderA = new File(workDir, "folderA");
File folderAA = new File(folderA, "folderAA");
File folderAB = new File(folderA, "folderAB");
File fileAAA = new File(folderAA, "fileAAA");
File fileAAB = new File(folderAA, "fileAAB");
File fileABA = new File(folderAB, "fileABA");
File fileABB = new File(folderAB, "fileABB");
folderAA.mkdirs();
folderAB.mkdirs();
fileAAA.createNewFile();
fileAAB.createNewFile();
fileABA.createNewFile();
fileABB.createNewFile();
getCache().refreshAllRoots(Collections.singleton(workDir));
Set<File> ignoredFiles = new HashSet<File>();
File[] parentFiles = new File[] { workDir };
// ignoredFiles is empty
assertIgnoreStatus(parentFiles, ignoredFiles);
// ignoring folderAA and all its descendants
toggleIgnore(folderAA, ignoredFiles);
ignoredFiles.addAll(getFiles(folderAA));
assertIgnoreStatus(parentFiles, ignoredFiles);
// ignoring folderA and all its descendants
toggleIgnore(folderA, ignoredFiles);
ignoredFiles.addAll(getFiles(folderA));
assertIgnoreStatus(parentFiles, ignoredFiles);
// unignoring folderAA and all its descendants - but has no effect since folderA is still ignored
toggleIgnore(folderAA, ignoredFiles);
assertIgnoreStatus(parentFiles, ignoredFiles);
// unignoring folderA
toggleIgnore(folderA, ignoredFiles);
ignoredFiles.removeAll(getFiles(folderA));
assertIgnoreStatus(parentFiles, ignoredFiles);
// ignoring folderAB and all its descendants
toggleIgnore(folderAB, ignoredFiles);
ignoredFiles.addAll(getFiles(folderAB));
assertIgnoreStatus(parentFiles, ignoredFiles);
Thread.sleep(2000); // time for refresh
// ignoring folderA and all its descendants
toggleIgnore(folderA, ignoredFiles);
ignoredFiles.addAll(getFiles(folderA));
assertIgnoreStatus(parentFiles, ignoredFiles);
Thread.sleep(2000); // time for refresh
// unignoring folderA and all its descendants - folder AB remains ignored
toggleIgnore(folderA, ignoredFiles);
ignoredFiles.removeAll(getFiles(folderA));
ignoredFiles.addAll(getFiles(folderAB));
assertIgnoreStatus(parentFiles, ignoredFiles);
Thread.sleep(2000); // time for refresh
// unignoring folderAB and all its descendants - no file is ignored
toggleIgnore(folderAB, ignoredFiles);
ignoredFiles.removeAll(getFiles(folderAB));
assertIgnoreStatus(parentFiles, ignoredFiles);
// bug #187304
ignoredFiles.clear();
File obscureFile = new File(folderA, "This + File + Might + Crash + Mercurial");
obscureFile.createNewFile();
getCache().refreshAllRoots(Collections.singleton(workDir));
// ignoring the file
toggleIgnore(obscureFile, ignoredFiles);
ignoredFiles.add(obscureFile);
assertIgnoreStatus(parentFiles, ignoredFiles);
// unignoring the file
toggleIgnore(obscureFile, ignoredFiles);
ignoredFiles.clear();
assertIgnoreStatus(parentFiles, ignoredFiles);
}
public void testRefreshPatternsAfterExternalModification () throws Exception {
File workDir = getWorkTreeDir();
File ignoreFile = new File(workDir, ".hgignore");
ignoreFile.delete();
File file = new File(workDir, "ignored");
File file2 = new File(workDir, "ignored2");
write(file, "aaa");
write(file2, "aaa");
getCache().refreshAllRoots(Collections.singleton(workDir));
assertEquals(FileInformation.STATUS_NOTVERSIONED_NEWLOCALLY, getCache().getCachedStatus(file).getStatus());
assertIgnoreStatus(file, Collections.<File>emptySet());
Thread.sleep(1100);
write(ignoreFile, "^ignored$");
getCache().refreshAllRoots(Collections.singleton(workDir));
assertIgnoreStatus(file, Collections.singleton(file));
Thread.sleep(1100);
write(ignoreFile, "^ignored$\n^ignored2$\n");
getCache().refreshAllRoots(Collections.singleton(workDir));
assertIgnoreStatus(file, new HashSet<File>(Arrays.asList(file, file2)));
Thread.sleep(1100);
ignoreFile.delete();
getCache().refreshAllRoots(Collections.singleton(workDir));
assertIgnoreStatus(file, Collections.<File>emptySet());
}
private void assertIgnoreStatus (File[] parents, Set<File> ignoredFiles) throws InterruptedException {
for (File parent : parents) {
assertIgnoreStatus(parent, ignoredFiles);
File[] files = parent.listFiles();
if (files != null) {
assertIgnoreStatus(files, ignoredFiles);
}
}
}
private void assertIgnoreStatus (File file, Set<File> ignoredFiles) throws InterruptedException {
FileInformation info = getCache().getCachedStatus(file);
String msg = null;
for (int i = 0; i < 100; ++i) {
int status = info.getStatus() & FileInformation.STATUS_NOTVERSIONED_EXCLUDED;
msg = null;
if (expectedIgnored(file, ignoredFiles)) {
if (status == 0) {
msg = "Supposed to be ignored: " + file.getAbsolutePath();
}
} else {
if (status != 0) {
msg = "Supposed to be normal: " + file.getAbsolutePath();
}
}
if (msg == null) {
break;
} else {
Thread.sleep(200);
}
}
assertNull(msg, msg);
}
private boolean expectedIgnored (File file, Set<File> ignoredFiles) {
File parent = file;
while (parent != null && !ignoredFiles.contains(parent)) {
parent = parent.getParentFile();
}
return ignoredFiles.contains(parent);
}
private void toggleIgnore (File folder, Set<File> ignoredFiles) throws InterruptedException {
Logger logger = Logger.getLogger("org.netbeans.modules.mercurial.fileStatusCacheNewGeneration");
logger.setLevel(Level.ALL);
LogHandler handler = new LogHandler(folder);
logger.addHandler(handler);
TestIgnoreAction tia = SystemAction.get(TestIgnoreAction.class);
tia.performContextAction(new Node[] { new AbstractNode(Children.LEAF, Lookups.singleton(folder)) });
synchronized (handler) {
if (!handler.flag) {
handler.wait(20000);
}
}
assert handler.flag : "Ignore action failed";
logger.removeHandler(handler);
}
private Set<File> getFiles (File file) {
Set<File> files = new HashSet<File>();
files.add(file);
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
files.addAll(getFiles(child));
}
}
return files;
}
public static class TestIgnoreAction extends IgnoreAction {
@Override
public void performContextAction(Node[] nodes) {
super.performContextAction(nodes);
}
}
private class LogHandler extends Handler {
private final File expectedFile;
private boolean flag;
private LogHandler(File folderAA) {
this.expectedFile = folderAA;
}
@Override
public void publish(LogRecord record) {
if (record.getMessage().contains("refreshIgnores: File {0} refreshed") && record.getParameters().length > 0 && expectedFile.equals(record.getParameters()[0])) {
synchronized (this) {
flag = true;
notify();
}
}
}
@Override
public void flush() {
//
}
@Override
public void close() throws SecurityException {
//
}
}
}
|
3e1a2697ef295d6136a9468459af4eaffeb8db1b | 18,721 | java | Java | Army.java | hhminh/continents | 87893f9669239c06c0d5d7445a377aaaa8762813 | [
"MIT"
] | 2 | 2015-08-15T10:12:28.000Z | 2015-08-15T10:53:18.000Z | Army.java | hhminh/continents | 87893f9669239c06c0d5d7445a377aaaa8762813 | [
"MIT"
] | null | null | null | Army.java | hhminh/continents | 87893f9669239c06c0d5d7445a377aaaa8762813 | [
"MIT"
] | null | null | null | 23.227047 | 173 | 0.61188 | 11,121 | //MIN01 - added leader capability
//MIN02 - bug?
//MIN03 - allow moving combat unit to front even if no points incase no others can combat
//
// ******************************************
// ARMY CAN BE NULL, MEANING A DEAD ARMY
// ******************************************
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
public class Army implements ResourceHolder, UnitSwappable, Serializable{
public static final int DEFAULT_LIMIT = 4;
public static final int ATTACK_MOVE_COST = 1;
public static final int MASK_AUTO_ORGANIZE = 1;
public static final int MASK_LEADER_ATTACK = 2;
public static final int MASK_ALLOW_RETREAT = 4;
public static final int MASK_LOAD_FOOD = 8;
public static final int MASK_ALLOW_ENTERTAIN = 16;
public static final int MASK_ALLOW_POLICE = 32;
protected ArrayList units;
protected int posx;
protected int posy;
protected int desx;
protected int desy;
protected int leader;
protected int owner;
protected int limit;
protected int leaderLevel;
protected int move;
protected int moveMax, moveType;
protected int[] resources;
protected Job job;
private boolean selected;
private boolean allowAI;
private int flag;
public Army(int o){
owner = o;
if (owner < 0){
owner = 0;
}else if (owner > GameWorld.OWNER_MAX){
owner = GameWorld.OWNER_MAX;
}
units = new ArrayList();
//start up no leader
leader = -1;
limit = DEFAULT_LIMIT;
//MIN10 - first created cant move yet
move = 0;
moveMax = 1;
//MIN29
moveType = GameWorld.TOWN_LAND;
//resources
resources = new int[GameWorld.RESOURCE_SIZE];
for (int i=0; i<resources.length; i++){
resources[i] = 0;
}
//job
job = null;
//run-time only
selected = false;
allowAI = true;
setFlag(MASK_AUTO_ORGANIZE);
setFlag(MASK_LEADER_ATTACK);
setFlag(MASK_ALLOW_RETREAT);
setFlag(MASK_LOAD_FOOD);
setFlag(MASK_ALLOW_POLICE);
}
public int getAlternativeLeader(UnitTypeLoader ul, int index){
int ldr = getLeader();
if (index == ldr) {
Unit u = get(index);
if (u != null) {
UnitType ut = ul.getUnitType(u.getType());
if (ut != null && ut.getLeaderLevel() > 0) {
for (int i=0; i<getCount(); i++) {
if (i == index) {
continue;
}
Unit u2 = get(i);
if (u2 != null) {
UnitType ut2 = ul.getUnitType(u2.getType());
if (ut2.getLeaderLevel() >= getCount()-1) {
return i;
}
}
}
}
}
return ldr;
}else{
return ldr;
}
}
public int getAlternativeLeader(UnitTypeLoader ul, Unit unt){
int index = getIndex(unt);
int ldr = getLeader();
if (index <0 || index>=getCount()) {
return ldr;
}
if (index == ldr) {
Unit u = get(index);
if (u != null) {
UnitType ut = ul.getUnitType(u.getType());
if (ut != null && ut.getLeaderLevel() > 0) {
for (int i=0; i<getCount(); i++) {
if (i == index) {
continue;
}
Unit u2 = get(i);
if (u2 != null) {
UnitType ut2 = ul.getUnitType(u2.getType());
if (ut2.getLeaderLevel() >= getCount()-1) {
return i;
}
}
}
}
}
return ldr;
}else{
return ldr;
}
}
public boolean canRemove(UnitTypeLoader ul, int index){
int ldr = getLeader();
if (getCount() > DEFAULT_LIMIT+1 && index == ldr) {
int alternative = getAlternativeLeader(ul, index);
//No other alternatives
if (alternative == ldr) {
if (getOwner() == GameWorld.PLAYER_OWNER) {
GameWorld.printMessage("The commander can not be removed from fleet because there is no alternative leader found. Please remove some units first to leave more rooms.");
}
return false;
}else{
return true;
}
}else{
return true;
}
}
public boolean canRemove(UnitTypeLoader ul, Unit unt){
int ldr = getLeader();
int index = getIndex(unt);
if (getCount() > DEFAULT_LIMIT+1 && index == ldr) {
int alternative = getAlternativeLeader(ul, index);
//No other alternatives
if (alternative == ldr) {
if (getOwner() == GameWorld.PLAYER_OWNER) {
GameWorld.printMessage("The commander can not be removed from fleet because there is no alternative leader found. Please remove some units first to leave more rooms.");
}
return false;
}else{
return true;
}
}else{
return true;
}
}
public void setJob(Job j){
job = j;
}
public Job getJob(){
return job;
}
public int getLimit(){
return limit;
}
public boolean transfer(Army other, UnitTypeLoader ul, int i){
//MH106
if (!other.canRemove(ul, i)) {
return false;
}
//MH106
Unit u = other.get(i);
boolean result = add(u, ul);
if (result){
other.remove(i, ul);
}
return result;
}
public boolean transfer(UnitSwappable other, int i, UnitTypeLoader ul, HouseTypeLoader hl, TerrainLoader tl, OverlayLoader ol, TechLoader tel){
//MH106
if (other instanceof Army && !((Army)other).canRemove(ul, i)) {
return false;
}
//MH106
Unit u = other.get(i);
boolean result = add(u, ul);
if (result){
//MIN17
if (other instanceof Army){
((Army)other).remove(i, ul);
}else{
other.remove(i);
}
if (other instanceof House){
((House)other).recalProduction(hl, ul, tel);
}else if (other instanceof Site){
((Site)other).recalProduction(tl, ol, ul, tel);
}
}
return result;
}
public boolean capture(Army enemy, UnitTypeLoader uloader){
int count = 0;
for (int i=0; i<enemy.getCount(); i++){
Unit eu = enemy.get(i);
if (eu == null){
continue;
}
UnitType eut = uloader.getUnitType(eu.getType());
if (eut != null){
int captureChance = (int)(Randomizer.getNextRandom() * GameWorld.CAPTURE_CHANCE);
int defendChance = (int)(Randomizer.getNextRandom() * (eu.getHP() + eut.getDefend(eu)));
if (captureChance > defendChance && add(enemy.get(i), uloader)){
enemy.remove(i, uloader);
count++;
}
}
}
return (count > 0);
}
public void clearFlag(int f){
flag &= ~f;
}
public void setFlag(int f){
flag |= f;
}
public int getFlag(int f){
//System.out.println(flag + "/" + f + "/" + (flag & f));
return flag & f;
}
public int getCombat(){
if (leader == -1){
return units.size();
}else{
return units.size() + leaderLevel;
}
}
public int getResourceCount(){
return resources.length;
}
public int getResource(int r){
return resources[r];
}
public int transfer(ResourceHolder other, int r, int amount){
if (resources[r] >= GameWorld.RESOURCE_LIMIT_SMALL[r]){
return 0;
}else if (amount + resources[r] > GameWorld.RESOURCE_LIMIT_SMALL[r]){
//cant store more than the limit
amount = GameWorld.RESOURCE_LIMIT_SMALL[r] - resources[r];
}
int moved = other.reduce(r, amount);
resources[r] += moved;
return moved;
}
public int reduce(int r, int amount){
if (amount > resources[r]){
return 0;
}else{
resources[r] -= amount;
return amount;
}
}
public void setResourceDebug(int r, int amount){
resources[r] = amount;
if (resources[r] > GameWorld.RESOURCE_LIMIT_SMALL[r]){
resources[r] = GameWorld.RESOURCE_LIMIT_SMALL[r];
}
if (resources[r]<0) {
resources[r] = 0;
}
}
public void setSelection(boolean s){
selected = s;
}
public boolean getSelection(){
return selected;
}
public void setDestination(int x, int y){
desx = x;
desy = y;
}
public void setPosition(int x, int y, int land){
posx = x;
posy = y;
//MIN29
moveType = land;
}
public void setPositionDynamic(int x, int y, int land, UnitTypeLoader ul){
posx = x;
posy = y;
//MIN29
if (moveType != land){
moveType = land;
recalMove(ul);
//forcing proper display
canMove(land, ul, true);
}else{
moveType = land;
}
}
public int getX(){
return posx;
}
public int getY(){
return posy;
}
public Point getPosition(){
return new Point(posx, posy);
}
public int getDX(){
return desx;
}
public int getDY(){
return desy;
}
public Point getDestination(){
return new Point(desx, desy);
}
public int getOwner(){
return owner;
}
public void changeOwner(int o){
if (owner < 0 || owner > GameWorld.OWNER_MAX){
return;
}
owner = o;
}
public Color getOwnerColor(){
return GameWorld.OWNER_COLOR[owner];
}
public boolean add(Unit u, UnitTypeLoader uloader){
//add unit only if in limit
if (units.size () >= limit || u == null || uloader == null){
return false;
}
//add unit only if valid type
UnitType ut = uloader.getUnitType(u.getType());
if (ut == null){
return false;
}
//auto-assign leader
int l = ut.getLeaderLevel();
if (l > 0){
if (leader <= -1){
leader = units.size();
leaderLevel = l;
limit = DEFAULT_LIMIT + leaderLevel;
}else{
Unit u2 = (Unit)units.get(leader);
UnitType ut2 = uloader.getUnitType(u2.getType());
if (ut2.getLeaderLevel() < l){
leader = units.size();
leaderLevel = l;
limit = DEFAULT_LIMIT + leaderLevel;
}
}
}
//add unit
units.add(u);
//MH106 Implement transport require complete look over army
recalMove(uloader);
//These are old rules
/*
//movement is the min of all unit
//MIN29 added land type
if (ut.canMove(moveType)){
//MH106 transport rules
if ((moveMax > ut.getMove(u)) || (ut.isTransport() && moveMax < ut.getMove(u))){
moveMax = ut.getMove(u);
//or when there is only 1, it is the max movement points
}else if (units.size() < 2){
moveMax = ut.getMove(u);
//special case when the olders are not moveable and the newer will carry them
}else if (moveMax == 0){
moveMax = ut.getMove(u);
}
if (move > moveMax){
move = moveMax;
}
//MIN29 when there is only 1
}else if (units.size() < 2){
moveMax = 0;
move = 0;
}
*/
return true;
}
public boolean chargeMove(int m){
move -= m;
//can move anymore?
if (move <=0){
move = 0;
return true;
}else{
return false;
}
}
public int getMoraleBonus(){
return (int)(resources[GameWorld.RESOURCE_HAPPY] * 100 / GameWorld.RESOURCE_LIMIT_SMALL[GameWorld.RESOURCE_HAPPY]);
}
public int getRecoveryBonus(){
return (int)(resources[GameWorld.RESOURCE_HAPPY] * GameWorld.RESOURCE_SLICE / GameWorld.RESOURCE_LIMIT_SMALL[GameWorld.RESOURCE_HAPPY]);
}
//restore
public boolean newTurn(UnitTypeLoader uloader){
move = moveMax;
int noSupplies = 0;
//Morales
int morale_increase = 0;
for (int i=0; i<units.size(); i++){
Unit u = (Unit)units.get(i);
//generate morales
UnitType ut = uloader.getUnitType(u.getType());
if (ut != null){
for (int j=0; j<ut.getProductions(); j++) {
if (ut.getProdType(j) == GameWorld.RESOURCE_HAPPY) {
morale_increase += ut.getProdQuant(j);
break;
}
}
}
}
setResourceDebug(GameWorld.RESOURCE_HAPPY, resources[GameWorld.RESOURCE_HAPPY] + morale_increase);
//Guard bonus
int guard_increase = 0;
for (int i=0; i<units.size(); i++){
Unit u = (Unit)units.get(i);
//generate morales
UnitType ut = uloader.getUnitType(u.getType());
if (ut != null){
for (int j=0; j<ut.getProductions(); j++) {
if (ut.getProdType(j) == GameWorld.RESOURCE_SECURITY) {
guard_increase += ut.getProdQuant(j);
break;
}
}
}
}
setResourceDebug(GameWorld.RESOURCE_SECURITY, resources[GameWorld.RESOURCE_SECURITY] + guard_increase);
//Morale bonus to healing
int recoverBonus = getRecoveryBonus();
//Consumption
for (int i=0; i<units.size(); i++){
Unit u = (Unit)units.get(i);
//consume supplies
UnitType ut = uloader.getUnitType(u.getType());
if (ut != null){
boolean noFood = true;
int failed = 0;
//consumption
for (int j=0; j<ut.getConsumptions(); j++){
int c = ut.getConsume(j);
if (c>= 0 && c <GameWorld.RESOURCE_SIZE){
int q = ut.getConQuant(j);
if (resources[c] < q){
failed++;
}else{
if (c == GameWorld.RESOURCE_FOOD) {
noFood = false;
}
resources[c] -= q;
}
}
}
//morale bonus to healing frontliners
while (recoverBonus > 0 && u.getHP()<u.getMaxHP()) {
u.heal();
recoverBonus--;
}
//normal healing process
//if (failed == 0){
if (!noFood) {
//heal unit
u.heal();
}
if (failed == 0){
//Restore combat points
u.setCombat(ut.getCombat(u));
}else{
noSupplies++;
//Apply penalty
if (ut.getCombat(u) > 0){
u.setCombat(GameWorld.RESOURCE_PENALTY);
}else{
u.setCombat(0);
}
}
}
}
//is it that serious to do a report?
if (noSupplies >= getCount()){
//if (owner == GameWorld.PLAYER_OWNER){
//GameWorld.printMessage("<%" + GameWorld.IMG_ADVISOR_SMALL + "%>Sir, there is not enough supplies for the army");
//}
return false;
}else{
return true;
}
}
//to-do need to change
public boolean canMove(int t, UnitTypeLoader uloader, boolean display){
//System.err.println("canMove");
for (int i=0; i<units.size(); i++){
Unit u = (Unit)units.get(i);
if (u != null) {
UnitType ut = uloader.getUnitType(u.getType());
if (ut != null){
if (ut.canMove(t)){
//MIN09 - swap unit to display rightly
if (display && i > 0){
swap(i, 0);
}
return true;
}
}
}
}
return false;
}
public int getMove(){
return move;
}
public int getMoveMax(){
return moveMax;
}
protected void recalMove(UnitTypeLoader uloader){
//System.err.println("recalMove " + units.size());
//something really big
moveMax = 999999;
int moveTP = 0;
int movable = 0;
for (int i=0; i<units.size(); i++){
Unit u = (Unit)units.get(i);
if (u != null) {
UnitType ut = uloader.getUnitType(u.getType());
//MH105 implement transport here
//Get the max of all transport
//System.err.println("type " + u.getType());
if (ut != null && ut.canMove(moveType)){
//if (ut.isTransport() && ut.getMove(u) > moveMax) {
// if (moveTP < ut.getMove(u)) {
//Transport unit carries others
if (ut.isTransport() && ut.getMove(u) > moveTP) {
moveMax = ut.getMove(u);
moveTP = moveMax;
movable++;
// }
//get the min but not if there is transport
}else if (moveMax > ut.getMove(u) && moveTP < ut.getMove(u)){
moveMax = ut.getMove(u);
movable++;
}
}
}
}
//This army get stuck
if (movable == 0) {
moveMax = 0;
}
//Average out
if (move > moveMax){
move = moveMax;
}
}
protected void findLeader(UnitTypeLoader uloader){
//System.err.println("findLeader");
leader = -1;
leaderLevel = 0;
limit = DEFAULT_LIMIT;
for (int i=0; i<units.size(); i++){
Unit u = (Unit)units.get(i);
UnitType ut = uloader.getUnitType(u.getType());
if (ut != null){
int lvl = ut.getLeaderLevel();
if (lvl > leaderLevel){
leader = i;
leaderLevel = lvl;
limit = DEFAULT_LIMIT + leaderLevel;
}
}
}
}
public void remove(int i){
//this is define to conform interface unitswappable but is not used
}
public void remove(int i, UnitTypeLoader uloader){
if (i >= 0 && i < units.size()){
Unit u = (Unit)units.get(i);
UnitType ut = uloader.getUnitType(u.getType());
if (ut != null){
//remove
units.remove(i);
//MIN02 - leader?
//if (i == leader){
findLeader(uloader);
//}
//movement?
//if (ut.canMove(moveType) && moveMax <= ut.getMove(u)){
//MH106 The new rule include transport which use larger move
if (ut.canMove(moveType)){
recalMove(uloader);
}
}
}
}
public void reorganize(UnitTypeLoader uloader, boolean force){
//for leader only
if (leader == -1 && !force){
return;
}
//user doesnt disable this option?
if (getFlag(MASK_AUTO_ORGANIZE) == 0){
return;
}
//sort by hp & attack
Unit uleader = null;
if (leader > -1 && leader < units.size()){
uleader = (Unit)units.get(leader);
}
ArrayList sortlist = new ArrayList();
for (int i=0; i<units.size(); i++){
Unit current = (Unit)units.get(i);
if (sortlist.size() == 0){
sortlist.add(current);
}else{
boolean done = false;
for (int j=0; j<sortlist.size(); j++){
Unit besthp = (Unit)sortlist.get(j);
if (besthp.getHP() < current.getHP()){
sortlist.add(j, current);
done = true;
break;
}else if (besthp.getHP() == current.getHP()){
UnitType ut1 = (UnitType)uloader.getUnitType(besthp.getType());
UnitType ut2 = (UnitType)uloader.getUnitType(current.getType());
if (ut1.getAttack(besthp) < ut2.getAttack(current)){
sortlist.add(j, current);
done = true;
break;
}
}
}
if (!done){
sortlist.add(current);
}
}
}
//reassign
units = sortlist;
leader = units.indexOf(uleader);
}
public int getCount(){
return units.size();
}
public Unit get(int i){
if (i >= 0 && i < units.size()){
return (Unit)units.get(i);
}else{
return null;
}
}
public int getIndex(Unit u){
return units.indexOf(u);
}
public void swap(int i1, int i2){
//swap but keep intact
Unit u1 = (Unit)units.get(i1);
units.set(i1, units.get(i2));
units.set(i2, u1);
//swap if leader?
if (leader == i1){
leader = i2;
}else if (leader == i2){
leader = i1;
}
}
public void moveCombatUnitToFront(UnitTypeLoader uloader){
int u = -1;
if (units.size() > 0){
int i = 0;
while (i < units.size()){
Unit u2 = (Unit)units.get(i);
UnitType ut = (UnitType)uloader.getUnitType(u2.getType());
//MIN03, combat enabled
if (ut.isCombatUnit()){
u = i;
//MIN03 - leader can only attack if specified
//therefore continue to search if leader is encountered
if ((i != leader || getFlag(MASK_LEADER_ATTACK) == MASK_LEADER_ATTACK) && u2.getCombat() > 0){
break;
}
}
i++;
}
}
//move combat unit to front
if (u > 0){
swap(u, 0);
}
}
public void moveRangeUnitToFront(UnitTypeLoader uloader, int r){
int u = -1;
if (units.size() > 0){
int i = 0;
while (i < units.size()){
Unit u2 = (Unit)units.get(i);
UnitType ut = (UnitType)uloader.getUnitType(u2.getType());
//MIN03
if (ut.isCombatUnit() && ut.getRange(u2) >= r){
u = i;
//MIN03 - leader can only attack if specified
//therefore continue to search if leader is encountered
if ((i != leader || getFlag(MASK_LEADER_ATTACK) == MASK_LEADER_ATTACK) && u2.getCombat() > 0){
break;
}
}
i++;
}
}
//move combat unit to front
if (u > 0){
//System.out.println("Swap " + u + " to 0");
swap(u, 0);
}
}
public int getLeader(){
return leader;
}
} |
3e1a26dc4f9425e48daf3a06853d5ac2727768b5 | 2,018 | java | Java | src/main/java/edu/neu/coe/info6205/life/base/geneticAlgorithm.java | kaiqiann/INFO6205_Life | ac88d57274796f4e35240f02c3619199bc0a72f5 | [
"MIT"
] | 1 | 2019-12-06T22:01:41.000Z | 2019-12-06T22:01:41.000Z | src/main/java/edu/neu/coe/info6205/life/base/geneticAlgorithm.java | kaiqiann/INFO6205_Life | ac88d57274796f4e35240f02c3619199bc0a72f5 | [
"MIT"
] | null | null | null | src/main/java/edu/neu/coe/info6205/life/base/geneticAlgorithm.java | kaiqiann/INFO6205_Life | ac88d57274796f4e35240f02c3619199bc0a72f5 | [
"MIT"
] | 1 | 2019-12-04T22:05:05.000Z | 2019-12-04T22:05:05.000Z | 28.027778 | 75 | 0.620912 | 11,122 | package edu.neu.coe.info6205.life.base;
import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.Lists;
public class geneticAlgorithm {
private List<Double> gList = new ArrayList<>();
private List<Double> grList = new ArrayList<>();
private Mutator m = new Mutator();
public List<String> initialPopulation() {
List<String> population = new ArrayList<>();
int j = 0;
for (int i = 0; i < Profile.GA_POPULATION; i++) {
InitialPattern ip = new InitialPattern(Profile.RANDOM_SEED + j);
population.add(ip.getPattern());
j += 2000;
}
return population;
}
public String run(List<String> population) {
for (int i = 0; i < Profile.MAX_GENERATION; i++) {
// Select
Selector.growrate = 0;
Selector.gen = 0;
System.out.println("----------------------------------------------");
System.out.println("current generation:" + (i + 1));
Selector.Select(population);
List<String> current = new ArrayList<>();
for (String s : population) {
current.add(s);
}
for (String s : population) {
Genotype g = new Genotype();
// Phenotype ==> Genotype
g.toChro(s);
for (int j = 0; j < (1 / Profile.SURVIVE_RATE) - 1; j++) {
//Mutate
List<Integer> l = m.Mutate(g.intList(g.getList()));
// Genotype ==> Phenotype
List<Chromosome> cl = m.intList(l);
g.setGeno(cl);
Phenotype p = new Phenotype(g);
current.add(p.getPheno());
}
}
population = current;
gList.add(Selector.getGen());
grList.add(Selector.getRate());
System.out.println("Average Generation: " + Selector.getGen());
System.out.println("Average Growth Rate: " + Selector.getRate() + "\n");
}
System.out.print("\nAverage generation route: ");
for (double d : gList) {
System.out.print(" ," + d);
}
System.out.print("\nAverage Growth Rate route: ");
for (double d : grList) {
System.out.print(" ," + d);
}
System.out.println();
//get the best individual
return Selector.getBest(population);
}
}
|
3e1a27105db6ffcd1ac9bb74dc90bd1bd504bc3d | 766 | java | Java | Clo_tter/src/main/java/base/Association.java | FrancoLuigi/Clo_tter | 3401c4bf430aafa6fa0e73d1dc4c01c17b15baab | [
"Apache-2.0"
] | null | null | null | Clo_tter/src/main/java/base/Association.java | FrancoLuigi/Clo_tter | 3401c4bf430aafa6fa0e73d1dc4c01c17b15baab | [
"Apache-2.0"
] | null | null | null | Clo_tter/src/main/java/base/Association.java | FrancoLuigi/Clo_tter | 3401c4bf430aafa6fa0e73d1dc4c01c17b15baab | [
"Apache-2.0"
] | null | null | null | 16.297872 | 76 | 0.701044 | 11,123 | package base;
public class Association {
public Association(String idClone, String idCommit, String version) {
this.idClone = idClone;
this.idCommit = idCommit;
this.version=version;
}
//ciao
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
@Override
public String toString() {
return "Association [idClone=" + idClone + ", idCommit=" + idCommit + "]";
}
public String getIdClone() {
return idClone;
}
public void setIdClone(String idClone) {
this.idClone = idClone;
}
public String getIdCommit() {
return idCommit;
}
public void setIdCommit(String idCommit) {
this.idCommit = idCommit;
}
private String idClone, idCommit;
private String version;
}
|
3e1a27f9f882411e0a516be13bfcb38d31a2a311 | 1,330 | java | Java | src/com/tactfactory/harmony/generator/androidxml/manifest/enums/SoftInputMode.java | TACTfactory/harmony-core | 037932a455c9e0f0a6b82453345b8aedd7a51edf | [
"MIT"
] | null | null | null | src/com/tactfactory/harmony/generator/androidxml/manifest/enums/SoftInputMode.java | TACTfactory/harmony-core | 037932a455c9e0f0a6b82453345b8aedd7a51edf | [
"MIT"
] | null | null | null | src/com/tactfactory/harmony/generator/androidxml/manifest/enums/SoftInputMode.java | TACTfactory/harmony-core | 037932a455c9e0f0a6b82453345b8aedd7a51edf | [
"MIT"
] | null | null | null | 23.189655 | 74 | 0.703346 | 11,124 | /**
* This file is part of the Harmony package.
*
* (c) Mickael Gaillard <ychag@example.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.tactfactory.harmony.generator.androidxml.manifest.enums;
public enum SoftInputMode {
STATE_UNSPECIFIED("stateUnspecified"),
STATE_UNCHANGED("stateUnchanged"),
STATE_HIDDEN("stateHidden"),
STATE_ALWAYS_HIDDEN("stateAlwaysHidden"),
STATE_VISIBLE("stateVisible"),
STATE_ALWAYS_VISIBLE("stateAlwaysVisible"),
ADJUST_UNSPECIFIED("adjustUnspecified"),
ADJUST_RESIZE("adjustResize"),
ADJUST_PAN("adjustPan");
private String value;
/**
* Private constructor.
* @param value The manifest value of this enum
*/
private SoftInputMode(String value) {
this.value = value;
}
/**
* Gets this enum's value.
* @return The value
*/
public String getValue() {
return this.value;
}
/**
* Returns the enum corresponding to the given value.
* @param value The value
* @return The enum found. Null if none
*/
public SoftInputMode fromValue(String value) {
SoftInputMode result = null;
for (SoftInputMode val : SoftInputMode.values()) {
if (val.getValue().equals(value)) {
result = val;
break;
}
}
return result;
}
}
|
3e1a2884abd333552baa9c4da1170749aff76c32 | 209 | java | Java | src/main/java/org/kiwi/proto/DepotRepository.java | hill-daniel/moving-average-crypto-lambda | fe35eb69d3a2feef44da044704003d4c0e1fa4c2 | [
"MIT"
] | null | null | null | src/main/java/org/kiwi/proto/DepotRepository.java | hill-daniel/moving-average-crypto-lambda | fe35eb69d3a2feef44da044704003d4c0e1fa4c2 | [
"MIT"
] | null | null | null | src/main/java/org/kiwi/proto/DepotRepository.java | hill-daniel/moving-average-crypto-lambda | fe35eb69d3a2feef44da044704003d4c0e1fa4c2 | [
"MIT"
] | null | null | null | 17.416667 | 50 | 0.760766 | 11,125 | package org.kiwi.proto;
import java.util.Optional;
import org.kiwi.proto.FloatingAverageProtos.Depot;
public interface DepotRepository {
Optional<Depot> load(String id);
void store(Depot depot);
}
|
3e1a2896fee208578400fdf96e08663f432def71 | 6,371 | java | Java | app/src/main/java/example/com/elmusicplayer/MusicService/MusicService.java | TuonglLe/ELMusicPlayer | 84f4230982881db5e57fcab534507ee4c5da67bb | [
"Apache-2.0"
] | null | null | null | app/src/main/java/example/com/elmusicplayer/MusicService/MusicService.java | TuonglLe/ELMusicPlayer | 84f4230982881db5e57fcab534507ee4c5da67bb | [
"Apache-2.0"
] | null | null | null | app/src/main/java/example/com/elmusicplayer/MusicService/MusicService.java | TuonglLe/ELMusicPlayer | 84f4230982881db5e57fcab534507ee4c5da67bb | [
"Apache-2.0"
] | null | null | null | 34.625 | 134 | 0.691414 | 11,126 | package example.com.elmusicplayer.MusicService;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.Process;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.transition.TransitionPropagation;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import example.com.elmusicplayer.ObservablePattern.PlaybackKits.PlaybackPublisher;
import example.com.elmusicplayer.ObservablePattern.SongTrackerKits.SongsTrackerPublisher;
import example.com.elmusicplayer.SongKits.DeviceSongsFinder;
import example.com.elmusicplayer.SongKits.RemoteSongsFinder;
import example.com.elmusicplayer.SongKits.Song;
import example.com.elmusicplayer.Utils.Constants;
import example.com.elmusicplayer.Utils.MediaConstants;
import example.com.elmusicplayer.Utils.MessageConstants;
public class MusicService extends Service {
private static final String LOG_TAG = MusicService.class.getSimpleName();
private class MusicHandler extends Handler{
private List<Song> remoteSongs;
public MusicHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case MessageConstants.MESSAGE_TYPE_DEVICE_SONGS:
remoteSongs = DeviceSongsFinder.findDeviceSongs(MusicService.this, null);
break;
case MessageConstants.MESSAGE_TYPE_REMOTE_JSON_SONGS:
remoteSongs = RemoteSongsFinder.fetRemoteSongs(RemoteSongsFinder.REMOTE_SONGS_URL);
break;
default:
break;
}
if(remoteSongs != null){
new Handler(getMainLooper()).post(
new Runnable() {
@Override
public void run() {
songsTracker.setCurrentSongList(remoteSongs);
}
}
);
}
}
}
private HandlerThread musicActionHandlerThread;
private MusicHandler musicHandler;
private Messenger messenger;
private Playback playback;
private SongsTracker songsTracker;
private MediaActionReceiver mediaActionReceiver;
private IntentFilter mediaActionIntentFilter;
private NotificationManager notificationManager;
private ExecutorService excuService;
// private boolean needToStartPlaybackThread = true;
@Override
public void onCreate() {
Log.d(LOG_TAG, "service is created");
notificationManager = new NotificationManager(this);
playback = new Playback(this);
songsTracker = new SongsTracker();
setUpMediaRecevier();
musicActionHandlerThread = new HandlerThread(LOG_TAG, Process.THREAD_PRIORITY_BACKGROUND);
musicActionHandlerThread.start();
musicHandler = new MusicHandler(musicActionHandlerThread.getLooper());
messenger = new Messenger(musicHandler);
excuService = Executors.newSingleThreadExecutor();
excuService.execute(new Runnable() {
@Override
public void run() {
while (true ){
if(playback.isPlaying()){
Intent intent = new Intent(MediaConstants.ACTION_HANDLE_PLAYBACK_CURRENT_POSITION);
intent.putExtra(MediaConstants.PLAYBACK_CURRENT_POSITION_KEY, playback.getMediaPlayer().getCurrentPosition());
sendBroadcast(intent);
}
}
}
});
}
//
// public void startPlaybackThread(){
// needToStartPlaybackThread = true;
// }
//
// public void stopPlaybackThread(){
// needToStartPlaybackThread = false;
// }
private void setUpMediaRecevier(){
mediaActionIntentFilter = new IntentFilter();
mediaActionIntentFilter.addAction(MediaConstants.ACTION_PLAY_FROM_MEDIA_ID);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_PLAY_CURRENT_SONG);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_RESUMED);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_PAUSED);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_STOPPED);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_SKIP_TO_NEXT);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_SKIP_TO_PREV);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_LOOP_MODE);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_NOTIFY_CURRENT_SONG);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_UPDATE_SONG_POSITION);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_START_NOTIFY_PLAYBACK);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_STOP_NOTIFY_PLAYBACK);
mediaActionIntentFilter.addAction(MediaConstants.ACTION_REASKED_CURRENT_MODE);
mediaActionReceiver = new MediaActionReceiver(this);
registerReceiver(mediaActionReceiver, mediaActionIntentFilter);
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
Log.d(LOG_TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d(LOG_TAG, "onDestroy");
unregisterReceiver(mediaActionReceiver);
// playback.killThread();
excuService.shutdownNow();
// thread.interrupt();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return messenger == null? null: messenger.getBinder();
}
public SongsTracker getSongsTracker() {
return songsTracker;
}
public Playback getPlayback() {
return playback;
}
public NotificationManager getNotificationManager() {
return notificationManager;
}
}
|
3e1a2a2d5edc3b36f25ba8fcd4b9e5c78a46ceaf | 141 | java | Java | CrowderApp/app/src/main/java/com/example/crowderapp/controllers/callbackInterfaces/endExperimentCallBack.java | CMPUT301W21T04/Crowder | 2f83eae60753c06578cfeb2ec5a089742042d8f7 | [
"Apache-2.0"
] | null | null | null | CrowderApp/app/src/main/java/com/example/crowderapp/controllers/callbackInterfaces/endExperimentCallBack.java | CMPUT301W21T04/Crowder | 2f83eae60753c06578cfeb2ec5a089742042d8f7 | [
"Apache-2.0"
] | 40 | 2021-02-17T19:29:56.000Z | 2021-04-09T10:02:01.000Z | CrowderApp/app/src/main/java/com/example/crowderapp/controllers/callbackInterfaces/endExperimentCallBack.java | CMPUT301W21T04/Crowder | 2f83eae60753c06578cfeb2ec5a089742042d8f7 | [
"Apache-2.0"
] | null | null | null | 23.5 | 62 | 0.822695 | 11,127 | package com.example.crowderapp.controllers.callbackInterfaces;
public interface endExperimentCallBack {
public void callBackResult();
}
|
3e1a2a84f3c761293038e48515dd8606730fe16b | 1,316 | java | Java | wavemaker-app-runtime-core/src/main/java/com/wavemaker/runtime/converters/WMCustomAbstractHttpMessageConverter.java | wavemaker/wavemaker-app-runtime | f1c7a7a345d2fb1ab0249d0332ca5e5c6b2227ed | [
"Apache-2.0"
] | 3 | 2018-12-23T14:52:55.000Z | 2020-08-30T11:07:28.000Z | wavemaker-app-runtime-core/src/main/java/com/wavemaker/runtime/converters/WMCustomAbstractHttpMessageConverter.java | wavemaker/wavemaker-app-runtime | f1c7a7a345d2fb1ab0249d0332ca5e5c6b2227ed | [
"Apache-2.0"
] | 2 | 2018-03-05T08:51:28.000Z | 2020-05-15T19:01:27.000Z | wavemaker-app-runtime-core/src/main/java/com/wavemaker/runtime/converters/WMCustomAbstractHttpMessageConverter.java | wavemaker/wavemaker-app-runtime | f1c7a7a345d2fb1ab0249d0332ca5e5c6b2227ed | [
"Apache-2.0"
] | 11 | 2017-04-05T06:50:49.000Z | 2021-11-26T20:46:33.000Z | 31.333333 | 146 | 0.74696 | 11,128 | /**
* Copyright © 2013 - 2017 WaveMaker, 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.wavemaker.runtime.converters;
import java.io.IOException;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
/**
* @Author: Uday
*/
public abstract class WMCustomAbstractHttpMessageConverter<T> extends AbstractHttpMessageConverter<T> implements WMCustomHttpMessageConverter<T> {
protected WMCustomAbstractHttpMessageConverter(MediaType... supportedMediaTypes) {
super(supportedMediaTypes);
}
@Override
public boolean supportsClazz(Class klass) {
return supports(klass);
}
@Override
protected MediaType getDefaultContentType(T t) throws IOException {
return null;
}
}
|
3e1a2af84e0eac9a2c441f15f13a1838408a6cab | 6,012 | java | Java | operator/src/test/java/oracle/kubernetes/operator/helpers/Matchers.java | Alfian878787/weblogic-kubernetes-operator | ac1730a3cdac15621515c1e392f1482a26694ac2 | [
"UPL-1.0",
"MIT"
] | null | null | null | operator/src/test/java/oracle/kubernetes/operator/helpers/Matchers.java | Alfian878787/weblogic-kubernetes-operator | ac1730a3cdac15621515c1e392f1482a26694ac2 | [
"UPL-1.0",
"MIT"
] | null | null | null | operator/src/test/java/oracle/kubernetes/operator/helpers/Matchers.java | Alfian878787/weblogic-kubernetes-operator | ac1730a3cdac15621515c1e392f1482a26694ac2 | [
"UPL-1.0",
"MIT"
] | null | null | null | 37.575 | 105 | 0.721557 | 11,129 | // Copyright (c) 2019, 2020, Oracle Corporation and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
package oracle.kubernetes.operator.helpers;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.openapi.models.V1Container;
import io.kubernetes.client.openapi.models.V1EnvVar;
import io.kubernetes.client.openapi.models.V1HostPathVolumeSource;
import io.kubernetes.client.openapi.models.V1PersistentVolumeClaimVolumeSource;
import io.kubernetes.client.openapi.models.V1Probe;
import io.kubernetes.client.openapi.models.V1Volume;
import io.kubernetes.client.openapi.models.V1VolumeMount;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasItem;
public class Matchers {
public static Matcher<Iterable<? super V1Container>> hasContainer(
String name, String image, String... command) {
return hasItem(createContainer(name, image, command));
}
public static Matcher<Iterable<? super V1EnvVar>> hasEnvVar(String name, String value) {
return hasItem(new V1EnvVar().name(name).value(value));
}
static Matcher<Map<? extends String, ? extends Quantity>> hasResourceQuantity(
String resource, String quantity) {
return hasEntry(resource, Quantity.fromString(quantity));
}
static Matcher<Iterable<? super V1VolumeMount>> hasVolumeMount(String name, String path) {
return hasItem(new V1VolumeMount().name(name).mountPath(path));
}
static Matcher<Iterable<? super V1Volume>> hasVolume(String name, String path) {
return hasItem(new V1Volume().name(name).hostPath(new V1HostPathVolumeSource().path(path)));
}
static Matcher<Iterable<? super V1Volume>> hasPvClaimVolume(String name, String claimName) {
return hasItem(new V1Volume().name(name).persistentVolumeClaim(
new V1PersistentVolumeClaimVolumeSource().claimName(claimName)));
}
private static V1Container createContainer(String name, String image, String... command) {
return new V1Container().name(name).image(image).command(Arrays.asList(command));
}
@SuppressWarnings("unused")
public static class VolumeMountMatcher
extends org.hamcrest.TypeSafeDiagnosingMatcher<io.kubernetes.client.openapi.models.V1VolumeMount> {
private String expectedName;
private String expectedPath;
private boolean readOnly;
private VolumeMountMatcher(String expectedName, String expectedPath, boolean readOnly) {
this.expectedName = expectedName;
this.expectedPath = expectedPath;
this.readOnly = readOnly;
}
public static VolumeMountMatcher writableVolumeMount(String expectedName, String expectedPath) {
return new VolumeMountMatcher(expectedName, expectedPath, false);
}
public static VolumeMountMatcher readOnlyVolumeMount(String expectedName, String expectedPath) {
return new VolumeMountMatcher(expectedName, expectedPath, true);
}
@Override
protected boolean matchesSafely(V1VolumeMount item, Description mismatchDescription) {
return expectedName.equals(item.getName())
&& expectedPath.equals(item.getMountPath())
&& readOnly == isReadOnly(item);
}
private Boolean isReadOnly(V1VolumeMount item) {
return item.getReadOnly() != null && item.getReadOnly();
}
@Override
public void describeTo(Description description) {
description
.appendText(getReadable())
.appendText(" V1VolumeMount ")
.appendValue(expectedName)
.appendText(" at ")
.appendValue(expectedPath);
}
private String getReadable() {
return readOnly ? "read-only" : "writable";
}
}
@SuppressWarnings("unused")
public static class ProbeMatcher
extends org.hamcrest.TypeSafeDiagnosingMatcher<io.kubernetes.client.openapi.models.V1Probe> {
private static final Integer EXPECTED_FAILURE_THRESHOLD = 1;
private Integer expectedInitialDelay;
private Integer expectedTimeout;
private Integer expectedPeriod;
private ProbeMatcher(int expectedInitialDelay, int expectedTimeout, int expectedPeriod) {
this.expectedInitialDelay = expectedInitialDelay;
this.expectedTimeout = expectedTimeout;
this.expectedPeriod = expectedPeriod;
}
public static ProbeMatcher hasExpectedTuning(
int expectedInitialDelay, int expectedTimeout, int expectedPeriod) {
return new ProbeMatcher(
expectedInitialDelay, expectedTimeout, expectedPeriod);
}
@Override
protected boolean matchesSafely(V1Probe item, Description mismatchDescription) {
if (Objects.equals(expectedInitialDelay, item.getInitialDelaySeconds())
&& Objects.equals(expectedTimeout, item.getTimeoutSeconds())
&& Objects.equals(expectedPeriod, item.getPeriodSeconds())
&& Objects.equals(EXPECTED_FAILURE_THRESHOLD, item.getFailureThreshold())) {
return true;
} else {
mismatchDescription
.appendText("probe with initial delay ")
.appendValue(item.getInitialDelaySeconds())
.appendText(", timeout ")
.appendValue(item.getTimeoutSeconds())
.appendText(", period ")
.appendValue(item.getPeriodSeconds())
.appendText(" and failureThreshold ")
.appendValue(item.getFailureThreshold());
return false;
}
}
@Override
public void describeTo(Description description) {
description
.appendText("probe with initial delay ")
.appendValue(expectedInitialDelay)
.appendText(", timeout ")
.appendValue(expectedTimeout)
.appendText(", period ")
.appendValue(expectedPeriod)
.appendText(" and failureThreshold ")
.appendValue(EXPECTED_FAILURE_THRESHOLD);
}
}
}
|
3e1a2ba3a7922f5e29f8a0ff115800664204e257 | 19,756 | java | Java | invoice/src/test/java/org/killbill/billing/invoice/tree/TestNodeInterval.java | continents-us/continents-killbill | f4339844cf5bf626af2f2f4dcf515684dba05e98 | [
"Apache-2.0"
] | 3 | 2018-08-24T17:35:56.000Z | 2020-01-25T11:57:18.000Z | invoice/src/test/java/org/killbill/billing/invoice/tree/TestNodeInterval.java | continents-us/continents-killbill | f4339844cf5bf626af2f2f4dcf515684dba05e98 | [
"Apache-2.0"
] | null | null | null | invoice/src/test/java/org/killbill/billing/invoice/tree/TestNodeInterval.java | continents-us/continents-killbill | f4339844cf5bf626af2f2f4dcf515684dba05e98 | [
"Apache-2.0"
] | 4 | 2019-01-03T09:48:55.000Z | 2022-01-04T05:26:51.000Z | 43.707965 | 210 | 0.679135 | 11,130 | /*
* Copyright 2010-2014 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.killbill.billing.invoice.tree;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import org.joda.time.LocalDate;
import org.killbill.billing.invoice.tree.NodeInterval.AddNodeCallback;
import org.killbill.billing.invoice.tree.NodeInterval.BuildNodeCallback;
import org.killbill.billing.invoice.tree.NodeInterval.SearchCallback;
import org.killbill.billing.invoice.tree.NodeInterval.WalkCallback;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
public class TestNodeInterval /* extends InvoiceTestSuiteNoDB */ {
private AddNodeCallback CALLBACK = new DummyAddNodeCallback();
public class DummyNodeInterval extends NodeInterval {
private final UUID id;
public DummyNodeInterval() {
this.id = UUID.randomUUID();
}
public DummyNodeInterval(final NodeInterval parent, final LocalDate startDate, final LocalDate endDate) {
super(parent, startDate, endDate);
this.id = UUID.randomUUID();
}
public UUID getId() {
return id;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof DummyNodeInterval)) {
return false;
}
final DummyNodeInterval that = (DummyNodeInterval) o;
if (id != null ? !id.equals(that.id) : that.id != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
public class DummyAddNodeCallback implements AddNodeCallback {
@Override
public boolean onExistingNode(final NodeInterval existingNode) {
return false;
}
@Override
public boolean shouldInsertNode(final NodeInterval insertionNode) {
return true;
}
}
@Test(groups = "fast")
public void testAddExistingItemSimple() {
final DummyNodeInterval root = new DummyNodeInterval();
final DummyNodeInterval top = createNodeInterval("2014-01-01", "2014-02-01");
root.addNode(top, CALLBACK);
final DummyNodeInterval firstChildLevel1 = createNodeInterval("2014-01-01", "2014-01-07");
final DummyNodeInterval secondChildLevel1 = createNodeInterval("2014-01-08", "2014-01-15");
final DummyNodeInterval thirdChildLevel1 = createNodeInterval("2014-01-16", "2014-02-01");
root.addNode(firstChildLevel1, CALLBACK);
root.addNode(secondChildLevel1, CALLBACK);
root.addNode(thirdChildLevel1, CALLBACK);
final DummyNodeInterval firstChildLevel2 = createNodeInterval("2014-01-01", "2014-01-03");
final DummyNodeInterval secondChildLevel2 = createNodeInterval("2014-01-03", "2014-01-5");
final DummyNodeInterval thirdChildLevel2 = createNodeInterval("2014-01-16", "2014-01-17");
root.addNode(firstChildLevel2, CALLBACK);
root.addNode(secondChildLevel2, CALLBACK);
root.addNode(thirdChildLevel2, CALLBACK);
checkNode(top, 3, root, firstChildLevel1, null);
checkNode(firstChildLevel1, 2, top, firstChildLevel2, secondChildLevel1);
checkNode(secondChildLevel1, 0, top, null, thirdChildLevel1);
checkNode(thirdChildLevel1, 1, top, thirdChildLevel2, null);
checkNode(firstChildLevel2, 0, firstChildLevel1, null, secondChildLevel2);
checkNode(secondChildLevel2, 0, firstChildLevel1, null, null);
checkNode(thirdChildLevel2, 0, thirdChildLevel1, null, null);
}
@Test(groups = "fast")
public void testAddExistingItemWithRebalance() {
final DummyNodeInterval root = new DummyNodeInterval();
final DummyNodeInterval top = createNodeInterval("2014-01-01", "2014-02-01");
root.addNode(top, CALLBACK);
final DummyNodeInterval firstChildLevel2 = createNodeInterval("2014-01-01", "2014-01-03");
final DummyNodeInterval secondChildLevel2 = createNodeInterval("2014-01-03", "2014-01-5");
final DummyNodeInterval thirdChildLevel2 = createNodeInterval("2014-01-16", "2014-01-17");
root.addNode(firstChildLevel2, CALLBACK);
root.addNode(secondChildLevel2, CALLBACK);
root.addNode(thirdChildLevel2, CALLBACK);
final DummyNodeInterval firstChildLevel1 = createNodeInterval("2014-01-01", "2014-01-07");
final DummyNodeInterval secondChildLevel1 = createNodeInterval("2014-01-08", "2014-01-15");
final DummyNodeInterval thirdChildLevel1 = createNodeInterval("2014-01-16", "2014-02-01");
root.addNode(firstChildLevel1, CALLBACK);
root.addNode(secondChildLevel1, CALLBACK);
root.addNode(thirdChildLevel1, CALLBACK);
checkNode(top, 3, root, firstChildLevel1, null);
checkNode(firstChildLevel1, 2, top, firstChildLevel2, secondChildLevel1);
checkNode(secondChildLevel1, 0, top, null, thirdChildLevel1);
checkNode(thirdChildLevel1, 1, top, thirdChildLevel2, null);
checkNode(firstChildLevel2, 0, firstChildLevel1, null, secondChildLevel2);
checkNode(secondChildLevel2, 0, firstChildLevel1, null, null);
checkNode(thirdChildLevel2, 0, thirdChildLevel1, null, null);
}
@Test(groups = "fast")
public void testBuild() {
final DummyNodeInterval root = new DummyNodeInterval();
final DummyNodeInterval top = createNodeInterval("2014-01-01", "2014-02-01");
root.addNode(top, CALLBACK);
final DummyNodeInterval firstChildLevel1 = createNodeInterval("2014-01-01", "2014-01-07");
final DummyNodeInterval secondChildLevel1 = createNodeInterval("2014-01-08", "2014-01-15");
final DummyNodeInterval thirdChildLevel1 = createNodeInterval("2014-01-16", "2014-02-01");
root.addNode(firstChildLevel1, CALLBACK);
root.addNode(secondChildLevel1, CALLBACK);
root.addNode(thirdChildLevel1, CALLBACK);
final DummyNodeInterval firstChildLevel2 = createNodeInterval("2014-01-01", "2014-01-03");
final DummyNodeInterval secondChildLevel2 = createNodeInterval("2014-01-03", "2014-01-5");
final DummyNodeInterval thirdChildLevel2 = createNodeInterval("2014-01-16", "2014-01-17");
root.addNode(firstChildLevel2, CALLBACK);
root.addNode(secondChildLevel2, CALLBACK);
root.addNode(thirdChildLevel2, CALLBACK);
final List<NodeInterval> output = new LinkedList<NodeInterval>();
// Just build the missing pieces.
root.build(new BuildNodeCallback() {
@Override
public void onMissingInterval(final NodeInterval curNode, final LocalDate startDate, final LocalDate endDate) {
output.add(createNodeInterval(startDate, endDate));
}
@Override
public void onLastNode(final NodeInterval curNode) {
// Nothing
return;
}
});
final List<NodeInterval> expected = new LinkedList<NodeInterval>();
expected.add(createNodeInterval("2014-01-05", "2014-01-07"));
expected.add(createNodeInterval("2014-01-07", "2014-01-08"));
expected.add(createNodeInterval("2014-01-15", "2014-01-16"));
expected.add(createNodeInterval("2014-01-17", "2014-02-01"));
assertEquals(output.size(), expected.size());
checkInterval(output.get(0), expected.get(0));
checkInterval(output.get(1), expected.get(1));
}
@Test(groups = "fast")
public void testSearch() {
final DummyNodeInterval root = new DummyNodeInterval();
final DummyNodeInterval top = createNodeInterval("2014-01-01", "2014-02-01");
root.addNode(top, CALLBACK);
final DummyNodeInterval firstChildLevel1 = createNodeInterval("2014-01-01", "2014-01-07");
final DummyNodeInterval secondChildLevel1 = createNodeInterval("2014-01-08", "2014-01-15");
final DummyNodeInterval thirdChildLevel1 = createNodeInterval("2014-01-16", "2014-02-01");
root.addNode(firstChildLevel1, CALLBACK);
root.addNode(secondChildLevel1, CALLBACK);
root.addNode(thirdChildLevel1, CALLBACK);
final DummyNodeInterval firstChildLevel2 = createNodeInterval("2014-01-01", "2014-01-03");
final DummyNodeInterval secondChildLevel2 = createNodeInterval("2014-01-03", "2014-01-5");
final DummyNodeInterval thirdChildLevel2 = createNodeInterval("2014-01-16", "2014-01-17");
root.addNode(firstChildLevel2, CALLBACK);
root.addNode(secondChildLevel2, CALLBACK);
root.addNode(thirdChildLevel2, CALLBACK);
final DummyNodeInterval firstChildLevel3 = createNodeInterval("2014-01-01", "2014-01-02");
final DummyNodeInterval secondChildLevel3 = createNodeInterval("2014-01-03", "2014-01-04");
root.addNode(firstChildLevel3, CALLBACK);
root.addNode(secondChildLevel3, CALLBACK);
final NodeInterval search1 = root.findNode(new LocalDate("2014-01-04"), new SearchCallback() {
@Override
public boolean isMatch(final NodeInterval curNode) {
return ((DummyNodeInterval) curNode).getId().equals(secondChildLevel3.getId());
}
});
checkInterval(search1, secondChildLevel3);
final NodeInterval search2 = root.findNode(new SearchCallback() {
@Override
public boolean isMatch(final NodeInterval curNode) {
return ((DummyNodeInterval) curNode).getId().equals(thirdChildLevel2.getId());
}
});
checkInterval(search2, thirdChildLevel2);
final NodeInterval nullSearch = root.findNode(new SearchCallback() {
@Override
public boolean isMatch(final NodeInterval curNode) {
return ((DummyNodeInterval) curNode).getId().equals("foo");
}
});
assertNull(nullSearch);
}
@Test(groups = "fast")
public void testWalkTree() {
final DummyNodeInterval root = new DummyNodeInterval();
final DummyNodeInterval firstChildLevel0 = createNodeInterval("2014-01-01", "2014-02-01");
root.addNode(firstChildLevel0, CALLBACK);
final DummyNodeInterval secondChildLevel0 = createNodeInterval("2014-02-01", "2014-03-01");
root.addNode(secondChildLevel0, CALLBACK);
final DummyNodeInterval firstChildLevel1 = createNodeInterval("2014-01-01", "2014-01-07");
final DummyNodeInterval secondChildLevel1 = createNodeInterval("2014-01-08", "2014-01-15");
final DummyNodeInterval thirdChildLevel1 = createNodeInterval("2014-01-16", "2014-02-01");
root.addNode(firstChildLevel1, CALLBACK);
root.addNode(secondChildLevel1, CALLBACK);
root.addNode(thirdChildLevel1, CALLBACK);
final DummyNodeInterval firstChildLevel2 = createNodeInterval("2014-01-01", "2014-01-03");
final DummyNodeInterval secondChildLevel2 = createNodeInterval("2014-01-03", "2014-01-05");
final DummyNodeInterval thirdChildLevel2 = createNodeInterval("2014-01-16", "2014-01-17");
root.addNode(firstChildLevel2, CALLBACK);
root.addNode(secondChildLevel2, CALLBACK);
root.addNode(thirdChildLevel2, CALLBACK);
final DummyNodeInterval firstChildLevel3 = createNodeInterval("2014-01-01", "2014-01-02");
final DummyNodeInterval secondChildLevel3 = createNodeInterval("2014-01-03", "2014-01-04");
root.addNode(firstChildLevel3, CALLBACK);
root.addNode(secondChildLevel3, CALLBACK);
final List<NodeInterval> expected = new LinkedList<NodeInterval>();
expected.add(root);
expected.add(firstChildLevel0);
expected.add(firstChildLevel1);
expected.add(firstChildLevel2);
expected.add(firstChildLevel3);
expected.add(secondChildLevel2);
expected.add(secondChildLevel3);
expected.add(secondChildLevel1);
expected.add(thirdChildLevel1);
expected.add(thirdChildLevel2);
expected.add(secondChildLevel0);
final List<NodeInterval> result = new LinkedList<NodeInterval>();
root.walkTree(new WalkCallback() {
@Override
public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) {
result.add(curNode);
}
});
assertEquals(result.size(), expected.size());
for (int i = 0; i < result.size(); i++) {
if (i == 0) {
assertTrue(result.get(0).isRoot());
checkInterval(result.get(0), createNodeInterval("2014-01-01", "2014-03-01"));
} else {
checkInterval(result.get(i), expected.get(i));
}
}
}
@Test(groups = "fast")
public void testRemoveLeftChildWithGrandChildren() {
final DummyNodeInterval root = new DummyNodeInterval();
final DummyNodeInterval top = createNodeInterval("2014-01-01", "2014-02-01");
root.addNode(top, CALLBACK);
final DummyNodeInterval firstChildLevel1 = createNodeInterval("2014-01-01", "2014-01-20");
final DummyNodeInterval secondChildLevel1 = createNodeInterval("2014-01-21", "2014-01-31");
root.addNode(firstChildLevel1, CALLBACK);
root.addNode(secondChildLevel1, CALLBACK);
final DummyNodeInterval firstChildLevel2 = createNodeInterval("2014-01-01", "2014-01-03");
final DummyNodeInterval secondChildLevel2 = createNodeInterval("2014-01-04", "2014-01-10");
final DummyNodeInterval thirdChildLevel2 = createNodeInterval("2014-01-11", "2014-01-20");
root.addNode(firstChildLevel2, CALLBACK);
root.addNode(secondChildLevel2, CALLBACK);
root.addNode(thirdChildLevel2, CALLBACK);
// Let's verify we get it right prior removing the node
final List<NodeInterval> expectedNodes = new ArrayList<NodeInterval>();
expectedNodes.add(root);
expectedNodes.add(top);
expectedNodes.add(firstChildLevel1);
expectedNodes.add(firstChildLevel2);
expectedNodes.add(secondChildLevel2);
expectedNodes.add(thirdChildLevel2);
expectedNodes.add(secondChildLevel1);
root.walkTree(new WalkCallback() {
@Override
public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) {
Assert.assertEquals(curNode, expectedNodes.remove(0));
}
});
// Remove node and verify again
top.removeChild(firstChildLevel1);
final List<NodeInterval> expectedNodesAfterRemoval = new ArrayList<NodeInterval>();
expectedNodesAfterRemoval.add(root);
expectedNodesAfterRemoval.add(top);
expectedNodesAfterRemoval.add(firstChildLevel2);
expectedNodesAfterRemoval.add(secondChildLevel2);
expectedNodesAfterRemoval.add(thirdChildLevel2);
expectedNodesAfterRemoval.add(secondChildLevel1);
root.walkTree(new WalkCallback() {
@Override
public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) {
Assert.assertEquals(curNode, expectedNodesAfterRemoval.remove(0));
}
});
}
@Test(groups = "fast")
public void testRemoveMiddleChildWithGrandChildren() {
final DummyNodeInterval root = new DummyNodeInterval();
final DummyNodeInterval top = createNodeInterval("2014-01-01", "2014-02-01");
root.addNode(top, CALLBACK);
final DummyNodeInterval firstChildLevel1 = createNodeInterval("2014-01-01", "2014-01-20");
final DummyNodeInterval secondChildLevel1 = createNodeInterval("2014-01-21", "2014-01-31");
root.addNode(firstChildLevel1, CALLBACK);
root.addNode(secondChildLevel1, CALLBACK);
final DummyNodeInterval firstChildLevel2 = createNodeInterval("2014-01-21", "2014-01-23");
final DummyNodeInterval secondChildLevel2 = createNodeInterval("2014-01-24", "2014-01-25");
final DummyNodeInterval thirdChildLevel2 = createNodeInterval("2014-01-26", "2014-01-31");
root.addNode(firstChildLevel2, CALLBACK);
root.addNode(secondChildLevel2, CALLBACK);
root.addNode(thirdChildLevel2, CALLBACK);
// Original List without removing node:
final List<NodeInterval> expectedNodes = new ArrayList<NodeInterval>();
expectedNodes.add(root);
expectedNodes.add(top);
expectedNodes.add(firstChildLevel1);
expectedNodes.add(secondChildLevel1);
expectedNodes.add(firstChildLevel2);
expectedNodes.add(secondChildLevel2);
expectedNodes.add(thirdChildLevel2);
root.walkTree(new WalkCallback() {
@Override
public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) {
Assert.assertEquals(curNode, expectedNodes.remove(0));
}
});
top.removeChild(secondChildLevel1);
final List<NodeInterval> expectedNodesAfterRemoval = new ArrayList<NodeInterval>();
expectedNodesAfterRemoval.add(root);
expectedNodesAfterRemoval.add(top);
expectedNodesAfterRemoval.add(firstChildLevel1);
expectedNodesAfterRemoval.add(firstChildLevel2);
expectedNodesAfterRemoval.add(secondChildLevel2);
expectedNodesAfterRemoval.add(thirdChildLevel2);
root.walkTree(new WalkCallback() {
@Override
public void onCurrentNode(final int depth, final NodeInterval curNode, final NodeInterval parent) {
Assert.assertEquals(curNode, expectedNodesAfterRemoval.remove(0));
}
});
}
private void checkInterval(final NodeInterval real, final NodeInterval expected) {
assertEquals(real.getStart(), expected.getStart());
assertEquals(real.getEnd(), expected.getEnd());
}
private void checkNode(final NodeInterval node, final int expectedChildren, final DummyNodeInterval expectedParent, final DummyNodeInterval expectedLeftChild, final DummyNodeInterval expectedRightSibling) {
assertEquals(node.getNbChildren(), expectedChildren);
assertEquals(node.getParent(), expectedParent);
assertEquals(node.getRightSibling(), expectedRightSibling);
assertEquals(node.getLeftChild(), expectedLeftChild);
assertEquals(node.getLeftChild(), expectedLeftChild);
}
private DummyNodeInterval createNodeInterval(final LocalDate startDate, final LocalDate endDate) {
return new DummyNodeInterval(null, startDate, endDate);
}
private DummyNodeInterval createNodeInterval(final String startDate, final String endDate) {
return createNodeInterval(new LocalDate(startDate), new LocalDate(endDate));
}
}
|
3e1a2c4ce2f693c7833289fb95de8dd31bc366a5 | 18,007 | java | Java | paas/tesla-authproxy/tesla-authproxy-server/src/main/java/com/alibaba/tesla/authproxy/outbound/oam/OamClient.java | iuskye/SREWorks | a2a7446767d97ec5f6d15bd00189c42150d6c894 | [
"Apache-2.0"
] | 407 | 2022-03-16T08:09:38.000Z | 2022-03-31T12:27:10.000Z | paas/tesla-authproxy/tesla-authproxy-server/src/main/java/com/alibaba/tesla/authproxy/outbound/oam/OamClient.java | iuskye/SREWorks | a2a7446767d97ec5f6d15bd00189c42150d6c894 | [
"Apache-2.0"
] | 25 | 2022-03-22T04:27:31.000Z | 2022-03-30T08:47:28.000Z | paas/tesla-authproxy/tesla-authproxy-server/src/main/java/com/alibaba/tesla/authproxy/outbound/oam/OamClient.java | iuskye/SREWorks | a2a7446767d97ec5f6d15bd00189c42150d6c894 | [
"Apache-2.0"
] | 109 | 2022-03-21T17:30:44.000Z | 2022-03-31T09:36:28.000Z | 44.818408 | 115 | 0.655437 | 11,131 | package com.alibaba.tesla.authproxy.outbound.oam;
import com.alibaba.tesla.authproxy.Constants;
import com.alibaba.tesla.authproxy.api.model.CheckPermissionRequest;
import com.alibaba.tesla.authproxy.lib.exceptions.AuthProxyThirdPartyError;
import com.alibaba.tesla.authproxy.outbound.acs.AcsClientFactory;
import com.alibaba.tesla.common.base.util.TeslaGsonUtil;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections;
/**
* OAM 客户端
*
* @author hzdkv@example.com
*/
@Component
@Slf4j
public class OamClient {
@Autowired
private AcsClientFactory acsClientFactory;
private Gson gson = new GsonBuilder().serializeNulls().create();
/**
* 获取当前的所有角色名称
*
* @param roleNameHas 模糊搜索名字
* @return 角色列表
*/
//public List<ListRolesResponse.OamRole> listRoles(String ownerAliyunPk, String ownerBid, String roleNameHas)
// throws AuthProxyThirdPartyError {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// ListRolesRequest request = new ListRolesRequest();
// request.setPageIndex(1);
// request.setPageSize(1000);
// request.setRoleNameHas(roleNameHas);
// log.info("Call OAM ListRoles, request={}", gson.toJson(request));
// ListRolesResponse response;
// try {
// response = acsClient.getAcsResponse(request);
// } catch (ClientException e) {
// throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_OAM,
// "ListRoles failed: " + TeslaGsonUtil.toJson(e));
// }
// log.info("Call OAM ListRoles, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 根据 OAM Username 来获取对应用户(副作用:让 OAM 认识该用户,用于新建用户过程中)
// *
// * @param username 用户名
// */
//public GetOamUserByUserNameResponse.Data getOamUserByUsername(String username) throws ClientException {
// IAcsClient acsClient = acsClientFactory.getSuperClient();
// GetOamUserByUserNameRequest request = new GetOamUserByUserNameRequest();
// request.setUserName(username);
// log.info("Call OAM GetOamUserByUserName, request={}", gson.toJson(request));
// GetOamUserByUserNameResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM GetOamUserByUserName, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 检查权限
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param aliyunPk 需要更新的用户 Aliyun PK
// * @param permissionName 新密码
// * @throws AuthProxyThirdPartyError OAM 系统错误时抛出
// */
//public Boolean checkPermission(String ownerAliyunPk, String ownerBid, String aliyunPk, String permissionName)
// throws ClientException, AuthProxyThirdPartyError {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// CheckPermissionRequest request = new CheckPermissionRequest();
// request.setResource(permissionName);
// request.setActionField("read");
// request.setAliUid(Long.valueOf(aliyunPk));
// log.info("Call OAM CheckPermission, request={}", gson.toJson(request));
// CheckPermissionResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM CheckPermission, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 获取某个 Role 的详细信息
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 角色名称
// */
//public GetRoleResponse.Data getRole(String ownerAliyunPk, String ownerBid, String roleName)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// GetRoleRequest request = new GetRoleRequest();
// request.setRoleName(roleName);
// log.info("Call OAM GetRole, request={}", gson.toJson(request));
// GetRoleResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM GetRole, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 获取某个用户的所有被授予的权限
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param aliyunPk 需要查询用户的 Aliyun ID
// */
//public List<OamRole> listRoleByOperator(String ownerAliyunPk, String ownerBid, String aliyunPk)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// ListRoleByOperatorRequest request = new ListRoleByOperatorRequest();
// request.setOperatorName(aliyunPk);
// request.setUserType("User");
// request.setPageSize(10000);
// request.setPageIndex(1);
// log.info("Call OAM ListRoleByOperator, request={}", gson.toJson(request));
// ListRoleByOperatorResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM ListRoleByOperator, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 获取某个角色当前被授权的所有用户
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 需要查询的角色名
// */
//public List<OamUser> listOperatorByRole(String ownerAliyunPk, String ownerBid, String roleName)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// ListOperatorByRoleRequest request = new ListOperatorByRoleRequest();
// request.setPageSize(10000);
// request.setPageIndex(1);
// request.setRoleName(roleName);
// log.info("Call OAM ListOperatorByRole, request={}", gson.toJson(request));
// ListOperatorByRoleResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM ListOperatorByRole, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 获取某个角色当前被授权的所有组
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 需要查询的角色名
// */
//public List<ListGroupsByRoleResponse.OamGroup> listGroupsByRole(
// String ownerAliyunPk, String ownerBid, String roleName)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// ListGroupsByRoleRequest request = new ListGroupsByRoleRequest();
// request.setPageSize(10000);
// request.setPageIndex(1);
// request.setRoleName(roleName);
// log.info("Call OAM ListGroupsByRole, request={}", gson.toJson(request));
// ListGroupsByRoleResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM ListGroupsByRole, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 获取某个用户的被授予的 Groups
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param aliyunPk 需要查询的用户 PK
// */
//public List<ListGroupsForUserResponse.OamGroup> listGroupsForUser(
// String ownerAliyunPk, String ownerBid, String aliyunPk)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// ListGroupsForUserRequest request = new ListGroupsForUserRequest();
// request.setPageSize(10000);
// request.setPageIndex(1);
// request.setUserName(aliyunPk);
// log.info("Call OAM ListGroupsForUser, request={}", gson.toJson(request));
// ListGroupsForUserResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM ListGroupsForUser, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 获取某个用户的被授予的 Groups
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param groupName 需要查询的 Group name
// */
//public List<ListUsersForGroupResponse.OamUser> listUsersForGroup(
// String ownerAliyunPk, String ownerBid, String groupName)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// ListUsersForGroupRequest request = new ListUsersForGroupRequest();
// request.setPageSize(10000);
// request.setPageIndex(1);
// request.setGroupName(groupName);
// log.info("Call OAM ListUsersForGroup, request={}", gson.toJson(request));
// ListUsersForGroupResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM ListUsersForGroup, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 获取某个 Role 的继承关系中所有的 Roles
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 需要查询的角色名称
// */
//public List<ListBaseRolesByRoleResponse.OamRole> listBaseRolesByRole(
// String ownerAliyunPk, String ownerBid, String roleName)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// ListBaseRolesByRoleRequest request = new ListBaseRolesByRoleRequest();
// request.setPageSize(10000);
// request.setPageIndex(1);
// request.setRoleName(roleName);
// log.info("Call OAM ListBaseRolesByRole, request={}", gson.toJson(request));
// ListBaseRolesByRoleResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM ListBaseRolesByRole, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 授权某个角色对某个用户
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 角色名
// * @param aliyunPk 需要授权对应的 Aliyun PK
// */
//public void grantRoleToOperator(String ownerAliyunPk, String ownerBid, String roleName, String aliyunPk)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// GrantRoleToOperatorRequest request = new GrantRoleToOperatorRequest();
// request.setUserType("User");
// request.setRoleName(roleName);
// request.setToOperatorName(aliyunPk);
// request.setGmtExpired("2099-12-31 00:00:00 UTC");
// log.info("Call OAM GrantRoleToOperator, request={}", gson.toJson(request));
// GrantRoleToOperatorResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM GrantRoleToOperator, response={}", gson.toJson(response));
//}
//
///**
// * 取消某个角色对某个用户的授权
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 角色名
// * @param aliyunPk 需要撤销对应的 Aliyun PK
// */
//public void revokeRoleFromOperator(String ownerAliyunPk, String ownerBid, String roleName, String aliyunPk)
// throws AuthProxyThirdPartyError, ClientException {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// RevokeRoleFromOperatorRequest request = new RevokeRoleFromOperatorRequest();
// request.setUserType("User");
// request.setRoleName(roleName);
// request.setOperatorName(aliyunPk);
// log.info("Call OAM RevokeRoleFromOperator, request={}", gson.toJson(request));
// RevokeRoleFromOperatorResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM RevokeRoleFromOperator, response={}", gson.toJson(response));
//}
//
///**
// * 在角色 roleName 中添加资源点 resource
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 角色名
// * @param resource 需要添加的资源
// */
//public void addRoleCellToRole(String ownerAliyunPk, String ownerBid, String roleName, String resource)
// throws AuthProxyThirdPartyError {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// AddRoleCellToRoleRequest request = new AddRoleCellToRoleRequest();
// request.setRoleName(roleName);
// request.setResource(resource);
// request.setActionLists(Collections.singletonList("*"));
// request.setGrantOption(0);
// log.info("Call OAM AddRoleCellToRole, request={}", TeslaGsonUtil.toJson(request));
// try {
// AddRoleCellToRoleResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM AddRoleCellToRole, response={}", gson.toJson(response));
// } catch (ClientException e) {
// throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_OAM,
// "AddRoleCellToRole failed: " + TeslaGsonUtil.toJson(e));
// }
//}
//
///**
// * Add role to role
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName roleName
// * @param baseRoleName baseRoleName
// */
//public void addRoleToRole(String ownerAliyunPk, String ownerBid, String roleName, String baseRoleName)
// throws AuthProxyThirdPartyError {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// AddRoleToRoleRequest request = new AddRoleToRoleRequest();
// request.setRoleName(roleName);
// request.setBaseRoleName(baseRoleName);
// log.info("Call OAM AddRoleToRole, request={}", TeslaGsonUtil.toJson(request));
// try {
// AddRoleToRoleResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM AddRoleToRole, response={}", gson.toJson(response));
// } catch (ClientException e) {
// throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_OAM,
// "AddRoleToRole failed: " + TeslaGsonUtil.toJson(e));
// }
//}
//
///**
// * 删除 Role Cell Id
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleCellId 权限点 ID
// */
//public void removeRoleCellFromRole(String ownerAliyunPk, String ownerBid, String roleCellId)
// throws AuthProxyThirdPartyError {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// RemoveRoleCellFromRoleRequest request = new RemoveRoleCellFromRoleRequest();
// request.setRoleCellId(roleCellId);
// log.info("Call OAM RemoveRoleCellFromRole, request={}", TeslaGsonUtil.toJson(request));
// try {
// RemoveRoleCellFromRoleResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM RemoveRoleCellFromRole, response={}", gson.toJson(response));
// } catch (ClientException e) {
// throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_OAM,
// "RemoveRoleCellFromRole failed: " + TeslaGsonUtil.toJson(e));
// }
//}
//
///**
// * 获取指定角色拥有哪些权限节点
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 角色名称
// * @return 权限列表
// */
//public List<ListRoleCellsByRoleNameResponse.OamRoleCell> listRoleCellsByRoleName(
// String ownerAliyunPk, String ownerBid, String roleName) throws AuthProxyThirdPartyError {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// ListRoleCellsByRoleNameRequest request = new ListRoleCellsByRoleNameRequest();
// request.setRoleName(roleName);
// request.setPageIndex(1);
// request.setPageSize(1000);
// log.info("Call OAM ListRoleCellsByRoleName, request={}", TeslaGsonUtil.toJson(request));
// ListRoleCellsByRoleNameResponse response;
// try {
// response = acsClient.getAcsResponse(request);
// } catch (ClientException e) {
// throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_OAM,
// "ListRoleCellsByRoleName failed: " + TeslaGsonUtil.toJson(e));
// }
// log.info("Call OAM ListRoleCellsByRoleName, response={}", gson.toJson(response));
// return response.getData();
//}
//
///**
// * 创建角色
// *
// * @param ownerAliyunPk 所有者 Aliyun PK
// * @param ownerBid 所有者 Bid
// * @param roleName 角色名称
// */
//public void createRole(String ownerAliyunPk, String ownerBid, String roleName, String description)
// throws AuthProxyThirdPartyError {
// IAcsClient acsClient = acsClientFactory.getOamClient(ownerAliyunPk, ownerBid);
// CreateRoleRequest request = new CreateRoleRequest();
// request.setRoleName(roleName);
// request.setDescription(description);
// request.setRoleType("OAM");
// log.info("Call OAM CreateRole, request={}", TeslaGsonUtil.toJson(request));
// try {
// CreateRoleResponse response = acsClient.getAcsResponse(request);
// log.info("Call OAM ListRoleCellsByRoleName, response={}", gson.toJson(response));
// } catch (ClientException e) {
// throw new AuthProxyThirdPartyError(Constants.THIRD_PARTY_OAM,
// "CreateRole failed: " + TeslaGsonUtil.toJson(e));
// }
//}
}
|
3e1a2c57fcd0febaf05e6f23e81e227e18065362 | 543 | java | Java | src/test/java/sk/webus/StartTestSuite.java | Johnz86/featureapp | 6efcf730b4490677fb8b40510d8fed9d64639c56 | [
"Apache-2.0"
] | null | null | null | src/test/java/sk/webus/StartTestSuite.java | Johnz86/featureapp | 6efcf730b4490677fb8b40510d8fed9d64639c56 | [
"Apache-2.0"
] | null | null | null | src/test/java/sk/webus/StartTestSuite.java | Johnz86/featureapp | 6efcf730b4490677fb8b40510d8fed9d64639c56 | [
"Apache-2.0"
] | null | null | null | 25.857143 | 113 | 0.714549 | 11,132 | package sk.webus;
import cucumber.api.CucumberOptions;
import cucumber.api.java.en.Given;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Created by jakubcik.jan on 27. 4. 2016.
*/
@RunWith(Cucumber.class)
@CucumberOptions(
format = { "pretty", "html:build/reports/cucumber-html-report", "json:build/reports/cucumber-report.json" },
strict = true,
features = "src/test/resources/features/register_user.feature"
)
public class StartTestSuite {
}
|
3e1a2cf835d91e28d6c7664a32d5e206f8cd6248 | 3,105 | java | Java | src/test/java/test/hifive/model/oa/propertypath/ProgramDocumentPP.java | ViaOA/oa-web | bd2ba3fb892f0ce199dc1ea239842cd07df0c06f | [
"Apache-2.0"
] | null | null | null | src/test/java/test/hifive/model/oa/propertypath/ProgramDocumentPP.java | ViaOA/oa-web | bd2ba3fb892f0ce199dc1ea239842cd07df0c06f | [
"Apache-2.0"
] | 1 | 2021-11-03T19:41:31.000Z | 2021-11-03T19:41:31.000Z | src/test/java/test/hifive/model/oa/propertypath/ProgramDocumentPP.java | ViaOA/oa-core | 5dc4cb805a1e3e37a54c740cf075a184e2497e19 | [
"Apache-2.0"
] | null | null | null | 34.5 | 124 | 0.723027 | 11,133 | // Generated by OABuilder
package test.hifive.model.oa.propertypath;
import test.hifive.model.oa.*;
public class ProgramDocumentPP {
private static LocationPPx announcementLocation;
private static ProgramPPx announcementProgram;
private static AwardTypePPx awardType;
private static AwardTypePPx awardTypes;
private static ProgramPPx blogPrograms;
private static EmployeeAwardPPx employeeAward;
private static LocationPageInfoPPx locationPageInfo;
private static PageGroupPageInfoPPx pageGroupPageInfos;
private static PageThemePageInfoPPx pageThemePageInfo;
private static ProgramPageInfoPPx programPageInfo;
public static LocationPPx announcementLocation() {
if (announcementLocation == null) announcementLocation = new LocationPPx(ProgramDocument.P_AnnouncementLocation);
return announcementLocation;
}
public static ProgramPPx announcementProgram() {
if (announcementProgram == null) announcementProgram = new ProgramPPx(ProgramDocument.P_AnnouncementProgram);
return announcementProgram;
}
public static AwardTypePPx awardType() {
if (awardType == null) awardType = new AwardTypePPx(ProgramDocument.P_AwardType);
return awardType;
}
public static AwardTypePPx awardTypes() {
if (awardTypes == null) awardTypes = new AwardTypePPx(ProgramDocument.P_AwardTypes);
return awardTypes;
}
public static ProgramPPx blogPrograms() {
if (blogPrograms == null) blogPrograms = new ProgramPPx(ProgramDocument.P_BlogPrograms);
return blogPrograms;
}
public static EmployeeAwardPPx employeeAward() {
if (employeeAward == null) employeeAward = new EmployeeAwardPPx(ProgramDocument.P_EmployeeAward);
return employeeAward;
}
public static LocationPageInfoPPx locationPageInfo() {
if (locationPageInfo == null) locationPageInfo = new LocationPageInfoPPx(ProgramDocument.P_LocationPageInfo);
return locationPageInfo;
}
public static PageGroupPageInfoPPx pageGroupPageInfos() {
if (pageGroupPageInfos == null) pageGroupPageInfos = new PageGroupPageInfoPPx(ProgramDocument.P_PageGroupPageInfos);
return pageGroupPageInfos;
}
public static PageThemePageInfoPPx pageThemePageInfo() {
if (pageThemePageInfo == null) pageThemePageInfo = new PageThemePageInfoPPx(ProgramDocument.P_PageThemePageInfo);
return pageThemePageInfo;
}
public static ProgramPageInfoPPx programPageInfo() {
if (programPageInfo == null) programPageInfo = new ProgramPageInfoPPx(ProgramDocument.P_ProgramPageInfo);
return programPageInfo;
}
public static String id() {
String s = ProgramDocument.P_Id;
return s;
}
public static String created() {
String s = ProgramDocument.P_Created;
return s;
}
public static String name() {
String s = ProgramDocument.P_Name;
return s;
}
public static String text() {
String s = ProgramDocument.P_Text;
return s;
}
}
|
3e1a2d37c667ae246bf1cc2a883b89b0eaf130cf | 937 | java | Java | src/com/tcl/launcher/json/ParseJsonUtil.java | tigline/roselauncher | 5260aa4401fd9afa4443c17721366f5503816326 | [
"Apache-2.0"
] | null | null | null | src/com/tcl/launcher/json/ParseJsonUtil.java | tigline/roselauncher | 5260aa4401fd9afa4443c17721366f5503816326 | [
"Apache-2.0"
] | null | null | null | src/com/tcl/launcher/json/ParseJsonUtil.java | tigline/roselauncher | 5260aa4401fd9afa4443c17721366f5503816326 | [
"Apache-2.0"
] | null | null | null | 34.703704 | 63 | 0.742796 | 11,134 | package com.tcl.launcher.json;
public class ParseJsonUtil {
// 根部字段(未加入semantic和ad)
public static final String RC = "rc";
public static final String ERROR = "error";
public static final String ACTION_COMMAND = "command";
public static final String ACTION_DATA = "data";
public static final String TIPS = "tips";
// "data"下字段
public static final String QUESTION = "question";
public static final String DOMAIN = "domain";
public static final String TOTAL = "total";
public static final String PN = "pn";
public static final String PS = "ps";
public static final String PC = "pc";
public static final String ACTION_RESULT = "result";
public static final String DYNAMIC_COMMAND = "dynamicCommand";
// "dynamicCommand"下字段
public static final String STATEMENT = "statement";
public static final String COMMAND = "command";
public static final String PARS = "pars";
public static final String MATCHTYPE = "matchtype";
}
|
3e1a2daf37bde933f52a050f7c4d4d7b4bcffc3e | 1,769 | java | Java | spring-boot-starters/spring-boot-starter-security/src/main/java/me/julb/springbootstarter/security/configurations/beans/authenticationtokens/CustomUsernamePasswordAuthenticationToken.java | julb/assets | 00332bfaabbab53178c483f21f109fed9c5a5523 | [
"MIT"
] | null | null | null | spring-boot-starters/spring-boot-starter-security/src/main/java/me/julb/springbootstarter/security/configurations/beans/authenticationtokens/CustomUsernamePasswordAuthenticationToken.java | julb/assets | 00332bfaabbab53178c483f21f109fed9c5a5523 | [
"MIT"
] | 7 | 2020-12-14T17:40:58.000Z | 2021-02-09T21:19:26.000Z | spring-boot-starters/spring-boot-starter-security/src/main/java/me/julb/springbootstarter/security/configurations/beans/authenticationtokens/CustomUsernamePasswordAuthenticationToken.java | julb/assets | 00332bfaabbab53178c483f21f109fed9c5a5523 | [
"MIT"
] | null | null | null | 38.456522 | 100 | 0.758621 | 11,135 | /**
* MIT License
*
* Copyright (c) 2017-2021 Julb
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.julb.springbootstarter.security.configurations.beans.authenticationtokens;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
/**
* A authentication token used to authenticate a user with its password.
* <br>
* @author Julb.
*/
public class CustomUsernamePasswordAuthenticationToken extends UsernamePasswordAuthenticationToken {
/**
* Default constructor.
* @param userName the username.
* @param password the password.
*/
public CustomUsernamePasswordAuthenticationToken(String userName, String password) {
super(userName, password);
}
}
|
3e1a2e6cc84a33569fd43c266ee5bb4e412b723a | 1,165 | java | Java | sdcct-core/src/main/java/gov/hhs/onc/sdcct/form/ws/FormWebService.java | elizabethso/sdcct | f09adc3e9f4ce4008b6ddcd109235ab7ee9f2348 | [
"Apache-2.0"
] | null | null | null | sdcct-core/src/main/java/gov/hhs/onc/sdcct/form/ws/FormWebService.java | elizabethso/sdcct | f09adc3e9f4ce4008b6ddcd109235ab7ee9f2348 | [
"Apache-2.0"
] | null | null | null | sdcct-core/src/main/java/gov/hhs/onc/sdcct/form/ws/FormWebService.java | elizabethso/sdcct | f09adc3e9f4ce4008b6ddcd109235ab7ee9f2348 | [
"Apache-2.0"
] | null | null | null | 40.172414 | 235 | 0.771674 | 11,136 | package gov.hhs.onc.sdcct.form.ws;
import com.github.sebhoss.warnings.CompilerWarnings;
import gov.hhs.onc.sdcct.data.SdcctResource;
import gov.hhs.onc.sdcct.data.db.SdcctResourceRegistry;
import gov.hhs.onc.sdcct.data.search.SearchService;
import gov.hhs.onc.sdcct.ws.metadata.InteractionWsMetadata;
import gov.hhs.onc.sdcct.ws.metadata.ResourceWsMetadata;
import gov.hhs.onc.sdcct.ws.metadata.WsMetadata;
import java.util.Map;
import org.springframework.beans.factory.InitializingBean;
public interface FormWebService<T extends SdcctResource, U extends SdcctResourceRegistry<?, ?, T>, V extends SearchService<?, ?, T, ?>, W extends InteractionWsMetadata, X extends ResourceWsMetadata<?, ?, W>, Y extends WsMetadata<W, X>>
extends InitializingBean {
public Y getMetadata();
public void setMetadata(Y metadata);
public Map<Class<?>, U> getResourceRegistries();
@SuppressWarnings({ CompilerWarnings.UNCHECKED })
public void setResourceRegistries(U ... resourceRegistries);
public Map<Class<?>, V> getSearchServices();
@SuppressWarnings({ CompilerWarnings.UNCHECKED })
public void setSearchServices(V ... searchServices);
}
|
3e1a2e7d6d8c54674521e785bc3898e0a1585120 | 1,223 | java | Java | smartsuites-server/src/test/java/com/smartsuites/ticket/TicketContainerTest.java | smartsuites/SmartSuites | 1f8def542c31b384ed5e880e7e439e738ea01b68 | [
"Apache-2.0"
] | 2 | 2018-04-02T01:46:17.000Z | 2018-04-03T02:21:26.000Z | smartsuites-server/src/test/java/com/smartsuites/ticket/TicketContainerTest.java | smartsuites/SmartSuites | 1f8def542c31b384ed5e880e7e439e738ea01b68 | [
"Apache-2.0"
] | null | null | null | smartsuites-server/src/test/java/com/smartsuites/ticket/TicketContainerTest.java | smartsuites/SmartSuites | 1f8def542c31b384ed5e880e7e439e738ea01b68 | [
"Apache-2.0"
] | null | null | null | 24.46 | 73 | 0.735078 | 11,137 | /*
* Copyright (c) 2017. 联思智云(北京)科技有限公司. All rights reserved.
*/
package com.smartsuites.ticket;
import org.junit.Before;
import org.junit.Test;
import java.net.UnknownHostException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TicketContainerTest {
private TicketContainer container;
@Before
public void setUp() throws Exception {
container = TicketContainer.instance;
}
@Test
public void isValidAnonymous() throws UnknownHostException {
boolean ok = container.isValid("anonymous", "anonymous");
assertTrue(ok);
}
@Test
public void isValidExistingPrincipal() throws UnknownHostException {
String ticket = container.getTicket("someuser1");
boolean ok = container.isValid("someuser1", ticket);
assertTrue(ok);
}
@Test
public void isValidNonExistingPrincipal() throws UnknownHostException {
boolean ok = container.isValid("unknownuser", "someticket");
assertFalse(ok);
}
@Test
public void isValidunkownTicket() throws UnknownHostException {
String ticket = container.getTicket("someuser2");
boolean ok = container.isValid("someuser2", ticket+"makeitinvalid");
assertFalse(ok);
}
}
|
3e1a2e9656331318c7b7c82115c800f023d2b953 | 2,502 | java | Java | src/main/java/application/Sevlet.java | cn03390/git-iot | aa7d599a6cc77b17091da5d9b69588edb5dd2268 | [
"MIT"
] | null | null | null | src/main/java/application/Sevlet.java | cn03390/git-iot | aa7d599a6cc77b17091da5d9b69588edb5dd2268 | [
"MIT"
] | null | null | null | src/main/java/application/Sevlet.java | cn03390/git-iot | aa7d599a6cc77b17091da5d9b69588edb5dd2268 | [
"MIT"
] | null | null | null | 32.649351 | 130 | 0.764519 | 11,138 | package application;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.ibm.cloud.sdk.core.http.Response;
import com.ibm.cloud.sdk.core.service.security.IamOptions;
import com.ibm.watson.visual_recognition.v3.VisualRecognition;
import com.ibm.watson.visual_recognition.v3.model.ClassifiedImages;
import com.ibm.watson.visual_recognition.v3.model.ClassifyOptions;
/**
* Servlet implementation class Test1
*/
@WebServlet("/Test1")
public class Sevlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
String url = request.getParameter("url");
System.out.println(name);
System.out.println(url);
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");// 注意設置為utf-8否則前端接收到的中文為亂碼
PrintWriter out = response.getWriter();
Gson gson = new Gson();
ArrayList<Test1Object> arraylistTest = new ArrayList<Test1Object>();
Test1Object t1 = new Test1Object();
Test1Object t2 = new Test1Object();
t1.setName(name);
t1.setUrl(url);
t2.setName(name);
t2.setUrl(url);
arraylistTest.add(t1);
arraylistTest.add(t2);
String info = gson.toJson(arraylistTest);
// 打印出檢查
System.out.println(info);
// 返回給前端
// out.write(info);
IamOptions options = new IamOptions.Builder()
.apiKey("caf86f4uutaoxfysmf7anj01xl6sv3ps")
.build();
VisualRecognition visualRecognition = new VisualRecognition("2018-03-19", options);
ClassifyOptions classifyOptions = new ClassifyOptions.Builder()
.url("https://watson-developer-cloud.github.io/doc-tutorial-downloads/visual-recognition/640px-IBM_VGA_90X8941_on_PS55.jpg")
.build();
Response<ClassifiedImages> result = visualRecognition.classify(classifyOptions).execute();
System.out.println(result.getResult());
out.write(result.getResult().toString());
}
} |
3e1a2f0f256b736a16f76b5f77e37dd1f0499912 | 7,274 | java | Java | twister2/resource-scheduler/src/java/edu/iu/dsc/tws/rsched/schedulers/k8s/mpi/MPIWorkerStarter.java | twister2/twister2 | c6ab9a5563a9e43d3fd1a16e5337da4edae71224 | [
"Apache-2.0"
] | null | null | null | twister2/resource-scheduler/src/java/edu/iu/dsc/tws/rsched/schedulers/k8s/mpi/MPIWorkerStarter.java | twister2/twister2 | c6ab9a5563a9e43d3fd1a16e5337da4edae71224 | [
"Apache-2.0"
] | null | null | null | twister2/resource-scheduler/src/java/edu/iu/dsc/tws/rsched/schedulers/k8s/mpi/MPIWorkerStarter.java | twister2/twister2 | c6ab9a5563a9e43d3fd1a16e5337da4edae71224 | [
"Apache-2.0"
] | null | null | null | 38.486772 | 95 | 0.731647 | 11,139 | // 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 edu.iu.dsc.tws.rsched.schedulers.k8s.mpi;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import edu.iu.dsc.tws.common.config.Config;
import edu.iu.dsc.tws.common.discovery.IWorkerDiscoverer;
import edu.iu.dsc.tws.common.discovery.WorkerNetworkInfo;
import edu.iu.dsc.tws.common.logging.LoggingHelper;
import edu.iu.dsc.tws.common.util.ReflectionUtils;
import edu.iu.dsc.tws.master.JobMasterContext;
import edu.iu.dsc.tws.master.client.JobMasterClient;
import edu.iu.dsc.tws.proto.system.job.JobAPI;
import edu.iu.dsc.tws.rsched.core.SchedulerContext;
import edu.iu.dsc.tws.rsched.schedulers.k8s.KubernetesConstants;
import edu.iu.dsc.tws.rsched.schedulers.k8s.KubernetesContext;
import edu.iu.dsc.tws.rsched.schedulers.k8s.worker.K8sPersistentVolume;
import edu.iu.dsc.tws.rsched.schedulers.k8s.worker.K8sVolatileVolume;
import edu.iu.dsc.tws.rsched.schedulers.k8s.worker.K8sWorkerUtils;
import edu.iu.dsc.tws.rsched.schedulers.mpi.MPIWorker;
import edu.iu.dsc.tws.rsched.spi.container.IPersistentVolume;
import edu.iu.dsc.tws.rsched.spi.container.IWorker;
import edu.iu.dsc.tws.rsched.spi.resource.ResourcePlan;
import edu.iu.dsc.tws.rsched.utils.JobUtils;
import mpi.MPI;
import mpi.MPIException;
import static edu.iu.dsc.tws.common.config.Context.JOB_ARCHIVE_DIRECTORY;
import static edu.iu.dsc.tws.rsched.schedulers.k8s.KubernetesConstants.KUBERNETES_CLUSTER_TYPE;
import static edu.iu.dsc.tws.rsched.schedulers.k8s.KubernetesConstants.POD_MEMORY_VOLUME;
public final class MPIWorkerStarter {
private static final Logger LOG = Logger.getLogger(MPIWorkerStarter.class.getName());
private static Config config = null;
private static int workerID = -1; // -1 means, not initialized
private static int numberOfWorkers = -1; // -1 means, not initialized
private static WorkerNetworkInfo workerNetworkInfo;
private static JobMasterClient jobMasterClient;
private MPIWorkerStarter() { }
public static void main(String[] args) {
// we can not initialize the logger fully yet,
// but we need to set the format as the first thing
LoggingHelper.setLoggingFormat(LoggingHelper.DEFAULT_FORMAT);
// load the configuration parameters from configuration directory
String configDir = POD_MEMORY_VOLUME + "/" + JOB_ARCHIVE_DIRECTORY + "/"
+ KUBERNETES_CLUSTER_TYPE;
config = K8sWorkerUtils.loadConfig(configDir);
// initialize MPI
try {
MPI.Init(args);
workerID = MPI.COMM_WORLD.getRank();
numberOfWorkers = MPI.COMM_WORLD.getSize();
} catch (MPIException e) {
LOG.log(Level.SEVERE, "Could not get rank or size from MPI.COMM_WORLD", e);
throw new RuntimeException(e);
}
// initialize persistent volume
K8sPersistentVolume pv = null;
if (KubernetesContext.persistentVolumeRequested(config)) {
// create persistent volume object
String persistentJobDir = KubernetesConstants.PERSISTENT_VOLUME_MOUNT;
pv = new K8sPersistentVolume(persistentJobDir, workerID);
}
// initialize persistent logging
K8sWorkerUtils.initWorkerLogger(workerID, pv, config);
// read job description file
String jobName = SchedulerContext.jobName(config);
String jobDescFileName = SchedulerContext.createJobDescriptionFileName(jobName);
jobDescFileName = POD_MEMORY_VOLUME + "/" + JOB_ARCHIVE_DIRECTORY + "/" + jobDescFileName;
JobAPI.Job job = JobUtils.readJobFile(null, jobDescFileName);
LOG.info("Job description file is loaded: " + jobDescFileName);
// add any configuration from job file to the config object
// if there are the same config parameters in both,
// job file configurations will override
config = K8sWorkerUtils.overrideConfigs(job, config);
InetAddress localHost = null;
try {
localHost = InetAddress.getLocalHost();
String podIP = localHost.getHostAddress();
String podName = localHost.getHostName();
int workerPort = KubernetesContext.workerBasePort(config) + workerID;
workerNetworkInfo = new WorkerNetworkInfo(localHost, workerPort, workerID);
LOG.info("Worker information summary: \n"
+ "MPI Rank(workerID): " + workerID + "\n"
+ "MPI Size(number of workers): " + numberOfWorkers + "\n"
+ "POD_IP: " + podIP + "\n"
+ "HOSTNAME(podname): " + podName
);
} catch (UnknownHostException e) {
LOG.log(Level.SEVERE, "Cannot get localHost.", e);
}
String jobMasterIP = MPIMasterStarter.getJobMasterIPCommandLineArgumentValue(args[0]);
if (jobMasterIP == null) {
throw new RuntimeException("JobMasterIP address is null");
}
config = Config.newBuilder()
.putAll(config)
.put(JobMasterContext.JOB_MASTER_IP, jobMasterIP)
.build();
jobMasterClient = K8sWorkerUtils.startJobMasterClient(config, workerNetworkInfo);
// we need to make sure that the worker starting message went through
jobMasterClient.sendWorkerStartingMessage();
// we will be running the Worker, send running message
jobMasterClient.sendWorkerRunningMessage();
// start the worker
startWorker(jobMasterClient.getWorkerController(), pv);
// finalize MPI
try {
MPI.Finalize();
} catch (MPIException ignore) { }
// close the worker
closeWorker();
}
/**
* start the Worker class specified in conf files
*/
public static void startWorker(IWorkerDiscoverer workerController,
IPersistentVolume pv) {
String workerClass = SchedulerContext.containerClass(config);
IWorker worker;
try {
Object object = ReflectionUtils.newInstance(workerClass);
worker = (IWorker) object;
LOG.info("loaded worker class: " + workerClass);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
LOG.severe(String.format("failed to load the worker class %s", workerClass));
throw new RuntimeException(e);
}
K8sVolatileVolume volatileVolume = null;
if (SchedulerContext.volatileDiskRequested(config)) {
volatileVolume =
new K8sVolatileVolume(SchedulerContext.jobName(config), workerID);
}
ResourcePlan resourcePlan = MPIWorker.createResourcePlan(config);
worker.init(config, workerID, resourcePlan, workerController, pv, volatileVolume);
}
/**
* last method to call to close the worker
*/
public static void closeWorker() {
// send worker completed message to the Job Master and finish
// Job master will delete the StatefulSet object
jobMasterClient.sendWorkerCompletedMessage();
jobMasterClient.close();
}
}
|
3e1a2f4076cc6c41d91818fa87b73f8f91bd17ef | 8,669 | java | Java | src/test/java/io/twasyl/jstackfx/search/QueryTest.java | batchmode/jstackfx | 10f98d24ec7a7f390fedb4cac1151f4a6e76bbc8 | [
"Apache-2.0"
] | 87 | 2016-11-24T07:51:16.000Z | 2022-01-04T15:11:02.000Z | src/test/java/io/twasyl/jstackfx/search/QueryTest.java | batchmode/jstackfx | 10f98d24ec7a7f390fedb4cac1151f4a6e76bbc8 | [
"Apache-2.0"
] | 1 | 2016-12-20T14:59:07.000Z | 2016-12-20T18:36:51.000Z | src/test/java/io/twasyl/jstackfx/search/QueryTest.java | batchmode/jstackfx | 10f98d24ec7a7f390fedb4cac1151f4a6e76bbc8 | [
"Apache-2.0"
] | 15 | 2016-11-24T07:51:19.000Z | 2020-10-12T01:50:56.000Z | 35.383673 | 116 | 0.690852 | 11,140 | package io.twasyl.jstackfx.search;
import io.twasyl.jstackfx.beans.ThreadElement;
import io.twasyl.jstackfx.search.exceptions.UnparsableQueryException;
import org.junit.Test;
import java.util.regex.Matcher;
import static io.twasyl.jstackfx.search.Query.*;
import static org.junit.Assert.*;
/**
* Testing class {@link Query}.
*
* @author Thierry Wasylczenko
* @since JStackFX 1.1
*/
public class QueryTest {
@Test
public void simpleExpressionWithEqualParsing() {
final String expression = "state = new";
final Matcher matcher = Query.EXPRESSION_PATTERN.matcher(expression);
assertTrue(matcher.find());
assertEquals("state", matcher.group(FIELD_NAME_GROUP));
assertEquals("=", matcher.group(COMPARATOR_GROUP));
assertEquals("new", matcher.group(FIELD_VALUE_GROUP));
}
@Test
public void simpleExpressionWithoutSpace() {
final String expression = "state=new";
final Matcher matcher = Query.EXPRESSION_PATTERN.matcher(expression);
assertTrue(matcher.find());
assertEquals("state", matcher.group(FIELD_NAME_GROUP));
assertEquals("=", matcher.group(COMPARATOR_GROUP));
assertEquals("new", matcher.group(FIELD_VALUE_GROUP));
}
@Test
public void simpleExpressionWithDifferentParsing() {
final String expression = "state != new";
final Matcher matcher = Query.EXPRESSION_PATTERN.matcher(expression);
assertTrue(matcher.find());
assertEquals("state", matcher.group(FIELD_NAME_GROUP));
assertEquals("!=", matcher.group(COMPARATOR_GROUP));
assertEquals("new", matcher.group(FIELD_VALUE_GROUP));
}
@Test
public void findOrOperand() {
final String expression = "state != new or";
final Matcher matcher = Query.EXPRESSION_PATTERN.matcher(expression);
assertTrue(matcher.find());
assertEquals("state", matcher.group(FIELD_NAME_GROUP));
assertEquals("!=", matcher.group(COMPARATOR_GROUP));
assertEquals("new", matcher.group(FIELD_VALUE_GROUP));
assertEquals(Operand.OR.getRegexExpression(), matcher.group(OPERAND_GROUP));
}
@Test
public void findAndOperand() {
final String expression = "state != new and";
final Matcher matcher = Query.EXPRESSION_PATTERN.matcher(expression);
assertTrue(matcher.find());
assertEquals("state", matcher.group(FIELD_NAME_GROUP));
assertEquals("!=", matcher.group(COMPARATOR_GROUP));
assertEquals("new", matcher.group(FIELD_VALUE_GROUP));
assertEquals(Operand.AND.getRegexExpression(), matcher.group(OPERAND_GROUP));
}
@Test
public void matchQuery() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = RUNNABLE");
assertTrue(query.match(element));
}
@Test
public void matchQueryWithOperandAndNotOtherExpression() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = RUNNABLE and ");
assertTrue(query.match(element));
}
@Test
public void matchQueryWithOperandAndOtherExpression() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = RUNNABLE and number = 20");
assertTrue(query.match(element));
}
@Test
public void matchQueryWithOperandAndOtherExpressionUsingLessOrEqual() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = RUNNABLE and number <= 20");
assertTrue(query.match(element));
}
@Test
public void matchQueryWithOperandAndOtherExpressionUsingLess() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = RUNNABLE and number < 21");
assertTrue(query.match(element));
}
@Test
public void matchQueryWithOperandAndOtherExpressionUsingGreaterOrEqual() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = RUNNABLE and number >= 20");
assertTrue(query.match(element));
}
@Test
public void matchQueryWithOperandAndOtherExpressionUsingGreater() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = RUNNABLE and number > 19");
assertTrue(query.match(element));
}
@Test
public void doesntMatchQuery() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = NEW");
assertFalse(query.match(element));
}
@Test
public void doesntMatchQueryWithOperandAndNotOtherExpression() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = NEW and ");
assertFalse(query.match(element));
}
@Test
public void doesntMatchQueryWithOperandAndOtherExpression() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = NEW and number = 20");
assertFalse(query.match(element));
}
@Test
public void doesntMatchQueryWithOperandAndOtherExpressionUsingLess() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = NEW and number < 20");
assertFalse(query.match(element));
}
@Test
public void doesntMatchQueryWithOperandAndOtherExpressionUsingLessOrEqual() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = NEW and number <= 19");
assertFalse(query.match(element));
}
@Test
public void doesntMatchQueryWithOperandAndOtherExpressionUsingGreater() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = NEW and number > 20");
assertFalse(query.match(element));
}
@Test
public void doesntMatchQueryWithOperandAndOtherExpressionUsingGreaterOrEqual() throws UnparsableQueryException {
final ThreadElement element = new ThreadElement();
element.setState(Thread.State.RUNNABLE);
element.setNumber(20);
final Query<ThreadElement> query = Query.create(ThreadElement.class);
query.parse("state = NEW and number > 21");
assertFalse(query.match(element));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.