hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
1e2f97649a3f0d024899c07aaf09f6f42d6fd711
18,112
package se.lth.cs.palcom.updatedistributionservice; import java.io.IOException; import java.util.HashMap; import java.util.Set; import ist.palcom.resource.descriptor.Command; import ist.palcom.resource.descriptor.DeviceID; import ist.palcom.resource.descriptor.PRDService; import ist.palcom.resource.descriptor.ServiceID; import se.lth.cs.palcom.communication.connection.Readable; import se.lth.cs.palcom.communication.connection.Writable; import se.lth.cs.palcom.device.AbstractDevice; import se.lth.cs.palcom.logging.Logger; import se.lth.cs.palcom.service.AbstractSimpleService; import se.lth.cs.palcom.service.ServiceTools; import se.lth.cs.palcom.service.command.CommandServiceProtocol; import se.lth.cs.palcom.service.distribution.UnicastDistribution; import se.lth.cs.palcom.updaterservice.UpdaterService; /** * Keeps track of updates and distributes them to devices running {@link UpdaterService} in monitoring mode (PalComStarters) * @author Christian Hernvall */ public class UpdateDistributionService extends AbstractSimpleService { public static final DeviceID CREATOR = new DeviceID("X:mojo"); public static final ServiceID SERVICE_VERSION = new ServiceID(CREATOR, "UPD1.0.0", CREATOR, "UPD1.0.0"); public static final String SERVICE_NAME = "UpdateDistributionService"; private static final String COMMAND_IN_BROADCAST_UPDATE_SINGLE_DEVICE_TYPE = "broadcast update for single device type"; private static final String COMMAND_IN_BROADCAST_UPDATE_MULTIPLE_DEVICES = "broadcast update for multiple device types"; private static final String COMMAND_IN_LIST_LATEST_UPDATES = "list the latest updates"; private static final String COMMAND_IN_LIST_ALL_UPDATES = "list all updates"; private static final String COMMAND_IN_UPDATE_CONTENT_REQUEST = se.lth.cs.palcom.updaterservice.UpdaterService.COMMAND_OUT_UPDATE_CONTENT_REQUEST; private static final String COMMAND_IN_CHECK_UPDATE_SERVER = se.lth.cs.palcom.updaterservice.UpdaterService.COMMAND_OUT_CHECK_UPDATE_SERVER; private static final String COMMAND_IN_CHECK_LATEST_VERSION = se.lth.cs.palcom.updaterservice.UpdaterService.COMMAND_OUT_CHECK_LATEST_VERSION; private static final String COMMAND_IN_BENCHMARK_END = se.lth.cs.palcom.updaterservice.UpdaterService.COMMAND_OUT_BENCHMARK_END; private static final String COMMAND_IN_ADD_UPDATE = "add update"; private static final String COMMAND_IN_REMOVE_SINGLE_UPDATE = "remove single update"; private static final String COMMAND_IN_REMOVE_ALL_OLD_UPDATES = "remove all old updates"; private static final String COMMAND_IN_REMOVE_ALL_UPDATES = "remove all updates"; private static final String COMMAND_OUT_UPDATE_DEVICE_TYPES = se.lth.cs.palcom.updaterservice.UpdaterService.COMMAND_IN_UPDATE_DEVICE_TYPES; private static final String COMMAND_OUT_UPDATE_DATA = se.lth.cs.palcom.updaterservice.UpdaterService.COMMAND_IN_UPDATE_DATA; private static final String COMMAND_OUT_CHECK_UPDATE_SERVER_CONFIRM = se.lth.cs.palcom.updaterservice.UpdaterService.COMMAND_IN_CHECK_UPDATE_SERVER_CONFIRM; private static final String COMMAND_OUT_STATUS = "status reply"; private static final String PARAM_VALUE_SEPARATOR = se.lth.cs.palcom.updaterservice.UpdaterService.PARAM_VALUE_SEPARATOR; private static final String PARAM_IMPLEMENTATION = se.lth.cs.palcom.updaterservice.UpdaterService.PARAM_IMPLEMENTATION; private static final String PARAM_VERSION = se.lth.cs.palcom.updaterservice.UpdaterService.PARAM_VERSION; private static final String PARAM_UPDATE_CONTENT = se.lth.cs.palcom.updaterservice.UpdaterService.PARAM_UPDATE_CONTENT; private static final String PARAM_DEVICE_TYPE = se.lth.cs.palcom.updaterservice.UpdaterService.PARAM_DEVICE_TYPE; private static final String PARAM_VERSION_ENTRY_UNKNOWN = se.lth.cs.palcom.updaterservice.UpdaterService.PARAM_NO_ENTRY; private static final String PARAM_STATUS = "status"; private long benchmark; private HashMap<String, String> implementationSuffix; private UpdateStore updateStore; public UpdateDistributionService(AbstractDevice container) { this(container, ServiceTools.getNextInstance(SERVICE_VERSION)); } public UpdateDistributionService(AbstractDevice container, String instance) { super(container, SERVICE_VERSION, "P1", "v0.0.1", "UpdateDistributionService", instance, "Distributes updates to PalCom devices", new UnicastDistribution(true)); implementationSuffix = new HashMap<String, String>(); implementationSuffix.put("java", ".jar"); try { updateStore = new UpdateStore(getServiceRoot()); } catch (IOException e) { Logger.log("Could not access service file system. Exiting.", Logger.CMP_SERVICE, Logger.LEVEL_ERROR); stop(); return; } if(!updateStore.parseUpdateFileSystem(implementationSuffix.keySet())) { stop(); return; } CommandServiceProtocol sp = getProtocolHandler(); Command broadcastSingleUpdateCmd = new Command(COMMAND_IN_BROADCAST_UPDATE_SINGLE_DEVICE_TYPE, "Upload specified update and send information about it to all connected clients.", Command.DIRECTION_IN); broadcastSingleUpdateCmd.addParam(PARAM_DEVICE_TYPE, "text/plain"); broadcastSingleUpdateCmd.addParam(PARAM_VERSION, "text/plain"); broadcastSingleUpdateCmd.addParam(PARAM_UPDATE_CONTENT, "application/x-jar"); sp.addCommand(broadcastSingleUpdateCmd); Command broadcastMultipleUpdateCmd = new Command(COMMAND_IN_BROADCAST_UPDATE_MULTIPLE_DEVICES, "Send information about the latest updates of all device types to all connected clients.", Command.DIRECTION_IN); sp.addCommand(broadcastMultipleUpdateCmd); Command addUpdateCmd = new Command(COMMAND_IN_ADD_UPDATE, "Add jar to database", Command.DIRECTION_IN); addUpdateCmd.addParam(PARAM_DEVICE_TYPE, "text/plain"); addUpdateCmd.addParam(PARAM_VERSION, "text/plain"); addUpdateCmd.addParam(PARAM_UPDATE_CONTENT, "application/x-jar"); sp.addCommand(addUpdateCmd); Command listLatestUpdatesCmd = new Command(COMMAND_IN_LIST_LATEST_UPDATES, "Lists the latest updates for all device types.", Command.DIRECTION_IN); sp.addCommand(listLatestUpdatesCmd); Command listAllUpdatesCmd = new Command(COMMAND_IN_LIST_ALL_UPDATES, "Lists all updates present.", Command.DIRECTION_IN); sp.addCommand(listAllUpdatesCmd); Command removeUpdateCmd = new Command(COMMAND_IN_REMOVE_SINGLE_UPDATE, "Remove a single update.", Command.DIRECTION_IN); removeUpdateCmd.addParam(PARAM_IMPLEMENTATION, "text/plain"); removeUpdateCmd.addParam(PARAM_DEVICE_TYPE, "text/plain"); removeUpdateCmd.addParam(PARAM_VERSION, "text/plain"); sp.addCommand(removeUpdateCmd); Command removeAllOldUpdatesCmd = new Command(COMMAND_IN_REMOVE_ALL_OLD_UPDATES, "Remove all updates except the latest for each device type.", Command.DIRECTION_IN); sp.addCommand(removeAllOldUpdatesCmd); Command removeAllUpdatesCmd = new Command(COMMAND_IN_REMOVE_ALL_UPDATES, "Remove all updates.", Command.DIRECTION_IN); sp.addCommand(removeAllUpdatesCmd); Command updateContentRequestCmd = new Command(COMMAND_IN_UPDATE_CONTENT_REQUEST, "Update content request.", Command.DIRECTION_IN); updateContentRequestCmd.addParam(PARAM_DEVICE_TYPE, "text/plain"); updateContentRequestCmd.addParam(PARAM_VERSION, "text/plain"); sp.addCommand(updateContentRequestCmd); Command checkUpdateServerCmd = new Command(COMMAND_IN_CHECK_UPDATE_SERVER, "Confirmation request from client.", Command.DIRECTION_IN); sp.addCommand(checkUpdateServerCmd); Command latestVersionRequestCmd = new Command(COMMAND_IN_CHECK_LATEST_VERSION, "Latest version request from client.", Command.DIRECTION_IN); latestVersionRequestCmd.addParam(PARAM_DEVICE_TYPE, "text/plain"); sp.addCommand(latestVersionRequestCmd); Command statusCmd = new Command(COMMAND_OUT_STATUS, "Generic status reply.", Command.DIRECTION_OUT); statusCmd.addParam(PARAM_STATUS, "text/plain"); sp.addCommand(statusCmd); Command updateCmd = new Command(COMMAND_OUT_UPDATE_DEVICE_TYPES, "", Command.DIRECTION_OUT); updateCmd.addParam(PARAM_DEVICE_TYPE, "text/plain"); updateCmd.addParam(PARAM_VERSION, "text/plain"); sp.addCommand(updateCmd); Command updateContentCmd = new Command(COMMAND_OUT_UPDATE_DATA, "Reply with content to content request.", Command.DIRECTION_OUT); updateContentCmd.addParam(PARAM_DEVICE_TYPE, "text/plain"); updateContentCmd.addParam(PARAM_VERSION, "text/plain"); updateContentCmd.addParam(PARAM_UPDATE_CONTENT, "application/x-jar"); sp.addCommand(updateContentCmd); Command confirmReqCmd = new Command(COMMAND_OUT_CHECK_UPDATE_SERVER_CONFIRM, "Confirmation reply to confirmation request.", Command.DIRECTION_OUT); sp.addCommand(confirmReqCmd); Command benchmarkEndCmd = new Command(COMMAND_IN_BENCHMARK_END, "benchmark end", Command.DIRECTION_IN); sp.addCommand(benchmarkEndCmd); } @Override protected void invoked(Readable connection, Command command) { if (connection instanceof Writable) { Writable conn = (Writable) connection; if(command.getID().equals(COMMAND_IN_BROADCAST_UPDATE_SINGLE_DEVICE_TYPE)) { benchmark = System.currentTimeMillis(); Logger.log("Benchmarking time to update. Current time: " + benchmark, Logger.CMP_SERVICE, Logger.LEVEL_BULK); String implementation = "java"; //TODO hard coded implementation String deviceType = UpdaterService.toUTF8String(command.findParam(PARAM_DEVICE_TYPE).getData()); String version = UpdaterService.toUTF8String(command.findParam(PARAM_VERSION).getData()); byte[] content = command.findParam(PARAM_UPDATE_CONTENT).getData(); Logger.log("Saving update " + deviceType + "(v" + version + ")", Logger.CMP_SERVICE, Logger.LEVEL_INFO); if (saveExecutable(implementation, deviceType, version, content.clone())) { Logger.log("Broadcasting update info to devices.", Logger.CMP_SERVICE, Logger.LEVEL_INFO); announceNewUpdate(new String[] {implementation}, new String[] {deviceType}, new String[] {version}); } else { return; } } else if (command.getID().equals(COMMAND_IN_UPDATE_CONTENT_REQUEST)) { String implementation = "java"; // TODO hard coded implementation String deviceType = UpdaterService.toUTF8String(command.findParam(PARAM_DEVICE_TYPE).getData()); String version = UpdaterService.toUTF8String(command.findParam(PARAM_VERSION).getData()); if(replyWithJar(implementation, deviceType, version, conn)) { Logger.log("Replying with update content (v" + version + ") to " + deviceType + ".", Logger.CMP_SERVICE, Logger.LEVEL_INFO); } else { Logger.log("Could not reply with update content (v" + version + ") to " + deviceType + ".", Logger.CMP_SERVICE, Logger.LEVEL_WARNING); } } else if (command.getID().equals(COMMAND_IN_CHECK_UPDATE_SERVER)) { Logger.log("Replying to a device checking its connection to me.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG); replyToConfirmRequest(conn); } else if (command.getID().equals(COMMAND_IN_CHECK_LATEST_VERSION)) { Logger.log("Replying with latest version info to device.", Logger.CMP_SERVICE, Logger.LEVEL_INFO); String deviceTypes = UpdaterService.toUTF8String(command.findParam(PARAM_DEVICE_TYPE).getData()); replyWithLatestVersion(conn, deviceTypes); } else if (command.getID().equals(COMMAND_IN_BENCHMARK_END)) { Logger.log("Got benchmark end command. Current time: " + System.currentTimeMillis(), Logger.CMP_SERVICE, Logger.LEVEL_BULK); Logger.log("Difference between start and now: " + (System.currentTimeMillis() - benchmark), Logger.CMP_SERVICE, Logger.LEVEL_BULK); } else if (command.getID().equals(COMMAND_IN_ADD_UPDATE)) { String implementation = "java"; //TODO hard coded implementation String deviceType = UpdaterService.toUTF8String(command.findParam(PARAM_DEVICE_TYPE).getData()); String version = UpdaterService.toUTF8String(command.findParam(PARAM_VERSION).getData()); byte[] content = command.findParam(PARAM_UPDATE_CONTENT).getData(); Logger.log("Adding " + deviceType + " version " + version + " to update database.", Logger.CMP_SERVICE, Logger.LEVEL_INFO); if (!saveExecutable(implementation, deviceType, version, content)) return; } else if (command.getID().equals(COMMAND_IN_BROADCAST_UPDATE_MULTIPLE_DEVICES)) { benchmark = System.currentTimeMillis(); Logger.log("Benchmarking time to update. Current time: " + benchmark, Logger.CMP_SERVICE, Logger.LEVEL_BULK); Set<UpdateEntry> latestUpdates = updateStore.getLatestUpdates(); int size = latestUpdates.size(); String[] implementationTypes = new String[size]; String[] deviceTypes = new String[size]; String[] versions = new String[size]; String msg = "Broadcasting update for device types:"; int i = 0; for (UpdateEntry updateEntry: latestUpdates) { implementationTypes[i] = updateEntry.implementation; deviceTypes[i] = updateEntry.deviceType; versions[i] = updateEntry.version; msg += " " + deviceTypes[i]; i++; } Logger.log(msg, Logger.CMP_SERVICE, Logger.LEVEL_INFO); announceNewUpdate(implementationTypes, deviceTypes, versions); } else if (command.getID().equals(COMMAND_IN_LIST_LATEST_UPDATES)) { String latestUpdates = updateStore.getLatestUpdatesInText(); Command reply = getProtocolHandler().findCommand(COMMAND_OUT_STATUS); reply.findParam(PARAM_STATUS).setData(latestUpdates.getBytes()); sendTo(conn, reply); } else if (command.getID().equals(COMMAND_IN_LIST_ALL_UPDATES)) { String allUpdates = updateStore.getAllUpdatesInText(); Command reply = getProtocolHandler().findCommand(COMMAND_OUT_STATUS); reply.findParam(PARAM_STATUS).setData(allUpdates.getBytes()); sendTo(conn, reply); } else if (command.getID().equals(COMMAND_IN_REMOVE_SINGLE_UPDATE)) { String implementation = UpdaterService.toUTF8String(command.findParam(PARAM_IMPLEMENTATION).getData()); String deviceType = UpdaterService.toUTF8String(command.findParam(PARAM_DEVICE_TYPE).getData()); String version = UpdaterService.toUTF8String(command.findParam(PARAM_VERSION).getData()); updateStore.deleteUpdate(implementation, deviceType, version); } else if (command.getID().equals(COMMAND_IN_REMOVE_ALL_OLD_UPDATES)) { updateStore.deleteAllOldUpdates(); } else if (command.getID().equals(COMMAND_IN_REMOVE_ALL_UPDATES)) { updateStore.deleteAllUpdates(); } } } private boolean saveExecutable(String implementation, String deviceType, String version, byte[] content) { return updateStore.saveUpdate(implementation, deviceType, version, implementationSuffix.get(implementation), content); } private void replyWithLatestVersion(Writable conn, String deviceTypes) { String[] splitDeviceTypes = deviceTypes.split(PARAM_VALUE_SEPARATOR); String versions = null; for (String deviceType: splitDeviceTypes) { UpdateEntry updateEntry = updateStore.getLatestUpdate("java", deviceType); String latestVersion = null; if (updateEntry == null) { latestVersion = PARAM_VERSION_ENTRY_UNKNOWN; } else { latestVersion = updateEntry.version; } if (versions != null) { versions += PARAM_VALUE_SEPARATOR; } else { versions = ""; } versions += latestVersion; } if (versions != null) { Command reply = getProtocolHandler().findCommand(COMMAND_OUT_UPDATE_DEVICE_TYPES); reply.findParam(PARAM_DEVICE_TYPE).setData(deviceTypes.getBytes()); reply.findParam(PARAM_VERSION).setData(versions.getBytes()); sendTo(conn, reply); } } private void replyToConfirmRequest(Writable conn) { Command reply = getProtocolHandler().findCommand(COMMAND_OUT_CHECK_UPDATE_SERVER_CONFIRM); sendTo(conn, reply); } private boolean replyWithJar(String implementation, String deviceType, String version, Writable conn) { UpdateEntry updateEntry = updateStore.getUpdate(implementation, deviceType, version); if (updateEntry == null) { Logger.log("Could not find update: " + implementation + " " + deviceType + " " + version, Logger.CMP_SERVICE, Logger.LEVEL_WARNING); return false; } byte[] content; try { content = updateEntry.executableFile.getContents(); } catch (IOException e1) { Logger.log("Could not access jar with version " + version + " for the client.", Logger.CMP_SERVICE, Logger.LEVEL_WARNING); return false; } if (content == null) { Logger.log("Could not find jar with version " + version + " for the client.", Logger.CMP_SERVICE, Logger.LEVEL_WARNING); return false; } Logger.log("Sending " + deviceType + " " + version + " content.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG); Command reply = getProtocolHandler().findCommand(COMMAND_OUT_UPDATE_DATA); reply.findParam(PARAM_DEVICE_TYPE).setData(deviceType.getBytes()); reply.findParam(PARAM_VERSION).setData(version.getBytes()); reply.findParam(PARAM_UPDATE_CONTENT).setData(content); try { blockingSendTo(conn, reply); } catch (InterruptedException e) { Logger.log("Could not send update data to client: SEND_ERROR", Logger.CMP_SERVICE, Logger.LEVEL_WARNING); return false; } return true; } private void announceNewUpdate(String[] implementationTypes, String[] deviceTypes, String[] versions) { //TODO send implementation types if (deviceTypes.length == 0) { Logger.log("No updates to announce. Use \"" + COMMAND_IN_ADD_UPDATE + "\" command to add an update.", Logger.CMP_SERVICE, Logger.LEVEL_INFO); return; } Command cmd = getProtocolHandler().findCommand(COMMAND_OUT_UPDATE_DEVICE_TYPES); String concDeviceTypes = null; String concVersions = null; for (int i = 0; i < deviceTypes.length; ++i) { if (concVersions != null) { concDeviceTypes += PARAM_VALUE_SEPARATOR; concVersions += PARAM_VALUE_SEPARATOR; } else { concDeviceTypes = ""; concVersions = ""; } concDeviceTypes += deviceTypes[i]; concVersions += versions[i]; } cmd.findParam(PARAM_DEVICE_TYPE).setData(concDeviceTypes.getBytes()); cmd.findParam(PARAM_VERSION).setData(concVersions.getBytes()); sendToAll(cmd); } public void start() { setStatus(PRDService.FULLY_OPERATIONAL); super.start(); } }
53.270588
210
0.77617
76b523057ee8de81782053a246f5b43273a4aab6
1,767
/* * Copyright 2016-2019 Tim Boudreau, Frédéric Yvon Vinet * * 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.nemesis.antlr.refactoring; import static java.lang.annotation.ElementType.FIELD; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.SOURCE; import java.lang.annotation.Target; import org.antlr.v4.runtime.Lexer; import org.netbeans.modules.refactoring.api.AbstractRefactoring; import org.netbeans.modules.refactoring.spi.RefactoringPlugin; import org.netbeans.modules.refactoring.spi.ui.RefactoringUI; /** * Unused at present. * * @author Tim Boudreau */ @Retention(SOURCE) @Target(FIELD) public @interface CustomRefactoringRegistration { int[] enabledOnTokens(); String mimeType(); String name(); String description() default ""; Class<? extends AbstractRefactoring> refactoring() default AbstractRefactoring.class; Class<? extends RefactoringPlugin> plugin(); Class<? extends RefactoringUI> ui() default RefactoringUI.class; Class<? extends Lexer> lexer(); int actionPosition() default 1000; String keybinding() default ""; String languageHierarchyPackage() default ""; boolean publicRefactoringPluginClass() default false; }
29.45
89
0.75382
763892f986362a488d778d1e9d15f861af5a1023
1,026
package org.maximkir.shcf4j.api.conn.ssl; import javax.net.ssl.SSLEngine; import javax.net.ssl.X509ExtendedTrustManager; import java.net.Socket; import java.security.cert.X509Certificate; class TrustAllCertsTrustManager extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
22.8
96
0.730019
74d0eb4f433a4e43a3736ae4f21b190112e99b0a
4,409
/* * Copyright 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 ai.djl.paddlepaddle.engine; import ai.djl.Device; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrayAdapter; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.paddlepaddle.jni.JniUtils; import ai.djl.util.NativeResource; import java.nio.ByteBuffer; /** {@code PpNDArray} is the PaddlePaddle implementation of {@link NDArray}. */ public class PpNDArray extends NativeResource<Long> implements NDArrayAdapter { private PpNDManager manager; // we keep the data to prevent GC from early collecting native memory private ByteBuffer data; private Shape shape; private DataType dataType; /** * Constructs an PpNDArray from a native handle (internal. Use {@link NDManager} instead). * * @param manager the manager to attach the new array to * @param data bytebuffer that holds the native memory * @param handle the pointer to the native MxNDArray memory */ public PpNDArray(PpNDManager manager, ByteBuffer data, long handle) { super(handle); this.manager = manager; this.data = data; manager.attachInternal(getUid(), this); } /** * Sets the Level-of-Detail field of the NDArray. * * <p>checkout https://www.bookstack.cn/read/PaddlePaddle-1.3-fluid/27.md * * @param lod the Level-of-Detail representation */ public void setLoD(long[][] lod) { JniUtils.setNdLoD(this, lod); } /** * Gets the Level-of-Detail field of the NDArray. * * @return the Level-of-Detail representation */ public long[][] getLoD() { return JniUtils.getNdLoD(this); } /** {@inheritDoc} */ @Override public NDManager getManager() { return manager; } /** {@inheritDoc} */ @Override public String getName() { return JniUtils.getNameFromNd(this); } /** {@inheritDoc} */ @Override public void setName(String name) { JniUtils.setNdName(this, name); } /** {@inheritDoc} */ @Override public DataType getDataType() { if (dataType == null) { dataType = JniUtils.getDTypeFromNd(this); } return dataType; } /** {@inheritDoc} */ @Override public Device getDevice() { return Device.cpu(); } /** {@inheritDoc} */ @Override public Shape getShape() { if (shape == null) { shape = JniUtils.getShapeFromNd(this); } return shape; } /** {@inheritDoc} */ @Override public void attach(NDManager manager) { detach(); this.manager = (PpNDManager) manager; manager.attachInternal(getUid(), this); } /** {@inheritDoc} */ @Override public void tempAttach(NDManager manager) { detach(); NDManager original = this.manager; this.manager = (PpNDManager) manager; manager.tempAttachInternal(original, getUid(), this); } /** {@inheritDoc} */ @Override public void detach() { manager.detachInternal(getUid()); manager = PpNDManager.getSystemManager(); } /** {@inheritDoc} */ @Override public ByteBuffer toByteBuffer() { if (data == null) { data = JniUtils.getByteBufferFromNd(this); } data.rewind(); return data; } /** {@inheritDoc} */ @Override public String toString() { if (isReleased()) { return "This array is already closed"; } return toDebugString(); } /** {@inheritDoc} */ @Override public void close() { Long pointer = handle.getAndSet(null); if (pointer != null) { JniUtils.deleteNd(pointer); data = null; } } }
27.04908
120
0.617147
fc1170df1a3e8ea6249a2d66687e7132b9d05379
1,687
/** * ***************************************************************************** * * Copyright (c) 2012 Oracle Corporation. * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Winston Prakash * ****************************************************************************** */ package org.jvnet.hudson.plugins.m2release; import hudson.maven.MavenBuild; import hudson.maven.MavenModule; import hudson.maven.MavenModuleSet; import hudson.maven.MavenModuleSetBuild; import java.io.IOException; import org.jvnet.hudson.test.HudsonTestCase; public class HudsonMavenTestCase extends HudsonTestCase { /** * Creates a empty Maven project with an unique name. * * @see #configureDefaultMaven() */ protected MavenModuleSet createMavenProject() throws IOException { return createMavenProject(createUniqueProjectName()); } /** * Creates a empty Maven project with the given name. * * @see #configureDefaultMaven() */ protected MavenModuleSet createMavenProject(String name) throws IOException { return hudson.createProject(MavenModuleSet.class, name); } public MavenModuleSetBuild buildAndAssertSuccess(MavenModuleSet job) throws Exception { return assertBuildStatusSuccess(job.scheduleBuild2(0)); } public MavenBuild buildAndAssertSuccess(MavenModule job) throws Exception { return assertBuildStatusSuccess(job.scheduleBuild2(0)); } }
31.830189
91
0.658566
9fa21ad2ccf3fb42071d7efe311d41babc736136
136
package com.djs.learn.behavioral.interpreter; public interface InterpreterInterface { String interpreter(ContextData contextData); }
17
45
0.830882
510ce6e4336025f02b4958b92b1c35b45423a65b
1,559
package es.tid.fiware.iot.ac.dao; /* * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U * * 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 es.tid.fiware.iot.ac.model.Policy; import java.util.Collection; public interface PolicyDao { Policy createPolicy(Policy policy); Policy loadPolicy(String tenant, String subject, String id); Collection<Policy> getPolicies(String tenant, String subject); Policy updatePolicy(Policy policy); Policy deletePolicy(Policy policy); /** * Removes the Tenant and all related objects: Tenant's Subjects and * Policies. */ void deleteFromTenant(String tenant); /** * Removes the Subject from the Tenant, and its Policies. */ void deleteFromSubject(String tenant, String subject); }
31.18
72
0.730597
4087a6638349a57455865eac6e1cf9d88b3f670a
1,346
/* * Copyright 2020 DataStax, 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.datastax.fallout.runner; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.auto.value.AutoValue; import com.datastax.fallout.service.core.TestRun; import com.datastax.fallout.service.core.TestRunIdentifier; @AutoValue @AutoValue.CopyAnnotations @JsonSerialize(as = TestRunStatusUpdate.class) public abstract class TestRunStatusUpdate { public abstract TestRunIdentifier getTestRunIdentifier(); public abstract TestRun.State getState(); @JsonCreator static public TestRunStatusUpdate of(TestRunIdentifier testRunIdentifier, TestRun.State state) { return new AutoValue_TestRunStatusUpdate(testRunIdentifier, state); } }
33.65
98
0.780089
b647a459064626d896aa89d23ea8df28aa0fabb0
6,026
package com.github.smartbuf.utils; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * ASMUtils wraps some useful function for bytecode operation * * @author sulin * @since 2019-10-31 14:29:16 */ public final class ASMUtils { private static final ASMByteArrayClassLoader INSTANCE = new ASMByteArrayClassLoader(); private ASMUtils() { } /** * Add the default constructor for the specified {@link ClassWriter} * * @param cw The specified ClassWriter to add constructor */ public static void addConstructor(ClassWriter cw) { MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } /** * Add push byte/short/int instruction into stack * * @param mv The MethodVisitor used to add instruction * @param i The number to add */ public static void addIntInstruction(MethodVisitor mv, int i) { switch (i) { case 0: mv.visitInsn(Opcodes.ICONST_0); break; case 1: mv.visitInsn(Opcodes.ICONST_1); break; case 2: mv.visitInsn(Opcodes.ICONST_2); break; case 3: mv.visitInsn(Opcodes.ICONST_3); break; case 4: mv.visitInsn(Opcodes.ICONST_4); break; case 5: mv.visitInsn(Opcodes.ICONST_5); break; default: if (i < 128) { mv.visitIntInsn(Opcodes.BIPUSH, i); } else if (i < Short.MAX_VALUE) { mv.visitIntInsn(Opcodes.SIPUSH, i); } else { mv.visitLdcInsn(i); } } } /** * Add a box instruction into {@link MethodVisitor} by the specified primary class * * @param mv MethodVistor to add box instruction * @param ps The primary class */ public static void addBoxInstruction(MethodVisitor mv, Class<?> ps) { if (ps == boolean.class) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false); } else if (ps == byte.class) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false); } else if (ps == short.class) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false); } else if (ps == int.class) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false); } else if (ps == long.class) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false); } else if (ps == float.class) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false); } else if (ps == double.class) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false); } else if (ps == char.class) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;", false); } else { throw new IllegalArgumentException("[ps] must be primary type: " + ps); } } /** * Add an unbox instruction into {@link MethodVisitor} by the specified primary class * * @param mv MethodVisitor to add unbox instruction * @param ps The primary class */ public static void addUnboxInstruction(MethodVisitor mv, Class<?> ps) { if (ps == boolean.class) { mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z", false); } else if (ps == byte.class) { mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B", false); } else if (ps == short.class) { mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S", false); } else if (ps == int.class) { mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I", false); } else if (ps == long.class) { mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J", false); } else if (ps == float.class) { mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F", false); } else if (ps == double.class) { mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D", false); } else if (ps == char.class) { mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C", false); } else { throw new IllegalArgumentException("[ps] must be primary type: " + ps); } } /** * Load named class from the specified {@link ClassWriter} * * @param writer The specified ClassWriter instance * @param clsName class's name * @return Class instance */ public static Class<?> loadClass(ClassWriter writer, String clsName) { return INSTANCE.loadClass(clsName, writer.toByteArray()); } /** * Helps load byte[] as class */ static final class ASMByteArrayClassLoader extends ClassLoader { ASMByteArrayClassLoader() { super(ASMByteArrayClassLoader.class.getClassLoader()); } public synchronized Class<?> loadClass(String name, byte[] code) { return INSTANCE.defineClass(name, code, 0, code.length); } } }
39.12987
122
0.586791
7a49388f7dcb32718bf7723ca2b76d995f2a2772
865
// Copyright (C) 2021 Intel Corporation // // SPDX-License-Identifier: Apache-2.0 // package com.intel.dai.dsapi.pojo; import lombok.EqualsAndHashCode; import lombok.ToString; @ToString @EqualsAndHashCode(callSuper = true) public class NodeInventory extends FruHost { public Dimm CPU0_DIMM_A1; public Dimm CPU0_DIMM_B1; public Dimm CPU0_DIMM_C1; public Dimm CPU0_DIMM_D1; public Dimm CPU0_DIMM_E1; public Dimm CPU0_DIMM_F1; public Dimm CPU0_DIMM_G1; public Dimm CPU0_DIMM_H1; public Dimm CPU1_DIMM_A1; public Dimm CPU1_DIMM_B1; public Dimm CPU1_DIMM_C1; public Dimm CPU1_DIMM_D1; public Dimm CPU1_DIMM_E1; public Dimm CPU1_DIMM_F1; public Dimm CPU1_DIMM_G1; public Dimm CPU1_DIMM_H1; public NodeInventory() { } public NodeInventory(FruHost fruHost) { super(fruHost); } }
22.179487
44
0.724855
fe16c9749c769dbde2ee6b861c3b927198c04b92
2,040
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.metrics.web.servlet; import io.micrometer.core.instrument.LongTaskTimer; import io.micrometer.core.instrument.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * A contributor of {@link Tag Tags} for Spring MVC-based request handling. Typically used * by a {@link WebMvcTagsProvider} to provide tags in addition to its defaults. * * @author Andy Wilkinson * @since 2.3.0 */ public interface WebMvcTagsContributor { /** * Provides tags to be associated with metrics for the given {@code request} and * {@code response} exchange. * @param request the request * @param response the response * @param handler the handler for the request or {@code null} if the handler is * unknown * @param exception the current exception, if any * @return tags to associate with metrics for the request and response exchange */ Iterable<Tag> getTags(HttpServletRequest request, HttpServletResponse response, Object handler, Throwable exception); /** * Provides tags to be used by {@link LongTaskTimer long task timers}. * @param request the HTTP request * @param handler the handler for the request or {@code null} if the handler is * unknown * @return tags to associate with metrics recorded for the request */ Iterable<Tag> getLongRequestTags(HttpServletRequest request, Object handler); }
36.428571
96
0.751961
58879a9e9731bd782c2c1da28b9439868875025e
713
package com.javarush.test.level06.lesson08.task05; /* Класс StringHelper Cделать класс StringHelper, у которого будут 2 статических метода: String multiply(String s, int count) – возвращает строку повторенную count раз. String multiply(String s) – возвращает строку повторенную 5 раз. Пример: Амиго -> АмигоАмигоАмигоАмигоАмиго */ public class StringHelper { public static String multiply(String s) { String result = ""; for (int x=0; x<5; x++ ) result=result+s; return result; } public static String multiply(String s, int count) { String result = ""; for (int x=0; x<count; x++ ) result=result+s; return result; } }
24.586207
79
0.652174
e4e24a2bebc840c03402fa7ae3e5e16bfdca8cdb
8,343
package voldemort.rest; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LOCATION; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TRANSFER_ENCODING; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK; import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.log4j.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpResponse; import voldemort.store.stats.StoreStats; import voldemort.store.stats.Tracked; import voldemort.utils.ByteArray; import voldemort.versioning.VectorClock; import voldemort.versioning.Versioned; public class GetAllResponseSender extends RestResponseSender { private Map<ByteArray, List<Versioned<byte[]>>> versionedResponses; private String storeName; private static final Logger logger = Logger.getLogger(GetAllResponseSender.class); public GetAllResponseSender(MessageEvent messageEvent, Map<ByteArray, List<Versioned<byte[]>>> versionedResponses, String storeName) { super(messageEvent); this.versionedResponses = versionedResponses; this.storeName = storeName; } /** * Sends nested multipart response. Outer multipart wraps all the keys * requested. Each key has a separate multipart for the versioned values. */ @Override public void sendResponse(StoreStats performanceStats, boolean isFromLocalZone, long startTimeInMs) throws Exception { /* * Pay attention to the code below. Note that in this method we wrap a multiPart object with a mimeMessage. * However when writing to the outputStream we only send the multiPart object and not the entire * mimeMessage. This is intentional. * * In the earlier version of this code we used to create a multiPart object and just send that multiPart * across the wire. * * However, we later discovered that upon setting the content of a MimeBodyPart, JavaMail internally creates * a DataHandler object wrapping the object you passed in. The part's Content-Type header is not updated * immediately. In order to get the headers updated, one needs to to call MimeMessage.saveChanges() on the * enclosing message, which cascades down the MIME structure into a call to MimeBodyPart.updateHeaders() * on the body part. It's this updateHeaders call that transfers the content type from the * DataHandler to the part's MIME Content-Type header. * * To make sure that the Content-Type headers are being updated (without changing too much code), we decided * to wrap the multiPart in a mimeMessage, call mimeMessage.saveChanges() and then just send the multiPart. * This is to make sure multiPart's headers are updated accurately. */ MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); // multiPartKeys is the outer multipart MimeMultipart multiPartKeys = new MimeMultipart(); ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream(); for(Entry<ByteArray, List<Versioned<byte[]>>> entry: versionedResponses.entrySet()) { ByteArray key = entry.getKey(); String base64Key = RestUtils.encodeVoldemortKey(key.get()); String contentLocationKey = "/" + this.storeName + "/" + base64Key; // Create the individual body part - for each key requested MimeBodyPart keyBody = new MimeBodyPart(); try { // Add the right headers keyBody.addHeader(CONTENT_TYPE, "application/octet-stream"); keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); keyBody.addHeader(CONTENT_LOCATION, contentLocationKey); } catch(MessagingException me) { logger.error("Exception while constructing key body headers", me); keysOutputStream.close(); throw me; } // multiPartValues is the inner multipart MimeMultipart multiPartValues = new MimeMultipart(); for(Versioned<byte[]> versionedValue: entry.getValue()) { byte[] responseValue = versionedValue.getValue(); VectorClock vectorClock = (VectorClock) versionedValue.getVersion(); String eTag = RestUtils.getSerializedVectorClock(vectorClock); numVectorClockEntries += vectorClock.getVersionMap().size(); // Create the individual body part - for each versioned value of // a key MimeBodyPart valueBody = new MimeBodyPart(); try { // Add the right headers valueBody.addHeader(CONTENT_TYPE, "application/octet-stream"); valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); valueBody.addHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK, eTag); valueBody.setContent(responseValue, "application/octet-stream"); valueBody.addHeader(RestMessageHeaders.CONTENT_LENGTH, Integer.toString(responseValue.length)); multiPartValues.addBodyPart(valueBody); } catch(MessagingException me) { logger.error("Exception while constructing value body part", me); keysOutputStream.close(); throw me; } } try { // Add the inner multipart as the content of the outer body part keyBody.setContent(multiPartValues); multiPartKeys.addBodyPart(keyBody); } catch(MessagingException me) { logger.error("Exception while constructing key body part", me); keysOutputStream.close(); throw me; } } message.setContent(multiPartKeys); message.saveChanges(); try { multiPartKeys.writeTo(keysOutputStream); } catch(Exception e) { logger.error("Exception while writing mutipart to output stream", e); throw e; } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(keysOutputStream.toByteArray()); // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Write the response to the Netty Channel if(logger.isDebugEnabled()) { String keyStr = getKeysHexString(this.versionedResponses.keySet()); debugLog("GET_ALL", this.storeName, keyStr, startTimeInMs, System.currentTimeMillis(), numVectorClockEntries); } this.messageEvent.getChannel().write(response); if(performanceStats != null && isFromLocalZone) { recordStats(performanceStats, startTimeInMs, Tracked.GET_ALL); } keysOutputStream.close(); } }
45.342391
116
0.655999
0c4b0c55df5bd359154f7117fa9bafc838b9d270
2,620
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.logstreams.log; import io.zeebe.logstreams.impl.log.LogStreamBuilderImpl; import io.zeebe.util.health.HealthMonitorable; import io.zeebe.util.sched.ActorCondition; import io.zeebe.util.sched.AsyncClosable; import io.zeebe.util.sched.future.ActorFuture; /** * Represents a stream of events. New events are append to the end of the log. With {@link * LogStream#newLogStreamRecordWriter()} or {@link LogStream#newLogStreamBatchWriter()} new writers * can be created, which can be used to append new events to the log. * * <p>To read events, the {@link LogStream#newLogStreamReader()} ()} can be used. */ public interface LogStream extends AsyncClosable, AutoCloseable, HealthMonitorable { /** @return a new default LogStream builder */ static LogStreamBuilder builder() { return new LogStreamBuilderImpl(); } /** @return the partition id of the log stream */ int getPartitionId(); /** * Returns the name of the log stream. * * @return the log stream name */ String getLogName(); /** * @return a future, when successfully completed it returns the current commit position, or a * negative value if no entry is committed */ ActorFuture<Long> getCommitPositionAsync(); /** sets the new commit position * */ void setCommitPosition(long position); /** @return a future, when successfully completed it returns a newly created log stream reader */ ActorFuture<LogStreamReader> newLogStreamReader(); /** * @return a future, when successfully completed it returns a newly created log stream record * writer */ ActorFuture<LogStreamRecordWriter> newLogStreamRecordWriter(); /** * @return a future, when successfully completed it returns a newly created log stream batch * writer */ ActorFuture<LogStreamBatchWriter> newLogStreamBatchWriter(); /** * Registers for on commit updates. * * @param condition the condition which should be signalled. */ void registerOnCommitPositionUpdatedCondition(ActorCondition condition); /** * Removes the registered condition. * * @param condition the condition which should be removed */ void removeOnCommitPositionUpdatedCondition(ActorCondition condition); }
33.589744
99
0.739695
6b6444fae24bfc02f659391dcb8acd5b0cc5f583
2,848
package org.ehrbase.client.flattener; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class PathExtractorTest { @Test public void testPathExtractorWithAttribut() { PathExtractor cut = new PathExtractor("/context/end_time|value"); assertThat(cut.getAttributeName()).isEqualTo("value"); assertThat(cut.getChildName()).isEqualTo("end_time"); assertThat(cut.getChildPath()).isEqualTo("/context/end_time"); assertThat(cut.getParentPath()).isEqualTo("/context"); } @Test public void testPathExtractorOnlyAttribut() { PathExtractor cut = new PathExtractor("|value"); assertThat(cut.getAttributeName()).isEqualTo("value"); assertThat(cut.getChildName()).isEqualTo(""); assertThat(cut.getChildPath()).isEqualTo(""); assertThat(cut.getParentPath()).isEqualTo("/"); } @Test public void testPathExtractorWithNodeId() { PathExtractor cut = new PathExtractor("/context/other_context[at0001]/items[at0006]/items[openEHR-EHR-CLUSTER.sample_device.v1]"); assertThat(cut.getAttributeName()).isNull(); assertThat(cut.getChildName()).isEqualTo("items"); assertThat(cut.getChildPath()).isEqualTo("/context/other_context[at0001]/items[at0006]/items[openEHR-EHR-CLUSTER.sample_device.v1]"); assertThat(cut.getParentPath()).isEqualTo("/context/other_context[at0001]/items[at0006]"); } @Test public void testPathExtractorWithName() { PathExtractor cut = new PathExtractor("/content[openEHR-EHR-SECTION.adhoc.v1 and name/value='Allgemeine Angaben']"); assertThat(cut.getAttributeName()).isNull(); assertThat(cut.getChildName()).isEqualTo("content"); assertThat(cut.getChildPath()).isEqualTo("/content[openEHR-EHR-SECTION.adhoc.v1 and name/value='Allgemeine Angaben']"); assertThat(cut.getParentPath()).isEqualTo("/"); } @Test public void testPathExtractor() { PathExtractor cut = new PathExtractor("/context/end_time"); assertThat(cut.getAttributeName()).isNull(); assertThat(cut.getChildName()).isEqualTo("end_time"); assertThat(cut.getChildPath()).isEqualTo("/context/end_time"); assertThat(cut.getParentPath()).isEqualTo("/context"); } @Test public void testPathExtractorWithAttributeAndAtCode() { PathExtractor cut = new PathExtractor("/data[at0001]/events[at0002]/data[at0003]/items[at0004]|magnitude"); assertThat(cut.getAttributeName()).isEqualTo("magnitude"); assertThat(cut.getChildName()).isEqualTo("items"); assertThat(cut.getChildPath()).isEqualTo("/data[at0001]/events[at0002]/data[at0003]/items[at0004]"); assertThat(cut.getParentPath()).isEqualTo("/data[at0001]/events[at0002]/data[at0003]"); } }
44.5
141
0.693118
3579caf173becee578553eae46863891e497e607
3,902
package com.ecorengia.org.cinemaapp.data.model; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; import android.arch.persistence.room.TypeConverters; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Maps the videos that have been added to a movie. * * @see <a href="https://developers.themoviedb.org/3/movies/get-movie-videos">get-movie-videos</a> */ @Entity(tableName = "videos_table") public final class VideoListObject implements Parcelable { @PrimaryKey(autoGenerate = true) private int dbId; @SerializedName("id") private Integer id = null; @TypeConverters(VideoResult.VideoResultTypeConverter.class) @SerializedName("results") private List<VideoResult> results = null; /** * Get DB id * * @return dbId **/ public int getDbId() { return dbId; } public void setDbId(int dbId) { this.dbId = dbId; } public VideoListObject id(Integer id) { this.id = id; return this; } /** * Get id * * @return id **/ public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public VideoListObject results(List<VideoResult> results) { this.results = results; return this; } public VideoListObject addResultsItem(VideoResult resultsItem) { if (this.results == null) { this.results = new ArrayList<>(); } this.results.add(resultsItem); return this; } /** * Get results * * @return results **/ public List<VideoResult> getResults() { return results; } public void setResults(List<VideoResult> results) { this.results = results; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VideoListObject videoListObject = (VideoListObject) o; return Objects.equals(this.id, videoListObject.id) && Objects.equals(this.results, videoListObject.results); } @Override public int hashCode() { return Objects.hash(id, results); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class VideoListObject {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" results: ").append(toIndentedString(results)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } public void writeToParcel(Parcel out, int flags) { out.writeValue(id); out.writeValue(results); } public VideoListObject() { super(); } VideoListObject(Parcel in) { id = (Integer) in.readValue(getClass().getClassLoader()); results = (List<VideoResult>) in.readValue(VideoResult.class.getClassLoader()); } public int describeContents() { return 0; } public static final Parcelable.Creator<VideoListObject> CREATOR = new Parcelable.Creator<VideoListObject>() { public VideoListObject createFromParcel(Parcel in) { return new VideoListObject(in); } public VideoListObject[] newArray(int size) { return new VideoListObject[size]; } }; }
24.08642
113
0.604305
082ea2749d9fe70e1cea449660dd32d8834691a1
1,909
package test.base; import org.junit.Test; import org.junit.Before; import org.junit.After; /** * Test Tester. * * @author <Authors name> * @since <pre>5月 1, 2020</pre> * @version 1.0 */ public class TestTest { base.Test test; @Before public void before() throws Exception { test = new base.Test(); } @After public void after() throws Exception { } /** * * Method: testCtl() * */ @Test public void testTestCtl() throws Exception { //TODO: Test goes here... test.testCtl(); } /** * * Method: main(String[] args) * */ @Test public void testMain() throws Exception { //TODO: Test goes here... } /** * * Method: getBinaryFromInt(int i) * */ @Test public void testGetBinaryFromInt() throws Exception { //TODO: Test goes here... } /** * * Method: test1(int i) * */ @Test public void testTest1() throws Exception { //TODO: Test goes here... } /** * * Method: test2() * */ @Test public void testTest2() throws Exception { //TODO: Test goes here... } /** * * Method: workerCountOf(int c) * */ @Test public void testWorkerCountOf() throws Exception { //TODO: Test goes here... /* try { Method method = Test.getClass().getMethod("workerCountOf", int.class); method.setAccessible(true); method.invoke(<Object>, <Parameters>); } catch(NoSuchMethodException e) { } catch(IllegalAccessException e) { } catch(InvocationTargetException e) { } */ } /** * * Method: ctlOf(int rs, int wc) * */ @Test public void testCtlOf() throws Exception { //TODO: Test goes here... /* try { Method method = Test.getClass().getMethod("ctlOf", int.class, int.class); method.setAccessible(true); method.invoke(<Object>, <Parameters>); } catch(NoSuchMethodException e) { } catch(IllegalAccessException e) { } catch(InvocationTargetException e) { } */ } // 测试 git rebase 1 // 测试 git rebase 222 }
15.031496
77
0.626506
c805427f09f868b850899e90a7284ba6bcf69af1
7,987
package org.fzu.cs03.daoyun.mapper; import org.apache.ibatis.annotations.*; import org.fzu.cs03.daoyun.entity.DataDictionary; import org.springframework.stereotype.Component; import java.util.List; @Component @Mapper public interface DataDictionaryMapper { // 空格:字段实体映射 // @Insert("INSERT INTO user (role_id, username, password, email, creation_date, is_active, is_deleted) VALUES (#{roleId},#{userName}, #{password}, #{email}, #{createDate}, #{isActive}, #{isDeleted} )") // @Select("SELECT username FROM user where email = #{email}") // // @Insert("INSERT INTO data_dictionary (dict_code, dict_name, data_code, data_name, creation_date, is_deleted) VALUES (#{dictCode},#{dictName}, #{dataCode}, #{dataName}, #{createDate}, #{isDeleted} )") // void insertData(Long dictCode, String dictName, Long dataCode, String dataName, String createDate, boolean isDeleted); // // @Select("SELECT dict_code, dict_name, data_code, data_name FROM data_dictionary WHERE dict_code = #{dictCode} and is_deleted = 0 ") // List<DataDictionary> getDataDictionaryByDictCode(Long dictCode); // // @Delete("DELETE FROM data_dictionary WHERE dict_code = #{dictCode} AND data_code = #{dataCode} ") // void deleteData(Long dictCode, Long dataCode); // // @Select("SELECT * FROM (SELECT dict_code, dict_name, data_code, data_name FROM data_dictionary where dict_code = #{dictCode} ) as tmp WHERE tmp.data_name like '%${dataName}%' and tmp.is_deleted = 0") // List<DataDictionary> getDataDictionaryByDataName(Long dictCode, String dataName); // // // 存在性的判定都不考虑is_deleted的属性, (软)删除/(软)插入/(软)更新在service写逻辑, // @Select("SELECT COUNT(1) FROM data_dictionary WHERE dict_code = #{dictCode} AND data_code = #{dataCode}") // boolean existDataDictionary(Long dictCode,Long dataCode); // // @Select( "SELECT data_order FROM data_dictionary order by data_order DESC limit 1" ) // Long getLastDataOrder(Long dictCode, Long dataCode); // // void updateDataDictionary(Long dictCode, Long dataCode, ) //注意参数不用@Param("obj") List<Object> objs注解的话顺序要对应.????到底需要吗???待测试 @Insert("INSERT INTO data_dictionary_key " + "(dict_name, creation_date, is_deleted) " + "VALUES (#{dictName}, #{createDate}, #{isDeleted} )") void insertDictKey(String dictName, String createDate, boolean isDeleted); @Select("SELECT id " + "FROM data_dictionary_key " + "WHERE dict_name = #{dictName} AND is_deleted = 0") Long getDictKeyByDictName(String dictName); @Update("UPDATE data_dictionary_key " + "SET dict_name = #{newDictName} " + "WHERE id = #{dictId}") void updateDictKeyByDictId(Long dictId,String newDictName); // @Delete("DELETE FROM data_dictionary WHERE dict_code = #{dictCode} AND data_code = #{dataCode} ") @Update("UPDATE data_dictionary_key " + "SET is_deleted = 1 " + "WHERE id = #{dictId}") void deleteDictKeyByDictId(Long dictId); @Update("UPDATE data_dictionary_key " + "SET is_deleted = 0 " + "WHERE id = #{dictId}") void removeDictKeyDeletionMarkByDictId(Long dictId); //-------- delimeter of key and value @Insert("INSERT INTO data_dictionary_value " + "(dict_id, data_name, data_order, creation_date, is_deleted) " + "VALUES (#{dictId},#{dataName}, #{dataOrder}, #{createDate}, #{isDeleted} )") void insertDictValue(Long dictId, String dataName, Long dataOrder, String createDate, boolean isDeleted); @Select("SELECT id " + "FROM data_dictionary_value " + "WHERE dict_id = #{dictId} AND data_name = #{dataName} AND is_deleted = 0") Long getDictValueByDictIdAndDataName(Long dictId, String dataName); @Select("SELECT COUNT(1) " + "FROM data_dictionary_value " + "WHERE dict_id = #{dictId} AND is_deleted = 0") Long getDictValueNumber(Long dictId); @Select("SELECT k.dict_name, v.data_name " + "FROM data_dictionary_key AS k INNER JOIN data_dictionary_value AS v " + "ON k.id = v.dict_id AND k.is_deleted = 0 AND v.is_deleted = 0 " + "ORDER BY k.id,v.data_order ASC " + "LIMIT #{size} OFFSET #{offset} ") List<DataDictionary> getAllDataFromDataDictionary(Long size, Long offset); @Select("SELECT data_name " + "FROM data_dictionary_value " + "WHERE dict_id = #{dictId} and is_deleted = 0 " + "LIMIT #{size} OFFSET #{offset}") List<DataDictionary> getDictValuesByDictId(Long dictId,Long size, Long offset); @Select("SELECT tmp.data_name FROM (SELECT data_name, is_deleted, data_order " + "FROM data_dictionary_value WHERE dict_id = #{dictId} ) AS tmp " + "WHERE tmp.data_name like '%${dataName}%' AND tmp.is_deleted = 0 " + "ORDER BY tmp.data_order ASC " + "LIMIT #{size} OFFSET #{offset}") List<DataDictionary> getDictValuesByDictIdAndDataNameLikely(Long dictId, String dataName,Long size, Long offset); @Select("SELECT k.dict_name, v.data_name " + "FROM data_dictionary_key AS k INNER JOIN data_dictionary_value AS v " + "ON k.id = v.dict_id AND k.is_deleted = 0 AND v.is_deleted = 0 " + "WHERE v.data_name LIKE '%${dataName}%' " + "ORDER BY k.id,v.data_order ASC " + "LIMIT #{size} OFFSET #{offset}") List<DataDictionary> getDictValuesByDataNameLikely(String dataName,Long size, Long offset); @Select("SELECT k.dict_name, v.data_name " + "FROM data_dictionary_key AS k INNER JOIN data_dictionary_value AS v " + "ON k.id = v.dict_id AND k.is_deleted = 0 AND v.is_deleted = 0 " + "WHERE k.dict_name LIKE '%${dictName}%' " + "AND v.data_name LIKE '%${dataName}%' " + "ORDER BY k.id,v.data_order ASC " + "LIMIT #{size} OFFSET #{offset}") List<DataDictionary> getDictValuesByDictNameLikelyAndDataNameLikely(String dictName, String dataName,Long size, Long offset); @Select("SELECT k.dict_name, v.data_name " + "FROM data_dictionary_key AS k INNER JOIN data_dictionary_value AS v " + "ON k.id = v.dict_id AND k.is_deleted = 0 AND v.is_deleted = 0 " + "WHERE v.data_name = #{dataName} " + "ORDER BY k.id,v.data_order ASC " + "LIMIT #{size} OFFSET #{offset}") List<DataDictionary> getDictValuesByDataName(String dataName,Long size, Long offset); @Select("SELECT k.dict_name, v.data_name " + "FROM data_dictionary_key AS k INNER JOIN data_dictionary_value AS v " + "ON k.id = v.dict_id AND k.is_deleted = 0 AND v.is_deleted = 0 " + "WHERE k.dict_name = #{dictName} " + "AND v.data_name = #{dataName} " + "ORDER BY k.id,v.data_order ASC " + "LIMIT #{size} OFFSET #{offset}") List<DataDictionary> getDictValuesByDictNameLikelyAndDataName(String dictName, String dataName,Long size, Long offset); //加不加@param注解似乎都可以,可能是java8以后 默认添加javac -param? 于是方法的反射也可以获得方法名了? @Update("UPDATE data_dictionary_value " + "SET data_name = #{newDataName} " + "WHERE id = #{dataId} ") // void updateDictValueByDataId(@Param("dataId") Long dataId, @Param("newDataName") String newDataName); void updateDictValueByDataId(Long dataId, String newDataName); @Update("UPDATE data_dictionary_value " + "SET data_order = #{order} " + "WHERE id = #{dataId} ") void updateDictValueOrderByDataId(@Param("dataId") Long dataId, @Param("order") Long order); @Update("UPDATE data_dictionary_value " + "SET is_deleted = 1 " + "WHERE id = #{dataId}") void deleteDictValueByDataId(Long dataId); @Update("UPDATE data_dictionary_value " + "SET is_deleted = 0 " + "WHERE id = #{dataId} ") void removeDictValueDeletionMarkByDataId(Long dataId); }
47.541667
205
0.653687
29c7eb9270c685285a439442f723bb1c820ff04d
1,970
package org.usfirst.frc.team1806.robot.util; import java.util.LinkedList; public class SamplingFilter { private LinkedList<SamplingFilterValue> samplingBuffer; int maxSamples; Double currentRunningTotal; /** * Uses a {@link LinkedList} to sample a double value and average the last n samples. * @param numberOfSamples number of samples to average. */ public SamplingFilter(int numberOfSamples){ samplingBuffer = new LinkedList<SamplingFilterValue>(); maxSamples = numberOfSamples; } /** * Updates the sample list and returns the current average. * @param sample the current sample to add to the list to filter. * @return {@link Double}- The current sample to add to the list. */ public Double update(Double sample){ if(!samplingBuffer.isEmpty()){ currentRunningTotal = samplingBuffer.getLast().getRunningTotal(); if(samplingBuffer.size() >= maxSamples) { currentRunningTotal -= samplingBuffer.getFirst().getCurrentValue(); samplingBuffer.removeFirst(); } currentRunningTotal += sample; samplingBuffer.add(new SamplingFilterValue(sample, currentRunningTotal)); return currentRunningTotal / samplingBuffer.size(); } else{ samplingBuffer.add(new SamplingFilterValue(sample, sample)); return sample; } } /** * * @return The current average value of the samples. */ public Double getCurrentAverage(){ if (!samplingBuffer.isEmpty()){ return samplingBuffer.getLast().getRunningTotal() / samplingBuffer.size(); } else{ return 0.0; } } /** * Clears the sample list so it can start averaging from no samples. */ public void clear(){ samplingBuffer.clear(); } }
29.848485
89
0.610152
690111b32f5417ae68b6256c2559b73597677368
4,311
/* * #%L * utils-aop * %% * Copyright (C) 2016 - 2018 Gilles Landel * %% * 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. * #L% */ package fr.landel.utils.aop.observable; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.landel.utils.commons.DateUtils; /** * AOP observable for tests * * @since Dec 2, 2015 * @author Gilles * */ public class AOPObservable { private static final long TIMEOUT = 6 * DateUtils.MILLIS_PER_SECOND; private static final Logger LOGGER = LoggerFactory.getLogger(AOPObservable.class); /** * Test method (logging) */ public void test() { // Observable method, no parameter } /** * Test method with object parameter (logging) * * @param object * Object */ public void test(final Object object) { // Observable method, object parameter } /** * Test method with parameters (logging) * * @param p1 * String * @param p2 * Character * @param p3 * Number * @param p4 * Boolean * @param p5 * EnumTest * @param p6 * Date */ public void test(final String p1, final Character p2, final Number p3, final Boolean p4, final EnumTest p5, final Date p6) { // Observable method, boxed simple type } /** * Test method with primitive parameters (logging) * * @param p1 * Double * @param p2 * Float * @param p3 * Long * @param p4 * Integer * @param p5 * Short */ public void test(final double p1, final float p2, final long p3, final int p4, final short p5) { // Observable method, unboxed simple type } /** * Test method with primitive parameters (logging) * * @param p1 * Character * @param p2 * Boolean * @param p3 * Byte */ public void test(final char p1, final boolean p2, final byte p3) { // Observable method, unboxed simple type } /** * Test method with complex parameters (logging) * * @param p1 * String array * @param p2 * String array * @param p3 * String array * @param p4 * List of string * @param p5 * List of string * @param p6 * Iterator of string * @param p7 * Map * @param p8 * Map * @param p9 * Map */ public void test(final String[] p1, final String[] p2, final String[] p3, final List<String> p4, final List<String> p5, final Iterator<String> p6, final Map<String, String> p7, final Map<String, String> p8, final Map<String, String> p9) { // Observable method, array, list and map } /** * Test method that throws an exception */ public void testThrowable() { throw new UnsupportedOperationException(); } /** * Test sleep method (reach profiling timeout) * * @throws InterruptedException * If sleep failed */ public void testSleep() throws InterruptedException { LOGGER.info("START AOPObservable#testSleep: " + System.currentTimeMillis()); Thread.sleep(TIMEOUT); LOGGER.info("STOP AOPObservable#testSleep: " + System.currentTimeMillis()); } }
27.113208
131
0.547901
f81fb222101c36ba62c6eba1cdab86750c1a196d
15,144
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.services.resources; import org.jboss.logging.Logger; import org.jboss.resteasy.annotations.cache.NoCache; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.keycloak.OAuthErrorException; import org.keycloak.authorization.AuthorizationProvider; import org.keycloak.authorization.AuthorizationService; import org.keycloak.common.ClientConnection; import org.keycloak.common.util.KeycloakUriBuilder; import org.keycloak.common.util.ObjectUtil; import org.keycloak.events.EventBuilder; import org.keycloak.models.ClientModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.utils.ModelToRepresentation; import org.keycloak.protocol.LoginProtocol; import org.keycloak.protocol.LoginProtocolFactory; import org.keycloak.services.CorsErrorResponseException; import org.keycloak.services.clientregistration.ClientRegistrationService; import org.keycloak.services.managers.RealmManager; import org.keycloak.services.resource.RealmResourceProvider; import org.keycloak.services.resources.account.AccountLoader; import org.keycloak.services.util.CacheControlUtil; import org.keycloak.services.util.ResolveRelative; import org.keycloak.wellknown.WellKnownProvider; import org.keycloak.representations.idm.GroupRepresentation; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.OPTIONS; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ @Path("/realms") public class RealmsResource { protected static final Logger logger = Logger.getLogger(RealmsResource.class); @Context protected KeycloakSession session; @Context protected ClientConnection clientConnection; @Context private HttpRequest request; public static UriBuilder realmBaseUrl(UriInfo uriInfo) { UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder(); return realmBaseUrl(baseUriBuilder); } public static UriBuilder realmBaseUrl(UriBuilder baseUriBuilder) { return baseUriBuilder.path(RealmsResource.class).path(RealmsResource.class, "getRealmResource"); } public static UriBuilder accountUrl(UriBuilder base) { return base.path(RealmsResource.class).path(RealmsResource.class, "getAccountService"); } public static UriBuilder protocolUrl(UriInfo uriInfo) { return uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(RealmsResource.class, "getProtocol"); } public static UriBuilder protocolUrl(UriBuilder builder) { return builder.path(RealmsResource.class).path(RealmsResource.class, "getProtocol"); } public static UriBuilder clientRegistrationUrl(UriInfo uriInfo) { return uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(RealmsResource.class, "getClientsService"); } public static UriBuilder brokerUrl(UriInfo uriInfo) { return uriInfo.getBaseUriBuilder().path(RealmsResource.class).path(RealmsResource.class, "getBrokerService"); } public static UriBuilder wellKnownProviderUrl(UriBuilder builder) { return builder.path(RealmsResource.class).path(RealmsResource.class, "getWellKnown"); } @Path("{realm}/protocol/{protocol}") public Object getProtocol(final @PathParam("realm") String name, final @PathParam("protocol") String protocol) { RealmModel realm = init(name); LoginProtocolFactory factory = (LoginProtocolFactory)session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, protocol); if(factory == null){ logger.debugf("protocol %s not found", protocol); throw new NotFoundException("Protocol not found"); } EventBuilder event = new EventBuilder(realm, session, clientConnection); Object endpoint = factory.createProtocolEndpoint(realm, event); ResteasyProviderFactory.getInstance().injectProperties(endpoint); return endpoint; } /** * Returns a temporary redirect to the client url configured for the given {@code clientId} in the given {@code realmName}. * <p> * This allows a client to refer to other clients just by their client id in URLs, will then redirect users to the actual client url. * The client url is derived according to the rules of the base url in the client configuration. * </p> * * @param realmName * @param clientId * @return * @since 2.0 */ @GET @Path("{realm}/clients/{client_id}/redirect") public Response getRedirect(final @PathParam("realm") String realmName, final @PathParam("client_id") String clientId) { RealmModel realm = init(realmName); if (realm == null) { return null; } ClientModel client = realm.getClientByClientId(clientId); if (client == null) { return null; } if (client.getRootUrl() == null && client.getBaseUrl() == null) { return null; } URI targetUri; if (client.getRootUrl() != null && (client.getBaseUrl() == null || client.getBaseUrl().isEmpty())) { targetUri = KeycloakUriBuilder.fromUri(client.getRootUrl()).build(); } else { targetUri = KeycloakUriBuilder.fromUri(ResolveRelative.resolveRelativeUri(session, client.getRootUrl(), client.getBaseUrl())).build(); } return Response.seeOther(targetUri).build(); } @Path("{realm}/login-actions") public LoginActionsService getLoginActionsService(final @PathParam("realm") String name) { RealmModel realm = init(name); EventBuilder event = new EventBuilder(realm, session, clientConnection); LoginActionsService service = new LoginActionsService(realm, event); ResteasyProviderFactory.getInstance().injectProperties(service); return service; } @Path("{realm}/clients-registrations") public ClientRegistrationService getClientsService(final @PathParam("realm") String name) { RealmModel realm = init(name); EventBuilder event = new EventBuilder(realm, session, clientConnection); ClientRegistrationService service = new ClientRegistrationService(event); ResteasyProviderFactory.getInstance().injectProperties(service); return service; } @Path("{realm}/clients-managements") public ClientsManagementService getClientsManagementService(final @PathParam("realm") String name) { RealmModel realm = init(name); EventBuilder event = new EventBuilder(realm, session, clientConnection); ClientsManagementService service = new ClientsManagementService(realm, event); ResteasyProviderFactory.getInstance().injectProperties(service); return service; } private RealmModel init(String realmName) { RealmManager realmManager = new RealmManager(session); RealmModel realm = realmManager.getRealmByName(realmName); if (realm == null) { throw new NotFoundException("Realm does not exist"); } session.getContext().setRealm(realm); return realm; } @Path("{realm}/account") public Object getAccountService(final @PathParam("realm") String name) { RealmModel realm = init(name); EventBuilder event = new EventBuilder(realm, session, clientConnection); AccountLoader accountLoader = new AccountLoader(session, event); ResteasyProviderFactory.getInstance().injectProperties(accountLoader); return accountLoader; } @Path("{realm}") public PublicRealmResource getRealmResource(final @PathParam("realm") String name) { RealmModel realm = init(name); PublicRealmResource realmResource = new PublicRealmResource(realm); ResteasyProviderFactory.getInstance().injectProperties(realmResource); return realmResource; } @Path("{realm}/broker") public IdentityBrokerService getBrokerService(final @PathParam("realm") String name) { RealmModel realm = init(name); IdentityBrokerService brokerService = new IdentityBrokerService(realm); ResteasyProviderFactory.getInstance().injectProperties(brokerService); brokerService.init(); return brokerService; } @OPTIONS @Path("{realm}/.well-known/{provider}") @Produces(MediaType.APPLICATION_JSON) public Response getVersionPreflight(final @PathParam("realm") String name, final @PathParam("provider") String providerName) { return Cors.add(request, Response.ok()).allowedMethods("GET").preflight().auth().build(); } @GET @Path("{realm}/.well-known/{provider}") @Produces(MediaType.APPLICATION_JSON) public Response getWellKnown(final @PathParam("realm") String name, final @PathParam("provider") String providerName) { RealmModel realm = init(name); checkSsl(realm); WellKnownProvider wellKnown = session.getProvider(WellKnownProvider.class, providerName); if (wellKnown != null) { ResponseBuilder responseBuilder = Response.ok(wellKnown.getConfig()).cacheControl(CacheControlUtil.noCache()); return Cors.add(request, responseBuilder).allowedOrigins("*").auth().build(); } throw new NotFoundException(); } @Path("{realm}/authz") public Object getAuthorizationService(@PathParam("realm") String name) { init(name); AuthorizationProvider authorization = this.session.getProvider(AuthorizationProvider.class); AuthorizationService service = new AuthorizationService(authorization); ResteasyProviderFactory.getInstance().injectProperties(service); return service; } /** * A JAX-RS sub-resource locator that uses the {@link org.keycloak.services.resource.RealmResourceSPI} to resolve sub-resources instances given an <code>unknownPath</code>. * * @param extension a path that could be to a REST extension * @return a JAX-RS sub-resource instance for the REST extension if found. Otherwise null is returned. */ @Path("{realm}/{extension}") public Object resolveRealmExtension(@PathParam("realm") String realmName, @PathParam("extension") String extension) { RealmResourceProvider provider = session.getProvider(RealmResourceProvider.class, extension); if (provider != null) { init(realmName); Object resource = provider.getResource(); if (resource != null) { return resource; } } throw new NotFoundException(); } /** * Get openids * * Returns a set of openids, filtered according to query parameters * * @param groups A String contained in groups * @param roles A String contained in roles * @return a non-null map of openids */ @GET @Path("{realm}/openid") @NoCache @Produces(MediaType.APPLICATION_JSON) public Map<String, List<String>> getOpenID(final @PathParam("realm") String name, @QueryParam("groups") String groups, @QueryParam("roles") @DefaultValue("hycr_operator,hycr_programmer") String roles) { RealmModel realm = init(name); checkSsl(realm); String[] gSet = groups.split(","); String[] rSet = roles.split(","); return realm.getTopLevelGroupsStream().filter(g -> { for (String gStr : gSet) { if (g.getName().contains(gStr.trim())) { return true; } } return false; }).flatMap(g -> session.users().getGroupMembersStream(realm, g) ).filter(u -> !ObjectUtil.isBlank(u.getEmail()) ).filter(u -> { for (String rStr : rSet) { if (u.getRealmRoleMappingsStream().anyMatch(r -> r.getName().equalsIgnoreCase(rStr.trim()))) { return true; } } return false; }).map(u -> ModelToRepresentation.toRepresentation(session, realm, u) ).collect(Collectors.toMap(e -> String.valueOf(e.getGroups().get(0)).split("\\|")[0], e -> { ArrayList<String> list = new ArrayList<>(); List<String> oids = e.getAttributes().get("openid"); if (oids != null) { list.add(oids.get(0)); } return list; }, (oldList, newList) -> { oldList.addAll(newList); return oldList; })); } @GET @Path("{realm}/groups") @NoCache @Produces(MediaType.APPLICATION_JSON) public Stream<GroupRepresentation> getGroups(final @PathParam("realm") String name) { RealmModel realm = init(name); checkSsl(realm); return ModelToRepresentation.toGroupHierarchy(session, realm, false); } @GET @Path("{realm}/groups/ex") @NoCache @Produces(MediaType.APPLICATION_JSON) public Stream<GroupRepresentation> getExGroups(final @PathParam("realm") String name) { RealmModel realm = init(name); checkSsl(realm); return ModelToRepresentation.toExGroupHierarchy(session, realm, false); } private void checkSsl(RealmModel realm) { if (!session.getContext().getUri().getBaseUri().getScheme().equals("https") && realm.getSslRequired().isRequired(clientConnection)) { Cors cors = Cors.add(request).auth().allowedMethods(request.getHttpMethod()).auth().exposedHeaders(Cors.ACCESS_CONTROL_ALLOW_METHODS); throw new CorsErrorResponseException(cors.allowAllOrigins(), OAuthErrorException.INVALID_REQUEST, "HTTPS required", Response.Status.FORBIDDEN); } } }
39.233161
176
0.683439
79bb5de421217138192432cafe957f5e3e1ebebb
2,182
package com.lunarku.order.service.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import com.lunarku.order.pojo.OrderInfo; import com.lunarku.order.service.OrderService; import com.lunarku.shop.common.util.ResponseResult; import com.lunarku.shop.mapper.TbOrderItemMapper; import com.lunarku.shop.mapper.TbOrderMapper; import com.lunarku.shop.mapper.TbOrderShippingMapper; import com.lunarku.shop.pojo.TbOrderItem; import com.lunarku.shop.pojo.TbOrderShipping; import com.lunarku.shop.redis.JedisClient; public class OrderServiceImpl implements OrderService{ @Autowired private TbOrderMapper orderMapper; @Autowired private TbOrderShippingMapper orderShippingMapper; @Autowired private TbOrderItemMapper orderItemMapper; @Autowired private JedisClient jedisClient; @Value("${ORDER_ID_GEN_KEY}") private String ORDER_ID_GEN_KEY; @Value("${ORDER_ID_BEGIN_VALUE}") private String ORDER_ID_BEGIN_VALUE; @Value("${ORDER_ITEM_ID_GEN_KEY}") private String ORDER_ITEM_ID_GEN_KEY; @Override public ResponseResult ccreateOrder(OrderInfo orderInfo) { // 生成订单单号 if(!jedisClient.exists(ORDER_ID_GEN_KEY)) { // 设置初始值 jedisClient.set(ORDER_ID_GEN_KEY, ORDER_ID_BEGIN_VALUE); } String orderId = jedisClient.incr(ORDER_ID_GEN_KEY).toString(); // 将订单插入表中,在此之前补全pojo属性 orderInfo.setOrderId(orderId); orderInfo.setPostFee("0"); Date date = new Date(); orderInfo.setCreateTime(date); orderInfo.setCreateTime(date); orderMapper.insert(orderInfo); // 向订单明细表插入数据 List<TbOrderItem> orderItems = orderInfo.getOrderItems(); for(TbOrderItem orderItem : orderItems) { String orderItemId = jedisClient.incr(ORDER_ITEM_ID_GEN_KEY).toString(); orderItem.setId(orderItemId); orderItem.setOrderId(orderId); orderItemMapper.insert(orderItem); } // 想订单物流表插入数据 TbOrderShipping orderShipping = orderInfo.getOrderShipping(); orderShipping.setOrderId(orderId); orderShipping.setCreated(date); orderShipping.setUpdated(date); orderShippingMapper.insert(orderShipping); // 返回订单号 return null; } }
29.093333
75
0.791476
347b8870d9729b6975839654792ef8bd98f64429
718
class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> triangle = new ArrayList<List<Integer>>(); if (numRows > 0) { List<Integer> row = new ArrayList<Integer>(); row.add(1); triangle.add(row); } for (int i = 1; i < numRows; i++) { List<Integer> row = new ArrayList<Integer>(triangle.get(i - 1)); row.add(0, 0); row.add(0); List<Integer> next = new ArrayList<Integer>(); for (int j = 1; j < row.size(); j++) { next.add(row.get(j - 1) + row.get(j)); } triangle.add(next); } return triangle; } }
34.190476
76
0.476323
1a2360da324e88064a42101b15f30fa4bb0b830b
1,451
package com.sequenceiq.cloudbreak.converter.v4.util; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.api.endpoint.v4.util.responses.StructuredParameterQueryV4Response; import com.sequenceiq.cloudbreak.converter.AbstractConversionServiceAwareConverter; import com.sequenceiq.cloudbreak.template.filesystem.query.ConfigQueryEntry; @Component public class ConfigQueryEntryToStructuredParameterQueryV4ResponseConverter extends AbstractConversionServiceAwareConverter<ConfigQueryEntry, StructuredParameterQueryV4Response> { @Override public StructuredParameterQueryV4Response convert(ConfigQueryEntry source) { StructuredParameterQueryV4Response structuredParameterQueryV4Response = new StructuredParameterQueryV4Response(); structuredParameterQueryV4Response.setDefaultPath(source.getDefaultPath()); structuredParameterQueryV4Response.setDescription(source.getDescription()); structuredParameterQueryV4Response.setPropertyName(source.getPropertyName()); structuredParameterQueryV4Response.setRelatedServices(source.getRelatedServices()); structuredParameterQueryV4Response.setPropertyFile(source.getPropertyFile()); structuredParameterQueryV4Response.setProtocol(source.getProtocol()); structuredParameterQueryV4Response.setPropertyDisplayName(source.getPropertyDisplayName()); return structuredParameterQueryV4Response; } }
55.807692
121
0.84011
d2e2202da4a264112f673aafccc380e414b86f64
15,965
package com.bergerkiller.bukkit.tc.attachments.control.seat; import java.util.Collection; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import com.bergerkiller.bukkit.common.controller.VehicleMountController; import com.bergerkiller.bukkit.common.math.Matrix4x4; import com.bergerkiller.bukkit.common.math.Quaternion; import com.bergerkiller.bukkit.common.utils.EntityUtil; import com.bergerkiller.bukkit.common.utils.MathUtil; import com.bergerkiller.bukkit.common.utils.PacketUtil; import com.bergerkiller.bukkit.common.utils.PlayerUtil; import com.bergerkiller.bukkit.common.wrappers.DataWatcher; import com.bergerkiller.bukkit.tc.TCConfig; import com.bergerkiller.bukkit.tc.attachments.FakePlayerSpawner; import com.bergerkiller.bukkit.tc.attachments.VirtualEntity; import com.bergerkiller.bukkit.tc.attachments.control.CartAttachmentSeat; import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutEntityDestroyHandle; import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutEntityMetadataHandle; import com.bergerkiller.generated.net.minecraft.world.entity.EntityHandle; /** * Information for a seated entity in a 'normal' way. The entity can only be * upright or upside-down. This is the classic behavior seats have in Traincarts. */ class SeatedEntityNormal extends SeatedEntity { private boolean _upsideDown = false; private int _fakeEntityId = -1; private boolean _fake = false; // Is initialized when the player needs to be displayed upside-down private VirtualEntity _upsideDownVehicle = null; public SeatedEntityNormal(CartAttachmentSeat seat) { super(seat); } public boolean isUpsideDown() { return this._upsideDown; } public void setUpsideDown(boolean upsideDown) { this._upsideDown = upsideDown; } public boolean isFake() { return this._fake; } public void setFake(boolean fake) { this._fake = fake; } /** * Sends the correct current metadata information the seated entity should have. * * @param viewer */ public void refreshUpsideDownMetadata(Player viewer, boolean upsideDown) { // We don't use the dinnerbone tag for players at all if (isEmpty() || isPlayer() || isDummyPlayer()) { return; } if (upsideDown) { // Apply metadata 'Dinnerbone' with nametag invisible DataWatcher metaTmp = new DataWatcher(); metaTmp.set(EntityHandle.DATA_CUSTOM_NAME, FakePlayerSpawner.UPSIDEDOWN.getPlayerName()); metaTmp.set(EntityHandle.DATA_CUSTOM_NAME_VISIBLE, false); PacketPlayOutEntityMetadataHandle metaPacket = PacketPlayOutEntityMetadataHandle.createNew(this.entity.getEntityId(), metaTmp, true); PacketUtil.sendPacket(viewer, metaPacket); } else { // Send the default metadata of this entity DataWatcher metaTmp = EntityHandle.fromBukkit(this.entity).getDataWatcher(); PacketUtil.sendPacket(viewer, PacketPlayOutEntityMetadataHandle.createNew(this.entity.getEntityId(), metaTmp, true)); } } private void makeFakePlayerVisible(VehicleMountController vmc, Player viewer) { // Generate an entity id if needed for the first time if (this._fakeEntityId == -1) { this._fakeEntityId = EntityUtil.getUniqueEntityId(); } // Position of the fake player Vector fpp_pos = seat.getTransform().toVector(); FakePlayerSpawner.FakePlayerPosition fpp = FakePlayerSpawner.FakePlayerPosition.create( fpp_pos.getX(), fpp_pos.getY(), fpp_pos.getZ(), this.orientation.getPassengerYaw(), this.orientation.getPassengerPitch(), this.orientation.getPassengerHeadYaw()); if (this._upsideDown) { // Player must be mounted inside the upside-down vehicle, which has a special offset so that the // upside-down butt is where the transform is at. if (this._upsideDownVehicle == null) { this._upsideDownVehicle = createPassengerVehicle(); this._upsideDownVehicle.addRelativeOffset(0.0, -0.65, 0.0); this._upsideDownVehicle.updatePosition(seat.getTransform(), new Vector(0.0, (double) this.orientation.getMountYaw(), 0.0)); this._upsideDownVehicle.syncPosition(true); } this._upsideDownVehicle.spawn(viewer, seat.calcMotion()); // Spawn player as upside-down. For dummy players, entity is null, so spawns a dummy. FakePlayerSpawner.UPSIDEDOWN.spawnPlayer(viewer, (Player) this.entity, this._fakeEntityId, fpp, this::applyFakePlayerMetadata); // Mount player inside the upside-down carrier vehicle vmc.mount(this._upsideDownVehicle.getEntityId(), this._fakeEntityId); } else { // Spawn a normal no-nametag player. For dummy players, entity is null, so spawns a dummy. FakePlayerSpawner.NO_NAMETAG.spawnPlayer(viewer, (Player) this.entity, this._fakeEntityId, fpp, this::applyFakePlayerMetadata); // Upright fake players can be put into the vehicle mount vmc.mount(this.parentMountId, this._fakeEntityId); } // Sync initial rotations of these entities, if locked if (seat.isRotationLocked()) { this.orientation.sendLockedRotations(viewer, this._fakeEntityId); } } private void applyFakePlayerMetadata(DataWatcher metadata) { metadata.setFlag(EntityHandle.DATA_FLAGS, EntityHandle.DATA_FLAG_FLYING, false); metadata.setFlag(EntityHandle.DATA_FLAGS, EntityHandle.DATA_FLAG_GLOWING, this.isDummyPlayer() && seat.isFocused()); } private void makeFakePlayerInvisible(VehicleMountController vmc, Player viewer) { // De-spawn the fake player itself PacketUtil.sendPacket(viewer, PacketPlayOutEntityDestroyHandle.createNewSingle(this._fakeEntityId)); vmc.remove(this._fakeEntityId); // If used, de-spawn the upside-down vehicle too if (this._upsideDown && this._upsideDownVehicle != null) { this._upsideDownVehicle.destroy(viewer); vmc.remove(this._upsideDownVehicle.getEntityId()); } } @Override public Vector getThirdPersonCameraOffset() { return new Vector(0.0, 1.6, 0.0); } @Override public Vector getFirstPersonCameraOffset() { return new Vector(0.0, VirtualEntity.PLAYER_SIT_BUTT_EYE_HEIGHT, 0.0); } @Override public void makeVisible(Player viewer) { VehicleMountController vmc = PlayerUtil.getVehicleMountController(viewer); spawnVehicleMount(viewer); // Makes parentMountId valid if (isDummyPlayer() && isEmpty()) { // For dummy players, spawn a fake version of the Player and seat it // The original player is also displayed, so that might be weird. Oh well. makeFakePlayerVisible(vmc, viewer); } else if (this.entity == viewer) { // In first-person, show the fake player, but do not mount the viewer in anything // That is up to the first-person controller to deal with. makeFakePlayerVisible(vmc, viewer); } else if (this._fake && isPlayer()) { // Despawn/hide original player entity vmc.despawn(this.entity.getEntityId()); // Respawn an upside-down player in its place, mounted into the vehicle makeFakePlayerVisible(vmc, viewer); } else if (!this.isEmpty()) { // Send metadata if (this._upsideDown) { refreshUpsideDownMetadata(viewer, true); } // Mount entity in vehicle vmc.mount(this.parentMountId, this.entity.getEntityId()); } } @Override public void makeHidden(Player viewer) { VehicleMountController vmc = PlayerUtil.getVehicleMountController(viewer); if (isDummyPlayer() && isEmpty()) { // Hide fake player again makeFakePlayerInvisible(vmc, viewer); } else if (this.entity == viewer) { // De-spawn a fake player makeFakePlayerInvisible(vmc, viewer); } else if (this._fake && this.isPlayer()) { // De-spawn a fake player, if any makeFakePlayerInvisible(vmc, viewer); // Respawn original player showRealPlayer(viewer); } else if (!this.isEmpty()) { // For non-player passengers, resend correct metadata to remove dinnerbone tags if (this._upsideDown) { refreshUpsideDownMetadata(viewer, false); } // Unmount original entity from the mount vmc.unmount(this.parentMountId, this.entity.getEntityId()); } // De-spawn the fake mount being used, if any despawnVehicleMount(viewer); } @Override public void updateMode(boolean silent) { // Compute new first-person state of whether the player sees himself from third person using a fake camera FirstPersonViewMode new_firstPersonMode = FirstPersonViewMode.DEFAULT; // Whether a fake entity is used to represent this seated entity boolean new_isFake; // Whether the (fake) entity is displayed upside-down boolean new_isUpsideDown; if (!this.isDisplayed()) { new_isFake = false; new_isUpsideDown = false; } else { Quaternion rotation = seat.getTransform().getRotation(); double selfPitch = rotation.getPitch(); // Compute new upside-down state new_isUpsideDown = this.isUpsideDown(); if (MathUtil.getAngleDifference(selfPitch, 180.0) < 89.0) { // Beyond the point where the entity should be rendered upside-down new_isUpsideDown = true; } else if (MathUtil.getAngleDifference(selfPitch, 0.0) < 89.0) { // Beyond the point where the entity should be rendered normally again new_isUpsideDown = false; } // Compute new first-person state of whether the player sees himself from third person using a fake camera new_firstPersonMode = seat.firstPerson.getMode(); if (new_firstPersonMode == FirstPersonViewMode.DYNAMIC) { if (TCConfig.enableSeatThirdPersonView && this.isPlayer() && Math.abs(selfPitch) > 70.0) { new_firstPersonMode = FirstPersonViewMode.THIRD_P; } else { new_firstPersonMode = FirstPersonViewMode.DEFAULT; } } // Whether a fake entity is used to represent this seated entity boolean noNametag = (this.displayMode == DisplayMode.NO_NAMETAG); new_isFake = isDummyPlayer() || (this.isPlayer() && (noNametag || new_isUpsideDown || new_firstPersonMode.hasFakePlayer())); } // When we change whether a fake entity is displayed, hide for everyone and make visible again if (silent) { // Explicitly requested we do not send any packets this.setFake(new_isFake); this.setUpsideDown(new_isUpsideDown); seat.firstPerson.setLiveMode(new_firstPersonMode); return; } if (new_isFake != this.isFake() || (this.isPlayer() && new_isUpsideDown != this.isUpsideDown())) { // Do we refresh the first player view as well? boolean refreshFPV = seat.firstPerson.doesViewModeChangeRequireReset(new_firstPersonMode); // Fake entity changed, this requires the entity to be respawned for everyone Entity entity = this.getEntity(); Collection<Player> viewers = seat.getViewersSynced(); for (Player viewer : viewers) { if (refreshFPV || viewer != entity) { seat.makeHiddenImpl(viewer, true); } } this.setFake(new_isFake); this.setUpsideDown(new_isUpsideDown); seat.firstPerson.setLiveMode(new_firstPersonMode); for (Player viewer : viewers) { if (refreshFPV || viewer != entity) { seat.makeVisibleImpl(viewer, true); } } } else { if (new_isUpsideDown != this.isUpsideDown()) { // Upside-down changed, but the seated entity is not a Player // All we have to do is refresh the Entity metadata this.setUpsideDown(new_isUpsideDown); if (!this.isEmpty()) { for (Player viewer : seat.getViewersSynced()) { this.refreshUpsideDownMetadata(viewer, new_isUpsideDown); } } } if (new_firstPersonMode != seat.firstPerson.getLiveMode()) { // Only first-person view useVirtualCamera changed Collection<Player> viewers = seat.getViewersSynced(); if (viewers.contains(this.getEntity())) { // Hide, change, and make visible again, just for the first-player-view player Player viewer = (Player) this.getEntity(); seat.makeHiddenImpl(viewer, true); seat.firstPerson.setLiveMode(new_firstPersonMode); seat.makeVisibleImpl(viewer, true); } else { // Silent seat.firstPerson.setLiveMode(new_firstPersonMode); } } } } @Override public boolean containsEntityId(int entityId) { if (entityId == this._fakeEntityId) { return true; } return false; } @Override public void updatePosition(Matrix4x4 transform) { if (isDisplayed()) { // Entity id is that of a fake entity if used, otherwise uses entity id // If in first-person the fake entity is not used, then we're sending packets // about an entity that does not exist. Is this bad? int entityId = this._fake ? this._fakeEntityId : ((this.entity == null) ? -1 : this.entity.getEntityId()); orientation.synchronizeNormal(seat, transform, this, entityId); } updateVehicleMountPosition(transform); if (this._upsideDownVehicle != null) { this._upsideDownVehicle.updatePosition(transform, new Vector(0.0, (double) this.orientation.getMountYaw(), 0.0)); } } @Override public void syncPosition(boolean absolute) { syncVehicleMountPosition(absolute); if (this._upsideDownVehicle != null) { this._upsideDownVehicle.syncPosition(absolute); } } @Override public void updateFocus(boolean focused) { // Send a metadata packet with the updated entity flags to set glowing appropriately if (this._fakeEntityId != -1 && this.isDisplayed()) { DataWatcher metadata; if (isPlayer()) { metadata = EntityUtil.getDataWatcher(this.entity).clone(); } else { metadata = new DataWatcher(); metadata.set(EntityHandle.DATA_FLAGS, (byte) 0); } applyFakePlayerMetadata(metadata); PacketPlayOutEntityMetadataHandle packet = PacketPlayOutEntityMetadataHandle.createNew( this._fakeEntityId, metadata, true); for (Player viewer : seat.getViewers()) { PacketUtil.sendPacket(viewer, packet); } } } }
42.916667
145
0.631193
22fb0d44b6fb02ab7c67f1df46ae10b99b80bc80
4,770
package com.prowidesoftware.swift.model.mx.dic; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Transaction totals during the reconciliation period, for a certain type of transaction. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TransactionTotals3", propOrder = { "poiGrpId", "cardPdctPrfl", "ccy", "tp", "ttlNb", "cmltvAmt" }) public class TransactionTotals3 { @XmlElement(name = "POIGrpId") protected String poiGrpId; @XmlElement(name = "CardPdctPrfl") protected String cardPdctPrfl; @XmlElement(name = "Ccy") protected String ccy; @XmlElement(name = "Tp", required = true) @XmlSchemaType(name = "string") protected TypeTransactionTotals2Code tp; @XmlElement(name = "TtlNb", required = true) protected BigDecimal ttlNb; @XmlElement(name = "CmltvAmt", required = true) protected BigDecimal cmltvAmt; /** * Gets the value of the poiGrpId property. * * @return * possible object is * {@link String } * */ public String getPOIGrpId() { return poiGrpId; } /** * Sets the value of the poiGrpId property. * * @param value * allowed object is * {@link String } * */ public TransactionTotals3 setPOIGrpId(String value) { this.poiGrpId = value; return this; } /** * Gets the value of the cardPdctPrfl property. * * @return * possible object is * {@link String } * */ public String getCardPdctPrfl() { return cardPdctPrfl; } /** * Sets the value of the cardPdctPrfl property. * * @param value * allowed object is * {@link String } * */ public TransactionTotals3 setCardPdctPrfl(String value) { this.cardPdctPrfl = value; return this; } /** * Gets the value of the ccy property. * * @return * possible object is * {@link String } * */ public String getCcy() { return ccy; } /** * Sets the value of the ccy property. * * @param value * allowed object is * {@link String } * */ public TransactionTotals3 setCcy(String value) { this.ccy = value; return this; } /** * Gets the value of the tp property. * * @return * possible object is * {@link TypeTransactionTotals2Code } * */ public TypeTransactionTotals2Code getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link TypeTransactionTotals2Code } * */ public TransactionTotals3 setTp(TypeTransactionTotals2Code value) { this.tp = value; return this; } /** * Gets the value of the ttlNb property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTtlNb() { return ttlNb; } /** * Sets the value of the ttlNb property. * * @param value * allowed object is * {@link BigDecimal } * */ public TransactionTotals3 setTtlNb(BigDecimal value) { this.ttlNb = value; return this; } /** * Gets the value of the cmltvAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getCmltvAmt() { return cmltvAmt; } /** * Sets the value of the cmltvAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public TransactionTotals3 setCmltvAmt(BigDecimal value) { this.cmltvAmt = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
22.394366
90
0.578826
c88415ad754d71d9e113ad64b7158ad55552be71
3,427
/* * 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.servicecomb.foundation.common.utils; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; /** * 规避fortify问题,仅仅是规避,如 * e.getMessage * e.printStackTrace * 调用会报安全问题(敏感信息泄露) * * */ public final class FortifyUtils { private static Method getMessageMethod; private static Method printStackTraceMethod; static { try { getMessageMethod = Throwable.class.getMethod("getMessage"); printStackTraceMethod = Throwable.class.getMethod("printStackTrace", PrintWriter.class); } catch (Exception e) { throw new Error(e); } } private FortifyUtils() { } public static String getErrorMsg(Throwable e) { if (e == null) { return ""; } try { return (String) getMessageMethod.invoke(e); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { return ""; } } public static String getErrorStack(Throwable e) { if (null == e) { return ""; } try { StringWriter errors = new StringWriter(); printStackTraceMethod.invoke(e, new PrintWriter(errors)); return errors.toString(); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { return ""; } } public static String getErrorInfo(Throwable e) { return getErrorInfo(e, true); } public static String getErrorInfo(Throwable e, boolean isPrintMsg) { StringBuffer error = new StringBuffer(System.lineSeparator()); error.append("Exception: ").append(e.getClass().getName()).append("; "); if (isPrintMsg) { error.append(getErrorMsg(e)).append(System.lineSeparator()); } error.append(getErrorStack(e)); return error.toString(); } public static DocumentBuilderFactory getSecurityXmlDocumentFactory() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setValidating(true); return factory; } }
31.154545
108
0.726875
4dfcc3b26a46a20de4a608811a56748817764ead
3,638
/* * Copyright 2019 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://www.apache.org/licenses/LICENSE-2.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.amazon.dlic.auth.http.jwt.keybyoidc; import java.util.Set; import org.apache.cxf.rs.security.jose.jwk.JsonWebKey; import org.apache.cxf.rs.security.jose.jws.JwsHeaders; import org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider; import org.apache.cxf.rs.security.jose.jws.JwsUtils; import org.apache.cxf.rs.security.jose.jwt.JoseJwtProducer; import org.apache.cxf.rs.security.jose.jwt.JwtClaims; import org.apache.cxf.rs.security.jose.jwt.JwtConstants; import org.apache.cxf.rs.security.jose.jwt.JwtToken; import org.apache.logging.log4j.util.Strings; import com.google.common.collect.ImmutableSet; class TestJwts { static final String ROLES_CLAIM = "roles"; static final Set<String> TEST_ROLES = ImmutableSet.of("role1", "role2"); static final String TEST_ROLES_STRING = Strings.join(TEST_ROLES, ','); static final String TEST_AUDIENCE = "TestAudience"; static final String MCCOY_SUBJECT = "Leonard McCoy"; static final JwtToken MC_COY = create(MCCOY_SUBJECT, TEST_AUDIENCE, ROLES_CLAIM, TEST_ROLES_STRING); static final JwtToken MC_COY_EXPIRED = create(MCCOY_SUBJECT, TEST_AUDIENCE, ROLES_CLAIM, TEST_ROLES_STRING, JwtConstants.CLAIM_EXPIRY, 10); static final String MC_COY_SIGNED_OCT_1 = createSigned(MC_COY, TestJwk.OCT_1); static final String MC_COY_SIGNED_RSA_1 = createSigned(MC_COY, TestJwk.RSA_1); static final String MC_COY_SIGNED_RSA_X = createSigned(MC_COY, TestJwk.RSA_X); static final String MC_COY_EXPIRED_SIGNED_OCT_1 = createSigned(MC_COY_EXPIRED, TestJwk.OCT_1); static class NoKid { static final String MC_COY_SIGNED_RSA_1 = createSignedWithoutKeyId(MC_COY, TestJwk.RSA_1); static final String MC_COY_SIGNED_RSA_2 = createSignedWithoutKeyId(MC_COY, TestJwk.RSA_2); static final String MC_COY_SIGNED_RSA_X = createSignedWithoutKeyId(MC_COY, TestJwk.RSA_X); } static JwtToken create(String subject, String audience, Object... moreClaims) { JwtClaims claims = new JwtClaims(); claims.setSubject(subject); claims.setAudience(audience); if (moreClaims != null) { for (int i = 0; i < moreClaims.length; i += 2) { claims.setClaim(String.valueOf(moreClaims[i]), moreClaims[i + 1]); } } JwtToken result = new JwtToken(claims); return result; } static String createSigned(JwtToken baseJwt, JsonWebKey jwk) { return createSigned(baseJwt, jwk, JwsUtils.getSignatureProvider(jwk)); } static String createSigned(JwtToken baseJwt, JsonWebKey jwk, JwsSignatureProvider signatureProvider) { JwsHeaders jwsHeaders = new JwsHeaders(); JwtToken signedToken = new JwtToken(jwsHeaders, baseJwt.getClaims()); jwsHeaders.setKeyId(jwk.getKeyId()); return new JoseJwtProducer().processJwt(signedToken, null, signatureProvider); } static String createSignedWithoutKeyId(JwtToken baseJwt, JsonWebKey jwk) { JwsHeaders jwsHeaders = new JwsHeaders(); JwtToken signedToken = new JwtToken(jwsHeaders, baseJwt.getClaims()); return new JoseJwtProducer().processJwt(signedToken, null, JwsUtils.getSignatureProvider(jwk)); } }
37.895833
143
0.771028
d045abc2a0a64a7f38730826dbebfd0d3614b10a
13,209
package cn.aezo.bigdata.hbase; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.PrefixFilter; import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; import org.apache.hadoop.hbase.util.Bytes; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Random; public class HBaseDemo { Configuration conf = null; Connection conn = null; //表的管理对象 Admin admin = null; Table table = null; //创建表的对象 TableName tableName = TableName.valueOf("phone"); @Before public void init() throws IOException { //创建配置文件对象 conf = HBaseConfiguration.create(); //加载zookeeper的配置 conf.set("hbase.zookeeper.quorum","node01,node02,node03"); //获取连接 conn = ConnectionFactory.createConnection(conf); //获取对象 admin = conn.getAdmin(); //获取数据操作对象 table = conn.getTable(tableName); } @After public void destory(){ try { table.close(); } catch (IOException e) { e.printStackTrace(); } try { admin.close(); } catch (IOException e) { e.printStackTrace(); } try { conn.close(); } catch (IOException e) { e.printStackTrace(); } } @Test public void createTable() throws IOException { //定义表描述对象 TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tableName); //定义列族描述对象 ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder("cf".getBytes()); //添加列族信息给表 tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptorBuilder.build()); if(admin.tableExists(tableName)){ // 必须先禁用表才能删除表 admin.disableTable(tableName); admin.deleteTable(tableName); } //创建表 admin.createTable(tableDescriptorBuilder.build()); } /** * ROW COLUMN+CELL * 1 column=cf:age, timestamp=2021-07-19T23:10:05.370, value=18 * 1 column=cf:name, timestamp=2021-07-19T23:10:05.370, value=zhangsan * 1 column=cf:sex, timestamp=2021-07-19T23:10:05.370, value=man */ @Test public void insert() throws IOException { // HBase所有的数据需要转成字节数组 Put put = new Put(Bytes.toBytes("1")); put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("name"),Bytes.toBytes("zhangsan")); put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("age"),Bytes.toBytes("18")); put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("sex"),Bytes.toBytes("man")); table.put(put); } /** * 通过get获取数据 * @throws IOException */ @Test public void get() throws IOException { Get get = new Get(Bytes.toBytes("1")); //在服务端做数据过滤,挑选出符合需求的列。如果不设置会把当前行的所有列都取出 get.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("name")); get.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("age")); get.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("sex")); Result result = table.get(get); Cell cell1 = result.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("name")); Cell cell2 = result.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("age")); Cell cell3 = result.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("sex")); String name = Bytes.toString(CellUtil.cloneValue(cell1)); String age = Bytes.toString(CellUtil.cloneValue(cell2)); String sex = Bytes.toString(CellUtil.cloneValue(cell3)); System.out.println(name); // zhangsan System.out.println(age); // 18 System.out.println(sex); // man } /** * 获取表中所有的记录 */ @Test public void scan() throws IOException { Scan scan = new Scan(); // scan.withStartRow(); // scan.withStopRow(); ResultScanner rss = table.getScanner(scan); for (Result rs: rss) { Cell cell1 = rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("name")); Cell cell2 = rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("age")); Cell cell3 = rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("sex")); String name = Bytes.toString(CellUtil.cloneValue(cell1)); String age = Bytes.toString(CellUtil.cloneValue(cell2)); String sex = Bytes.toString(CellUtil.cloneValue(cell3)); System.out.println(name); System.out.println(age); System.out.println(sex); } } // public void delete() throws IOException { // Delete delete = new Delete("1".getBytes()); // table.delete(delete); // } // ========================== 基于原始数据测试通话记录 /** * 假设有10个用户,每个用户一年产生10000条记录 * * 每插入一条数据hfile格式如下(弊端,重复的key太长,可将所有值合并以对象的形式提交,参考下文ProtoBuf序列化): * K: 15894059762_9223370490667733807/cf:date/1626707671567/Put/vlen=14/seqid=9 V: 20190100002402 * K: 15894059762_9223370490667733807/cf:dnum/1626707671567/Put/vlen=11/seqid=9 V: 17747324329 * K: 15894059762_9223370490667733807/cf:length/1626707671567/Put/vlen=2/seqid=9 V: 62 * K: 15894059762_9223370490667733807/cf:type/1626707671567/Put/vlen=1/seqid=9 V: 0 */ @Test public void insertManyData() throws Exception { List<Put> puts = new ArrayList<>(); for(int i = 0;i<10;i++){ String phoneNumber = getNumber("158"); for(int j = 0 ;j<10000;j++){ String dnum = getNumber("177"); String length = String.valueOf(random.nextInt(100)); String date = getDate("2019"); String type = String.valueOf(random.nextInt(2)); // rowKey: 基于电话号码_"时间"降序插入(从而将新的显示在上面) String rowKey = phoneNumber + "_" + (Long.MAX_VALUE - sdf.parse(date).getTime()); Put put = new Put(Bytes.toBytes(rowKey)); put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("dnum"),Bytes.toBytes(dnum)); put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("length"),Bytes.toBytes(length)); put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("date"),Bytes.toBytes(date)); // type=1主叫, type=0被叫 put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("type"),Bytes.toBytes(type)); puts.add(put); } } table.put(puts); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); private String getDate(String s) { return s + String.format("%02d%02d%02d%02d%02d", random.nextInt(12)+1,random.nextInt(31), random.nextInt(24),random.nextInt(60),random.nextInt(60)); } Random random = new Random(); public String getNumber(String str){ return str+String.format("%08d",random.nextInt(99999999)); } /** * 查询某一个用户3月份的通话记录 * * 17700233072--1--2--20190330224547 * 17717070538--1--29--20190330223550 * ... * 17716264968--0--56--20190301003236 * 17730830313--1--65--20190229000453 */ @Test public void scanByCondition() throws Exception { Scan scan = new Scan(); // 可先从数据查到一个随机生成的电话 String startRow = "15803261499_"+(Long.MAX_VALUE-sdf.parse("20190331000000").getTime()); String stopRow = "15803261499_"+(Long.MAX_VALUE-sdf.parse("20190301000000").getTime()); scan.withStartRow(Bytes.toBytes(startRow)); scan.withStopRow(Bytes.toBytes(stopRow)); ResultScanner rss = table.getScanner(scan); for (Result rs:rss) { System.out.print(Bytes.toString(CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("dnum"))))); System.out.print("--"+Bytes.toString(CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("type"))))); System.out.print("--"+Bytes.toString(CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("length"))))); System.out.println("--"+Bytes.toString(CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("date"))))); } } /** * 查询某个用户所有的主叫电话(type=1) * 17799333115--1--71--20191230235100 * 17751261096--1--16--20191230203001 * ... * 17786256027--1--86--20190100041527 * 17746066937--1--71--20190100001450 */ @Test public void getTypeByScanFilter() throws IOException { Scan scan = new Scan(); //创建过滤器集合,HBase提供多种过滤器 FilterList filters = new FilterList(FilterList.Operator.MUST_PASS_ALL); //创建过滤器 SingleColumnValueFilter filter1 = new SingleColumnValueFilter(Bytes.toBytes("cf"),Bytes.toBytes("type"),CompareOperator.EQUAL,Bytes.toBytes("1")); filters.addFilter(filter1); //前缀过滤器 PrefixFilter filter2 = new PrefixFilter(Bytes.toBytes("15803261499")); filters.addFilter(filter2); scan.setFilter(filters); ResultScanner rss = table.getScanner(scan); for (Result rs:rss) { System.out.print(Bytes.toString(CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("dnum"))))); System.out.print("--"+Bytes.toString(CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("type"))))); System.out.print("--"+Bytes.toString(CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("length"))))); System.out.println("--"+Bytes.toString(CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("date"))))); } } // ===================== 基于ProtoBuf序列化(存储空间更小)测试通话记录 /** * 保存的数据如(scan查看): * 15804800005_9223370459882064807 column=cf:phone, timestamp=2021-07-19T23:34:56.798, value=\x0A\x0B17716244196\x12\x0262\x1A\x010"\x0E20191222075831 * 15804800005_9223370459884573807 column=cf:phone, timestamp=2021-07-19T23:34:56.798, value=\x0A\x0B17741530312\x12\x0228\x1A\x011"\x0E20191222071642 * 15804800005_9223370459894120807 column=cf:phone, timestamp=2021-07-19T23:34:56.798, value=\x0A\x0B17726052445\x12\x0251\x1A\x011"\x0E20191222043735 * * hfile查看格式如: * K: 15837361825_9223370475391601807/cf:phone/1626708899430/Put/vlen=36/seqid=6 V: \x0A\x0B17797821003\x12\x0237\x1A\x011"\x0E20190625194614 * K: 15837361825_9223370475413054807/cf:phone/1626708899430/Put/vlen=36/seqid=6 V: \x0A\x0B17704808683\x12\x0258\x1A\x011"\x0E20190625134841 * K: 15837361825_9223370475418711807/cf:phone/1626708899430/Put/vlen=36/seqid=6 V: \x0A\x0B17770997313\x12\x0247\x1A\x011"\x0E20190625121424 * K: 15837361825_9223370475420841807/cf:phone/1626708899430/Put/vlen=36/seqid=6 V: \x0A\x0B17790869307\x12\x0256\x1A\x011"\x0E20190625113854 */ @Test public void insertByProtoBuf() throws ParseException, IOException { List<Put> puts = new ArrayList<>(); for(int i = 0;i<10;i++){ String phoneNumber = getNumber("158"); for(int j = 0 ;j<10000;j++){ String dnum = getNumber("177"); String length = String.valueOf(random.nextInt(100)); String date = getDate("2019"); String type = String.valueOf(random.nextInt(2)); // rowKey String rowKey = phoneNumber+"_"+(Long.MAX_VALUE-sdf.parse(date).getTime()); // 使用 ProtoBuf 自动生成的类 Phone.PhoneDetail.Builder builder = Phone.PhoneDetail.newBuilder(); builder.setDate(date); builder.setDnum(dnum); builder.setLength(length); builder.setType(type); Put put = new Put(Bytes.toBytes(rowKey)); put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("phone"),builder.build().toByteArray()); puts.add(put); } } table.put(puts); } @Test public void getByProtoBuf() throws IOException { // 可先从数据查到一个随机生成的记录 Get get = new Get("15804800005_9223370459871794807".getBytes()); Result rs = table.get(get); byte[] b = CellUtil.cloneValue(rs.getColumnLatestCell(Bytes.toBytes("cf"),Bytes.toBytes("phone"))); Phone.PhoneDetail phoneDetail = Phone.PhoneDetail.parseFrom(b); /** * dnum: "17765838241" * length: "66" * type: "1" * date: "20191222104941" */ System.out.println(phoneDetail); } }
43.166667
190
0.612158
972c91fa3e9e0937dae3e42dcbde0079ae5002a8
589
package test.http.server; import java.io.IOException; import nn1211.http.server.HttpServer; import static nn1211.http.server.ServerResponse.*; //import org.junit.Test; /** * HttpServer's test cases. * * @author nn1211 * @since 1.0 */ public class TestHttpServer { // @Test // public void test400() throws IOException { // new HttpServer().start(); // } public static void main(String[] args) throws IOException { new HttpServer() .registerHandler("GET /oauth-result", r -> ok(r.param("code"))) .start(); } }
21.814815
79
0.616299
7a800d5a0c350c6b6022f043f2ac0e3e5175cfe9
6,893
package com.diamondq.common.storage.jdbc; import com.diamondq.common.storage.kv.IKVColumnDefinition; import com.diamondq.common.storage.kv.IKVTableDefinition; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Map; import java.util.UUID; import org.checkerframework.checker.nullness.qual.Nullable; public class JDBCColumnSerializer implements IPreparedStatementSerializer { private final IKVTableDefinition mDefinition; private final IJDBCDialect mDialect; public JDBCColumnSerializer(IJDBCDialect pDialect, IKVTableDefinition pDefinition) { mDialect = pDialect; mDefinition = pDefinition; } /** * @see com.diamondq.common.storage.jdbc.IPreparedStatementSerializer#serializeColumnToPreparedStatement(java.lang.Object, * com.diamondq.common.storage.kv.IKVColumnDefinition, java.sql.PreparedStatement, int) */ @Override public @Nullable Object serializeColumnToPreparedStatement(@Nullable Object obj, IKVColumnDefinition pColDef, PreparedStatement pPs, int pParamCount) { try { switch (pColDef.getType()) { case Boolean: { Boolean value; if (obj == null) value = null; else if (obj instanceof String) value = Boolean.valueOf((String) obj); else if (obj instanceof Boolean) value = (Boolean) obj; else throw new IllegalArgumentException("Only Boolean or String supported, but found " + obj.getClass()); mDialect.writeBoolean(pPs, pParamCount, value); return value; } case Decimal: { BigDecimal minValue = pColDef.getMinValue(); BigDecimal maxValue = pColDef.getMaxValue(); if ((minValue != null) && (minValue.equals(JDBCKVStore.sLONG_MIN_VALUE)) && (maxValue != null) && (maxValue.equals(JDBCKVStore.sLONG_MAX_VALUE))) { Long value; if (obj == null) value = null; else if (obj instanceof String) value = Long.valueOf((String) obj); else if (obj instanceof Long) value = (Long) obj; else if (obj instanceof BigDecimal) value = ((BigDecimal) obj).longValue(); else throw new IllegalArgumentException( "Only Long, BigDecimal or String supported, but found " + obj.getClass()); mDialect.writeLong(pPs, pParamCount, value); return value; } else { BigDecimal value; if (obj == null) value = null; else if (obj instanceof String) value = new BigDecimal((String) obj); else if (obj instanceof BigDecimal) value = (BigDecimal) obj; else throw new IllegalArgumentException("Only BigDecimal or String supported, but found " + obj.getClass()); mDialect.writeDecimal(pPs, pParamCount, value); return value; } } case Integer: { Integer value; if (obj == null) value = null; else if (obj instanceof String) value = Integer.valueOf((String) obj); else if (obj instanceof Integer) value = (Integer) obj; else if (obj instanceof BigDecimal) value = ((BigDecimal) obj).intValue(); else throw new IllegalArgumentException( "Only Integer, BigDecimal or String supported, but found " + obj.getClass()); mDialect.writeInteger(pPs, pParamCount, value); return value; } case Long: { Long value; if (obj == null) value = null; else if (obj instanceof String) value = Long.valueOf((String) obj); else if (obj instanceof Integer) value = ((Integer) obj).longValue(); else if (obj instanceof Long) value = (Long) obj; else if (obj instanceof BigDecimal) value = ((BigDecimal) obj).longValue(); else throw new IllegalArgumentException( "Only Integer, Long, BigDecimal or String supported, but found " + obj.getClass()); mDialect.writeLong(pPs, pParamCount, value); return value; } case String: { String value; if (obj == null) value = null; else if (obj instanceof String) value = (String) obj; else if (obj instanceof UUID) value = ((UUID) obj).toString(); else throw new IllegalArgumentException("Only String and UUID are supported, but found " + obj.getClass()); Integer maxLength = pColDef.getMaxLength(); if (maxLength != null) mDialect.writeText(pPs, pParamCount, value); else mDialect.writeUnlimitedText(pPs, pParamCount, value); return value; } case Timestamp: { Long value; if (obj == null) value = null; else if (obj instanceof String) value = Long.valueOf((String) obj); else if (obj instanceof Long) value = (Long) obj; else if (obj instanceof BigDecimal) value = ((BigDecimal) obj).longValue(); else throw new IllegalArgumentException("Only Long, BigDecimal or String supported, but found " + obj.getClass()); mDialect.writeTimestamp(pPs, pParamCount, value); return value; } case UUID: { UUID value; if (obj == null) value = null; else if (obj instanceof UUID) value = (UUID) obj; else throw new IllegalArgumentException("Only UUID supported, but found " + obj.getClass()); mDialect.writeUUID(pPs, pParamCount, value); return value; } case Binary: { byte[] value; if (obj == null) value = null; else if (obj instanceof byte[]) value = (byte[]) obj; else throw new IllegalArgumentException("Only byte[] supported, but found " + obj.getClass()); mDialect.writeBinary(pPs, pParamCount, value); return value; } } return null; } catch (SQLException ex) { throw new RuntimeException(ex); } } @Override public <@Nullable O> int serializeToPreparedStatement(O pObj, PreparedStatement pPs, int pStartAtIndex) throws SQLException { if (pObj == null) throw new UnsupportedOperationException(); if (Map.class.isAssignableFrom(pObj.getClass()) == false) throw new UnsupportedOperationException(); @SuppressWarnings("unchecked") Map<String, Object> data = (Map<String, Object>) pObj; int index = pStartAtIndex; for (IKVColumnDefinition cd : mDefinition.getColumnDefinitions()) { Object obj = data.get(cd.getName()); serializeColumnToPreparedStatement(obj, cd, pPs, index); index++; } return index; } }
35.168367
124
0.6112
222da1c49ebf731f2563542caeeecafcaf5fa690
614
package com.dhcc.shanjupay.user.convert; import com.dhcc.shanjupay.user.api.dto.menu.MenuDTO; import com.dhcc.shanjupay.user.entity.ResourceMenu; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; import java.util.List; @Mapper public interface ResourceMenuConvert { ResourceMenuConvert INSTANCE = Mappers.getMapper(ResourceMenuConvert.class); MenuDTO entity2dto(ResourceMenu entity); ResourceMenu dto2entity(MenuDTO dto); List<MenuDTO> entitylist2dto(List<ResourceMenu> resourceMenu); List<ResourceMenu> dtolist2entity(List<MenuDTO> menuDTO); }
25.583333
81
0.765472
1335e349f13c616da685b78bccaf26b9b9649b1c
1,339
// https://leetcode.com/problems/kth-largest-element-in-a-stream/ class KthLargest { // https://leetcode.com/problems/kth-largest-element-in-a-stream/discuss/544481/Java-With-Explanation private int k; private Queue<Integer> queue; public KthLargest(int k, int[] nums) { this.k = k; this.queue = new PriorityQueue<>(); for (int num : nums) { add(num); } } public int add(int val) { queue.add(val); if (queue.size() > this.k) { queue.poll(); } int kthLargest = queue.peek(); return kthLargest; } // Alternative accepted, but much slower solution /* private List<Integer> numbers; private int k; public KthLargest(int k, int[] nums) { this.k = k; this.numbers = new ArrayList<>(); for (int num : nums) { numbers.add(num); } } public int add(int val) { numbers.add(val); Collections.sort(numbers); int kthLargest = numbers.get( numbers.size()-k ); return kthLargest; } */ } /** * Your KthLargest object will be instantiated and called as such: * KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */
22.316667
105
0.534727
fe9bbdd649703411009998f94c78f15a244f2f91
2,122
package com.netthreads.gwt.client.service; import java.util.LinkedList; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestBuilder; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.RequestException; import com.google.gwt.http.client.Response; import com.google.gwt.user.client.Window; import com.netthreads.gwt.client.common.TrafficData; import com.netthreads.gwt.client.view.MainView; public class TrafficDataService { private static final String JSON_URL = GWT.getHostPageBaseURL(); public static final String DATA_M25 = "M60.json"; /** * Fetch data. * * @param view */ public void getTrafficData(final MainView view) { String url = JSON_URL + DATA_M25; RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url); try { builder.sendRequest(null, new RequestCallback() { public void onError(Request request, Throwable exception) { Window.alert("Couldn't retrieve JSON"); } public void onResponseReceived(Request request, Response response) { if (200 == response.getStatusCode()) { List<TrafficData> list = new LinkedList<TrafficData>(); JsArray<TrafficData> trafficData = asArrayOfTrafficData(response.getText()); for (int i = 0; i < trafficData.length(); i++) { TrafficData data = trafficData.get(i); list.add(data); } // Add data to view. view.setItemData(list); } else { Window.alert("Couldn't retrieve JSON (" + response.getStatusText() + ")"); } } }); } catch (RequestException e) { Window.alert("Couldn't retrieve JSON"); } } /** * Convert json data to array of data. * * @param json * The json * * @return The array of data. */ private final native JsArray<TrafficData> asArrayOfTrafficData(String json) /*-{ return eval(json); }-*/; }
24.674419
83
0.654571
6b447e12d6effed31a03acbace568c86bf4bb90b
2,756
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.samples.litho.java.errors; import android.graphics.Typeface; import android.util.Log; import androidx.annotation.ColorInt; import com.facebook.litho.ClickEvent; import com.facebook.litho.Column; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.annotations.LayoutSpec; import com.facebook.litho.annotations.OnCreateLayout; import com.facebook.litho.annotations.OnEvent; import com.facebook.litho.annotations.Prop; import com.facebook.litho.utils.StacktraceHelper; import com.facebook.litho.widget.Text; import com.facebook.yoga.YogaEdge; /** * Renders a throwable as a text with a title and provides a touch callback that logs the throwable * with WTF level. */ @LayoutSpec public class DebugErrorComponentSpec { private static final String TAG = "DebugErrorComponentSpec"; private static final @ColorInt int DARK_RED_FRAME = 0xffcd4928; private static final @ColorInt int LIGHT_RED_BACKGROUND = 0xfffcece9; private static final @ColorInt int LIGHT_GRAY_TEXT = 0xff606770; @OnCreateLayout public static Component onCreateLayout( ComponentContext c, @Prop String message, @Prop Throwable throwable) { Log.e(TAG, message, throwable); return Column.create(c) .backgroundColor(DARK_RED_FRAME) .paddingDip(YogaEdge.ALL, 1f) .child( Text.create(c) .backgroundColor(LIGHT_RED_BACKGROUND) .paddingDip(YogaEdge.ALL, 4f) .textSizeDip(16f) .text(message)) .child( Text.create(c) .backgroundColor(LIGHT_RED_BACKGROUND) .paddingDip(YogaEdge.ALL, 4f) .textSizeDip(12f) .textColor(LIGHT_GRAY_TEXT) .typeface(Typeface.MONOSPACE) .text(StacktraceHelper.formatStacktrace(throwable))) .clickHandler(DebugErrorComponent.onClick(c)) .build(); } @OnEvent(ClickEvent.class) static void onClick(ComponentContext c, @Prop String message, @Prop Throwable throwable) { Log.wtf(TAG, message, throwable); } }
35.333333
99
0.714441
8e869bb6a2d6d1bdc5df841afd5437cc7dcfc45d
4,289
package org.z.component.cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import lombok.extern.slf4j.Slf4j; import org.springframework.cache.caffeine.CaffeineCache; import org.springframework.lang.Nullable; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 默认最多缓存30天 * * @author z */ @Slf4j public class MemoryZCache extends CaffeineCache implements ZCache { private static final String NAME = "Z_CACHE_NAME"; private static final int EXPIRE_AFTER_ACCESS_DAYS = 30; public MemoryZCache() { super(NAME, Caffeine.newBuilder().expireAfterAccess(EXPIRE_AFTER_ACCESS_DAYS, TimeUnit.DAYS).build()); new ScheduledThreadPoolExecutor(1, r -> new Thread(r, "LocalMemoryCacheCleaner")) .scheduleWithFixedDelay(this::evict, 1, 1, TimeUnit.MINUTES); } @Override public void put(String key, Object value, long timeout) { this.put(key, new CacheData(value, timeout)); } @Override public ValueWrapper get(Object key) { if (getNativeCache() instanceof LoadingCache) { Object value = ((LoadingCache<Object, Object>) this.getNativeCache()).get(key); if (value instanceof CacheData) { CacheData cd = (CacheData) value; if (cd.isExpired()) { return toValueWrapper(null); } value = cd.data; } return toValueWrapper(value); } return toValueWrapper(lookup(key)); } @SuppressWarnings("unchecked") @Override public <T> T get(Object key, final Callable<T> valueLoader) { Object value = fromStoreValue(this.getNativeCache().get(key, x -> { try { return toStoreValue(valueLoader.call()); } catch (Exception e) { throw new ValueRetrievalException(x, valueLoader, e); } })); if (value instanceof CacheData) { CacheData cd = (CacheData) value; if (cd.isExpired()) { return null; } return (T) cd.data; } return (T) value; } @Override @Nullable protected Object lookup(Object key) { Object value = this.getNativeCache().getIfPresent(key); if (value instanceof CacheData) { CacheData cd = (CacheData) value; if (cd.isExpired()) { return null; } return cd.data; } return value; } @Override public void expire(String key, long timeout) { CacheData value = get(key, CacheData.class); if (value == null) { return; } if (value.isExpired()) { evict(key); return; } value.setExpireTime(timeout); } private void evict() { Set<Map.Entry<Object, Object>> keys = getNativeCache().asMap().entrySet(); Set<String> set = new HashSet<>(); for (Map.Entry<Object, Object> entry : keys) { CacheData value = (CacheData) entry.getValue(); if (value.isExpired()) { evict(entry.getKey()); set.add((String) entry.getKey()); } } log.info("清理本地内存缓存{}个,keys:{}", set.size(), set.toString()); } private static class CacheData { private final Object data; private long expireTime; public CacheData(Object t, long expire) { this.data = t; if (expire <= 0) { this.expireTime = 0L; } else { this.expireTime = System.currentTimeMillis() + expire; } } /** * 判断缓存数据是否过期 * * @return true表示过期,false表示未过期 */ public boolean isExpired() { if (expireTime <= 0) { return false; } return expireTime <= System.currentTimeMillis(); } public void setExpireTime(long expireTime) { this.expireTime = expireTime; } } }
29.376712
110
0.567265
54cd2feeea698d6eff27533413cb974e4c83f2c8
2,909
/** * Copyright (C) 2002 Mike Hummel (mh@mhus.de) * * 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 de.mhus.lib.internal; /** * @author hummel * <p>To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public class TThread { protected static TLog log = TLog.getLog(TThread.class); /** * Sleeps _millisec milliseconds. On Interruption it will throw an RuntimeInterruptedException * * @param _millisec */ public static void sleep(long _millisec) { try { Thread.sleep(_millisec); } catch (InterruptedException e) { throw new TRuntimeInterruptedException(e); } } /** * Sleeps _millisec milliseconds. On Interruption it will throw an InterruptedException. If * thread is already interrupted, it will throw the exception directly. * * <p>This can be used in loops if a interrupt should be able to stop the loop. * * @param _millisec * @throws InterruptedException on interrupt */ public static void sleepInLoop(long _millisec) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); Thread.sleep(_millisec); } /** * Sleeps _millisec milliseconds. On Interruption it will print a debug stack trace but not * break. It will leave the Thread.interrupted state to false see * https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html * * @param _millisec * @return true if the thread was interrupted in the sleep time */ public static boolean sleepForSure(long _millisec) { boolean interrupted = false; while (true) { long start = System.currentTimeMillis(); try { Thread.sleep(_millisec); return interrupted; } catch (InterruptedException e) { interrupted = true; try { Thread.sleep(1); // clear interrupted state } catch (InterruptedException e1) { } log.d(e); long done = System.currentTimeMillis() - start; _millisec = _millisec - done; if (_millisec <= 0) return interrupted; } } } }
34.223529
98
0.633207
45c52c53177b21ed8c7db77d2e41650d1dbea07b
475
package com.mb.model.bonusPoint; import com.mb.model.AbstractEntity; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @Table(name = "bonus_point") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "type") @Getter @NoArgsConstructor public class BonusPoint extends AbstractEntity { @Column(nullable = false) private Long value; public BonusPoint(final Long value) { this.value = value; } }
19.791667
53
0.776842
181d32bdd29e8e8c76e76e5a4e3d58b79915a7c1
9,728
package GlobalUtilities; /* * AudioLoop.java * * This file is part of jsresources.org */ /* * Copyright (c) 1999 - 2003 by Matthias Pfisterer * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* |<--- this code is formatted to fit into 80 columns --->| */ import java.io.IOException; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.TargetDataLine; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.AudioFileFormat; /* If the compilation fails because this class is not available, get gnu.getopt from the URL given in the comment below. */ import gnu.getopt.Getopt; // TODO: params for audio quality, optionally use compression and decompression in the loop (see ~/AudioLoop.java) /** <titleabbrev>AudioLoop</titleabbrev> <title>Recording and playing back the recorded data immediately</title> <formalpara><title>Purpose</title> <para> This program opens two lines: one for recording and one for playback. In an infinite loop, it reads data from the recording line and writes them to the playback line. You can use this to measure the delays inside Java Sound: Speak into the microphone and wait untill you hear yourself in the speakers. This can be used to experience the effect of changing the buffer sizes: use the <option>-e</option> and <option>-i</option> options. You will notice that the delays change, too. </para></formalpara> <formalpara><title>Usage</title> <para> <cmdsynopsis> <command>java AudioLoop</command> <arg choice="plain"><option>-l</option></arg> </cmdsynopsis> <cmdsynopsis> <command>java AudioLoop</command> <arg><option>-M <replaceable>mixername</replaceable></option></arg> <arg><option>-e <replaceable>buffersize</replaceable></option></arg> <arg><option>-i <replaceable>buffersize</replaceable></option></arg> </cmdsynopsis> </para></formalpara> <formalpara><title>Parameters</title> <variablelist> <varlistentry> <term><option>-l</option></term> <listitem><para>lists the available mixers</para></listitem> </varlistentry> <varlistentry> <term><option>-M <replaceable>mixername</replaceable></option></term> <listitem><para>selects a mixer to play on</para></listitem> </varlistentry> <varlistentry> <term><option>-e <replaceable>buffersize</replaceable></option></term> <listitem><para>the buffer size to use in the application ("extern")</para></listitem> </varlistentry> <varlistentry> <term><option>-i <replaceable>buffersize</replaceable></option></term> <listitem><para>the buffer size to use in Java Sound ("intern")</para></listitem> </varlistentry> </variablelist> </formalpara> <formalpara><title>Bugs, limitations</title> <para> There is no way to stop the program besides brute force (ctrl-C). There is no way to set the audio quality. </para> <para>The example requires that the soundcard and its driver as well as the Java Sound implementation support full-duplex operation. In Linux either use <ulink url="http://www.tritonus.org/">Tritonus</ulink> or enable full-duplex in Sun's Java Sound implementation (search the archive of java-linux).</para> </formalpara> <formalpara><title>Source code</title> <para> <ulink url="AudioLoop.java.html">AudioLoop.java</ulink>, <ulink url="AudioCommon.java.html">AudioCommon.java</ulink>, <ulink url="http://www.urbanophile.com/arenn/hacking/download.html">gnu.getopt.Getopt</ulink> </para> </formalpara> */ public class AudioLoop extends Thread { /** Flag for debugging messages. * If true, some messages are dumped to the console * during operation. */ private static boolean DEBUG; private static final int DEFAULT_INTERNAL_BUFSIZ = 40960; private static final int DEFAULT_EXTERNAL_BUFSIZ = 40960; private TargetDataLine m_targetLine; private SourceDataLine m_sourceLine; private boolean m_bRecording; private int m_nExternalBufferSize; /* * We have to pass an AudioFormat to describe in which * format the audio data should be recorded and played. */ public AudioLoop(AudioFormat format, int nInternalBufferSize, int nExternalBufferSize, String strMixerName) throws LineUnavailableException { Mixer mixer = null; if (strMixerName != null) { Mixer.Info mixerInfo = AudioCommon.getMixerInfo(strMixerName); if (DEBUG) { out("AudioLoop.<init>(): mixer info: " + mixerInfo); } mixer = AudioSystem.getMixer(mixerInfo); if (DEBUG) { out("AudioLoop.<init>(): mixer: " + mixer); } } /* * We retrieve and open the recording and the playback line. */ DataLine.Info targetInfo = new DataLine.Info(TargetDataLine.class, format, nInternalBufferSize); DataLine.Info sourceInfo = new DataLine.Info(SourceDataLine.class, format, nInternalBufferSize); if (mixer != null) { m_targetLine = (TargetDataLine) mixer.getLine(targetInfo); m_sourceLine = (SourceDataLine) mixer.getLine(sourceInfo); } else { m_targetLine = (TargetDataLine) AudioSystem.getLine(targetInfo); m_sourceLine = (SourceDataLine) AudioSystem.getLine(sourceInfo); } if (DEBUG) { out("AudioLoop.<init>(): SourceDataLine: " + m_sourceLine); } if (DEBUG) { out("AudioLoop.<init>(): TargetDataLine: " + m_targetLine); } m_targetLine.open(format, nInternalBufferSize); m_sourceLine.open(format, nInternalBufferSize); m_nExternalBufferSize = nExternalBufferSize; } public void start() { m_targetLine.start(); m_sourceLine.start(); // start thread super.start(); } /* public void stopRecording() { m_line.stop(); m_line.close(); m_bRecording = false; } */ public void run() { byte[] abBuffer = new byte[m_nExternalBufferSize]; int nBufferSize = abBuffer.length; m_bRecording = true; while (m_bRecording) { if (DEBUG) { out("Trying to read: " + nBufferSize); } /* * read a block of data from the recording line. */ int nBytesRead = m_targetLine.read(abBuffer, 0, nBufferSize); if (DEBUG) { out("Read: " + nBytesRead); } /* * And now, we write the block to the playback * line. */ m_sourceLine.write(abBuffer, 0, nBytesRead); } } public static void main(String[] args) { String strMixerName = null; float fFrameRate = 44100.0F; int nInternalBufferSize = DEFAULT_INTERNAL_BUFSIZ; int nExternalBufferSize = DEFAULT_EXTERNAL_BUFSIZ; Getopt g = new Getopt("AudioLoop", args, "hlr:i:e:M:D"); int c; while ((c = g.getopt()) != -1) { switch (c) { case 'h': printUsageAndExit(); case 'l': AudioCommon.listMixersAndExit(); case 'r': fFrameRate = Float.parseFloat(g.getOptarg()); if (DEBUG) { out("AudioLoop.main(): frame rate: " + fFrameRate); } break; case 'i': nInternalBufferSize = Integer.parseInt(g.getOptarg()); if (DEBUG) { out("AudioLoop.main(): internal buffer size: " + nInternalBufferSize); } break; case 'e': nExternalBufferSize = Integer.parseInt(g.getOptarg()); if (DEBUG) { out("AudioLoop.main(): external buffer size: " + nExternalBufferSize); } break; case 'M': strMixerName = g.getOptarg(); if (DEBUG) { out("AudioLoop.main(): mixer name: " + strMixerName); } break; case 'D': DEBUG = true; break; case '?': printUsageAndExit(); default: out("AudioLoop.main(): getopt() returned: " + c); break; } } AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, fFrameRate, 16, 2, 4, fFrameRate, false); if (DEBUG) { out("AudioLoop.main(): audio format: " + audioFormat); } AudioLoop audioLoop = null; try { audioLoop = new AudioLoop(audioFormat, nInternalBufferSize, nExternalBufferSize, strMixerName); } catch (LineUnavailableException e) { e.printStackTrace(); System.exit(1); } audioLoop.start(); } private static void printUsageAndExit() { out("AudioLoop: usage:"); out("\tjava AudioLoop -h"); out("\tjava AudioLoop -l"); out("\tjava AudioLoop [-D] [-M <mixername>] [-e <buffersize>] [-i <buffersize>]"); System.exit(1); } private static void out(String strMessage) { System.out.println(strMessage); } } /*** AudioLoop.java ***/
29.389728
118
0.71176
6f07d656fed7a32ae3facb26f33d2d4428fa7878
5,082
package ch.hslu.ad.sw02_D1.list; import java.util.Iterator; import java.util.NoSuchElementException; public class MyList<T> implements Iterable<T>{ private Node head; private Node tail; private int size; public MyList() { this.head = null; this.tail = null; this.size = 0; } public boolean isEmpty(){ return size == 0; } public void addFirst(T data) { Node<T> newNode = new Node<T>(data); if (isEmpty()){ head = newNode; tail = newNode; } else { head.setPrevious(newNode); newNode.setNext(head); head = newNode; } size ++; } public void addAllFirst(T... datas) { for (T data : datas) { addFirst(data); } } public void addLast(T data) { Node<T> newNode = new Node<T>(data); if (isEmpty()){ head = newNode; tail = newNode; } else { tail.setNext(newNode); newNode.setPrevious(tail); tail = newNode; } size ++; } public Node<T> removeFirst() { if (isEmpty()){ throw new NoSuchElementException(); } else { Node<T> firstNode = head; Node<T> newFirstNode = firstNode.getNext(); newFirstNode.previous = null; head = newFirstNode; size --; return firstNode; } } /* public T getElement(T data){ Iterator<T> it = iterator(); if (isEmpty()){ throw new NoSuchElementException(); } while (it.hasNext()){ T node = it.next(); if ( node.equals(data)){ return node; } } return null; }*/ public Node<T> getElement(T data){ if (isEmpty()){ throw new NoSuchElementException(); } Node currentNode = head; while (currentNode != null){ if (currentNode.data.equals(data)){ return currentNode; } currentNode = currentNode.next; } throw new NoSuchElementException(); } public void removeElement(T data) { Node<T> node = getElement(data); Node<T> previousNode = node.previous; Node<T> nextNode = node.next; previousNode.next = nextNode; nextNode.previous = previousNode; node.previous = null; node.next = null; size--; } public int getSize() { return size; } @Override public String toString() { Node node = head; StringBuilder string = new StringBuilder(); while (node != null) { string.append(" ").append(node.toString()).append(System.lineSeparator()); node = node.getNext(); } string.append(" size: ").append(size); return string.toString(); } @Override public Iterator<T> iterator() { return new ListIterator<>(); } public class ListIterator<T> implements Iterator<T> { private Node<T> currentNode; private Node<T> previousNode; public ListIterator() { this.currentNode = head; this.previousNode = null; } @Override public boolean hasNext() { if (currentNode != null) { return true; } else { return false; } } @Override public T next() { if (!hasNext()){ return null; } T data = currentNode.getData(); previousNode = currentNode; currentNode = currentNode.getNext(); return data; } @Override public void remove(){ if (currentNode != null) { if (previousNode != null) { previousNode.next = currentNode.next; } else { head = currentNode.next; } } } } private static class Node<T> { private Node<T> next; private Node<T> previous; private T data; public Node(T data) { this(null,null,data); } public Node(Node<T> next, Node<T> previous, T data) { this.next = next; this.previous = previous; this.data = data; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node<T> next){ this.next = next; } public Node<T> getPrevious() { return previous; } public void setPrevious(Node<T> previous) { this.previous = previous; } @Override public String toString() { return "data: " + data.toString(); } } }
22.995475
86
0.482487
792df2efabd8f020dd8de69a462272ab4a0f3742
279
package com.webprague.service; import java.sql.Timestamp; import java.sql.Date; import java.util.List; public interface DateService { public int addDate(int num, Date dateTime); public List<com.webprague.model.Date> findAllByMonth(Date start_month, Date end_month); }
23.25
91
0.774194
d882e85c479abb6f13c6c3e7841e655c2d5b6449
1,431
package com.jj.server; import com.jj.client.ClientInitialTask; import com.jj.protocol.MessageRequest; import com.jj.protocol.MessageResponse; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.util.Map; /** * Created by jomalone_jia on 2018/3/15. */ public class ServerHandler extends SimpleChannelInboundHandler { private static final Logger logger = LoggerFactory.getLogger(ServerHandler.class); private Map<String, Class<?>> handlerMap; public ServerHandler(Map<String, Class<?>> handlerMap) { this.handlerMap = handlerMap; } @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception { MessageRequest request = (MessageRequest) msg; logger.info(logger.toString()); System.out.println(request.toString()); Class<?> aClass = handlerMap.get(request.getClassName()); if(aClass != null){ Method method = aClass.getMethod(request.getMethodName(), request.getTypeParameters()); MessageResponse messageResponse = new MessageResponse(); messageResponse.setResult(method.invoke(aClass.newInstance(), request.getParametersVal())); channelHandlerContext.writeAndFlush(messageResponse); } } }
34.071429
107
0.730259
54e41598e28c38ea017f46d31844ac718a58f922
600
package com.alibaba.alink.pipeline.nlp; import com.alibaba.alink.operator.common.nlp.bert.BertTextEmbeddingMapper; import com.alibaba.alink.params.tensorflow.bert.BertTextEmbeddingParams; import com.alibaba.alink.pipeline.MapTransformer; import org.apache.flink.ml.api.misc.param.Params; public class BertTextEmbedding extends MapTransformer<BertTextEmbedding> implements BertTextEmbeddingParams<BertTextEmbedding> { public BertTextEmbedding() { this(new Params()); } public BertTextEmbedding(Params params) { super(BertTextEmbeddingMapper::new, params); } }
30
74
0.781667
85b6ec54020f2b0ae3b2a3ac12587d0c8439185e
396
package pnet.data.api.util; import java.time.LocalDateTime; /** * A restriction for the update timestamp * * @author ham * @param <SELF> the type of the restrict for chaining */ public interface RestrictUpdatedAfter<SELF extends Restrict<SELF>> extends Restrict<SELF> { default SELF updatedAfter(LocalDateTime updatedAfter) { return restrict("up", updatedAfter); } }
19.8
89
0.717172
9d98ccdb2dd18ba4366ac62792a91f3b8b79020c
2,039
/* * $Id: PwsIntegerField.java 297 2004-02-24 22:29:25Z preecek $ * * Copyright (c) 2008-2014 David Muller <roxon@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ package org.pwsafe.lib.file; /** * Provides a wrapper for fields that holds the passwordsafe file version. * Integer values are stored in the database in little-endian order and are * converted to and from this format on writing and reading. * * @author Glen Smith */ public class PwsVersionField extends PwsIntegerField { /** * Constructs the object * * @param type the field type. Values depend on the version of the file * being read. * @param value the byte array holding the integer value. * * @throws IndexOutOfBoundsException If <code>value.length</code> &lt; 4. */ public PwsVersionField(int type, byte[] value) { super(type, new byte[] { 0, 0, value.length > 0 ? value[0] : 0, value.length > 1 ? value[1] : 0 }); } /** * Constructs the object * * @param type the field type. Values depend on the version of the file * being read. * @param value the byte array holding the integer value. * * @throws IndexOutOfBoundsException If <code>value.length</code> &lt; 4. */ public PwsVersionField(PwsFieldType type, byte[] value) { super(type, new byte[] { 0, 0, value.length > 0 ? value[0] : 0, value.length > 1 ? value[1] : 0 }); } /** * Returns this integer as an array of bytes. The returned array will have a * length of PwsFile.BLOCK_LENGTH and is thus suitable to be written to the * database. * * @return a byte array containing the field's integer value. * * @see org.pwsafe.lib.file.PwsField#getBytes() */ @Override public byte[] getBytes() { final byte[] intRetval = super.getBytes(); return new byte[] { intRetval[2], intRetval[3] }; } }
31.369231
77
0.681216
05662e06ecf69fda246911a8d5110726bdcb6e12
211
package net.teumert.prime.api; import io.quarkus.test.junit.NativeImageTest; @NativeImageTest public class NativePrimeResourceIT extends PrimeResourceTest { // Execute the same tests but in native mode. }
23.444444
62
0.800948
1ae452418da846bbf7b09d3f3ad79288dc7f2312
310
package nl.lxtreme.user.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; /** * Nothing special here, just a sample "user" resource. */ @Path("/") public class UserResource { @GET public Response getUserStuff() { return Response.ok("Hello User!").build(); } }
16.315789
55
0.693548
60112bf73338f5c2628c02f530c4beb2e05b78bf
8,694
package kr.ac.kopo.kopo40.web; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Optional; import javax.transaction.Transactional; import org.hibernate.Hibernate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.web.PageableDefault; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import kr.ac.kopo.kopo40.domain.Board; import kr.ac.kopo.kopo40.domain.BoardItem; import kr.ac.kopo.kopo40.domain.Comment; import kr.ac.kopo.kopo40.repository.BoardItemRepository; import kr.ac.kopo.kopo40.repository.BoardRepository; import kr.ac.kopo.kopo40.repository.CommentRepository; @Controller public class BoardItemController { @Autowired private BoardRepository boardRepository; @Autowired private BoardItemRepository boardItemRepository; @Autowired private CommentRepository commentRepository; /* 게시글 목록 */ @RequestMapping("/BoardItemList/{board_index}") public String listBoardItem(Model model, @PathVariable("board_index") int board_index, @PageableDefault(size = 10) Pageable pageable, @RequestParam(required = false, defaultValue = "") String field, @RequestParam(required = false, defaultValue = "") String word) { Page<BoardItem> boardItems = boardItemRepository.findAllByBoard_idOrderByIdDesc(board_index, pageable); int pageNumber = boardItems.getPageable().getPageNumber(); // 현재페이지 int totalPages = boardItems.getTotalPages(); // 총 페이지 수. 검색에따라 10개면 10개.. int pageBlock = 5; // 블럭의 수 1, 2, 3, 4, 5 int startBlockPage = ((pageNumber) / pageBlock) * pageBlock + 1; // 현재 페이지가 7이라면 1*5+1=6 int endBlockPage = startBlockPage + pageBlock - 1; // 6+5-1=10. 6,7,8,9,10해서 10. endBlockPage = totalPages < endBlockPage ? totalPages : endBlockPage; model.addAttribute("startBlockPage", startBlockPage); model.addAttribute("endBlockPage", endBlockPage); model.addAttribute("boardItems", boardItems); Optional<Board> board = boardRepository.findById(board_index); model.addAttribute("board", board.get()); return "/BoardItemList"; } /* 새로운 게시글 작성 */ @RequestMapping(value = "/BoardItemInsert/{board_index}") public String InsertBoardItem(@PathVariable("board_index") int board_index, Model model) { int lastCnt = boardItemRepository.max(board_index); int[] values = { board_index, lastCnt }; model.addAttribute("values", values); return "/BoardItemInsert"; } /* 새로운 게시글 등록 */ @Transactional @RequestMapping("/BoardItemWrite/{board_index}") public String writeBoardItem(@RequestParam("board_index") int board_index, @RequestParam("get_id") int id, @RequestParam("get_viewcnt") int viewcnt, @RequestParam("get_title") String title, @RequestParam("get_content") String content, Model model) { int[] values = { board_index, id }; model.addAttribute("values", values); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Optional<Board> board = boardRepository.findById(board_index); BoardItem boardItem = new BoardItem(); boardItem.setBoard(board.get()); boardItem.setId(id); boardItem.setTitle(title); boardItem.setContent(content); boardItem.setViewCnt(viewcnt); boardItem.setDate(sdf.format(date)); board.get().addBoardItem(boardItem); Hibernate.initialize(boardItem); boardRepository.save(board.get()); return "/BoardItemWrite"; } /* 게시글 보기 */ @Modifying @Transactional @RequestMapping(value = "/BoardItemView/{board_index}/{id}") public String selectOne(@PathVariable("board_index") int board_id, @PathVariable("id") int id, Model model) { boardItemRepository.addViewCnt(board_id, id); Optional<BoardItem> returnedBoardItem = boardItemRepository.findOneByIdAndBoard_id(id, board_id); List<Comment> returnedComments = commentRepository.findOneByBoard_idAndPost_id(board_id, id); BoardItem boardItem = new BoardItem(); boardItem = returnedBoardItem.get(); model.addAttribute("boardItem", boardItem); model.addAttribute("comments", returnedComments); return "/BoardItemView"; } /* 게시글 수정 페이지 */ @RequestMapping(value = "/BoardItemUpdate/{board_id}/{id}") public String updateBoardItem(@PathVariable("board_id") int board_id, @PathVariable("id") int id, Model model) { Optional<BoardItem> boardItem = boardItemRepository.findOneByBoard_idAndId(board_id, id); model.addAttribute("boardItem", boardItem.get()); return "/BoardItemUpdate"; } /* 게시글 수정 등록 */ @RequestMapping(value = "/BoardItemSet/{board_id}/{id}") public String setBoardItem(@PathVariable("board_id") int board_id, @PathVariable("id") int id, @RequestParam("get_title") String title, @RequestParam("get_content") String content, Model model) { Optional<BoardItem> boardItem = boardItemRepository.findOneByBoard_idAndId(board_id, id); model.addAttribute("boardItem", boardItem.get()); boardItemRepository.setBoardItem(title, content, board_id, id); return "/BoardItemSet"; } /* 게시글 삭제 */ @Modifying @Transactional @RequestMapping(value = "/BoardItemDelete/{board_id}/{id}") public String deleteBoardItem(@PathVariable("board_id") int board_id, @PathVariable("id") int id, Model model) { int[] values = { board_id, id }; model.addAttribute("values", values); Optional<Board> board = boardRepository.findById(board_id); Optional<BoardItem> boardItem = boardItemRepository.findOneByBoard_idAndId(board_id, id); board.get().getBoardItems().remove(boardItem.get()); boardItem.get().setBoard(null); boardItemRepository.delete(boardItem.get()); boardRepository.save(board.get()); return "/BoardItemDelete"; } @RequestMapping(value = "/BoardItemSearch") public String searchBoardItem(@RequestParam("keyword") String keyword, @PageableDefault(size = 10) Pageable pageable, @RequestParam(required = false, defaultValue = "") String field, @RequestParam(required = false, defaultValue = "") String word, Model model) { Page<BoardItem> boardItems = boardItemRepository.searchByKeyword(keyword, pageable); String noResult = ""; if (boardItems.isEmpty()) { noResult = "검색결과가 없습니다."; } int pageNumber = boardItems.getPageable().getPageNumber(); // 현재페이지 int totalPages = boardItems.getTotalPages(); // 총 페이지 수. 검색에따라 10개면 10개.. int pageBlock = 5; // 블럭의 수 1, 2, 3, 4, 5 int startBlockPage = ((pageNumber) / pageBlock) * pageBlock + 1; // 현재 페이지가 7이라면 1*5+1=6 int endBlockPage = startBlockPage + pageBlock - 1; // 6+5-1=10. 6,7,8,9,10해서 10. endBlockPage = totalPages < endBlockPage ? totalPages : endBlockPage; model.addAttribute("startBlockPage", startBlockPage); model.addAttribute("endBlockPage", endBlockPage); model.addAttribute("boardItems", boardItems); model.addAttribute("keyword", keyword); model.addAttribute("noResult", noResult); return "/BoardItemSearch"; } @RequestMapping(value = "/BoardItemSearch/{keyword}") public String searchBoardItemPaging(@PathVariable("keyword") String keyword, @PageableDefault(size = 10) Pageable pageable, @RequestParam(required = false, defaultValue = "") String field, @RequestParam(required = false, defaultValue = "") String word, Model model) { Page<BoardItem> boardItems = boardItemRepository.searchByKeyword(keyword, pageable); String noResult = ""; if (boardItems.isEmpty()) { noResult = "검색결과가 없습니다."; } int pageNumber = boardItems.getPageable().getPageNumber(); // 현재페이지 int totalPages = boardItems.getTotalPages(); // 총 페이지 수. 검색에따라 10개면 10개.. int pageBlock = 5; // 블럭의 수 1, 2, 3, 4, 5 int startBlockPage = ((pageNumber) / pageBlock) * pageBlock + 1; // 현재 페이지가 7이라면 1*5+1=6 int endBlockPage = startBlockPage + pageBlock - 1; // 6+5-1=10. 6,7,8,9,10해서 10. endBlockPage = totalPages < endBlockPage ? totalPages : endBlockPage; model.addAttribute("startBlockPage", startBlockPage); model.addAttribute("endBlockPage", endBlockPage); model.addAttribute("boardItems", boardItems); model.addAttribute("keyword", keyword); model.addAttribute("noResult", noResult); return "/BoardItemSearch"; } // @RequestMapping(value = "/BoardItemView") // public String selectAll(Model model) { // PageRequest pageable = PageRequest.of(0, 10); // Page<BoardItem> page = boardItemRepository.findAll(pageable); // model.addAttribute("BoardItems", page.getContent()); // // return "/BoardItemView"; // } }
37.8
113
0.745802
fedb030b88ad4522c2080feca2d128161be24dd9
1,053
package com.yarolegovich.slidingrootnav.sample.conexion; import android.content.Context; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; /** * Created by Yerko on 08/06/2017. */ public class Singleton { private static Singleton singleton; private RequestQueue requestQueue; private static Context context; private Singleton(Context context) { Singleton.context = context; requestQueue = getRequestQueue(); } public static synchronized Singleton getInstance(Context context) { if (singleton == null) { singleton = new Singleton(context.getApplicationContext()); } return singleton; } public RequestQueue getRequestQueue() { if (requestQueue == null) { requestQueue = Volley.newRequestQueue(context.getApplicationContext()); } return requestQueue; } public <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } }
24.488372
83
0.679012
4c3fff7e11ea2816fc3edcf858e3a0cd71698cac
3,955
package mchorse.blockbuster.api.loaders.lazy; import mchorse.blockbuster.api.Model; import mchorse.blockbuster.api.ModelLimb; import mchorse.blockbuster.api.ModelPose; import mchorse.blockbuster.api.ModelTransform; import mchorse.blockbuster.api.formats.IMeshes; import mchorse.blockbuster.api.formats.obj.OBJDataMesh; import mchorse.blockbuster.api.resource.FileEntry; import mchorse.blockbuster.api.resource.IResourceEntry; import mchorse.blockbuster.api.formats.obj.OBJParser; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.StringJoiner; public class ModelLazyLoaderOBJ extends ModelLazyLoaderJSON { public IResourceEntry obj; public IResourceEntry mtl; private OBJParser parser; private long lastModified; public ModelLazyLoaderOBJ(IResourceEntry model, IResourceEntry obj, IResourceEntry mtl) { super(model); this.obj = obj; this.mtl = mtl; } @Override public int getFilenameHash() { return (this.model.getName() + "/" + this.obj.getName() + "/" + this.mtl.getName()).hashCode(); } @Override public long lastModified() { return Math.max(this.model.lastModified(), Math.max(this.obj.lastModified(), this.mtl.lastModified())); } @Override public Model loadModel(String key) throws Exception { Model model = null; try { model = super.loadModel(key); } catch (Exception e) {} if (model == null) { model = this.generateOBJModel(key); } return model; } @Override @SideOnly(Side.CLIENT) protected Map<String, IMeshes> getMeshes(String key, Model model) throws Exception { try { Map<String, IMeshes> meshes = this.getOBJParser(key, model).compile(); this.parser = null; this.lastModified = 0; return meshes; } catch (Exception e) {} return null; } /** * Create an OBJ parser */ public OBJParser getOBJParser(String key, Model model) { if (!model.providesObj) { return null; } long lastModified = this.lastModified(); if (this.lastModified < lastModified) { this.lastModified = lastModified; } else { return this.parser; } try { InputStream obj = this.obj.getStream(); InputStream mtl = model.providesMtl ? this.mtl.getStream() : null; this.parser = new OBJParser(obj, mtl); this.parser.read(); if (this.mtl instanceof FileEntry) { this.parser.setupTextures(key, ((FileEntry) this.mtl).file.getParentFile()); } model.materials.putAll(this.parser.materials); } catch (Exception e) { return null; } return this.parser; } /** * Generate custom model based on given OBJ */ private Model generateOBJModel(String model) { /* Generate custom model for an OBJ model */ Model data = new Model(); ModelPose blocky = new ModelPose(); blocky.setSize(1, 1, 1); data.poses.put("flying", blocky.clone()); data.poses.put("standing", blocky.clone()); data.poses.put("sneaking", blocky.clone()); data.poses.put("sleeping", blocky.clone()); data.poses.put("riding", blocky.clone()); data.name = model; data.providesObj = true; data.providesMtl = this.mtl.exists(); /* Generate limbs */ OBJParser parser = this.getOBJParser(model, data); if (parser != null) { for (OBJDataMesh mesh : parser.objects) { data.addLimb(mesh.name); } } if (data.limbs.isEmpty()) { data.addLimb("body"); } /* Flip around the X axis */ for (ModelPose pose : data.poses.values()) { for (ModelTransform transform : pose.limbs.values()) { transform.scale[0] *= -1; } } return data; } @Override public boolean copyFiles(File folder) { boolean skins = super.copyFiles(folder); boolean obj = this.obj.copyTo(new File(folder, this.obj.getName())); boolean mtl = this.mtl.copyTo(new File(folder, this.mtl.getName())); return skins || obj || mtl; } }
21.149733
105
0.69507
aeb3304b8218078cdb021fa9c2fc26f494e9d56b
1,212
package com.xwintop.xTransfer.sender.service.impl; import com.xwintop.xTransfer.sender.bean.SenderConfig; import com.xwintop.xTransfer.sender.service.Sender; import com.xwintop.xTransfer.sender.service.SenderManager; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; /** * @ClassName: SenderManagerImpl * @Description: 获取发送服务管理类 * @author: xufeng * @date: 2018/6/13 16:07 */ @Service("senderManager") @Slf4j public class SenderManagerImpl implements SenderManager { @Override public Sender getSender(SenderConfig senderConfig) { Sender sender = null; try { String className = this.getClass().getPackage().getName() + "." + senderConfig.getServiceName().replaceFirst("sender", "Sender") + "Impl"; sender = (Sender) Class.forName(className).newInstance(); } catch (Exception e) { log.error("获取Sender失败:", e); } if (sender == null) { try { sender = (Sender) Class.forName(senderConfig.getServiceName()).newInstance(); } catch (Exception e) { log.warn("获取SenderByClassName失败:", e); } } return sender; } }
31.894737
150
0.64604
14c7880b775eb258589cfd9966f3a0bf45c706aa
791
// Template Source: BaseEntityCollectionResponse.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.windowsupdates.requests; import com.microsoft.graph.windowsupdates.models.CatalogEntry; import com.microsoft.graph.http.BaseCollectionResponse; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Catalog Entry Collection Response. */ public class CatalogEntryCollectionResponse extends BaseCollectionResponse<CatalogEntry> { }
41.631579
152
0.638432
12bdf93ed8e284e1ba375bb277031c620caf2026
338
package io.github.jackzheng870.tofusite; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TofusiteApplication { public static void main(String[] args) { SpringApplication.run(TofusiteApplication.class, args); } }
28.166667
68
0.801775
3adcf49d3d08cbd0e965e8912d2b05042fef573a
691
package ObjectTracker; import javax.swing.*; import java.awt.*; /** * This class contains any methods that are needed * to change the look and feel of the GUI components. * * @author Eoin O'Connor * @see UserOptionsPanel * @see Browser */ public class WindowUtilities { /** * Tells the system to use native look and feel, as in previous * releases. Metal (Java) LAF is the default otherwise. */ public static void setNativeLookAndFeel() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { System.err.println("Error setting native LAF: " + e); } } }
22.290323
77
0.6411
cf47e3d0b2ca0620d1e4609761ba8c6a6a51dc5b
1,898
package org.openpaas.servicebroker.model; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * PreviousValues 정보를 가지고 있는 데이터 모델 bean 클래스. * Json 어노테이션을 사용해서 JSON 형태로 제공 * * @author 김세영 * @date 2017.05.23 */ @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true) public class PreviousValues { @JsonSerialize @JsonProperty("plan_id") private String planId; @JsonSerialize @JsonProperty("service_id") private String serviceDefinitionId; @JsonSerialize @JsonProperty("organization_id") private String organizationId; @JsonSerialize @JsonProperty("space_id") private String spaceId; public PreviousValues() {} public PreviousValues(String planId, String serviceDefinitionId, String organizationId, String spaceId) { this.planId = planId; this.serviceDefinitionId = serviceDefinitionId; this.organizationId = organizationId; this.spaceId = spaceId; } public String getPlanId() { return planId; } public void setPlanId(String planId) { this.planId = planId; } public String getServiceDefinitionId() { return serviceDefinitionId; } public void setServiceDefinitionId(String serviceDefinitionId) { this.serviceDefinitionId = serviceDefinitionId; } public String getOrganizationId() { return organizationId; } public void setOrganizationId(String organizationId) { this.organizationId = organizationId; } public String getSpaceId() { return spaceId; } public void setSpaceId(String spaceId) { this.spaceId = spaceId; } }
24.973684
109
0.710748
d21791df93d6974ba9b136ee00a413f9d912c088
5,500
package com.ch.pojo; public class StockInfo { private String id; private String compabbre; private String compname; private String englishname; private String regadd; private String sharescode; private String sharesaddre; private String timemarket; private String totalequity; private String flowequity; private String bsharescode; private String bsharesaddre; private String btimemarket; private String btotalequity; private String bflowequity; private String area; private String province; private String city; private String website; private String industry; private String industry2; private String industry3; private String status; public StockInfo() { } public StockInfo(String id) { setId(id); } public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getCompabbre() { return compabbre; } public void setCompabbre(String compabbre) { this.compabbre = compabbre == null ? null : compabbre.trim(); } public String getCompname() { return compname; } public void setCompname(String compname) { this.compname = compname == null ? null : compname.trim(); } public String getEnglishname() { return englishname; } public void setEnglishname(String englishname) { this.englishname = englishname == null ? null : englishname.trim(); } public String getRegadd() { return regadd; } public void setRegadd(String regadd) { this.regadd = regadd == null ? null : regadd.trim(); } public String getSharescode() { return sharescode; } public void setSharescode(String sharescode) { this.sharescode = sharescode == null ? null : sharescode.trim(); } public String getSharesaddre() { return sharesaddre; } public void setSharesaddre(String sharesaddre) { this.sharesaddre = sharesaddre == null ? null : sharesaddre.trim(); } public String getTimemarket() { return timemarket; } public void setTimemarket(String timemarket) { this.timemarket = timemarket == null ? null : timemarket.trim(); } public String getTotalequity() { return totalequity; } public void setTotalequity(String totalequity) { this.totalequity = totalequity == null ? null : totalequity.trim(); } public String getFlowequity() { return flowequity; } public void setFlowequity(String flowequity) { this.flowequity = flowequity == null ? null : flowequity.trim(); } public String getBsharescode() { return bsharescode; } public void setBsharescode(String bsharescode) { this.bsharescode = bsharescode == null ? null : bsharescode.trim(); } public String getBsharesaddre() { return bsharesaddre; } public void setBsharesaddre(String bsharesaddre) { this.bsharesaddre = bsharesaddre == null ? null : bsharesaddre.trim(); } public String getBtimemarket() { return btimemarket; } public void setBtimemarket(String btimemarket) { this.btimemarket = btimemarket == null ? null : btimemarket.trim(); } public String getBtotalequity() { return btotalequity; } public void setBtotalequity(String btotalequity) { this.btotalequity = btotalequity == null ? null : btotalequity.trim(); } public String getBflowequity() { return bflowequity; } public void setBflowequity(String bflowequity) { this.bflowequity = bflowequity == null ? null : bflowequity.trim(); } public String getArea() { return area; } public void setArea(String area) { this.area = area == null ? null : area.trim(); } public String getProvince() { return province; } public void setProvince(String province) { this.province = province == null ? null : province.trim(); } public String getCity() { return city; } public void setCity(String city) { this.city = city == null ? null : city.trim(); } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website == null ? null : website.trim(); } public String getIndustry() { return industry; } public void setIndustry(String industry) { this.industry = industry == null ? null : industry.trim(); } public String getIndustry2() { return industry2; } public void setIndustry2(String industry2) { this.industry2 = industry2 == null ? null : industry2.trim(); } public String getIndustry3() { return industry3; } public void setIndustry3(String industry3) { this.industry3 = industry3 == null ? null : industry3.trim(); } public String getStatus() { return status; } public void setStatus(String status) { this.status = status == null ? null : status.trim(); } }
22.916667
79
0.594182
8c83148691c9b622b5b808bc28f35be8cb2e2461
9,321
/* * MIT License * Copyright (c) 2020 Alexandros Gelbessis * 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.k8scms.cms.mongo; import com.k8scms.cms.CmsProperties; import com.k8scms.cms.model.CollectionMeta; import com.k8scms.cms.model.GetOptions; import com.k8scms.cms.resource.DataFilter; import com.mongodb.ConnectionString; import com.mongodb.MongoBulkWriteException; import com.mongodb.MongoClientSettings; import com.mongodb.bulk.BulkWriteResult; import com.mongodb.client.model.*; import com.mongodb.reactivestreams.client.MongoClients; import io.quarkus.mongodb.FindOptions; import io.quarkus.mongodb.impl.ReactiveMongoClientImpl; import io.quarkus.mongodb.reactive.ReactiveMongoClient; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import org.bson.Document; import org.bson.conversions.Bson; import org.eclipse.microprofile.config.ConfigProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @ApplicationScoped public class MongoService { private static final Logger logger = LoggerFactory.getLogger(MongoService.class); private Map<String, ReactiveMongoClient> mongoClients; @Inject CmsProperties cmsProperties; @PostConstruct void postConstruct() { mongoClients = new HashMap<>(); int i = 0; while (true) { try { String clusterProperty = ConfigProvider.getConfig().getValue("cms.cluster-" + (i++), String.class); logger.debug("Adding cluster connection '{}'", clusterProperty); // 0 is the cluster name // 1 is the cluster connection String[] clusterTokens = clusterProperty.split(",", 2); MongoClientSettings mongoClientSettings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(clusterTokens[1])) .applyToConnectionPoolSettings(builder -> { builder.maxWaitTime(cmsProperties.getMongoTimeout(), TimeUnit.SECONDS); }) .build(); mongoClients.put(clusterTokens[0], new ReactiveMongoClientImpl(MongoClients.create(mongoClientSettings))); } catch (NoSuchElementException e) { // expected break; } if (i == 100) { break; } } } private ReactiveMongoClient findMongoClient(String clusterName) { return mongoClients.get(Optional.ofNullable(clusterName).orElse(cmsProperties.getCluster())); } public Uni<String> createIndex(String cluster, String database, String collection, Document index, IndexOptions indexOptions) { index.forEach((k, o) -> { if (!o.equals("2dsphere")) { // add the value as an integer, always store indexes in JSON as Strings, not Numbers index.put(k, Integer.parseInt(o.toString())); } }); return findMongoClient(cluster).getDatabase(database).getCollection(collection).createIndex(index, indexOptions); } public Multi<Document> get(String cluster, String database, String collection, Document filter) { GetOptions getOptions = new GetOptions(); return get(cluster, database, collection, filter, getOptions); } public Multi<Document> get(String cluster, String database, String collection, Bson filter, GetOptions getOptions) { FindOptions findOptions = new FindOptions(); findOptions.filter(filter); if (getOptions.getSort() != null) { Document document = new Document(); document.put(getOptions.getSort(), getOptions.getSortDirection()); findOptions.sort(document); } if (getOptions.getSkip() != null) { findOptions.skip(getOptions.getSkip()); } if (getOptions.getLimit() != null) { findOptions.limit(Math.min(getOptions.getLimit(), cmsProperties.getLimit())); } else { if (getOptions.getNoLimit()) { // no limit logger.debug("get without limit"); } else { findOptions.limit(cmsProperties.getLimit()); } } return findMongoClient(cluster).getDatabase(database) .getCollection(collection) .find(findOptions); } public Uni<CollectionMeta> getMeta(String cluster, String database, String collection) { return findMongoClient(cluster).getDatabase(database) .getCollection(collection) .estimatedDocumentCount() .map(l -> { CollectionMeta collectionMeta = new CollectionMeta(); collectionMeta.setEstimatedDocumentCount(l); return collectionMeta; }); } public Uni<BulkWriteResult> post(String cluster, String database, String collection, List<Document> data, boolean ordered) { return bulkWrite( cluster, database, collection, data.stream().map(InsertOneModel::new).collect(Collectors.toList()), ordered); } // when updating from the UI form the _id is used, on upload the field id public Uni<BulkWriteResult> put(String cluster, String database, String collection, List<DataFilter> dataFilters, boolean upsert, boolean ordered) { List<ReplaceOneModel<Document>> replaceOneModels = new ArrayList<>(); dataFilters.forEach(dataFilter -> { // never change _id(s) dataFilter.getData().remove("_id"); ReplaceOneModel<Document> replaceOneModel = new ReplaceOneModel<>(dataFilter.getFilter(), dataFilter.getData(), new ReplaceOptions().upsert(upsert)); replaceOneModels.add(replaceOneModel); }); return bulkWrite( cluster, database, collection, replaceOneModels, ordered); } public Uni<BulkWriteResult> patch(String cluster, String database, String collection, List<DataFilter> dataFilters, boolean upsert, boolean ordered) { List<UpdateOneModel<Document>> updateOneModels = new ArrayList<>(); dataFilters.forEach(dataFilter -> { UpdateOneModel<Document> updateOneModel = new UpdateOneModel<>(dataFilter.getFilter(), new Document("$set", dataFilter.getData()), new UpdateOptions().upsert(upsert)); updateOneModels.add(updateOneModel); }); return bulkWrite( cluster, database, collection, updateOneModels, ordered); } public Uni<BulkWriteResult> delete(String cluster, String database, String collection, List<Document> filters, boolean ordered) { List<DeleteOneModel<Document>> deleteOneModels = new ArrayList<>(); filters.forEach(filter -> { DeleteOneModel<Document> deleteOneModel = new DeleteOneModel<>(filter); deleteOneModels.add(deleteOneModel); }); return bulkWrite( cluster, database, collection, deleteOneModels, ordered); } private Uni<BulkWriteResult> bulkWrite(String cluster, String database, String collection, List<? extends WriteModel<Document>> writeModels, boolean ordered) { return findMongoClient(cluster).getDatabase(database) .getCollection(collection) .bulkWrite(writeModels, new BulkWriteOptions().ordered(ordered)) .onFailure() .recoverWithItem(throwable -> { if (throwable instanceof MongoBulkWriteException) { return new MongoBulkWriteExceptionBulkWriteResult((MongoBulkWriteException) throwable); } else { throw new RuntimeException(throwable); } }); } }
42.561644
179
0.645639
61d47138d45f8f8f824b9fdd09532f7d22da1fe5
3,683
/* * ModeShape (http://www.modeshape.org) * * 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.modeshape.sequencer.javafile; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.modeshape.sequencer.JavaSequencerHelper.JAVA_FILE_HELPER; import static org.modeshape.sequencer.classfile.ClassFileSequencerLexicon.IMPORTS; import java.util.ArrayList; import java.util.List; import javax.jcr.Node; import javax.jcr.Value; import org.junit.Test; import org.modeshape.jcr.sequencer.AbstractSequencerTest; import org.modeshape.sequencer.testdata.MockClass; import org.modeshape.sequencer.testdata.MockEnum; /** * Unit test for {@link JavaFileSequencer} * * @author Horia Chiorean */ public class JavaFileSequencerTest extends AbstractSequencerTest { private void assertClassImports( final Node classNode ) throws Exception { assertThat(classNode.hasProperty(IMPORTS), is(true)); final Value[] values = classNode.getProperty(IMPORTS).getValues(); assertThat(values.length, is(3)); final List<String> items = new ArrayList<String>(3); items.add(values[0].getString()); items.add(values[1].getString()); items.add(values[2].getString()); assertThat(items, hasItems("java.io.Serializable", "java.util.ArrayList", "java.util.List")); } private void assertEnumImports( final Node classNode ) throws Exception { assertThat(classNode.hasProperty(IMPORTS), is(true)); final Value[] values = classNode.getProperty(IMPORTS).getValues(); assertThat(values.length, is(2)); final List<String> items = new ArrayList<String>(2); items.add(values[0].getString()); items.add(values[1].getString()); assertThat(items, hasItems("java.util.Random", "java.text.DateFormat")); } @Test public void sequenceEnum() throws Exception { String packagePath = MockEnum.class.getName().replaceAll("\\.", "/"); createNodeWithContentFromFile("enum.java", packagePath + ".java"); // expected by sequencer in a different location String expectedOutputPath = "java/enum.java"; Node outputNode = getOutputNode(rootNode, expectedOutputPath); assertNotNull(outputNode); Node enumNode = outputNode.getNode(packagePath); JAVA_FILE_HELPER.assertSequencedMockEnum(enumNode); assertEnumImports(enumNode); } @Test public void sequenceJavaFile() throws Exception { String packagePath = MockClass.class.getName().replaceAll("\\.", "/"); createNodeWithContentFromFile("mockclass.java", packagePath + ".java"); // expected by sequencer in a different location String expectedOutputPath = "java/mockclass.java"; Node outputNode = getOutputNode(rootNode, expectedOutputPath); assertNotNull(outputNode); Node javaNode = outputNode.getNode(packagePath); JAVA_FILE_HELPER.assertSequencedMockClass(javaNode); assertClassImports(javaNode); } }
39.180851
101
0.716535
20b63949780a7486d21dd024a0fd577cb59fc485
288
package org.rhett.admin.service; import com.baomidou.mybatisplus.extension.service.IService; import org.rhett.admin.model.entity.Permission; import java.util.List; public interface PermissionService extends IService<Permission> { List<Permission> getPermissions(Integer roleId); }
26.181818
65
0.815972
d0f2753db4714412874167485ea6829811c8c567
552
package com.oim.core.business.manager; import com.onlyxiahui.app.base.AppContext; import com.onlyxiahui.app.base.component.AbstractManager; import com.onlyxiahui.im.bean.UserCategoryMember; /** * 描述: * * @author XiaHui * @date 2015年4月12日 上午10:18:18 * @version 0.0.1 */ public class MessageManager extends AbstractManager { //private Map<String, List> map = new ConcurrentHashMap<String, List>(); public MessageManager(AppContext appContext) { super(appContext); } public void put(UserCategoryMember userCategoryMember) { } }
19.034483
73
0.744565
3ee20e0d5a68523558923ae509d358ca2b2569d7
258
package gm; import org.apache.mina.core.session.IoSession; import tools.data.input.SeekableLittleEndianAccessor; /** * * @author Kevin */ public interface GMPacketHandler { void handlePacket(SeekableLittleEndianAccessor slea, IoSession session); }
18.428571
76
0.77907
fae64967fc77cb166f3861dad19191b0d560c5f3
1,091
package org.sylrsykssoft.rest.java.musbands.aspects.logger.annotation; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Class and method level annotation to turn on automatic logging. * Adding it to class or method enables logging for it. * Annotation on method takes precedence over that on class. * * @author juan.gonzalez.fernandez.jgf * */ @Documented @Retention(RUNTIME) @Target({ TYPE, METHOD }) public @interface Logging { /** * TRACE level of logging. */ int TRACE = 0; /** * DEBUG level of logging. */ int DEBUG = 1; /** * INFO level of logging. */ int INFO = 2; /** * WARN level of logging. */ int WARN = 3; /** * ERROR level of logging. */ int ERROR = 4; /** * Level of logging. */ int value() default Logging.INFO; }
20.584906
70
0.655362
14b6a9f9dc67ea5f89cc3dfa2cf6b505c5b7d715
2,491
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2020-2021 The JReleaser authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jreleaser.maven.plugin; import static org.jreleaser.util.StringUtils.isNotBlank; /** * @author Andres Almiray * @since 0.1.0 */ abstract class AbstractRepositoryTap implements Activatable { protected Active active; private String owner; private String name; private String branch; private String username; private String token; void setAll(AbstractRepositoryTap tap) { this.active = tap.active; this.owner = tap.owner; this.name = tap.name; this.branch = tap.branch; this.username = tap.username; this.token = tap.token; } @Override public Active getActive() { return active; } @Override public void setActive(Active active) { this.active = active; } @Override public String resolveActive() { return active != null ? active.name() : null; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public boolean isSet() { return active != null || isNotBlank(owner) || isNotBlank(name) || isNotBlank(branch) || isNotBlank(username) || isNotBlank(token); } }
23.280374
75
0.626255
a1e3c7d35ba29bd33a513fdad5f26a25fd04eaa4
1,277
package com.mallplanet.clienttoolbox.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.google.gson.annotations.SerializedName; @JsonInclude(Include.NON_NULL) public class CampaignBalance { @SerializedName("campaign_id") private String campaignid; @SerializedName("campaign_type") private String campaigntype; @SerializedName("campaign_name") private String campaignName; @SerializedName("reward_ratio") private String rewardRatio; private Customer customer; public String getCampaignid() { return campaignid; } public void setCampaignid(String campaignid) { this.campaignid = campaignid; } public String getCampaigntype() { return campaigntype; } public void setCampaigntype(String campaigntype) { this.campaigntype = campaigntype; } public String getCampaignName() { return campaignName; } public void setCampaignName(String campaignName) { this.campaignName = campaignName; } public String getRewardRatio() { return rewardRatio; } public void setRewardRatio(String rewardRatio) { this.rewardRatio = rewardRatio; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
25.54
60
0.783085
c88a5fbbd51320876f293c04eed4516bcee9ed97
1,019
package com.jayu.note.bmo; import com.jayu.exception.BusinessException; import com.jayu.mybatis.bmo.BaseBMO; import com.jayu.mybatis.entity.PageModel; import com.jayu.note.dao.model.Mquartz; /** * 文章归档 业务接口 概述 . * <P> * @author jayu * @version V1.0 2015-12-25 * @createDate 2015-12-25 21:22:36 * @modifyDate jayu 2015-12-25 * @since JDK1.7 */ public interface MquartzBmo extends BaseBMO<Mquartz, String> { public static final String TABLE_ALIAS = "mquartz."; public static final String COLUMN_SORT_ORDER_ASC = "SORT_ORDER ASC"; public static final String COLUMN_SORT_ORDER_DESC = "SORT_ORDER DESC"; /** * * 分页业务逻辑方法 无需事务处理.默认升序排序查询所有 * @param pageNo 当前页码 * @return PageModel<Mquartz> 分页数据对象 * @throws BusinessException * 业务层自定义异常 */ public PageModel<Mquartz> query(int pageNo) throws BusinessException; public Integer deleteByBizIdType(String bizId, String actionType) throws BusinessException; public Integer deleteByUserId(long userId) throws BusinessException; }
27.540541
92
0.743867
f859e46c975f6a9a20c18037376fbb3673580afc
6,118
/* * */ package com.synectiks.process.server.streams.matchers; import org.junit.Test; import com.synectiks.process.server.plugin.Message; import com.synectiks.process.server.plugin.streams.StreamRule; import com.synectiks.process.server.plugin.streams.StreamRuleType; import com.synectiks.process.server.streams.matchers.GreaterMatcher; import com.synectiks.process.server.streams.matchers.StreamRuleMatcher; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class GreaterMatcherTest extends MatcherTest { @Test public void testSuccessfulMatch() { StreamRule rule = getSampleRule(); rule.setValue("3"); Message msg = getSampleMessage(); msg.addField("something", "4"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); } @Test public void testSuccessfulDoubleMatch() { StreamRule rule = getSampleRule(); rule.setValue("1.0"); Message msg = getSampleMessage(); msg.addField("something", "1.1"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); } @Test public void testSuccessfulMatchWithNegativeValue() { StreamRule rule = getSampleRule(); rule.setValue("-54354"); Message msg = getSampleMessage(); msg.addField("something", "4"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); } @Test public void testSuccessfulDoubleMatchWithNegativeValue() { StreamRule rule = getSampleRule(); rule.setValue("-54354.0"); Message msg = getSampleMessage(); msg.addField("something", "4.1"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); } @Test public void testSuccessfullInvertedMatch() { StreamRule rule = getSampleRule(); rule.setValue("10"); rule.setInverted(true); Message msg = getSampleMessage(); msg.addField("something", "4"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); } @Test public void testMissedMatch() { StreamRule rule = getSampleRule(); rule.setValue("25"); Message msg = getSampleMessage(); msg.addField("something", "12"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Test public void testMissedDoubleMatch() { StreamRule rule = getSampleRule(); rule.setValue("25"); Message msg = getSampleMessage(); msg.addField("something", "12.4"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Test public void testMissedInvertedMatch() { StreamRule rule = getSampleRule(); rule.setValue("25"); rule.setInverted(true); Message msg = getSampleMessage(); msg.addField("something", "30"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Test public void testMissedMatchWithEqualValues() { StreamRule rule = getSampleRule(); rule.setValue("-9001"); Message msg = getSampleMessage(); msg.addField("something", "-9001"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Test public void testMissedDoubleMatchWithEqualValues() { StreamRule rule = getSampleRule(); rule.setValue("-9001.45"); Message msg = getSampleMessage(); msg.addField("something", "-9001.45"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Test public void testSuccessfullInvertedMatchWithEqualValues() { StreamRule rule = getSampleRule(); rule.setValue("-9001"); rule.setInverted(true); Message msg = getSampleMessage(); msg.addField("something", "-9001"); StreamRuleMatcher matcher = getMatcher(rule); assertTrue(matcher.match(msg, rule)); } @Test public void testMissedMatchWithInvalidValue() { StreamRule rule = getSampleRule(); rule.setValue("LOL I AM NOT EVEN A NUMBER"); Message msg = getSampleMessage(); msg.addField("something", "90000"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Test public void testMissedDoubleMatchWithInvalidValue() { StreamRule rule = getSampleRule(); rule.setValue("LOL I AM NOT EVEN A NUMBER"); Message msg = getSampleMessage(); msg.addField("something", "90000.23"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Test public void testMissedMatchMissingField() { StreamRule rule = getSampleRule(); rule.setValue("42"); Message msg = getSampleMessage(); msg.addField("someother", "50"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Test public void testMissedInvertedMatchMissingField() { StreamRule rule = getSampleRule(); rule.setValue("42"); rule.setInverted(true); Message msg = getSampleMessage(); msg.addField("someother", "30"); StreamRuleMatcher matcher = getMatcher(rule); assertFalse(matcher.match(msg, rule)); } @Override protected StreamRule getSampleRule() { StreamRule rule = super.getSampleRule(); rule.setType(StreamRuleType.GREATER); return rule; } @Override protected StreamRuleMatcher getMatcher(StreamRule rule) { StreamRuleMatcher matcher = super.getMatcher(rule); assertEquals(matcher.getClass(), GreaterMatcher.class); return matcher; } }
27.809091
71
0.641223
9e67e9403e3b6ec1abc899036246b3fba189ce90
10,990
package br.com.basis.abaco.web.rest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.math.BigDecimal; import java.util.List; import javax.persistence.EntityManager; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import br.com.basis.abaco.AbacoApp; import br.com.basis.abaco.domain.EsforcoFase; import br.com.basis.abaco.repository.EsforcoFaseRepository; import br.com.basis.abaco.repository.search.EsforcoFaseSearchRepository; import br.com.basis.abaco.web.rest.errors.ExceptionTranslator; /** * Test class for the EsforcoFaseResource REST controller. * * @see EsforcoFaseResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = AbacoApp.class) public class EsforcoFaseResourceIT { private static final BigDecimal DEFAULT_ESFORCO = new BigDecimal(1); private static final BigDecimal UPDATED_ESFORCO = new BigDecimal(2); @Autowired private EsforcoFaseRepository esforcoFaseRepository; @Autowired private EsforcoFaseSearchRepository esforcoFaseSearchRepository; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restEsforcoFaseMockMvc; private EsforcoFase esforcoFase; @Before public void setup() { MockitoAnnotations.initMocks(this); EsforcoFaseResource esforcoFaseResource = new EsforcoFaseResource(esforcoFaseRepository, esforcoFaseSearchRepository); this.restEsforcoFaseMockMvc = MockMvcBuilders.standaloneSetup(esforcoFaseResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static EsforcoFase createEntity(EntityManager em) { EsforcoFase esforcoFase = new EsforcoFase() .esforco(DEFAULT_ESFORCO); return esforcoFase; } @Before public void initTest() { esforcoFaseSearchRepository.deleteAll(); esforcoFase = createEntity(em); } @Test @Transactional public void createEsforcoFase() throws Exception { int databaseSizeBeforeCreate = esforcoFaseRepository.findAll().size(); // Create the EsforcoFase restEsforcoFaseMockMvc.perform(post("/api/esforco-fases") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(esforcoFase))) .andExpect(status().isCreated()); // Validate the EsforcoFase in the database List<EsforcoFase> esforcoFaseList = esforcoFaseRepository.findAll(); assertThat(esforcoFaseList).hasSize(databaseSizeBeforeCreate + 1); EsforcoFase testEsforcoFase = esforcoFaseList.get(esforcoFaseList.size() - 1); assertThat(testEsforcoFase.getEsforco()).isEqualTo(DEFAULT_ESFORCO); // Validate the EsforcoFase in Elasticsearch EsforcoFase esforcoFaseEs = esforcoFaseSearchRepository.findOne(testEsforcoFase.getId()); assertThat(esforcoFaseEs).isEqualToComparingFieldByField(testEsforcoFase); } @Test @Transactional public void createEsforcoFaseWithExistingId() throws Exception { int databaseSizeBeforeCreate = esforcoFaseRepository.findAll().size(); // Create the EsforcoFase with an existing ID EsforcoFase existingEsforcoFase = new EsforcoFase(); existingEsforcoFase.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail restEsforcoFaseMockMvc.perform(post("/api/esforco-fases") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(existingEsforcoFase))) .andExpect(status().isBadRequest()); // Validate the Alice in the database List<EsforcoFase> esforcoFaseList = esforcoFaseRepository.findAll(); assertThat(esforcoFaseList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllEsforcoFases() throws Exception { // Initialize the database esforcoFaseRepository.saveAndFlush(esforcoFase); // Get all the esforcoFaseList restEsforcoFaseMockMvc.perform(get("/api/esforco-fases?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(esforcoFase.getId().intValue()))) .andExpect(jsonPath("$.[*].esforco").value(hasItem(DEFAULT_ESFORCO.intValue()))); } @Test @Transactional public void getEsforcoFase() throws Exception { // Initialize the database esforcoFaseRepository.saveAndFlush(esforcoFase); // Get the esforcoFase restEsforcoFaseMockMvc.perform(get("/api/esforco-fases/{id}", esforcoFase.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(esforcoFase.getId().intValue())) .andExpect(jsonPath("$.esforco").value(DEFAULT_ESFORCO.intValue())); } @Test @Transactional public void getNonExistingEsforcoFase() throws Exception { // Get the esforcoFase restEsforcoFaseMockMvc.perform(get("/api/esforco-fases/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateEsforcoFase() throws Exception { // Initialize the database esforcoFaseRepository.saveAndFlush(esforcoFase); esforcoFaseSearchRepository.save(esforcoFase); int databaseSizeBeforeUpdate = esforcoFaseRepository.findAll().size(); // Update the esforcoFase EsforcoFase updatedEsforcoFase = esforcoFaseRepository.findOne(esforcoFase.getId()); updatedEsforcoFase .esforco(UPDATED_ESFORCO); restEsforcoFaseMockMvc.perform(put("/api/esforco-fases") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(updatedEsforcoFase))) .andExpect(status().isOk()); // Validate the EsforcoFase in the database List<EsforcoFase> esforcoFaseList = esforcoFaseRepository.findAll(); assertThat(esforcoFaseList).hasSize(databaseSizeBeforeUpdate); EsforcoFase testEsforcoFase = esforcoFaseList.get(esforcoFaseList.size() - 1); assertThat(testEsforcoFase.getEsforco()).isEqualTo(UPDATED_ESFORCO); // Validate the EsforcoFase in Elasticsearch EsforcoFase esforcoFaseEs = esforcoFaseSearchRepository.findOne(testEsforcoFase.getId()); assertThat(esforcoFaseEs).isEqualToComparingFieldByField(testEsforcoFase); } @Test @Transactional public void updateNonExistingEsforcoFase() throws Exception { int databaseSizeBeforeUpdate = esforcoFaseRepository.findAll().size(); // Create the EsforcoFase // If the entity doesn't have an ID, it will be created instead of just being updated restEsforcoFaseMockMvc.perform(put("/api/esforco-fases") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(esforcoFase))) .andExpect(status().isCreated()); // Validate the EsforcoFase in the database List<EsforcoFase> esforcoFaseList = esforcoFaseRepository.findAll(); assertThat(esforcoFaseList).hasSize(databaseSizeBeforeUpdate + 1); } @Test @Transactional public void deleteEsforcoFase() throws Exception { // Initialize the database esforcoFaseRepository.saveAndFlush(esforcoFase); esforcoFaseSearchRepository.save(esforcoFase); int databaseSizeBeforeDelete = esforcoFaseRepository.findAll().size(); // Get the esforcoFase restEsforcoFaseMockMvc.perform(delete("/api/esforco-fases/{id}", esforcoFase.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate Elasticsearch is empty boolean esforcoFaseExistsInEs = esforcoFaseSearchRepository.exists(esforcoFase.getId()); assertThat(esforcoFaseExistsInEs).isFalse(); // Validate the database is empty List<EsforcoFase> esforcoFaseList = esforcoFaseRepository.findAll(); assertThat(esforcoFaseList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void searchEsforcoFase() throws Exception { // Initialize the database esforcoFaseRepository.saveAndFlush(esforcoFase); esforcoFaseSearchRepository.save(esforcoFase); // Search the esforcoFase restEsforcoFaseMockMvc.perform(get("/api/_search/esforco-fases?query=id:" + esforcoFase.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(esforcoFase.getId().intValue()))) .andExpect(jsonPath("$.[*].esforco").value(hasItem(DEFAULT_ESFORCO.intValue()))); } @Test public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(EsforcoFase.class); } }
41.007463
130
0.728207
019cf502c483f45987d4cb88914326d991be8b35
355
package io.dropwizard.redis.delay; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.dropwizard.jackson.Discoverable; import io.lettuce.core.resource.Delay; import java.util.function.Supplier; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") public interface DelayFactory extends Discoverable { Supplier<Delay> build(); }
27.307692
60
0.8
96ec9c4432f0922cb6b5692dabd15095d79e0261
3,878
/* * 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.flink.runtime.state.context; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.runtime.state.heap.KeyContextImpl; import org.apache.flink.runtime.state.internal.InternalListState; import org.apache.flink.runtime.state.subkeyed.SubKeyedListState; import org.apache.flink.runtime.state.subkeyed.SubKeyedState; import java.util.Collection; import java.util.List; /** * used for ListState. * * @param <K> The type of key the state is associated to. * @param <N> The type of the namespace. * @param <E> The type of elements in the list. */ public class ContextSubKeyedListState<K, N, E> implements ContextSubKeyedAppendingState<K, N, E, List<E>, Iterable<E>>, InternalListState<K, N, E> { private N namespace; private final KeyContextImpl<K> keyContext; private final SubKeyedListState<Object, N, E> subKeyedListState; public ContextSubKeyedListState(KeyContextImpl<K> keyContext, SubKeyedListState<Object, N, E> subKeyedListState) { this.keyContext = keyContext; this.subKeyedListState = subKeyedListState; } @Override public Iterable<E> get() throws Exception { return subKeyedListState.get(getCurrentKey(), namespace); } @Override public void add(E value) throws Exception { subKeyedListState.add(getCurrentKey(), namespace, value); } @Override public void clear() { subKeyedListState.remove(getCurrentKey(), namespace); } private Object getCurrentKey() { return keyContext.getCurrentKey(); } @Override public void mergeNamespaces(N target, Collection<N> sources) throws Exception { if (sources != null) { for (N source : sources) { List<E> list = subKeyedListState.get(getCurrentKey(), source); if (list != null) { subKeyedListState.addAll(getCurrentKey(), target, list); subKeyedListState.remove(getCurrentKey(), source); } } } } @Override public void update(List<E> values) { if (values == null || values.isEmpty()) { subKeyedListState.remove(getCurrentKey(), namespace); } else { subKeyedListState.putAll(getCurrentKey(), namespace, values); } } @Override public void addAll(List<E> values) { if (values != null && !values.isEmpty()) { subKeyedListState.addAll(getCurrentKey(), namespace, values); } } @Override public TypeSerializer<K> getKeySerializer() { return keyContext.getKeySerializer(); } @Override public TypeSerializer<N> getNamespaceSerializer() { return subKeyedListState.getDescriptor().getNamespaceSerializer(); } @Override public TypeSerializer<List<E>> getValueSerializer() { return subKeyedListState.getDescriptor().getValueSerializer(); } @Override public void setCurrentNamespace(N namespace) { this.namespace = namespace; } @Override public byte[] getSerializedValue(byte[] serializedKeyAndNamespace, TypeSerializer<K> safeKeySerializer, TypeSerializer<N> safeNamespaceSerializer, TypeSerializer<List<E>> safeValueSerializer) throws Exception { return new byte[0]; } @Override public SubKeyedState getSubKeyedState() { return subKeyedListState; } }
30.062016
211
0.748582
d9c6aaf67aacd3868e6c444621da3b3ef801aa01
888
package bigdata; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class MatrixMultiplicationGroupComparator extends WritableComparator { public MatrixMultiplicationGroupComparator() { super(TupleWritable.class,true); } //Group a tuple by the first two entries of the matrix (go to the same reduce call) //All tuples that have the same first two attributes should belong to the same Reducer! (Natural key) @Override public int compare(WritableComparable a, WritableComparable b) { TupleWritable t1 = (TupleWritable) a; TupleWritable t2 = (TupleWritable) b; int result = t1.getList().get(0).compareTo(t2.getList().get(0)); if(result != 0) return result; result = t1.getList().get(1).compareTo(t2.getList().get(1)); return result; } }
32.888889
105
0.693694
d5264ec330d2d4af272c4be2ff29b31dc4d0cf76
613
package com.appl_maint_mngt.common.errors; import com.appl_maint_mngt.common.errors.interfaces.IErrorPayload; import com.appl_maint_mngt.common.errors.interfaces.IErrorPayloadBuilder; import java.util.ArrayList; import java.util.List; /** * Created by Kyle on 16/04/2017. */ public class ErrorPayloadBuilder implements IErrorPayloadBuilder { @Override public IErrorPayload buildForString(String error) { ErrorPayload payload = new ErrorPayload(); List<String> errors = new ArrayList<>(); errors.add(error); payload.setErrors(errors); return payload; } }
26.652174
73
0.732463
4cd94d81fc8577682113730f261612a78fe1e638
2,145
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.ac.cam.ceb.como.math.trendline; import java.util.Arrays; import org.apache.commons.math.linear.MatrixUtils; import org.apache.commons.math.stat.regression.OLSMultipleLinearRegression; import org.xmlcml.euclid.RealMatrix; /** * * @author pb556 */ public abstract class TrendLine implements TrendLineIntf { RealMatrix coef = null; // will hold prediction coefs once we get values protected abstract double[] xVector(double x); // create vector of values from x protected abstract boolean logY(); // set true to predict log of y (note: y must be positive) @Override public void setValues(double[] y, double[] x) { if (x.length != y.length) { throw new IllegalArgumentException(String.format("The numbers of y and x values must be equal (%d != %d)",y.length,x.length)); } double[][] xData = new double[x.length][]; for (int i = 0; i < x.length; i++) { // the implementation determines how to produce a vector of predictors from a single x xData[i] = xVector(x[i]); } if(logY()) { // in some models we are predicting ln y, so we replace each y with ln y y = Arrays.copyOf(y, y.length); // user might not be finished with the array we were given for (int i = 0; i < x.length; i++) { y[i] = Math.log(y[i]); } } OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression(); ols.setNoIntercept(true); // let the implementation include a constant in xVector if desired ols.newSampleData(y, xData); // provide the data to the model coef = (RealMatrix) MatrixUtils.createColumnRealMatrix(ols.estimateRegressionParameters()); // get our coefs } @Override public double predict(double x) { // double yhat = coef.preMultiply(xVector(x))[0]; // apply coefs to xVector // if (logY()) yhat = (Math.exp(yhat)); // if we predicted ln y, we still need to get y // return yhat; return 0.0; } }
40.471698
138
0.641026
df18764b8d7751e5d86dee63dce6c51ad8a384bb
8,598
/* * Copyright 2021 StreamThoughts. * * 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 io.streamthoughts.kafka.specs.change; import io.streamthoughts.kafka.specs.OperationResult; import io.streamthoughts.kafka.specs.model.V1QuotaEntityObject; import io.streamthoughts.kafka.specs.model.V1QuotaObject; import io.streamthoughts.kafka.specs.model.V1QuotaType; import io.streamthoughts.kafka.specs.operation.quotas.QuotaOperation; import io.streamthoughts.kafka.specs.resources.Configs; import io.vavr.Tuple2; import org.apache.kafka.common.KafkaFuture; import org.apache.kafka.common.quota.ClientQuotaEntity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static io.streamthoughts.kafka.specs.internal.FutureUtils.makeCompletableFuture; public class QuotaChanges implements Changes<QuotaChange, QuotaOperation> { public static QuotaChanges computeChanges(@NotNull final Iterable<V1QuotaObject> beforeQuotasObjects, @NotNull final Iterable<V1QuotaObject> afterQuotasObjects) { final Map<ClientQuotaKey, V1QuotaObject> beforeQuotasMapByEntity = StreamSupport .stream(beforeQuotasObjects.spliterator(), false) .collect(Collectors.toMap(it -> newClientQuotaKey(it.type(), it.entity()), o -> o)); final Map<ClientQuotaKey, QuotaChange> changes = new HashMap<>(); for (final V1QuotaObject afterQuota : afterQuotasObjects) { final ClientQuotaKey key = newClientQuotaKey(afterQuota.type(), afterQuota.entity()); final V1QuotaObject beforeQuota = beforeQuotasMapByEntity.get(key); final QuotaChange change = beforeQuota == null ? buildChangeForNewQuota(afterQuota) : buildChangeForExistingQuota(beforeQuota, afterQuota); changes.put( newClientQuotaKey(change.getType(), change.getEntity()), change ); } Map<ClientQuotaKey, QuotaChange> changeForDeletedQuotas = buildChangesForOrphanQuotas( beforeQuotasMapByEntity.values(), changes.keySet() ); changes.putAll(changeForDeletedQuotas); return new QuotaChanges(changes); } @NotNull private static QuotaChanges.ClientQuotaKey newClientQuotaKey(final V1QuotaType type, final V1QuotaEntityObject entity) { return new ClientQuotaKey(type, type.toEntities(entity)); } public static QuotaChange buildChangeForNewQuota(@NotNull final V1QuotaObject quota) { final List<ConfigEntryChange> configChanges = quota.configs() .toMapDouble() .entrySet() .stream().map(it -> new ConfigEntryChange(it.getKey(), ValueChange.withAfterValue(it.getValue()))) .collect(Collectors.toList()); return new QuotaChange(Change.OperationType.ADD, quota.type(), quota.entity(), configChanges); } public static QuotaChange buildChangeForExistingQuota(@NotNull final V1QuotaObject before, @NotNull final V1QuotaObject after) { final Tuple2<Change.OperationType, List<ConfigEntryChange>> computed = ConfigEntryChanges.computeChange( Configs.of(before.configs().toMapDouble()), Configs.of(after.configs().toMapDouble()) ); return new QuotaChange(computed._1(), before.type(), before.entity(), computed._2()); } private static @NotNull Map<ClientQuotaKey, QuotaChange> buildChangesForOrphanQuotas( @NotNull final Collection<V1QuotaObject> quotas, @NotNull final Set<ClientQuotaKey> changes) { return quotas .stream() .filter(it -> !changes.contains(newClientQuotaKey(it.type(), it.entity()))) .map(quota -> { final List<ConfigEntryChange> configChanges = quota.configs() .toMapDouble() .entrySet() .stream().map(it -> new ConfigEntryChange(it.getKey(), ValueChange.withBeforeValue(it.getValue()))) .collect(Collectors.toList()); return new QuotaChange( Change.OperationType.DELETE, quota.type(), quota.entity(), configChanges ); }) .collect(Collectors.toMap(it -> newClientQuotaKey(it.getType(), it.getEntity()), it -> it)); } private final Map<ClientQuotaKey, QuotaChange> changes; /** * Creates a new {@link QuotaChanges} instance. * * @param changes the changes. */ public QuotaChanges(@NotNull final Map<ClientQuotaKey, QuotaChange> changes) { this.changes = changes; } /** * {@inheritDoc} */ @Override public Collection<QuotaChange> all() { return new ArrayList<>(changes.values()); } /** * {@inheritDoc} */ @Override public List<OperationResult<QuotaChange>> apply(final @NotNull QuotaOperation operation) { Map<ClientQuotaKey, QuotaChange> filtered = filter(operation) .stream() .collect(Collectors.toMap( it -> newClientQuotaKey(it.getType(), it.getEntity()), it -> it )); Map<ClientQuotaEntity, KafkaFuture<Void>> results = operation.apply(new QuotaChanges(filtered)); List<CompletableFuture<OperationResult<QuotaChange>>> completableFutures = results.entrySet() .stream() .map(entry -> { final Future<Void> future = entry.getValue(); ClientQuotaEntity clientQuotaEntity = entry.getKey(); Map<String, String> entries = clientQuotaEntity.entries(); V1QuotaType type = V1QuotaType.from(entries); return makeCompletableFuture(future, changes.get(new ClientQuotaKey(type, entries)), operation); }).collect(Collectors.toList()); return completableFutures .stream() .map(CompletableFuture::join) .collect(Collectors.toList()); } /** * Class used for identifying a unique client-quota. */ private static final class ClientQuotaKey { private final V1QuotaType type; private final Map<String, String> entities; public ClientQuotaKey(@NotNull final V1QuotaType type, @NotNull final Map<String, String> entities) { this.type = type; this.entities = entities; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClientQuotaKey quotaKey = (ClientQuotaKey) o; return type == quotaKey.type && Objects.equals(entities, quotaKey.entities); } @Override public int hashCode() { return Objects.hash(type, entities); } @Override public String toString() { return "ClientQuotaKey{" + "type=" + type + ", entities=" + entities + '}'; } } }
39.260274
127
0.621424
ae7b295a60118ad0198db1b4ee397a2d3478d4f1
14,687
package com.example.potato.couchpotatoes; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.ValueEventListener; import com.wdullaer.swipeactionadapter.SwipeActionAdapter; import com.wdullaer.swipeactionadapter.SwipeDirection; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class ChatRoomActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private DBHelper dbHelper = DBHelper.getInstance(); private ArrayList<String> listItems = new ArrayList<>(); private ArrayAdapter<String> listAdapter; private SwipeActionAdapter mAdapter; private ListView listView; private Map<String,String> chats = new HashMap<>(); private String userID = dbHelper.getAuth().getUid(); private String displayName = dbHelper.getAuthUserDisplayName(); private String userNames = ""; // The list of users in a chat exl. displayName // For the side navigation bar private DrawerLayout mDrawer; private NavigationView navView; private android.widget.TextView sidebarUserName; private android.widget.TextView sidebarUserEmail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat_room); // places toolbar into the screen Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitleTextColor(Color.WHITE); // set up the side navigation bar on the left side of screen mDrawer = (DrawerLayout) findViewById(R.id.chatroom_drawer_layout); navView = (NavigationView) findViewById(R.id.chatroom_nav_view); setSideBarDrawer( mDrawer, navView, toolbar , dbHelper); // Use a ListView to display the list of chats listView = findViewById(R.id.chatList); listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems); // Wrap your content in a SwipeActionAdapter mAdapter = new SwipeActionAdapter(listAdapter); // Pass a reference of your ListView to the SwipeActionAdapter mAdapter.setListView(listView); // Set the SwipeActionAdapter as the Adapter for your ListView listView.setAdapter(mAdapter); mAdapter.addBackground(SwipeDirection.DIRECTION_FAR_LEFT,R.layout.row_bg_left_far) .addBackground(SwipeDirection.DIRECTION_NORMAL_LEFT,R.layout.row_bg_left); // Listen to swipes mAdapter.setSwipeActionListener(new SwipeActionAdapter.SwipeActionListener(){ @Override public boolean hasActions(int position, SwipeDirection direction){ return (direction.isLeft()); } @Override public boolean shouldDismiss(int position, SwipeDirection direction){ // Only dismiss an item when swiping normal left return false; } //Listener for swipe direction @Override public void onSwipe(int[] positionList, SwipeDirection[] directionList){ for(int i=0;i<positionList.length;i++) { SwipeDirection direction = directionList[i]; AlertDialog.Builder builder; int position = positionList[i]; final String chatID = chats.get( String.valueOf( listView.getItemAtPosition( position ))); switch (direction) { case DIRECTION_FAR_LEFT: builder = new AlertDialog.Builder(ChatRoomActivity.this); builder.setTitle("Delete Conversation") .setMessage("This will permanently delete the conversation history.") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dbHelper.removeFromChatUser(chatID, userID); dbHelper.removeFromUserChat(userID, chatID); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create().show(); break; case DIRECTION_NORMAL_LEFT: builder = new AlertDialog.Builder(ChatRoomActivity.this); builder.setTitle("Delete Conversation") .setMessage("This will permanently delete the conversation history.") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dbHelper.removeFromChatUser(chatID, userID); dbHelper.removeFromUserChat(userID, chatID); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create().show(); break; } mAdapter.notifyDataSetChanged(); } } }); // Fetch and display all chats the current user belongs to. // The names of all chat members that belong to a chat are displayed and identify each chat. dbHelper.getDb().getReference( dbHelper.getUserChatPath() + userID ).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Iterator<DataSnapshot> elems = dataSnapshot.getChildren().iterator(); // Make sure not to display already existing chatIDs more than once listItems.clear(); // Get the next chat while ( elems.hasNext() ) { String chatID = elems.next().getKey(); // Fetch the names of all users that belong to the selected chat dbHelper.getDb().getReference( dbHelper.getChatUserPath() + chatID ).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Iterator<DataSnapshot> users = dataSnapshot.getChildren().iterator(); userNames = ""; // Concatenate the names of all users that belong to the current chat, delimited by a comma. while ( users.hasNext() ) { String currUser = (String) users.next().getValue(); // Do not display own name if other users exist in chat if (currUser.equals(displayName)) continue; if ( !userNames.equals( "" ) ) { userNames += ", "; } userNames += currUser; } // Display app name if only the current user is present in the chat // NOTE: If another a user removes themselves from a chat with a different user, // the other user's chat will now display the app name. This may result // in duplicate chats with the same name. if ( userNames.equals( "" ) ) { userNames += "Couch Potatoes"; } // Keep track of the chatID corresponding to the list of user names chats.put( userNames, dataSnapshot.getKey() ); // Add the list of user names identifying the current chat to the ListView listItems.add( userNames ); // Notify ListAdapter of changes listAdapter.notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) {} }); } } @Override public void onCancelled(DatabaseError databaseError) {} }); // Add an event handler to begin the MessageActivity corresponding to the clicked chatID listView.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { String chatID = chats.get( String.valueOf( parent.getItemAtPosition( position ) ) ); // Create new Intent, keeping track of the selected chatID Intent intent = new Intent( getApplicationContext(), MessageActivity.class ); intent.putExtra( "chatID", chatID ); intent.putExtra("otherUsers", String.valueOf(parent.getItemAtPosition(position))); intent.putExtra( "message", "1" ); // Begin the messaging activity corresponding to the selected chat startActivity( intent ); } }); } // Make sure the navView highlight the correct location @Override public void onResume() { super.onResume(); // highlight the current location navView.setCheckedItem(R.id.nav_chats); } // Handles pressing back button in bottom navigation bar when sidebar is on the screen @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.chatroom_drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } /* * The method sets up the navigation drawer (a.k.a. the sidebar) on the * left side of the screen. */ private void setSideBarDrawer( DrawerLayout mDrawer, NavigationView navView, Toolbar toolbar, DBHelper helper) { // enables toggle button on toolbar to open the sidebar ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); mDrawer.addDrawerListener(toggle); toggle.syncState(); // set up side navigation bar layout navView.setNavigationItemSelectedListener(this); // Want to display icons in original color scheme navView.setItemIconTintList(null); // highlight the current location navView.setCheckedItem(R.id.nav_matches); // sets up TextViews in sidebar to display the user's name and email sidebarUserName = (android.widget.TextView) navView.getHeaderView(0) .findViewById(R.id.sidebar_username); sidebarUserEmail = (android.widget.TextView) navView.getHeaderView(0) .findViewById(R.id.sidebar_user_email); setSideBarText( sidebarUserName, sidebarUserEmail, helper ); } /* * This method sets the text of the TextViews in the sidebar to display the * user's name and email. */ private void setSideBarText( TextView nameView, TextView emailView, DBHelper helper ) { // fetches user's name and email String displayName = helper.getAuthUserDisplayName(); String displayEmail = helper.getUser().getEmail(); nameView.setText( displayName ); emailView.setText( displayEmail ); } // Handles action in the sidebar menu public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_profile) { Intent intent = new Intent( getApplicationContext(), ProfileActivity.class ); startActivity( intent ); finish(); } else if (id == R.id.nav_matches) { finish(); } else if (id == R.id.nav_chats) { // user is already at the Chats page; do nothing } else if (id == R.id.nav_settings) { startActivity( new Intent( getApplicationContext(), AppSettingsActivity.class ) ); } else if (id == R.id.nav_info) { Intent intent = new Intent( getApplicationContext(), AboutUsActivity.class ); startActivity( intent ); } else if (id == R.id.nav_logout) { // logs out and redirects user to LoginActivity.xml dbHelper.getAuth().signOut(); startActivity( new Intent( getApplicationContext(), LoginActivity.class ) ); finish(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.chatroom_drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onPointerCaptureChanged(boolean hasCapture) {} }
45.330247
146
0.58242
c3fb42951968c40d5a368557e6d7c4c9c54af858
2,640
package br.com.salon.carine.lima.dto; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import br.com.salon.carine.lima.enuns.StatusAtendimento; import br.com.salon.carine.lima.enuns.TipoEndereco; import br.com.salon.carine.lima.models.Pagamento; public class AtendimentoDTO implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private ClienteDTO cliente; private BigDecimal totalBruto; private BigDecimal totalLiquido; private String data; private String hora; private EnderecoDTO endereco; private TipoEndereco tipoEndereco; private StatusAtendimento status; private Pagamento pagamento; private BigDecimal desconto; private BigDecimal taxa; private List<ServicoItemCarrinhoDTO> itens = new ArrayList<>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public ClienteDTO getCliente() { return cliente; } public void setCliente(ClienteDTO cliente) { this.cliente = cliente; } public BigDecimal getTotalBruto() { return totalBruto; } public void setTotalBruto(BigDecimal totalBruto) { this.totalBruto = totalBruto; } public BigDecimal getTotalLiquido() { return totalLiquido; } public void setTotalLiquido(BigDecimal totalLiquido) { this.totalLiquido = totalLiquido; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getHora() { return hora; } public void setHora(String hora) { this.hora = hora; } public EnderecoDTO getEndereco() { return endereco; } public void setEndereco(EnderecoDTO endereco) { this.endereco = endereco; } public StatusAtendimento getStatus() { return status; } public void setStatus(StatusAtendimento status) { this.status = status; } public Pagamento getPagamento() { return pagamento; } public void setPagamento(Pagamento pagamento) { this.pagamento = pagamento; } public BigDecimal getDesconto() { if (this.desconto == null) { return BigDecimal.ZERO; } return desconto; } public void setDesconto(BigDecimal desconto) { this.desconto = desconto; } public BigDecimal getTaxa() { return taxa; } public void setTaxa(BigDecimal taxa) { this.taxa = taxa; } public List<ServicoItemCarrinhoDTO> getItens() { return itens; } public void setItens(List<ServicoItemCarrinhoDTO> itens) { this.itens = itens; } public TipoEndereco getTipoEndereco() { return tipoEndereco; } public void setTipoEndereco(TipoEndereco tipoEndereco) { this.tipoEndereco = tipoEndereco; } }
19.270073
64
0.743939
a5de02359649759dabb7e0924670e83570bf0443
802
package com.fo0.lmp.ui.utils; import org.vaadin.alump.materialicons.MaterialIcons; import com.vaadin.icons.VaadinIcons; import com.vaadin.server.FontAwesome; public class ICON { public static final FontAwesome SAVE = FontAwesome.SAVE; public static final FontAwesome CANCEL = FontAwesome.TIMES; public static final FontAwesome HOST = FontAwesome.GLOBE; public static final FontAwesome ACTION = FontAwesome.LIST; public static final MaterialIcons BACKUP = MaterialIcons.SETTINGS; public static final FontAwesome CERTIFICATE = FontAwesome.LOCK; public static final VaadinIcons REGISTER = VaadinIcons.USER; public static final VaadinIcons SETTING = VaadinIcons.COG; public static final VaadinIcons DASHBOARD = VaadinIcons.HOME; public static final VaadinIcons CHECK = VaadinIcons.CHECK; }
36.454545
67
0.814214
00680a43794c1bae9ec6e70456f4cdf911776463
157
package io.leopard.burrow.lang; /** * 参数验证 * * @author 阿海 * */ @Deprecated class AssertUtil extends io.leopard.boot.util.AssertUtil { }
12.076923
59
0.617834
5a309aa0db84642213613c557c10b2f029fad502
4,690
import java.util.ArrayList; import java.util.Scanner; import java.util.Stack; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Interpreter { public void start(String filePath) { Stack<Integer> pile = new Stack<>(); ArrayList<String> vic = new ArrayList<String>(); int CO = 0; BufferedReader reader; try { reader = new BufferedReader(new FileReader(filePath)); String line = reader.readLine(); while (line != null) { String[] lineParts = line.split(" "); if (lineParts.length == 2) { pile.push(Integer.parseInt(lineParts[1])); } else if (lineParts.length == 1) { pile.push(0); } vic.add(lineParts[0]); line = reader.readLine(); } reader.close(); } catch (IOException e) { e.printStackTrace(); } while(!vic.get(CO).equals("END")) { String Instr_Courante = vic.get(CO); switch(Instr_Courante) { case "ADD": Integer operd1 = Integer.hashCode((Integer) pile.pop()); Integer operd2 = Integer.hashCode((Integer) pile.pop()); int v = operd1 + operd2; pile.push(v); break; case "SUB": Integer operd11 = Integer.hashCode((Integer) pile.pop()); Integer operd21 = Integer.hashCode((Integer) pile.pop()); int v1 = operd11 - operd21; pile.push(v1); break; case "MUL": Integer operd12 = Integer.hashCode((Integer) pile.pop()); Integer operd22 = Integer.hashCode((Integer) pile.pop()); int v2 = operd12 * operd22; pile.push(v2); break; case "DIV": Integer operd13 = Integer.hashCode((Integer) pile.pop()); Integer operd23 = Integer.hashCode((Integer) pile.pop()); int v3 = operd13 / operd23; pile.push(v3); break; case "SUP": int n; Integer n1 = Integer.hashCode((Integer) pile.pop()); Integer n2 = Integer.hashCode((Integer) pile.pop()); if (n2 > n1){ n = n2; } else n = n1; pile.push(n); break; case "INF": int m; Integer m1 = Integer.hashCode((Integer) pile.pop()); Integer m2 = Integer.hashCode((Integer) pile.pop()); if (m1 < m2){ m = m1; } else m = m2; pile.push(m); break; case "SUPE": int L; Integer n11 = Integer.hashCode((Integer) pile.pop()); Integer n21 = Integer.hashCode((Integer) pile.pop()); if (n11 >= n21){ L= n11; } else L = n21; pile.push(L); break; case "INFE": int L1; Integer n12 = Integer.hashCode((Integer) pile.pop()); Integer n22 = Integer.hashCode((Integer) pile.pop()); if (n22 <= n12){ L1 = n22; } else L1 = n12; pile.push(L1); break; case "EQUAL": int x1 = Integer.hashCode((Integer) pile.pop()); int x2 = Integer.hashCode((Integer) pile.pop()); if(x1 == x2) { pile.push(1); } else { pile.push(0); } break; case "LOAD": pile.push(pile.get(pile.get(CO))); break; case "LOADC": pile.push(pile.get(CO)); break; case "STORE": pile.set(pile.get(CO), pile.pop()); break; case "JUMP": CO = pile.get(CO); CO--; break; case "JZERO": int val = pile.pop(); if (val == 0) { CO = pile.get(CO); CO--; } break; case "READ": Scanner sc = new Scanner(System.in); pile.set(pile.get(CO), sc.nextInt()); break; case "WRITEC": System.out.println(pile.get(CO)); break; case "WRITE": System.out.println(pile.get(pile.get(CO))); break; } CO++; } System.out.println(pile.peek()); } }
32.569444
73
0.439446
5e7ab4dcdda1cd544f8ef1afe9e90c16c5de2852
3,713
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; /** * Utility class for converting between various ASCII case formats. Behavior is undefined for * non-ASCII input. * * @author Mike Bostock * @since 1.0 */ public enum CaseFormat { /** * C++ variable naming convention, e.g., "lower_underscore". */ LOWER_UNDERSCORE(CharMatcher.is('_'), "_") { @Override String normalizeWord(String word) { return Ascii.toLowerCase(word); } @Override String convert(CaseFormat format, String s) { return super.convert(format, s); } }, /** * Java variable naming convention, e.g., "lowerCamel". */ LOWER_CAMEL(CharMatcher.inRange('A', 'Z'), "") { @Override String normalizeWord(String word) { return firstCharOnlyToUpper(word); } }, /** * Java and C++ class naming convention, e.g., "UpperCamel". */ UPPER_CAMEL(CharMatcher.inRange('A', 'Z'), "") { @Override String normalizeWord(String word) { return firstCharOnlyToUpper(word); } }; private final CharMatcher wordBoundary; private final String wordSeparator; CaseFormat(CharMatcher wordBoundary, String wordSeparator) { this.wordBoundary = wordBoundary; this.wordSeparator = wordSeparator; } /** * Converts the specified {@code String str} from this format to the specified {@code format}. A * "best effort" approach is taken; if {@code str} does not conform to the assumed format, then * the behavior of this method is undefined but we make a reasonable effort at converting anyway. */ public final String to(CaseFormat format, String str) { return (format == this) ? str : convert(format, str); } /** * Enum values can override for performance reasons. */ String convert(CaseFormat format, String s) { // deal with camel conversion StringBuilder out = null; int i = 0; int j = -1; while ((j = wordBoundary.indexIn(s, ++j)) != -1) { if (i == 0) { // include some extra space for separators out = new StringBuilder(s.length() + 4 * wordSeparator.length()); out.append(format.normalizeFirstWord(s.substring(i, j))); } else { out.append(format.normalizeWord(s.substring(i, j))); } out.append(format.wordSeparator); i = j + wordSeparator.length(); } return (i == 0) ? format.normalizeFirstWord(s) : out.append(format.normalizeWord(s.substring(i))).toString(); } abstract String normalizeWord(String word); private String normalizeFirstWord(String word) { return (this == LOWER_CAMEL) ? Ascii.toLowerCase(word) : normalizeWord(word); } private static String firstCharOnlyToUpper(String word) { return word.isEmpty() ? word : Ascii.toUpperCase(word.charAt(0)) + Ascii.toLowerCase(word.substring(1)); } }
32.570175
101
0.615944
27d70847047d1b7f079b1d6b583886b4872ac999
760
package com.doduck.prototype.cli.dir2server.cmd; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.ParameterException; public class EmailValide implements IParameterValidator { public static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); public boolean validate(String emailStr) { Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(emailStr); return matcher.find(); } @Override public void validate(String name, String value) throws ParameterException { if(!this.validate(value)){ throw new ParameterException("email is invalide"); } } }
28.148148
93
0.743421
fad22ae7405cf12ce0ae2e16cfa64c0add6807d8
2,115
package com.fo0.google.promotion.crawler; import java.io.UnsupportedEncodingException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import lombok.extern.log4j.Log4j2; @SpringBootApplication @EnableScheduling @Log4j2 public class Main { @Autowired private PromotionCrawler crawler; @Autowired private MailService mail; @Value("${crawler.username}") private String receiver; public static void main(String[] args) { SpringApplication.run(Main.class, args); } /** * crawling schedule 1 per day, after you started * * @param receiver * @throws Exception * @throws UnsupportedEncodingException */ @Scheduled(fixedRate = (1000 * 60 * 60) * 24) private void startCrawler() throws Exception, UnsupportedEncodingException { if (crawler.isPromotionAvailable()) { log.info("Promotions available - sending mail to: {}", receiver); mail.sendSimpleMessage(receiver, "Google Promotion sind wieder Verfügbar!", "Hey, \n es gibt wieder Promotions. \n Schau doch mal auf https://home.google.com/promotions"); } else { log.info("Promotions not available - skip sending mail to: {}", receiver); } } /** * For Debugging Input! <br> * Also need to implements ApplicationRunner to the Main */ // @Override // public void run(ApplicationArguments args) throws Exception { // log.info("Application started with command-line arguments: {}", Arrays.toString(args.getSourceArgs())); // log.info("NonOptionArgs: {}", args.getNonOptionArgs()); // log.info("OptionNames: {}", args.getOptionNames()); // // for (String name : args.getOptionNames()) { // log.info("arg-" + name + "=" + args.getOptionValues(name)); // } // // boolean containsOption = args.containsOption("person.name"); // log.info("Contains person.name: " + containsOption); // } }
30.652174
107
0.737589
8e104f530aa417f9fd4d2c4b0230f37f00176e15
544
package robertefry.penguin.input.mouse.listener; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; /** * @author Robert E Fry * @date 15 Feb 2019 */ public class MouseActionAdapter implements MouseActionListener { @Override public void onMouseEnter( MouseEvent e ) { } @Override public void onMouseExit( MouseEvent e ) { } @Override public void onMouseMove( MouseEvent e ) { } @Override public void onMouseDrag( MouseEvent e ) { } @Override public void onWheelAction( MouseWheelEvent e ) { } }
16
64
0.731618
bb7667861722bf382a35c3bf9cd78f707cd79612
270
package com.sap.icn.hello.tmp; import java.lang.instrument.Instrumentation; /** * Created by I321761 on 2017/7/31. */ public class ObjectSizeSample { public static void main(String[] args) { Instrumentation ins; Object o = new Object(); } }
18
44
0.662963
c2e0da816c1fafe5073d5bf2f3b08a9c2b7a2801
503
package com.luna.fastjson.exception; import exception.FormativeException; /** * @author lunasaw * 2019/4/10 22:35 */ public class FastjsonException extends FormativeException { public FastjsonException() { super(); } public FastjsonException(String message) { super(message); } public FastjsonException(Throwable cause) { super(cause); } public FastjsonException(String format, Object... arguments) { super(format, arguments); } }
19.346154
66
0.664016
e388263fe85d868e73f12a69161ed2c7ab0dbf6f
3,318
/* * Encog(tm) Core v3.3 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2014 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.neural.hyperneat; import java.util.List; import java.util.Random; import org.encog.engine.network.activation.ActivationBipolarSteepenedSigmoid; import org.encog.engine.network.activation.ActivationClippedLinear; import org.encog.engine.network.activation.ActivationFunction; import org.encog.engine.network.activation.ActivationGaussian; import org.encog.engine.network.activation.ActivationSIN; import org.encog.neural.neat.NEATPopulation; import org.encog.neural.neat.training.NEATGenome; import org.encog.neural.neat.training.NEATLinkGene; import org.encog.neural.neat.training.NEATNeuronGene; import org.encog.util.obj.ChooseObject; /** * A HyperNEAT genome. */ public class HyperNEATGenome extends NEATGenome { /** * A HyperNEAT genome. */ private static final long serialVersionUID = 1L; /** * Build the CPPN activation functions. * @param activationFunctions The activation functions collection to add to. */ public static void buildCPPNActivationFunctions( final ChooseObject<ActivationFunction> activationFunctions) { activationFunctions.add(0.25, new ActivationClippedLinear()); activationFunctions.add(0.25, new ActivationBipolarSteepenedSigmoid()); activationFunctions.add(0.25, new ActivationGaussian()); activationFunctions.add(0.25, new ActivationSIN()); activationFunctions.finalizeStructure(); } /** * Construct a HyperNEAT genome. */ public HyperNEATGenome() { } public HyperNEATGenome(final HyperNEATGenome other) { super(other); } /** * Construct a HyperNEAT genome from a list of neurons and links. * @param neurons The neurons. * @param links The links. * @param inputCount The input count. * @param outputCount The output count. */ public HyperNEATGenome(final List<NEATNeuronGene> neurons, final List<NEATLinkGene> links, final int inputCount, final int outputCount) { super(neurons, links, inputCount, outputCount); } /** * Construct a random HyperNEAT genome. * @param rnd Random number generator. * @param pop The target population. * @param inputCount The input count. * @param outputCount The output count. * @param connectionDensity The connection densitoy, 1.0 for fully connected. */ public HyperNEATGenome(final Random rnd, final NEATPopulation pop, final int inputCount, final int outputCount, final double connectionDensity) { super(rnd, pop, inputCount, outputCount, connectionDensity); } }
32.529412
78
0.760398
540fa3ba8e685a9b489e4bbc4a90bcf58d78dd49
715
package la.renzhen.remoting; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; @Accessors(chain = true) public class ChannelEvent<Channel> { public enum Type { CONNECT, CLOSE, IDLE, EXCEPTION } //@formatter:off @Getter private final Type type; @Getter private final RemotingChannel<Channel> channel; @Setter @Getter private Object data; //@formatter:on public ChannelEvent(Type type, RemotingChannel<Channel> channel) { this.type = type; this.channel = channel; } @Override public String toString() { return "ChannelEvent [type=" + type + ", channel=" + channel + "]"; } }
21.666667
75
0.640559
47844d1098eb57416151f2a67da88bbef417175f
7,197
package model; import javafx.collections.ObservableList; import java.io.File; import java.io.IOException; import java.util.Scanner; public class Search { public static int eleindex[] = new int[100]; public static int schindex[] = new int[100]; public static int couindex[] = new int[100]; public static int teaindex[] = new int[100]; public static int coursenum;//The number of Classes of a student public static Myfile f2; static { try { f2 = new Myfile(new File("Student.txt")); } catch (IOException e) { e.printStackTrace(); } } public static Myfile f3; static { try { f3 = new Myfile(new File("Teacher.txt")); } catch (IOException e) { e.printStackTrace(); } } public static Myfile f4; static { try { f4 = new Myfile(new File("Course.txt")); } catch (IOException e) { e.printStackTrace(); } } public static Myfile f5; static { try { f5 = new Myfile(new File("Schedule.txt")); } catch (IOException e) { e.printStackTrace(); } } public static Myfile f6; static { try { f6 = new Myfile(new File("Electivecourse.txt")); } catch (IOException e) { e.printStackTrace(); } } public static Student[] studentlist = new Student[100]; public static Teacher[] teacherlist = new Teacher[100]; public static Course[] courselist = new Course[100]; public static Schedule[] schedulelist = new Schedule[100]; public static Electivecourse[] electivecourselist = new Electivecourse[100]; public Search() throws IOException { } public void writeALLfile(){ //Student Student s1 = new Student("sid1", "Student1", "m", 15, "CS"); Student s2 = new Student("sid2", "Student2", "f", 16, "EE"); Student s3 = new Student("sid3", "Student3", "m", 17, "ECE"); Student s4 = new Student("sid4", "Student4", "f", 18, "EE"); Student s5 = new Student("sid5", "Student5", "m", 19, "CS"); f2.writeFile(s1); f2.writeFile(s2); f2.writeFile(s3); f2.writeFile(s4); f2.writeFile(s5); //Teacher Teacher t1 = new Teacher("tid1", "Teacher1", "m", 15, "Assistant Professor"); Teacher t2 = new Teacher("tid2", "Teacher2", "f", 20, "Professor"); Teacher t3 = new Teacher("tid3", "Teacher3", "m", 25, "Assistant Professor"); Teacher t4 = new Teacher("tid4", "Teacher4", "f", 30, "Professor"); Teacher t5 = new Teacher("tid5", "Teacher5", "m", 35, "Assistant Professor"); f3.writeFile(t1); f3.writeFile(t2); f3.writeFile(t3); f3.writeFile(t4); f3.writeFile(t5); //Course Course c1 = new Course("JAVA", "cid1", 8); Course c2 = new Course("C", "cid2", 16); Course c3 = new Course("PYTHON", "cid3", 32); Course c4 = new Course("MATLAB", "cid4", 64); Course c5 = new Course("GO", "cid5", 128); f4.writeFile(c1); f4.writeFile(c2); f4.writeFile(c3); f4.writeFile(c4); f4.writeFile(c5); //Schedule Schedule sc1 = new Schedule("C1", "cid1", "tid1", "Room1"); Schedule sc2 = new Schedule("C2", "cid2", "tid2", "Room2"); Schedule sc3 = new Schedule("C3", "cid3", "tid3", "Room3"); Schedule sc4 = new Schedule("C4", "cid4", "tid4", "Room4"); Schedule sc5 = new Schedule("C5", "cid5", "tid5", "Room5"); f5.writeFile(sc1); f5.writeFile(sc2); f5.writeFile(sc3); f5.writeFile(sc4); f5.writeFile(sc5); //Electivecourse Electivecourse e1 = new Electivecourse("elid1", "sid1", "C1"); Electivecourse e11 = new Electivecourse("elid11", "sid1", "C2"); Electivecourse e12 = new Electivecourse("elid12", "sid1", "C3"); Electivecourse e2 = new Electivecourse("elid2", "sid2", "C2"); Electivecourse e3 = new Electivecourse("elid3", "sid3", "C3"); Electivecourse e4 = new Electivecourse("elid4", "sid4", "C4"); Electivecourse e5 = new Electivecourse("elid5", "sid5", "C5"); f6.writeFile(e1); f6.writeFile(e2); f6.writeFile(e3); f6.writeFile(e4); f6.writeFile(e5); f6.writeFile(e11); f6.writeFile(e12); } public void searchALLfile(String sidin, ObservableList<TableContent> tablelist){ coursenum=0; for (int i = 0; i < electivecourselist.length; i++) { if((electivecourselist[i])!=null&&sidin.compareToIgnoreCase(electivecourselist[i].getSid())==0){ eleindex[coursenum++] = i; } } for(int j = 0; j<coursenum;j++){ for (int i = 0; i < schedulelist.length; i++) { if(schedulelist[i]!=null&&(electivecourselist[eleindex[j]].getClassid()).compareToIgnoreCase(schedulelist[i].getClassid())==0){ schindex[j]= i; } } } for(int j = 0; j<coursenum;j++){ for (int i = 0; i < courselist.length; i++) { if(courselist[i]!=null&&(schedulelist[schindex[j]].getCid()).compareToIgnoreCase(courselist[i].getCid())==0){ couindex[j]= i; } } } for(int j = 0; j<coursenum;j++){ for (int i = 0; i < teacherlist.length; i++) { if(teacherlist[i]!=null&&(schedulelist[schindex[j]].getTid()).compareToIgnoreCase(teacherlist[i].getTid())==0){ teaindex[j]= i; } } } for(int i = 0; i<coursenum;i++){ tablelist.add(new TableContent(courselist[couindex[i]].getCname(),teacherlist[teaindex[i]].getName(),schedulelist[schindex[i]].getClassroom())); } } public void readALLfile() throws IOException, ClassNotFoundException { //Read f2.readFile(studentlist); f3.readFile(teacherlist); f4.readFile(courselist); f5.readFile(schedulelist); f6.readFile(electivecourselist); } public void writeOneData() throws IOException, ClassNotFoundException { //Read f2.readFile(studentlist); f3.readFile(teacherlist); f4.readFile(courselist); f5.readFile(schedulelist); f6.readFile(electivecourselist); } // public static void main(String[] args) throws IOException, ClassNotFoundException { // Declare and Construct an instance of the Circle class // // Scanner in = new Scanner(System.in); // String sidin =in.nextLine(); // // Search search=new Search(); // search.writeALLfile(); // search.readALLfile(); // search.searchALLfile(sidin,tablelist); // // for(int i = 0 ;i<coursenum;i++) // System.out.println("Sid : "+sidin+", Classname : "+courselist[couindex[i]].getCname()+", Teachername : "+teacherlist[teaindex[i]].getName()+", Classroom : "+schedulelist[schindex[i]].getClassroom()); // } }
32.863014
213
0.560928
e1c1452d5d87d5df8bbb4297b187dcb48f13f6b9
2,549
/* * (c) Copyright 2015 Micro Focus or one of its affiliates. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. * * The only warranties for products and services of Micro Focus and its affiliates * and licensors ("Micro Focus") are as may be set forth in the express warranty * statements accompanying such products and services. Nothing herein should be * construed as constituting an additional warranty. Micro Focus shall not be * liable for technical or editorial errors or omissions contained herein. The * information contained herein is subject to change without notice. */ package com.hp.autonomy.searchcomponents.core.test; import com.hp.autonomy.searchcomponents.core.search.DocumentsService; import com.hp.autonomy.searchcomponents.core.search.GetContentRequest; import com.hp.autonomy.searchcomponents.core.search.QueryRequest; import com.hp.autonomy.searchcomponents.core.search.QueryRequestBuilder; import com.hp.autonomy.searchcomponents.core.search.QueryRestrictions; import com.hp.autonomy.searchcomponents.core.search.SearchResult; import com.hp.autonomy.types.requests.Documents; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; @SuppressWarnings("SpringJavaAutowiringInspection") public abstract class IntegrationTestUtils<Q extends QueryRestrictions<?>, D extends SearchResult, E extends Exception> { @Autowired protected DocumentsService<? extends QueryRequest<Q>, ?, ?, Q, D, E> documentsService; @Autowired protected ObjectFactory<QueryRequestBuilder<? extends QueryRequest<Q>, Q, ?>> queryRequestBuilderFactory; @Autowired protected TestUtils<Q> testUtils; public Q buildQueryRestrictions() { return testUtils.buildQueryRestrictions(); } public <RC extends GetContentRequest<?>> RC buildGetContentRequest(final String reference) { return testUtils.buildGetContentRequest(reference); } public String getValidReference() throws E { final Q queryRestrictions = buildQueryRestrictions(); final QueryRequest<Q> queryRequest = queryRequestBuilderFactory.getObject() .queryRestrictions(queryRestrictions) .build(); @SuppressWarnings("unchecked") final Documents<D> documents = ((DocumentsService<QueryRequest<Q>, ?, ?, Q, D, E>) documentsService).queryTextIndex(queryRequest); return documents.getDocuments().get(0).getReference(); } }
45.517857
138
0.766183
4eb300210898fb778d7ef87e86120141e1b586a3
3,013
/* * ControladorServlet.java * * Created on 7 de agosto de 2007, 20:31 */ package controladores; import java.io.IOException; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Carmen * @version */ public class ControladorServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws javax.servlet.ServletException * @throws java.io.IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uri = request.getRequestURI(); uri = uri.substring(uri.lastIndexOf("/") + 1, uri.length()); uri = uri.substring(0, uri.lastIndexOf(".")); uri = ejecutarLogicaDeNegocio(uri, request); uri = "/" + uri + ".jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(uri); rd.forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws javax.servlet.ServletException * @throws java.io.IOException */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws javax.servlet.ServletException * @throws java.io.IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return */ @Override public String getServletInfo() { return "Short description"; } // </editor-fold> private String ejecutarLogicaDeNegocio(String uri, HttpServletRequest request) { if (uri.equals("discriminar")) { double valor = Math.random(); if (valor <= 0.5d) { request.setAttribute("fecha", new Date()); return "primera"; } else { request.setAttribute("nombre", "Un usuario cualquiera"); return "segunda"; } } else { return "index"; } } }
30.13
123
0.63923
8bedd7ccb0e06fd49bd19128c2ab40fcc5abf384
23,173
package controller; import Modelos.Cliente; import Modelos.ClienteValidate; import Modelos.Conexion; import Modelos.JSONValid; import Modelos.Usuario; import Modelos.UsuarioCasinoValidate; import Modelos.UsuarioValidate; import com.google.gson.Gson; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.servlet.ModelAndView; @Controller public class UsuarioController { private UsuarioValidate usuarioValidate; private UsuarioCasinoValidate usuarioCasinoValidate; private JdbcTemplate jdbcTemplate; public UsuarioController(){ this.usuarioValidate=new UsuarioValidate(); //Implementar Validator Conexion con= new Conexion(); this.jdbcTemplate=new JdbcTemplate(con.conectar()); } /* @RequestMapping(value = "Administracion/infoCliente.htm") public ModelAndView infoCliente(HttpServletRequest request) { ModelAndView mav=new ModelAndView(); String rut=request.getParameter("rut"); Cliente datos=this.selectCliente(rut); mav.setViewName("Administracion/infoCliente"); mav.addObject("cliente",new Cliente(rut,datos.getNombre(),datos.getNombreLargo(),datos.getEmail(),datos.getTelefono(),datos.getComuna(),datos.getRegion(),datos.getDireccion())); return mav; }*/ @RequestMapping(value = "Administracion/listaUsuario.htm") public ModelAndView listaUsuario(HttpServletRequest request) { ModelAndView mav= new ModelAndView(); String rut=request.getParameter("rut"); Cliente datos=this.selectCliente(rut); String sql ="SELECT CODIGO_USUARIO,NOMBE_PERFIL, NOMBRE_USUARIO, APELLIDO_USUARIO, CORREO_USUARIO, PASS_USUARIO from USUARIO inner join PERFIL on USUARIO.CODIGO_PERFIL = PERFIL.CODIGO_PERFIL where RUT_EMPRESA_USUARIO='"+rut+"'"; List datos2=this.jdbcTemplate.queryForList(sql); String NombreEmpresa=this.jdbcTemplate.queryForObject("SELECT NOMBRE_EMPRESA from EMPRESA where RUT_EMPRESA='"+rut+"'", String.class); mav.addObject("datos",datos2); mav.addObject("rutEmp",rut); mav.addObject("nomEmp",NombreEmpresa); mav.setViewName("Administracion/listaUsuario"); mav.addObject("cliente",new Cliente(rut,datos.getNombre(),datos.getEmail(),datos.getTelefono(),datos.getComuna(),datos.getRegion(),datos.getDireccion())); return mav; } @RequestMapping(value = "Administracion/DetalleUsuarioCasino.htm") public ModelAndView listaUsuarioCasino(HttpServletRequest request) { ModelAndView mav= new ModelAndView(); String rutUser=request.getParameter("rutUser"); Usuario datos=this.selectUsuario(rutUser); List datos2=this.jdbcTemplate.queryForList("SELECT RUT_USUARIO,NOMBRE_CASINO,ID_CASINO from USUARIO_CASINO inner join CASINO on ID_CASINO=CODIGO_CASINO where RUT_USUARIO='"+rutUser+"'"); String perfiles= this.jdbcTemplate.queryForObject("SELECT NOMBE_PERFIL FROM Minugest.PERFIL inner join USUARIO on USUARIO.CODIGO_PERFIL = PERFIL.CODIGO_PERFIL where CODIGO_USUARIO='"+rutUser+"'",String.class); mav.addObject("nombre",datos.getNombre()); mav.addObject("apellido",datos.getApellido()); mav.addObject("rut",datos.getRut()); mav.addObject("perfil",perfiles); mav.addObject("correo",datos.getCorreo()); mav.addObject("pass",datos.getPass()); mav.addObject("rutEmp",datos.getRutEmpresa()); mav.addObject("datos2",datos2); mav.setViewName("Administracion/DetalleUsuarioCasino"); return mav; } @RequestMapping(value = "Administracion/ValidarUsuario.do", method = RequestMethod.GET) @ResponseBody public void ValidarClienteRut(@RequestParam(value = "rut") String Ingrediente, HttpServletRequest request, HttpServletResponse response) { String Nombre= request.getParameter("rut"); JSONValid valida= new JSONValid(); int ingrediente = this.jdbcTemplate.queryForObject("SELECT COUNT(*) from USUARIO where CODIGO_USUARIO='"+Nombre+"'", Integer.class); Boolean valid = true; if (ingrediente != 0) { valid=false; } valida.setValid(valid); String json = null; json = new Gson().toJson(valida); response.setContentType("Administracion/AñadirUsuario"); try { response.getWriter().write(json); } catch (IOException ex) { Logger.getLogger(AdministracionController.class.getName()).log(Level.SEVERE, null, ex); } } @RequestMapping(value="Administracion/AñadirUsuario.htm",method = RequestMethod.GET) public ModelAndView añadirUsuario(HttpServletRequest request) { ModelAndView mav = new ModelAndView(); String rut=request.getParameter("rutEmpresa"); mav.setViewName("Administracion/AñadirUsuario"); List perfiles= this.jdbcTemplate.queryForList("SELECT * FROM Minugest.PERFIL where CODIGO_PERFIL != 1"); mav.addObject("rutEmpresa",rut); mav.addObject("perfiles",perfiles); mav.addObject("usuario",new Usuario()); return mav; } @RequestMapping(value="Administracion/AñadirUsuario.htm",method = RequestMethod.POST) public ModelAndView form(@ModelAttribute ("usuario") Usuario user,BindingResult result, SessionStatus status ) { this.jdbcTemplate.update("INSERT INTO USUARIO (CODIGO_USUARIO, CODIGO_PERFIL, NOMBRE_USUARIO, CORREO_USUARIO, PASS_USUARIO, APELLIDO_USUARIO,RUT_EMPRESA_USUARIO) VALUES (?,?,?,?,?,?,?)" ,user.getRut(),user.getCod_perfil(),user.getNombre(),user.getCorreo(),user.getPass(),user.getApellido(),user.getRutEmpresa()); return new ModelAndView("redirect:listaUsuario.htm?rut="+user.getRutEmpresa()); } @RequestMapping(value="Administracion/DesasignarCasino.htm",method = RequestMethod.GET) public ModelAndView formdeleteCasino(@ModelAttribute ("usuario") Usuario user,BindingResult result, SessionStatus status , HttpServletRequest request ) { String rutUser=request.getParameter("RUT"); String COD=request.getParameter("COD"); String Query = "DELETE FROM `Minugest`.`USUARIO_CASINO` WHERE `ID_CASINO`='"+COD+"' and`RUT_USUARIO`='"+rutUser+"';"; this.jdbcTemplate.execute(Query); return new ModelAndView("redirect:DetalleUsuarioCasino.htm?rutUser="+rutUser+""); } @RequestMapping(value="Administracion/editarUsuario.htm",method=RequestMethod.GET) public ModelAndView editarUsuario(HttpServletRequest request) { ModelAndView mav=new ModelAndView(); String rutUser=request.getParameter("rutUser"); Usuario datos=this.selectUsuario(rutUser); List perfiles= this.jdbcTemplate.queryForList("SELECT * FROM Minugest.PERFIL"); mav.addObject("perfiles",perfiles); mav.setViewName("Administracion/editarUsuario"); mav.addObject("usuario",new Usuario(datos.getRutEmpresa(),datos.getRut(),datos.getCod_perfil(),datos.getNombre(),datos.getCorreo(),datos.getPass(),datos.getApellido())); return mav; } @RequestMapping(value="Administracion/editarUsuario.htm",method = RequestMethod.POST) public ModelAndView formeditUsuario(@ModelAttribute ("usuario") Usuario user,BindingResult result, SessionStatus status ) { this.jdbcTemplate.update("UPDATE USUARIO SET CODIGO_PERFIL=?, NOMBRE_USUARIO=?, CORREO_USUARIO=?, PASS_USUARIO=?, APELLIDO_USUARIO=? WHERE CODIGO_USUARIO=?" ,user.getCod_perfil(),user.getNombre(),user.getCorreo(),user.getPass(),user.getApellido(),user.getRut()); return new ModelAndView("redirect:listaUsuario.htm?rut="+user.getRutEmpresa()); } @RequestMapping(value="Administracion/CasinoUsuario.htm",method=RequestMethod.GET) public ModelAndView UsuarioCasino(HttpServletRequest request) { ModelAndView mav=new ModelAndView(); String rutUser=request.getParameter("rutUser"); Usuario datos=this.selectUsuario(rutUser); List casino = this.jdbcTemplate.queryForList("SELECT CODIGO_CASINO,NOMBRE_CASINO from CASINO where RUT_EMPRESA='"+datos.getRutEmpresa()+"'"); mav.addObject("Casino",casino); mav.addObject("rutEmp", datos.getRutEmpresa()); mav.setViewName("Administracion/CasinoUsuario"); mav.addObject("Usuario",new Usuario(rutUser,datos.getRutEmpresa())); return mav; } @RequestMapping(value="Administracion/CasinoUsuario.htm",method=RequestMethod.POST) public ModelAndView UsuarioCasinoPost(@ModelAttribute("Usuario") Usuario usuario, BindingResult result, SessionStatus status,HttpServletRequest request) { List<String> lista = new ArrayList<>(); lista =usuario.getCombobox(); for (int i = 0; i < lista.size(); i++) { this.jdbcTemplate.update("insert into USUARIO_CASINO (RUT_USUARIO, " + "ID_CASINO)" + "values (?,?)" ,usuario.getRut() ,lista.get(i)); } return new ModelAndView("redirect:DetalleUsuarioCasino.htm?rutUser="+usuario.getRut()+""); } public Usuario selectUsuario(String rut) { final Usuario usuario = new Usuario(); // String quer = "SELECT * FROM EMPRESA WHERE RUT_EMPRESA='" + rut+"'"; String quer="SELECT RUT_EMPRESA_USUARIO,CODIGO_USUARIO, PERFIL.CODIGO_PERFIL, NOMBRE_USUARIO, APELLIDO_USUARIO, CORREO_USUARIO, PASS_USUARIO " + "from USUARIO inner join PERFIL on USUARIO.CODIGO_PERFIL = PERFIL.CODIGO_PERFIL" + " Where CODIGO_USUARIO='" + rut+"'"; return (Usuario) jdbcTemplate.query ( quer, new ResultSetExtractor<Usuario>() { public Usuario extractData(ResultSet rs) throws SQLException, DataAccessException { if (rs.next()) { usuario.setRutEmpresa(rs.getString("RUT_EMPRESA_USUARIO")); usuario.setRut(rs.getString("CODIGO_USUARIO")); usuario.setNombre(rs.getString("NOMBRE_USUARIO")); usuario.setApellido(rs.getString("APELLIDO_USUARIO")); usuario.setPass(rs.getString("PASS_USUARIO")); usuario.setCorreo(rs.getString("CORREO_USUARIO")); usuario.setCod_perfil(rs.getString("CODIGO_PERFIL")); } return usuario; } } ); } public Cliente selectCliente(String rut) { final Cliente cliente = new Cliente(); // String quer = "SELECT * FROM EMPRESA WHERE RUT_EMPRESA='" + rut+"'"; String quer="SELECT\n" + " COMUNA_NOMBRE,\n" + " REGION_NOMBRE,\n" + " RUT_EMPRESA,\n" + " NOMBRE_EMPRESA,\n" + " TELEFONO_EMPRESA,\n" + " CORREO_EMPRESA,\n" + " DIRECCION_EMPRESA,RAZON_SOCIAL\n" + "FROM\n" + " region inner join\n" + " provincia on REGION_ID = PROVINCIA_REGION_ID inner join\n" + " comuna on PROVINCIA_ID = COMUNA_PROVINCIA_ID inner join\n" + " EMPRESA on COMUNA_EMPRESA = COMUNA_ID" + " WHERE RUT_EMPRESA='" + rut+"'"; return (Cliente) jdbcTemplate.query ( quer, new ResultSetExtractor<Cliente>() { public Cliente extractData(ResultSet rs) throws SQLException, DataAccessException { if (rs.next()) { cliente.setNombre(rs.getString("Nombre_EMPRESA")); cliente.setEmail(rs.getString("CORREO_EMPRESA")); cliente.setTelefono(rs.getString("TELEFONO_EMPRESA")); cliente.setComuna(rs.getString("COMUNA_NOMBRE")); cliente.setDireccion(rs.getString("DIRECCION_EMPRESA")); cliente.setRegion(rs.getString("REGION_NOMBRE")); cliente.setNombreLargo(rs.getString("RAZON_SOCIAL")); } return cliente; } } ); } /*------------ADMINISTRACION CLIENTE-----------------------*/ @RequestMapping(value = "AdministracionCliente/Usuarios.htm") public ModelAndView listaUsuarioC(HttpServletRequest request) { ModelAndView mav= new ModelAndView(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UserDetails userDetail = (UserDetails) auth.getPrincipal(); String rutUser=userDetail.getUsername(); Usuario datosU=this.selectUsuario(rutUser); Cliente datos=this.selectCliente(datosU.getRutEmpresa()); String sql ="SELECT CODIGO_USUARIO,NOMBE_PERFIL, NOMBRE_USUARIO, APELLIDO_USUARIO, CORREO_USUARIO, PASS_USUARIO from USUARIO inner join PERFIL on USUARIO.CODIGO_PERFIL = PERFIL.CODIGO_PERFIL where RUT_EMPRESA_USUARIO='"+datosU.getRutEmpresa()+"'"; List datos2=this.jdbcTemplate.queryForList(sql); String NombreEmpresa=this.jdbcTemplate.queryForObject("SELECT NOMBRE_EMPRESA from EMPRESA where RUT_EMPRESA='"+datosU.getRutEmpresa()+"'", String.class); mav.addObject("datos",datos2); mav.addObject("rutEmp",datosU.getRutEmpresa()); mav.addObject("nomEmp",NombreEmpresa); mav.setViewName("Administracion2/listaUsuario"); mav.addObject("cliente",new Cliente(datosU.getRutEmpresa(),datos.getNombre(),datos.getEmail(),datos.getTelefono(),datos.getComuna(),datos.getRegion(),datos.getDireccion())); return mav; } @RequestMapping(value = "AdministracionCliente/DetalleUsuarioCasino.htm") public ModelAndView listaUsuarioCasinoc(HttpServletRequest request) { ModelAndView mav= new ModelAndView(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UserDetails userDetail = (UserDetails) auth.getPrincipal(); String rutUser=userDetail.getUsername(); Usuario datos=this.selectUsuario(rutUser); List datos2=this.jdbcTemplate.queryForList("SELECT RUT_USUARIO,NOMBRE_CASINO,ID_CASINO from USUARIO_CASINO inner join CASINO on ID_CASINO=CODIGO_CASINO where RUT_USUARIO='"+rutUser+"'"); String perfiles= this.jdbcTemplate.queryForObject("SELECT NOMBE_PERFIL FROM Minugest.PERFIL inner join USUARIO on USUARIO.CODIGO_PERFIL = PERFIL.CODIGO_PERFIL where CODIGO_USUARIO='"+rutUser+"'",String.class); mav.addObject("nombre",datos.getNombre()); mav.addObject("apellido",datos.getApellido()); mav.addObject("rut",datos.getRut()); mav.addObject("perfil",perfiles); mav.addObject("correo",datos.getCorreo()); mav.addObject("pass",datos.getPass()); mav.addObject("rutEmp",datos.getRutEmpresa()); mav.addObject("datos2",datos2); mav.setViewName("Administracion2/DetalleUsuarioCasino"); return mav; } @RequestMapping(value = "AdministracionCliente/ValidarUsuario.do", method = RequestMethod.GET) @ResponseBody public void ValidarClienteRutC(@RequestParam(value = "rut") String Ingrediente, HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UserDetails userDetail = (UserDetails) auth.getPrincipal(); String Nombre=userDetail.getUsername(); JSONValid valida= new JSONValid(); int ingrediente = this.jdbcTemplate.queryForObject("SELECT COUNT(*) from USUARIO where CODIGO_USUARIO='"+Nombre+"'", Integer.class); Boolean valid = true; if (ingrediente != 0) { valid=false; } valida.setValid(valid); String json = null; json = new Gson().toJson(valida); response.setContentType("Administracion2/AñadirUsuario"); try { response.getWriter().write(json); } catch (IOException ex) { Logger.getLogger(AdministracionController.class.getName()).log(Level.SEVERE, null, ex); } } @RequestMapping(value="AdministracionCliente/AñadirUsuario.htm",method = RequestMethod.GET) public ModelAndView añadirUsuarioC(HttpServletRequest request) { ModelAndView mav = new ModelAndView(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UserDetails userDetail = (UserDetails) auth.getPrincipal(); String rutUser=userDetail.getUsername(); Usuario datos=this.selectUsuario(rutUser); mav.setViewName("Administracion2/AñadirUsuario"); List perfiles= this.jdbcTemplate.queryForList("SELECT * FROM Minugest.PERFIL"); mav.addObject("rutEmpresa",datos.getRutEmpresa()); mav.addObject("perfiles",perfiles); mav.addObject("usuario",new Usuario()); return mav; } @RequestMapping(value="AdministracionCliente/AñadirUsuario.htm",method = RequestMethod.POST) public ModelAndView formC(@ModelAttribute ("usuario") Usuario user,BindingResult result, SessionStatus status ) { this.jdbcTemplate.update("INSERT INTO USUARIO (CODIGO_USUARIO, CODIGO_PERFIL, NOMBRE_USUARIO, CORREO_USUARIO, PASS_USUARIO, APELLIDO_USUARIO,RUT_EMPRESA_USUARIO) VALUES (?,?,?,?,?,?,?)" ,user.getRut(),user.getCod_perfil(),user.getNombre(),user.getCorreo(),user.getPass(),user.getApellido(),user.getRutEmpresa()); return new ModelAndView("redirect:Usuarios.htm"); } @RequestMapping(value="AdministracionCliente/DesasignarCasino.htm",method = RequestMethod.GET) public ModelAndView formdeleteCasinoC(@ModelAttribute ("usuario") Usuario user,BindingResult result, SessionStatus status , HttpServletRequest request ) { String rutUser=request.getParameter("RUT"); String COD=request.getParameter("COD"); String Query = "DELETE FROM `Minugest`.`USUARIO_CASINO` WHERE `ID_CASINO`='"+COD+"' and`RUT_USUARIO`='"+rutUser+"';"; this.jdbcTemplate.execute(Query); return new ModelAndView("redirect:DetalleUsuarioCasino.htm?rutUser="+rutUser+""); } @RequestMapping(value="AdministracionCliente/editarUsuario.htm",method=RequestMethod.GET) public ModelAndView editarUsuarioC(HttpServletRequest request) { ModelAndView mav=new ModelAndView(); String rutUser=request.getParameter("rutUser"); Usuario datos=this.selectUsuario(rutUser); List perfiles= this.jdbcTemplate.queryForList("SELECT * FROM Minugest.PERFIL"); mav.addObject("perfiles",perfiles); mav.setViewName("Administracion2/editarUsuario"); mav.addObject("usuario",new Usuario(datos.getRutEmpresa(),datos.getRut(),datos.getCod_perfil(),datos.getNombre(),datos.getCorreo(),datos.getPass(),datos.getApellido())); return mav; } @RequestMapping(value="AdministracionCliente/editarUsuario.htm",method = RequestMethod.POST) public ModelAndView formeditUsuarioC(@ModelAttribute ("usuario") Usuario user,BindingResult result, SessionStatus status ) { this.jdbcTemplate.update("UPDATE USUARIO SET CODIGO_PERFIL=?, NOMBRE_USUARIO=?, CORREO_USUARIO=?, PASS_USUARIO=?, APELLIDO_USUARIO=? WHERE CODIGO_USUARIO=?" ,user.getCod_perfil(),user.getNombre(),user.getCorreo(),user.getPass(),user.getApellido(),user.getRut()); return new ModelAndView("redirect:Usuarios.htm"); } @RequestMapping(value="AdministracionCliente/CasinoUsuario.htm",method=RequestMethod.GET) public ModelAndView UsuarioCasinoC(HttpServletRequest request) { ModelAndView mav=new ModelAndView(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UserDetails userDetail = (UserDetails) auth.getPrincipal(); String rutUser=userDetail.getUsername(); Usuario datos=this.selectUsuario(rutUser); List casino = this.jdbcTemplate.queryForList("SELECT CODIGO_CASINO,NOMBRE_CASINO from CASINO where RUT_EMPRESA='"+datos.getRutEmpresa()+"'"); mav.addObject("Casino",casino); mav.addObject("rutEmp", datos.getRutEmpresa()); mav.addObject("rut", rutUser); mav.setViewName("Administracion2/CasinoUsuario"); mav.addObject("Usuario",new Usuario(rutUser,datos.getRutEmpresa())); return mav; } @RequestMapping(value="AdministracionCliente/CasinoUsuario.htm",method=RequestMethod.POST) public ModelAndView UsuarioCasinoPostC(@ModelAttribute("Usuario") Usuario usuario, BindingResult result, SessionStatus status,HttpServletRequest request) { List<String> lista = new ArrayList<>(); lista =usuario.getCombobox(); for (int i = 0; i < lista.size(); i++) { this.jdbcTemplate.update("insert into USUARIO_CASINO (RUT_USUARIO, " + "ID_CASINO)" + "values (?,?)" ,usuario.getRut() ,lista.get(i)); } return new ModelAndView("redirect:DetalleUsuarioCasino.htm?rutUser="+usuario.getRut()+""); } }
50.049676
256
0.660165
82b5bd1302cb97df42892d74306c35bc980f26b9
1,960
package pl.itcraft.appstract.core.api.files; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import pl.itcraft.appstract.core.BaseAppModuleConfig; import pl.itcraft.appstract.core.api.error.ApiException; import pl.itcraft.appstract.core.api.error.RC; import pl.itcraft.appstract.core.dto.ErrorDto; import pl.itcraft.appstract.core.dto.StringDto; import pl.itcraft.appstract.core.entities.UploadedFile; import pl.itcraft.appstract.core.file.UploadedFilesReaderService; import pl.itcraft.appstract.core.security.DisposableTokenService; @RestController @Api(tags = {"files"}, produces = "application/json") public class DisposableFilesController { @Autowired private UploadedFilesReaderService filesService; @Autowired private DisposableTokenService tokenService; @Autowired private BaseAppModuleConfig appModuleConfig; @GetMapping("disposable-url/{path:.+}") @ApiOperation(value = "Generate disposable URL", notes = "Generate disposable URL for given file path") @ApiResponses({ @ApiResponse(code = RC.OK, message = "Successfully logged in"), @ApiResponse(code = RC.RESOURCE_NOT_FOUND, message = "File not found in given path", response = ErrorDto.class) }) public StringDto generateDisposableUrl(@PathVariable("path") String path) { UploadedFile uf = filesService.findByPath(path); if (uf == null) { throw new ApiException(RC.RESOURCE_NOT_FOUND); } filesService.checkPermission(uf); String signedToken = tokenService.createToken( uf.getId().toString() ); return new StringDto( appModuleConfig.getCurrentApiUrl() + "/disposable-file/" + signedToken ); } }
39.2
113
0.79949
886ed99127d848369131e1640c6d8c5dcb1227b9
3,009
package mekanism.common.item.block.machine; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nonnull; import mekanism.api.NBTConstants; import mekanism.api.Upgrade; import mekanism.api.text.EnumColor; import mekanism.client.render.item.ISTERProvider; import mekanism.common.MekanismLang; import mekanism.common.block.machine.prefab.BlockTile; import mekanism.common.content.blocktype.Machine; import mekanism.common.item.IItemSustainedInventory; import mekanism.common.security.ISecurityItem; import mekanism.common.tile.TileEntitySolarNeutronActivator; import mekanism.common.util.ItemDataUtils; import mekanism.common.util.MekanismUtils; import mekanism.common.util.SecurityUtils; import mekanism.common.util.text.BooleanStateDisplay.YesNo; import mekanism.common.util.text.OwnerDisplay; import mekanism.common.util.text.UpgradeDisplay; import net.minecraft.block.BlockState; import net.minecraft.client.Minecraft; import net.minecraft.item.BlockItemUseContext; import net.minecraft.item.ItemStack; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.util.Constants.NBT; public class ItemBlockSolarNeutronActivator extends ItemBlockMachine implements IItemSustainedInventory, ISecurityItem { public ItemBlockSolarNeutronActivator(BlockTile<TileEntitySolarNeutronActivator, Machine<TileEntitySolarNeutronActivator>> block) { super(block, ISTERProvider::activator); } @Override @OnlyIn(Dist.CLIENT) public void addDetails(@Nonnull ItemStack stack, World world, @Nonnull List<ITextComponent> tooltip, boolean advanced) { tooltip.add(OwnerDisplay.of(Minecraft.getInstance().player, getOwnerUUID(stack)).getTextComponent()); tooltip.add(MekanismLang.SECURITY.translateColored(EnumColor.GRAY, SecurityUtils.getSecurity(stack, Dist.CLIENT))); if (SecurityUtils.isOverridden(stack, Dist.CLIENT)) { tooltip.add(MekanismLang.SECURITY_OVERRIDDEN.translateColored(EnumColor.RED)); } tooltip.add(MekanismLang.HAS_INVENTORY.translateColored(EnumColor.AQUA, EnumColor.GRAY, YesNo.of(hasInventory(stack)))); if (ItemDataUtils.hasData(stack, NBTConstants.UPGRADES, NBT.TAG_LIST)) { Map<Upgrade, Integer> upgrades = Upgrade.buildMap(ItemDataUtils.getDataMap(stack)); for (Entry<Upgrade, Integer> entry : upgrades.entrySet()) { tooltip.add(UpgradeDisplay.of(entry.getKey(), entry.getValue()).getTextComponent()); } } } @Override public boolean placeBlock(@Nonnull BlockItemUseContext context, @Nonnull BlockState state) { if (!MekanismUtils.isValidReplaceableBlock(context.getWorld(), context.getPos().up())) { //If there isn't room then fail return false; } return super.placeBlock(context, state); } }
47.015625
135
0.772017
b1950c51df148ab87830353dddc2dfa9515f91ad
3,157
package com.joshng.util.collect; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.AbstractQueue; import java.util.Iterator; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * A simple <em>non-thread-safe</em> queue that allows traversal in FIFO order. * Differs from the standard FIFO implementations (LinkedList, Deque, BlockingQueue) by always exposing * new items added <em>during iteration</em> to the active iterator. * <p> * IMPORTANT NOTE: this queue only supports a single iterator at a time; interacting with multiple * iterators simultaneously will result in an IllegalStateException. */ public class SimpleIterableQueue<T> extends AbstractQueue<T> { private final Node<T> sentinel = new Node<T>(null); private final int maxSize; private Node<T> last; private WeakReference<Iter> currentIterator; int size; public SimpleIterableQueue(int maxSize) { this.maxSize = maxSize; clear(); } public static <T> SimpleIterableQueue<T> create() { return new SimpleIterableQueue<T>(); } public SimpleIterableQueue() { this(Integer.MAX_VALUE); } @Override public int size() { return size; } @Override public void clear() { currentIterator = null; last = sentinel.next = sentinel; size = 0; } @Nullable public T poll() { if (isEmpty()) return null; return removeAfter(sentinel); } @Nullable public T peek() { return sentinel.next.value; } public boolean offer(@Nonnull T value) { checkNotNull(value, "Tried to insert null"); if (size == maxSize) return false; Node<T> node = new Node<T>(value); node.next = sentinel; last.next = node; last = node; size++; return true; } public Iterator<T> iterator() { Iter iter = new Iter(); currentIterator = new WeakReference<Iter>(iter); return iter; } private class Iter implements Iterator<T> { private Node<T> current = sentinel; private Node<T> prev = current; public boolean hasNext() { checkStaleIterator(); return current.next != sentinel; } public T next() { checkStaleIterator(); checkState(hasNext(), "No more elements"); prev = current; current = current.next; return current.value; } public void remove() { checkStaleIterator(); checkState(prev != current, "Already removed this element, or iterator was not started"); removeAfter(prev); current = prev; } private void checkStaleIterator() { checkState(currentIterator != null && currentIterator.get() == this, "Stale iterator: another iterator"); } } private T removeAfter(Node<T> prev) { Node<T> removed = prev.next; assert removed != sentinel; prev.next = removed.next; if (last == removed) last = prev; size--; return removed.value; } private static class Node<T> { private final T value; Node<T> next = null; private Node(T value) { this.value = value; } } }
24.099237
111
0.669306
fc8837d03c6a4b6ae9b3b8c7e7e0be33e5d737d8
2,936
/******************************************************************************* * ZuseCoin 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. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. *******************************************************************************/ package org.zusecoin.wam; import java.nio.ByteBuffer; /** * Factory for creating prolog terms. These terms are encoded with their * corresponding tags and values so the machine can place them on the heap. */ public class TermFactory { public static final byte REF_TAG = (byte) 0;// REF public static final byte STRUCTURE_TAG = (byte) 1; public static final byte LIST_TAG = (byte) 2; /** * Tag encoding for constants */ public static final byte CONSTANT_TAG = (byte) 4; public static final byte INT_TAG = (byte) 3; public static final byte FUNCTOR_TAG = (byte) 5; /** * Encodes a string constant value as bytes. The specified value must begin with * a lower case character. * * @param value * the value to encode * @return the constant as bytes */ public static byte[] constant(String value) { if (value == null) { throw new IllegalArgumentException("value is null"); } // TODO: check that this is lower case return ByteBuffer.allocate(value.length() + 1).put(CONSTANT_TAG).put(value.getBytes()).array(); } private static byte[] encodeInt(byte tag, int i) { return ByteBuffer.allocate(5).put(tag).putInt(i).array(); } /** * Encodes a functor and its arity. The subterm values of the functor are not * encoded within this method * * @param functor * @return encoded functor */ public static byte[] functor(String functor) { return ByteBuffer.allocate(functor.length() + 5).put(FUNCTOR_TAG).put(functor.getBytes()).array(); } public static byte[] integer(int value) { return encodeInt(INT_TAG, value); } public static byte[] list(int address) { return encodeInt(LIST_TAG, address); } public static byte[] structure(int address) { return encodeInt(STRUCTURE_TAG, address); } /** * Creates a variable encoded as bytes. A variable may be bounded or unbounded. * * @param address * the store address in the heap * @return bytes to be placed on the heap */ public static byte[] variable(int address) { return encodeInt(REF_TAG, address); } }
30.583333
100
0.666553
ba0c61ec32123ec55547bb379f7bbfe033430ba0
10,722
/* * Copyright (c) 1998-2020 John Caron and University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.grid; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import ucar.ma2.InvalidRangeException; import ucar.nc2.dataset.CoordinateAxis1D; import ucar.nc2.dataset.CoordinateAxis1DTime; import ucar.nc2.ft2.coverage.*; import ucar.nc2.internal.util.CompareArrayToMa2; import ucar.unidata.util.test.TestDir; import ucar.unidata.util.test.category.NeedsCdmUnitTest; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; /** Compare reading netcdf with Array */ @RunWith(Parameterized.class) @Category(NeedsCdmUnitTest.class) public class TestReadGridCompare { @Parameterized.Parameters(name = "{0}") public static List<Object[]> getTestParameters() { FileFilter ff = TestDir.FileFilterSkipSuffix( ".ncx4 .gbx9 .cdl .pdf perverse.nc aggFmrc.xml 2003021212_avn-x.nc wrfout_01_000000_0003.nc wrfout_01_000000_0003.ncml"); List<Object[]> result = new ArrayList<>(500); try { // in this case the time coordinate is not monotonic. // result.add(new Object[] {TestDir.cdmUnitTestDir + "conventions/nuwg/2003021212_avn-x.nc"}); // in this case the vert coordinate is not identified. // Note that TestDir skips this in favor of the ncml file in the same directory (true?) // result.add(new Object[] {TestDir.cdmUnitTestDir + "conventions/avhrr/amsr-avhrr-v2.20040729.nc"}); // result.add(new Object[] {TestDir.cdmUnitTestDir + "wrf/wrfout_01_000000_0003.ncml"}); result.add(new Object[] {TestDir.cdmLocalTestDataDir + "ncml/nc/ubyte_1.nc4"}); result.add(new Object[] {TestDir.cdmLocalTestDataDir + "ncml/nc/cldc.mean.nc"}); result.add(new Object[] {TestDir.cdmLocalTestDataDir + "ncml/fmrc/GFS_Puerto_Rico_191km_20090729_0000.nc"}); TestDir.actOnAllParameterized(TestDir.cdmUnitTestDir + "conventions/", ff, result); TestDir.actOnAllParameterized(TestDir.cdmUnitTestDir + "ft/grid/", ff, result); } catch (Exception e) { e.printStackTrace(); } return result; } ///////////////////////////////////////////////////////////// public TestReadGridCompare(String filename) { this.filename = filename; } private final String filename; @Test public void compareGrid() throws Exception { // these are failing in old code. if (filename.endsWith("cdm_sea_soundings.nc4")) return; if (filename.endsWith("IntTimSciSamp.nc")) return; compareGridDataset(filename); // Coverage has lots of bugs - fix later // compareGridCoverage(filename); } public static void compareGridDataset(String filename) throws Exception { Formatter errlog = new Formatter(); try (GridDataset newDataset = GridDatasetFactory.openGridDataset(filename, errlog); ucar.nc2.dt.grid.GridDataset dataset = ucar.nc2.dt.grid.GridDataset.open(filename)) { if (newDataset == null) { System.out.printf("Cant open as GridDataset: %s%n", filename); return; } System.out.printf("compareGridDataset: %s%n", newDataset.getLocation()); boolean ok = true; for (Grid grid : newDataset.getGrids()) { ucar.nc2.dt.grid.GeoGrid geogrid = dataset.findGridByName(grid.getName()); if (geogrid == null) { System.out.printf("Grid %s not in Geogrid: ", grid.getName()); return; } System.out.println(" Grid/GeoGrid: " + grid.getName()); ucar.nc2.dt.GridCoordSystem gcs = geogrid.getCoordinateSystem(); GridCoordinateSystem newGcs = grid.getCoordinateSystem(); assertThat(newGcs.getTimeAxis() == null).isEqualTo(gcs.getTimeAxis() == null); if (newGcs.getTimeAxis() != null) { GridAxis1DTime newTimeAxis = newGcs.getTimeAxis(); CoordinateAxis1DTime timeAxis = (CoordinateAxis1DTime) gcs.getTimeAxis(); assertThat(newTimeAxis.getNcoords()).isEqualTo(timeAxis.getSize()); int timeIdx = 0; for (Object timeCoord : newTimeAxis) { if (newGcs.getVerticalAxis() != null) { ok &= doVert(grid, geogrid, timeCoord, timeIdx); // time and vertical } else { // time, no vertical GridSubset subset = new GridSubset(); subset.setTimeCoord(timeCoord); ok &= doOne(grid, geogrid, subset, timeIdx, -1); // no time, no vertical } timeIdx++; } } else { if (newGcs.getVerticalAxis() != null) { ok &= doVert(grid, geogrid, 0.0, -1); // no time, only vertical } else { doOne(grid, geogrid, new GridSubset(), -1, -1); // no time, no vertical } } } assertThat(ok).isTrue(); } catch (RuntimeException rte) { if (rte.getMessage() != null && rte.getMessage().contains("not monotonic")) { return; } rte.printStackTrace(); fail(); } } private static boolean doVert(Grid grid, ucar.nc2.dt.grid.GeoGrid geogrid, Object timeCoord, int timeIdx) throws Exception { boolean ok = true; GridAxis1D newVertAxis = grid.getCoordinateSystem().getVerticalAxis(); CoordinateAxis1D vertAxis = geogrid.getCoordinateSystem().getVerticalAxis(); assertThat(newVertAxis.getNcoords()).isEqualTo(vertAxis.getSize()); int vertIdx = 0; for (Object vertCoord : newVertAxis) { GridSubset subset = new GridSubset(); subset.setTimeCoord(timeCoord); subset.setVertCoord(vertCoord); ok &= doOne(grid, geogrid, subset, timeIdx, vertIdx); vertIdx++; } return ok; } private static boolean doOne(Grid grid, ucar.nc2.dt.grid.GeoGrid geogrid, GridSubset subset, int timeIdx, int vertIdx) throws IOException, InvalidRangeException { GridReferencedArray geoArray = grid.readData(subset); ucar.ma2.Array org = geogrid.readDataSlice(timeIdx, vertIdx, -1, -1); Formatter f = new Formatter(); boolean ok1 = CompareArrayToMa2.compareData(f, grid.getName(), org, geoArray.data(), true, true); if (!ok1) { System.out.printf("gridSubset= %s; time vert= (%d %d) %n%s%n", subset, timeIdx, vertIdx, f); } return ok1; } public static void compareGridCoverage(String filename) throws Exception { Formatter errlog = new Formatter(); try (GridDataset newDataset = GridDatasetFactory.openGridDataset(filename, errlog); FeatureDatasetCoverage covDataset = CoverageDatasetFactory.open(filename)) { if (newDataset == null) { System.out.printf("Cant open as GridDataset: %s%n", filename); return; } System.out.printf("compareGridCoverage: %s%n", newDataset.getLocation()); CoverageCollection covCollection = covDataset.getCoverageCollections().get(0); boolean ok = true; for (Grid grid : newDataset.getGrids()) { Coverage coverage = covCollection.findCoverage(grid.getName()); if (coverage == null) { System.out.printf(" Grid %s not in coverage: " + grid.getName()); return; } System.out.println(" Grid/Coverage: " + grid.getName()); CoverageCoordSys gcs = coverage.getCoordSys(); GridCoordinateSystem newGcs = grid.getCoordinateSystem(); assertThat(newGcs.getTimeAxis() == null).isEqualTo(gcs.getTimeAxis() == null); if (newGcs.getTimeAxis() != null) { GridAxis1DTime newTimeAxis = newGcs.getTimeAxis(); assertThat(gcs.getTimeAxis()).isNotNull(); CoverageCoordAxis axis = gcs.getTimeAxis(); assertThat(axis).isInstanceOf(CoverageCoordAxis1D.class); CoverageCoordAxis1D timeAxis = (CoverageCoordAxis1D) axis; assertThat(newTimeAxis.getNcoords()).isEqualTo(timeAxis.getNcoords()); for (int timeIdx = 0; timeIdx < newTimeAxis.getNcoords(); timeIdx++) { double timeCoord = newTimeAxis.getCoordMidpoint(timeIdx); if (newGcs.getVerticalAxis() != null) { ok &= doVert(grid, coverage, timeCoord); // both time and vert } else { // just time GridSubset subset = new GridSubset(); subset.setTimeCoord(timeCoord); SubsetParams subsetp = new SubsetParams(); subsetp.setTimeCoord(timeCoord); ok &= doOne(grid, coverage, subset, subsetp); } } } else { // no time, just vert if (newGcs.getVerticalAxis() != null) { ok &= doVert(grid, coverage, 0.0); // no time, only vertical } else { doOne(grid, coverage, new GridSubset(), new SubsetParams()); // no time, no vertical } } } assertThat(ok).isTrue(); } catch (RuntimeException rte) { if (rte.getMessage() != null && rte.getMessage().contains("not monotonic")) { return; } rte.printStackTrace(); fail(); } } private static boolean doVert(Grid grid, Coverage coverage, double timeCoord) throws Exception { boolean ok = true; GridAxis1D newVertAxis = grid.getCoordinateSystem().getVerticalAxis(); CoverageCoordAxis zAxis = coverage.getCoordSys().getZAxis(); assertThat(zAxis).isInstanceOf(CoverageCoordAxis1D.class); CoverageCoordAxis1D vertAxis = (CoverageCoordAxis1D) zAxis; assertThat(newVertAxis.getNcoords()).isEqualTo(vertAxis.getNcoords()); for (int vertIdx = 0; vertIdx < newVertAxis.getNcoords(); vertIdx++) { GridSubset subset = new GridSubset(); subset.setTimeCoord(timeCoord); subset.setVertCoord(newVertAxis.getCoordMidpoint(vertIdx)); SubsetParams subsetp = new SubsetParams(); subsetp.setTimeCoord(timeCoord); subsetp.setVertCoord(vertAxis.getCoordMidpoint(vertIdx)); ok &= doOne(grid, coverage, subset, subsetp); } return ok; } private static boolean doOne(Grid grid, Coverage coverage, GridSubset subset, SubsetParams subsetp) throws IOException, InvalidRangeException { GridReferencedArray gridArray = grid.readData(subset); GeoReferencedArray covArray = coverage.readData(subsetp); Formatter f = new Formatter(); boolean ok1 = CompareArrayToMa2.compareData(f, grid.getName(), covArray.getData(), gridArray.data(), true, true); if (!ok1) { System.out.printf("gridSubset= %s; covSubset= %s%n%s%n", subset, subsetp, f); } return ok1; } }
38.989091
129
0.660138
9c5041c0af026951c7675c8a36c296eda6b4b33d
1,276
package ru.obolensk.afff.beetle2.protocol.stream.packet; import javax.annotation.Nonnull; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; import ru.obolensk.afff.beetle2.protocol.channel.PacketType; import ru.obolensk.afff.beetle2.protocol.channel.RawPacket; import ru.obolensk.afff.beetle2.protocol.channel.RawPacketBuilder; import static ru.obolensk.afff.beetle2.protocol.channel.ByteBufferBuilder.createBuffer; import static ru.obolensk.afff.beetle2.protocol.channel.PacketType.WINDOW_UPDATE; import static ru.obolensk.afff.beetle2.util.ByteArrayUtil.read4BytesUnsignedInt; /** * Created by Dilmukhamedov_A on 03.07.2018. */ @Getter @RequiredArgsConstructor @ToString public class WindowUpdatePacket extends AbstractPacket { private final int windowSizeIncrement; public WindowUpdatePacket(@Nonnull RawPacket rawPacket) { super(rawPacket); byte[] payload = rawPacket.getPayload(); windowSizeIncrement = read4BytesUnsignedInt(payload, 0); } @Override public PacketType getType() { return WINDOW_UPDATE; } @Nonnull @Override protected RawPacket createRawPacket() { return new RawPacketBuilder(this) .withPayload(createBuffer(4) .with4Bytes(windowSizeIncrement) .build()) .build(); } }
27.73913
87
0.795455
0e711d98787961a999de0128aa7d597eb2f1bed1
75,347
package com.buykop.console.controller; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSONObject; import com.buykop.console.entity.PMember; import com.buykop.console.service.DataFormService; import com.buykop.framework.annotation.Menu; import com.buykop.framework.annotation.Module; import com.buykop.framework.annotation.Security; import com.buykop.framework.cache.location.ExpiringMap; import com.buykop.framework.entity.DiyInfField; import com.buykop.framework.entity.DiyInfOutField; import com.buykop.framework.entity.DiyInfQueryOperation; import com.buykop.framework.http.HttpEntity; import com.buykop.framework.http.PageInfo; import com.buykop.framework.log.Logger; import com.buykop.framework.log.LoggerFactory; import com.buykop.framework.oauth2.PRole; import com.buykop.framework.oauth2.UserToken; import com.buykop.framework.redis.RdClient; import com.buykop.framework.scan.ExportTemplate; import com.buykop.framework.scan.Field; import com.buykop.framework.scan.FieldCalculationFormula; import com.buykop.framework.scan.PFormInField; import com.buykop.framework.scan.PFormOutField; import com.buykop.framework.scan.PFormQuery; import com.buykop.framework.scan.PFormQueryOperation; import com.buykop.framework.scan.PClob; import com.buykop.framework.scan.PDiyUri; import com.buykop.framework.scan.PForm; import com.buykop.framework.scan.PFormAction; import com.buykop.framework.scan.PFormDiy; import com.buykop.framework.scan.PFormField; import com.buykop.framework.scan.PFormMember; import com.buykop.framework.scan.PFormMsgPush; import com.buykop.framework.scan.PFormRowAction; import com.buykop.framework.scan.PFormSlave; import com.buykop.framework.scan.LabelDisplay; import com.buykop.framework.scan.MsgTemplate; import com.buykop.framework.scan.PRoot; import com.buykop.framework.scan.PSysCode; import com.buykop.framework.scan.PTreeForm; import com.buykop.framework.scan.Statement; import com.buykop.framework.scan.Table; import com.buykop.framework.scan.TableRedicSubConfig; import com.buykop.framework.util.CacheTools; import com.buykop.framework.util.ClassInnerNotice; import com.buykop.framework.util.BosConstants; import com.buykop.framework.util.data.DataChange; import com.buykop.framework.util.data.MyString; import com.buykop.framework.util.type.BaseController; import com.buykop.framework.util.type.BosEntity; import com.buykop.framework.util.type.QueryFetchInfo; import com.buykop.framework.util.type.QueryListInfo; import com.buykop.framework.util.type.SelectBidding; import com.buykop.framework.util.type.ServiceInf; import com.buykop.framework.util.type.TableJson; import com.buykop.console.util.Constants; @Module(display = "表单", sys = Constants.current_sys) @RestController @RequestMapping(DataFormController.URI) public class DataFormController extends BaseController{ private static Logger logger=LoggerFactory.getLogger(DataFormController.class); protected static final String URI="/dtform"; //private static Logger logger = Logger.getLogger(DataFormController.class); @Autowired private DataFormService service; @Security(accessType = "1", displayName = "表单列表(根据业务类)", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/listForClassName", method = RequestMethod.POST) @ResponseBody public JSONObject listForClassName(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } Vector<String> v=new Vector<String>(); PForm search=json.getSearch(PForm.class, "className,!formType",ut,this.service); search.setStatus(1L); QueryListInfo<PForm> list=this.service.getMgClient().getList(search,this.service); //String className=json.getSelectedId(Constants.current_sys, "/dtform/listForClassName", PForm.class.getName(), "className", true); Table table=this.service.getMgClient().getTableById(search.getClassName()); if(table==null) { json.setUnSuccessForNoRecord(Table.class,search.getClassName()); return json.jsonValue(); } for(PForm t:list.getList()) { v.add(t.getFormId()); t.setSelected(); } super.listToJson(list, json,BosConstants.getTable(PForm.class)); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "模板匹配机构列表", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/memberFetch", method = RequestMethod.POST) @ResponseBody public JSONObject memberFetch(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String formId=json.getSelectedId(Constants.current_sys, URI+"/memberFetch", PForm.class.getName(), null, true,this.getService()); PFormMember fm=new PFormMember(); fm.setFormId(formId); Vector<String> mv=this.service.getMgClient().getVector(fm, "memberId",this.service); BosEntity search=json.getSearch(PMember.class.getName(),null,ut,this.service); if(search==null) { search=new TableJson(PMember.class.getName()); } PageInfo page=json.getPageInfo(PMember.class.getName()); QueryFetchInfo<BosEntity> fetch=this.service.getFetch(search,"seq,name,status", page.getCurrentPage(), page.getPageSize()); for(BosEntity x:fetch.getList()) { if(mv.contains(x.getPk())) { x.setSelected(); } } super.fetchToJson(fetch, json, BosConstants.getTable(PMember.class.getName())); //super.selectToJson(Field.getJsonForSelectDateRange(SysConstants.memberClassName,null), json, SysConstants.getTable(SysConstants.memberClassName).getSimpleName(), "queryDateProperty"); //super.selectToJson(Field.getJsonForSelectNumRange(SysConstants.memberClassName,null), json, SysConstants.getTable(SysConstants.memberClassName).getSimpleName(), "queryNumProperty"); //super.selectToJson(search.showTable().getFieldJsonForSelectCodeValue(json,null), json, SysConstants.getTable(SysConstants.memberClassName).getSimpleName(), "queryCodeValueProperty"); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "模板匹配机构清理", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/memberClear", method = RequestMethod.POST) @ResponseBody public JSONObject memberClear(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String formId=json.getSelectedId(Constants.current_sys, URI+"/memberFetch", PForm.class.getName(), null, true,this.getService()); PFormMember fm=new PFormMember(); fm.setFormId(formId); this.service.getMgClient().delete(fm,ut,this.service); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "模板匹配机构保存", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/memberSave", method = RequestMethod.POST) @ResponseBody public JSONObject memberSave(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String formId=json.getSelectedId(Constants.current_sys, URI+"/memberFetch", PForm.class.getName(), null, true,this.getService()); Vector<String> idsV=json.showIds(); PFormMember fm=new PFormMember(); fm.setFormId(formId); List<BosEntity> list=json.getList(PMember.class.getName(), null,this.service); for(BosEntity x:list) { fm.setMemberId(x.getPk()); this.service.getMgClient().deleteByPK(fm.getPk(), PFormMember.class,ut,this.service); } for(String x:idsV) { fm.setMemberId(x); this.service.save(fm,ut); } json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Menu(js = "form", name = "数据维护表单", trunk = "开发服务,模板管理") @Security(accessType = "1", displayName = "流程列表", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/fetch", method = RequestMethod.POST) @ResponseBody public JSONObject fetch(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } PForm search = json.getSearch(PForm.class, "",ut,this.service); search.setFormType(1L); PageInfo page = json.getPageInfo(PForm.class); if(!DataChange.isEmpty(search.getSys())) { QueryListInfo<PForm> fetch = this.service.getMgClient().getList(search,this.service); BosConstants.debug(fetch); for(PForm x:fetch.getList()) { if(x.getAllowAdd()==null) x.setAllowAdd(1L); if(x.getAllowDelete()==null) x.setAllowDelete(1L); if(DataChange.isEmpty(x.getClassName())) continue; Table table=BosConstants.getTable(x.getClassName()); if(table!=null) { x.setSys(table.getSys()); } } super.selectToJson(Table.getJsonForSelect(search.getSys(),null,this.service), json, PForm.class.getSimpleName(), "className"); super.listToJson(fetch, json, BosConstants.getTable(PForm.class.getName())); }else { QueryFetchInfo<PForm> fetch = this.service.getMgClient().getFetch(search, page.getCurrentPage(),page.getPageSize(),this.service); fetch.initBiddingForSysClassName(this, json, "sys", "className",null); super.fetchToJson(fetch, json, BosConstants.getTable(PForm.class.getName())); } super.selectToJson(PRoot.getJsonForDev(ut.getMemberId(),this.service), json, PForm.class.getSimpleName(), "sys"); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1,2", displayName = "主表单更换类名", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/formClassChange", method = RequestMethod.POST) @ResponseBody public JSONObject formClassChange(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } PForm obj=json.getObj(PForm.class, "formId,className",this.service); Table table = BosConstants.getTable(obj.getClassName()); BosConstants.debug(table); if (table == null) { json.setUnSuccessForNoRecord(Table.class,obj.getClassName()); return json.jsonValue(); } PForm src=this.service.getMgClient().getById(obj.getFormId(), PForm.class); if(src==null) { json.setUnSuccessForNoRecord(PForm.class,obj.getFormId()); return json.jsonValue(); } src.setClassName(obj.getClassName()); this.service.save(src,ut); json.setSelectedId(Constants.current_sys, "/dtform/info", obj.getFormId()); return this.info(json,request); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } } @Security(accessType = "1", displayName = "主表单详情", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/info", method = RequestMethod.POST) @ResponseBody public JSONObject info(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id=json.getSelectedId(Constants.current_sys, "/dtform/info", PForm.class.getName(), "", true,this.getService()); PForm obj = this.service.getMgClient().getById(id, PForm.class); if (obj == null) { json.setUnSuccessForNoRecord(PForm.class,id); return json.jsonValue(); } if(obj.getDiyService()==null) { obj.setDiyService(0L); } if(DataChange.isEmpty(obj.getSys())) { json.setUnSuccess(-1, "请设置所属系统"); return json.jsonValue(); } if(DataChange.isEmpty(obj.getClassName())) { json.setUnSuccess(-1, "请设置绑定业务类"); return json.jsonValue(); } Table table = this.service.getMgClient().getTableById(obj.getClassName()); if(table==null) { json.setUnSuccessForNoRecord(Table.class,obj.getClassName()); return json.jsonValue(); } super.objToJson(table, json); json.putUserInfo(ut); super.selectToJson(PRoot.getJsonForSelect(1L,this.service), json, PForm.class.getSimpleName(), "sys"); //if (!DataChange.isEmpty(obj.getClassName())) { super.selectToJson(Table.getPkDBJsonForSelect(obj.getSys(),this.service), json, PForm.class.getSimpleName(),"className"); if(!DataChange.isEmpty(obj.getClassName())) { super.selectToJson(Statement.getJsonForSelect(obj.getClassName(),this.service), json, PForm.class.getSimpleName(),"mapId"); } super.selectToJson(PSysCode.getForSelect("126",this.service), json, PForm.class.getSimpleName(),"dataPerType"); super.selectToJson(Table.getCodeValueFieldJsonForSelect(obj.getClassName(),this.service), json, PForm.class.getSimpleName(),"tabField"); super.selectToJson(PTreeForm.getJsonForTreeSelect(ut.getMemberId(),obj.getClassName(),this.service), json, PForm.class.getSimpleName(),"treeId"); //设置树形结构关联id super.selectToJson(Field.getJsonForSelectWithFK(obj.getClassName(), 1L, null,this.service), json, PForm.class.getSimpleName(),"treeIdRField"); //super.selectToJson(PRole.getJsonForMember(ut.getMemberId(),obj.getSys()), json, PForm.class.getSimpleName(),"roleId"); if(true) { SelectBidding msb=CacheTools.getSysCodeSelectBidding("103",json.getLan()); PDiyUri dpu=new PDiyUri(); dpu.setClassName(obj.getClassName()); dpu.setExport(1L); QueryListInfo<PDiyUri> dpuList=this.service.getMgClient().getList(dpu,"uri",this.service); BosConstants.debug("PDiyUri "+obj.getClassName()+" export=1 size="+dpuList.size()); for(PDiyUri x:dpuList.getList()) { msb.put(x.getUri(), x.getDisplay()); } ExportTemplate tempate=new ExportTemplate(); tempate.setClassName(obj.getClassName()); tempate.setStatus(1L); QueryListInfo<ExportTemplate> tList=this.service.getMgClient().getList(tempate,"templateName",this.service); for(ExportTemplate x:tList.getList()) { if(DataChange.isEmpty(x.getFields())) continue; msb.put(BosConstants.EXPORT_TEMPLATE_URI+"/download/"+x.getTemplateId(), x.getTemplateName()); } //加入个性化的导出配置 super.selectToJson(msb, json, PForm.class.getName(), "exportMode"); } PClob clob=this.service.getMgClient().getById(obj.getScriptId(), PClob.class); if(clob!=null) { obj.setScript(clob.getContent()); } clob=this.service.getMgClient().getById(obj.getOnloadScriptId(), PClob.class); if(clob!=null) { obj.setOnloadScript(clob.getContent()); } clob=this.service.getMgClient().getById(obj.getSubmitScriptId(), PClob.class); if(clob!=null) { obj.setSubmitScript(clob.getContent()); } //Constants.debug("id="+obj.getScriptId()+" content="+obj.getScript()); if(obj.getMultiFileNum()==null) { obj.setMultiFileNum(0L); } if(true) { SelectBidding data=new SelectBidding(); PDiyUri dpu=new PDiyUri(); dpu.setClassName(obj.getClassName()); dpu.setExport(0L); QueryListInfo<PDiyUri> dpuList=this.service.getMgClient().getList(dpu,"uri",this.service); BosConstants.debug("PDiyUri "+obj.getClassName()+" export=0 size="+dpuList.size()); for(PDiyUri x:dpuList.getList()) { data.put(x.getUri(), x.getDisplay()+"["+x.getUri()+"]"); } super.selectToJson(data, json, PForm.class, "diyUri"); } super.objToJson(obj, json); SelectBidding sbIn = new SelectBidding(); SelectBidding sbOut = new SelectBidding(); SelectBidding sbQuery = new SelectBidding(); QueryListInfo<PFormField> fList=new QueryListInfo<PFormField>(); QueryListInfo<PFormSlave> tableList =new QueryListInfo<PFormSlave>(); HashMap<String,Field> fkFieldHash=new HashMap<String,Field>(); if(!DataChange.isEmpty(obj.getClassName())) { //super.selectToJson(cn.powerbos.framework.util.Util.getIcoJson(Table.class.getName(), obj.getClassName()), json, PForm.class.getSimpleName(), "icoId"); //HashMap<String,Field> fHash=new HashMap<String,Field>(); HashMap<String,PFormField> fieldHash=new HashMap<String,PFormField>(); PFormField field = new PFormField(); field.setFormId(obj.getFormId()); field.setClassName(obj.getClassName()); QueryListInfo<PFormField> oList = this.service.getMgClient().getList(field, "seq",this.service); for (PFormField x : oList.getList()) { fieldHash.put(x.getProperty(), x); fList.getList().add(x); } Vector<String> notV=MyString.splitBy("queryCodeValue,queryCodeValueProperty,queryDateMax,queryDateMin,queryDateProperty,queryNumMax,queryNumMin,queryNumProperty", ","); Field sf = new Field(); sf.setClassName(obj.getClassName()); sf.setCustomer(0L); //sf.setPropertyType(1L); //sf.setIsKey(0L); QueryListInfo<Field> fxList=this.service.getMgClient().getTableFieldList(sf, "!isKey,!propertyType,property"); for(Field x:fxList.getList()) { sbIn.put(x.getProperty(), x.getDisplay() + "[" + x.getProperty() + " " + CacheTools.getSysCodeDisplay("5", String.valueOf(x.getPropertyType()), json.getLan()) + " ]"); sbOut.put(x.getProperty(), x.getDisplay() + "[" + x.getProperty() + " " + CacheTools.getSysCodeDisplay("5", String.valueOf(x.getPropertyType()), json.getLan()) + " ]"); if(x.judgeDB()) { sbQuery.put(x.getProperty(), x.getDisplay() + "[" + x.getProperty() + " " + CacheTools.getSysCodeDisplay("5", String.valueOf(x.getPropertyType()), json.getLan()) + " ]"); } PFormField o=fieldHash.get(x.getProperty()); if(o==null) { if(notV.contains(x.getProperty())) { continue; } o= new PFormField(); o.setClassName(obj.getClassName()); o.setProperty(x.getProperty()); o.setDefaultValue(x.getDefaultValue()); if(o.getIsRead()==null) { o.setIsRead(0L); } if(o.getIsNotNuLL()==null) { o.setIsNotNuLL(0L); } if(DataChange.isEmpty(o.getDisType())){ o.setDisType("T"); } o.setFormId(obj.getFormId()); o.setDisplay(x._getSimpleDisplay()); o.setValueClass(x.getValueClass()); o.setFkClasss(x.getFkClasss()); o.setDbLen(x.getDbCol()); o.setPropertyType(x.getPropertyType()); fList.getList().add(o); }else { o.setSelected("checked"); if(!DataChange.isEmpty(x.getFkClasss())) { fkFieldHash.put(x.getProperty(), x); } if(o.getIsRead()==null) { o.setIsRead(0L); } if(o.getIsNotNuLL()==null) { o.setIsNotNuLL(0L); } if(DataChange.isEmpty(o.getDisType())){ o.setDisType("T"); } o.setFormId(obj.getFormId()); o.setDisplay(x._getSimpleDisplay()); o.setValueClass(x.getValueClass()); o.setFkClasss(x.getFkClasss()); o.setDbLen(x.getDbCol()); o.setPropertyType(x.getPropertyType()); fieldHash.remove(x.getProperty()); continue; } //if(!DataChange.isEmpty(x.getFkClasss()) && x.getFkClasss().equals(obj.getClassName()) ) continue; //if(BosConstants._fieldV.contains(x.getProperty())) continue; //fHash.put(x.getProperty(), x); } Iterator<String> its=fieldHash.keySet().iterator(); while(its.hasNext()) { PFormField ff=fieldHash.get(its.next()); fList.getList().remove(ff); } //Vector<PFormSlave> delV1 = new Vector<PFormSlave>(); Vector<String> tV = Table.getSlaverV(obj.getClassName()); BosConstants.debug("*******"+obj.getClassName()+" slaver-size1="+tV.size()); // 查询所有的从表信息 PFormSlave slave = new PFormSlave(); slave.setFormId(obj.getFormId()); Vector<String> ev= this.service.getMgClient().getVector(slave, "className", service); for(String x:ev) { if(!tV.contains(x)) { PFormSlave wf = new PFormSlave(); wf.setFormId(obj.getFormId()); wf.setClassName(x); this.service.getMgClient().deleteByPK(wf.getPk(), PFormSlave.class,ut,this.service); //删除 } } for(String x:tV) { PFormSlave wf = new PFormSlave(); wf.setFormId(obj.getFormId()); wf.setClassName(x); if (ev.contains(x)) { wf.setSelected(); } tableList.getList().add(wf); } /**tableList = this.service.getMgClient().getList(slave, "className",this.service); for (PFormSlave t : tableList.getList()) { if (!tV.contains(t.getClassName())) { delV1.add(t); this.service.getMgClient().deleteByPK(t.getPk(), PFormSlave.class,ut,this.service); continue; } t.setSelected("checked"); tV.remove(t.getClassName()); } for (PFormSlave x :delV1) { tableList.getList().remove(x); } for (String x : tV) { PFormSlave wf = new PFormSlave(); wf.setFormId(obj.getFormId()); wf.setClassName(x); tableList.getList().add(wf); }*/ } // super.listToJson(fList, json, BosConstants.getTable(PFormField.class)); super.listToJson(tableList, json, BosConstants.getTable(PFormSlave.class.getName())); if(true) { PFormInField dif = new PFormInField(); dif.setId(id); QueryListInfo<PFormInField> dList = this.service.getList(dif, "field"); super.listToJson(dList, json, dif.showTable()); super.selectToJson(sbIn, json, PFormInField.class, "field"); } if(true) { PFormOutField dif = new PFormOutField(); dif.setId(id); QueryListInfo<PFormOutField> dList = this.service.getList(dif, "field"); for(PFormOutField x:dList.getList()) { if(fkFieldHash.containsKey(x.getField())) { Field field=fkFieldHash.get(x.getField()); Table fkT=BosConstants.getTable(field.getFkClasss()); if(fkT!=null) { SelectBidding sb=new SelectBidding(); //加入redis属性 for(Field rf:fkT.listDBFields()) { if(DataChange.getIntValueWithDefault(rf.getSynRedis(), 0)==1) { sb.put(rf.getProperty(), rf.getDisplay()+"["+CacheTools.getSysCodeDisplay("121", rf.getValueClass(), json.getLan()) +"]"); } } if(sb.size()>0) { super.selectToJson2(sb, json, x, "fkRedisFields"); fkFieldHash.remove(x.getField()); } } x.setFkClasss(field.getFkClasss()); } } /**Iterator<String> its=fkFieldHash.keySet().iterator(); while(its.hasNext()) { String f=its.next(); Field field=fkFieldHash.get(f); PFormOutField added=new PFormOutField(); added.setId(id); added.setFkClasss(field.getFkClasss()); added.setField(field.getProperty()); Table fkT=BosConstants.getTable(field.getFkClasss()); if(fkT!=null) { SelectBidding sb=new SelectBidding(); //加入redis属性 for(Field rf:fkT.listDBFields()) { if(DataChange.getIntValueWithDefault(rf.getSynRedis(), 0)==1) { sb.put(rf.getProperty(), rf.getDisplay()+"["+CacheTools.getSysCodeDisplay("121", rf.getValueClass(), json.getLan()) +"]"); } } if(sb.size()>0) { dList.getList().add(added); super.selectToJson2(sb, json, added, "fkRedisFields"); } } }*/ super.listToJson(dList, json, dif.showTable()); super.selectToJson(sbOut, json, PFormOutField.class, "field"); } //js操作 PFormAction js=new PFormAction(); js.setFormId(id); QueryListInfo<PFormAction> jsList=this.service.getMgClient().getList(js, "seq,actionName",this.service); super.listToJson(jsList, json, BosConstants.getTable(PFormAction.class)); super.selectToJson(PRole.getJsonForDev(ut.getMemberId(), obj.getSys(),this.service), json, PFormAction.class, "actionRole"); PFormDiy diy=new PFormDiy(); diy.setFormId(id); QueryListInfo<PFormDiy> diyList=this.service.getMgClient().getList(diy, "action,diyUrl",this.service); super.listToJson(diyList, json, BosConstants.getTable(PFormDiy.class)); SelectBidding actions=new SelectBidding(); actions.put("info", "详情"); actions.put("delete", "删除"); actions.put("saveList", "列表保存"); actions.put("showAdd", "显示新增"); actions.put("save", "单个保存"); for(PFormAction x:jsList.getList()) { actions.put(x.getAction(), x.getActionName()); } super.selectToJson(actions, json, PFormDiy.class, "action"); SelectBidding urls=new SelectBidding(); PDiyUri dpu=new PDiyUri(); dpu.setClassName(obj.getClassName()); dpu.setExport(0L); QueryListInfo<PDiyUri> dpuList=this.service.getMgClient().getList(dpu,"uri",this.service); BosConstants.debug("PDiyUri "+obj.getClassName()+" export=0 size="+dpuList.size()); for(PDiyUri x:dpuList.getList()) { urls.put(x.getUri(), x.getDisplay()); } super.selectToJson(urls, json, PFormDiy.class, "diyUrl"); //----------------------------------------------------------------------------------------------------------------------- if(true) { PFormQuery bq=new PFormQuery(); bq.setFormId(id); QueryListInfo<PFormQuery> dList=service.getList(bq, "seq"); super.listToJson(dList, json, bq.showTable()); } if(true) { PFormMsgPush bq=new PFormMsgPush(); bq.setId(id); QueryListInfo<PFormMsgPush> dList=service.getList(bq, "sort"); super.listToJson(dList, json, bq.showTable()); super.selectToJson(MsgTemplate.getJsonForSelect(obj.getClassName(),this.service), json, PFormMsgPush.class, "templateId"); } if(true) { PFormQueryOperation qo=new PFormQueryOperation(); qo.setId(id); QueryListInfo<PFormQueryOperation> list=this.service.getList(qo, "field"); super.listToJson(list, json, qo.showTable()); super.selectToJson(sbQuery, json, PFormQueryOperation.class, "field"); } json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "复制", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/copy", method = RequestMethod.POST) @ResponseBody public JSONObject copy(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/copy", PForm.class.getName(), null,true,this.getService()); PForm obj=this.service.getMgClient().getById(id, PForm.class); if(obj==null) { json.setUnSuccessForNoRecord(PForm.class,id); return json.jsonValue(); } PForm.copy(id, ut.getMemberId(),this.service); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "主表单列表保存", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/saveList", method = RequestMethod.POST) @ResponseBody public JSONObject saveList(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } List<PForm> list=json.getList(PForm.class, "formId,formName,sys,!className,!diyJs",this.service); for(PForm x:list) { PForm src=this.service.getMgClient().getById(x.getFormId(), PForm.class); if(src!=null) { if(!src.getSys().equals(x.getSys())) { x.setClassName(null); } } x.setFormType(1L); this.service.save(x,ut); BosConstants.debug(x); BosConstants.getExpireHash().remove(PForm.class, x.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), x.getFormId()); } json.setSuccess("保存成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "主表单设置", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/save", method = RequestMethod.POST) @ResponseBody public JSONObject save(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } PForm obj = json.getObj(PForm.class, "formId,className,allowAdd,allowDelete,allowModify",this.service); if(DataChange.isEmpty(obj.getDiyUri())) { obj.setDiyService(0L); }else { obj.setDiyService(1L); } if(!DataChange.isEmpty(obj.getCodeFormula()) && obj.getCodeScope()==null) { json.setUnSuccess(-1, "请选择编码作用域"); return json.jsonValue(); } if(obj.getRowCols()==null) { obj.setRowCols(4L); } PForm src=this.service.getMgClient().getById(obj.getFormId(), PForm.class); if (src == null) { json.setUnSuccessForNoRecord(PForm.class,obj.getFormId()); return json.jsonValue(); } Vector<String> dpV=MyString.splitBy(obj.getDataPerType(), ","); //0:所属用户 1:所属部门 2:所属组织 3:综合所属权 4:数据权限 5:地区 10:无 if(dpV.contains("5") ) { Table table=BosConstants.getTable(obj.getClassName()); if(DataChange.getLongValueWithDefault(table.getIsMap(), 0)==0) { json.setUnSuccess(-1, table.getDisplayName()+"不支持地图操作,无法按照所属地区查询"); return json.jsonValue(); } } Table table = BosConstants.getTable(obj.getClassName()); if (table == null) { json.setUnSuccessForNoRecord(Table.class,obj.getClassName()); return json.jsonValue(); } if(DataChange.isEmpty(obj.getScript())) { this.service.getMgClient().deleteByPK(obj.getFormId(), PClob.class,ut,this.service); obj.setScriptId(null); }else { PClob clob=new PClob(); clob.setClobId(obj.getFormId()); clob.setContent(obj.getScript()); clob.addToMust("content"); this.service.save(clob,ut); BosConstants.debug(clob); obj.setScriptId(obj.getFormId()); } obj.addToMust("scriptId"); if(DataChange.isEmpty(obj.getOnloadScript())) { this.service.getMgClient().deleteByPK(obj.getFormId()+"1", PClob.class,ut,this.service); obj.setOnloadScriptId(null); }else { PClob clob=new PClob(); clob.setClobId(obj.getFormId()+"1"); clob.setContent(obj.getOnloadScript()); clob.addToMust("content"); this.service.save(clob,ut); BosConstants.debug(clob); obj.setOnloadScriptId(obj.getFormId()+"1"); } obj.addToMust("onloadScriptId"); if(DataChange.isEmpty(obj.getSubmitScript())) { this.service.getMgClient().deleteByPK(obj.getFormId()+"2", PClob.class,ut,this.service); obj.setSubmitScriptId(null); }else { PClob clob=new PClob(); clob.setClobId(obj.getFormId()+"2"); clob.setContent(obj.getSubmitScript()); clob.addToMust("content"); this.service.save(clob,ut); BosConstants.debug(clob); obj.setSubmitScriptId(obj.getFormId()+"2"); } obj.addToMust("submitScriptId"); //Constants.debug("id="+form.getFormId()+" content="+form.getScript()); this.service.save(obj,ut); BosConstants.debug(obj); PFormField del=new PFormField(); del.setFormId(obj.getFormId()); del.setClassName(src.getClassName()); Vector<String> fieldV=this.service.getMgClient().getVector(del, "property",this.service); Vector<String> ids = json.showIds("ids"); List<PFormField> list = json.getList(PFormField.class,"property,!disType,!isNotNuLL,!attribute,!condition,!singleLine,!defaultValue",this.service); long seq = 0; for (PFormField x : list) { x.setFormId(obj.getFormId()); x.setClassName(src.getClassName()); if(x.getRowspan()==null) { x.setRowspan(1L); } if(x.getColspan()==null) { x.setColspan(1L); } if (ids.contains(x.getPk())) { fieldV.remove(x.getProperty()); x.setSeq(seq++); if (DataChange.isEmpty(x.getDisType())) { json.setUnSuccess(-1, LabelDisplay.get("属性:", json.getLan()) + x.getProperty() + LabelDisplay.get("未设置显示方式", json.getLan()),true ); return json.jsonValue(); } this.service.save(x,ut); BosConstants.debug(x); } else { this.service.getMgClient().deleteByPK(x.getPk(), PFormField.class,ut,this.service); } } for(String x:fieldV) { del=new PFormField(); del.setFormId(obj.getFormId()); del.setClassName(src.getClassName()); del.setProperty(x); this.service.getMgClient().delete(del,ut,this.service); } if(!DataChange.isEmpty(obj.getSearchFields())) { Vector<String> fv=Field.split(obj.getSearchFields()); for(String f:fv) { if(DataChange.isEmpty(f)) continue; if(f.indexOf("|")!=-1) f=f.substring(0, f.indexOf("|")); Field field=new Field(); field.setClassName(obj.getClassName()); field.setProperty(f); field=this.service.getMgClient().get(field,this.service); if(field==null) { json.setUnSuccess(-1, LabelDisplay.get("自定义查询条件:", json.getLan()) +obj.getSearchFields()+LabelDisplay.get(" 检查,不存在属性:", json.getLan()) +f,true); return json.jsonValue(); }else if(DataChange.getLongValueWithDefault(field.getPropertyType(), 0)==1) { PFormField pff=new PFormField(); pff.setFormId(obj.getFormId()); pff.setProperty(f); pff=this.service.getMgClient().get(pff,this.service); if(pff==null) { json.setUnSuccess(-1, LabelDisplay.get("自定义查询条件:", json.getLan()) +obj.getSearchFields()+LabelDisplay.get(" 检查,模板中没有属性:", json.getLan()) +f,true); return json.jsonValue(); } } } } if(!DataChange.isEmpty(obj.getListFields())) { Vector<String> fv=Field.split(obj.getListFields()); for(String f:fv) { Field field=new Field(); field.setClassName(obj.getClassName()); field.setProperty(f); field=this.service.getMgClient().get(field,this.service); if(field==null) { json.setUnSuccess(-1, LabelDisplay.get("自定义列表字段:", json.getLan()) +obj.getListFields()+LabelDisplay.get(" 检查,不存在属性:", json.getLan()) +f,true); return json.jsonValue(); }else if(DataChange.getLongValueWithDefault(field.getPropertyType(), 0)==1) { PFormField pff=new PFormField(); pff.setFormId(obj.getFormId()); pff.setProperty(f); pff=this.service.getMgClient().get(pff,this.service); if(pff==null) { json.setUnSuccess(-1, LabelDisplay.get("自定义列表字段:", json.getLan()) +obj.getListFields()+LabelDisplay.get(" 检查,模板中没有属性:", json.getLan()) +f,true); return json.jsonValue(); } } } } if(!DataChange.isEmpty(obj.getListEditFields())) { Vector<String> fv=Field.split(obj.getListEditFields()); for(String f:fv) { Field field=new Field(); field.setClassName(obj.getClassName()); field.setProperty(f); field=this.service.getMgClient().get(field,this.service); if(field==null) { json.setUnSuccess(-1, LabelDisplay.get("列表可编辑字段:", json.getLan()) +obj.getListFields()+LabelDisplay.get(" 检查,不存在属性:", json.getLan()) +f,true); return json.jsonValue(); }else if(DataChange.getLongValueWithDefault(field.getPropertyType(), 0)==1) { PFormField pff=new PFormField(); pff.setFormId(obj.getFormId()); pff.setProperty(f); pff=this.service.getMgClient().get(pff,this.service); if(pff==null) { json.setUnSuccess(-1,LabelDisplay.get("列表可编辑字段:", json.getLan()) +obj.getListFields()+LabelDisplay.get(" 检查,模板中没有属性:", json.getLan()) +f,true); return json.jsonValue(); } } } } if(true) { Vector<String> ids1 = json.showIds("ids1"); PFormSlave slave = new PFormSlave(); slave.setFormId(obj.getFormId()); QueryListInfo<PFormSlave> slaveList=this.service.getMgClient().getList(slave,this.service); for(PFormSlave x:slaveList.getList()) { if(!ids1.contains(x.getPk())) { this.service.getMgClient().deleteByPK(x.getPk(), PFormSlave.class,ut,this.service); } } for(String x:ids1) { PFormSlave fs=new PFormSlave(); fs.setPK(x); if(!DataChange.isEmpty(fs.getPk())) { this.service.save(fs, ut); } } } if(true) { PFormAction old=new PFormAction(); old.setFormId(obj.getFormId()); this.service.getMgClient().delete(old,ut,this.service); seq=0; List<PFormAction> alist = json.getList(PFormAction.class,"action,actionType,actionName,!actionRole,!condition,!attribute",this.service); for(PFormAction x:alist) { x.setClassName(src.getClassName()); x.setFormId(obj.getFormId()); this.service.save(x,null); } } if(true) { PFormInField ds=new PFormInField(); ds.setId(obj.getFormId()); this.service.getMgClient().delete(ds,ut,this.service); seq=0; List<PFormInField> dlist = json.getList(PFormInField.class,"field,formula",this.service); for(PFormInField x:dlist) { x.setId(obj.getFormId()); this.service.save(x,null); } } if(true) { PFormQuery ds=new PFormQuery(); ds.setFormId(obj.getFormId()); this.service.getMgClient().delete(ds,ut,this.service); seq=0; List<PFormQuery> dlist = json.getList(PFormQuery.class,"fields,value,type",this.service); for(PFormQuery x:dlist) { Vector<String> v=Field.split(x.getFields()); for(String f:v) { if(table.getDBField(f)==null) { json.setUnSuccess(-1, LabelDisplay.get("查询特殊条件:", json.getLan()) +x.getFields()+LabelDisplay.get(" 检查,不存在属性:", json.getLan()) +f,true); return json.jsonValue(); } } x.setFormId(obj.getFormId()); x.setSeq(seq++); this.service.save(x,null); } } if(true) { PFormQueryOperation ds=new PFormQueryOperation(); ds.setId(obj.getFormId()); this.service.getMgClient().delete(ds,ut,this.service); seq=0; List<PFormQueryOperation> dlist = json.getList(PFormQueryOperation.class,"field,queryOperation",this.service); for(PFormQueryOperation x:dlist) { x.setId(obj.getFormId()); this.service.save(x,null); } } if(true) { PFormMsgPush ds=new PFormMsgPush(); ds.setId(obj.getFormId()); this.service.getMgClient().delete(ds,ut,this.service); seq=0; List<PFormMsgPush> dlist = json.getList(PFormMsgPush.class,"templateId,msgType,actionType",this.service); for(PFormMsgPush x:dlist) { x.setId(obj.getFormId()); x.setSort(seq++); this.service.save(x,null); } } if(true) { PFormOutField ds=new PFormOutField(); ds.setId(obj.getFormId()); this.service.getMgClient().delete(ds,ut,this.service); seq=0; List<PFormOutField> dlist = json.getList(PFormOutField.class,"field,!formula",this.service); for(PFormOutField x:dlist) { x.setId(obj.getFormId()); this.service.save(x,null); } } List<PFormDiy> dist=json.getList(PFormDiy.class, "action,diyUrl", service); for(PFormDiy x:dist) { x.setFormId(obj.getFormId()); this.service.save(x,null); } BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); json.setSuccess("保存成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "从表单信息", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/slaveInfo", method = RequestMethod.POST) @ResponseBody public JSONObject slaveInfo(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } PFormSlave form = json.getObj(PFormSlave.class, "formId,className",this.service); PForm formObj=this.service.getMgClient().getById(form.getFormId(),PForm.class); if(formObj==null) { json.setUnSuccessForNoRecord(PForm.class,form.getFormId()); return json.jsonValue(); } if(DataChange.isEmpty(formObj.getClassName())) { json.setUnSuccess(-1, "流程节点业务类对象未设置"); return json.jsonValue(); } Table table = this.service.getMgClient().getTableById(form.getClassName()); if (table == null) { json.setUnSuccessForNoRecord(Table.class,form.getClassName()); return json.jsonValue(); } if(table.getRegType()==null) { table.setRegType(1L); } super.objToJson(table, json); PFormSlave obj = this.service.getMgClient().getById(form.getPk(), PFormSlave.class); if (obj == null) { obj = new PFormSlave(); } obj.setFormId(form.getFormId()); obj.setClassName(form.getClassName()); if(!DataChange.replaceNull(obj.getAllowAdd()).equals("0")) { obj.setAllowAdd("1"); } if(!DataChange.replaceNull(obj.getAllowDelete()).equals("0")) { obj.setAllowDelete("1"); } if(!DataChange.replaceNull(obj.getAllowVisible()).equals("0")) { obj.setAllowVisible("1"); } super.objToJson(obj, json); super.selectToJson(CacheTools.getSysCodeSelectBidding("3",json.getLan()), json, PFormSlave.class.getSimpleName(), "allowAdd"); super.selectToJson(CacheTools.getSysCodeSelectBidding("3",json.getLan()), json, PFormSlave.class.getSimpleName(), "allowDelete"); super.selectToJson(CacheTools.getSysCodeSelectBidding("3",json.getLan()), json, PFormSlave.class.getSimpleName(), "allowVisible"); //HashMap<String,Field> fHash=new HashMap<String,Field>(); QueryListInfo<PFormField> fList=new QueryListInfo<PFormField>(); HashMap<String,PFormField> fieldHash=new HashMap<String,PFormField>(); PFormField field = new PFormField(); field.setFormId(form.getFormId()); field.setClassName(form.getClassName()); QueryListInfo<PFormField> oList = this.service.getMgClient().getList(field, "seq",this.service); for (PFormField x : oList.getList()) { fieldHash.put(x.getProperty(), x); fList.getList().add(x); } Vector<String> notV=MyString.splitBy("queryCodeValue,queryCodeValueProperty,queryDateMax,queryDateMin,queryDateProperty,queryNumMax,queryNumMin,queryNumProperty", ","); Field sf = new Field(); sf.setClassName(form.getClassName()); sf.setCustomer(0L); //sf.setPropertyType(1L); //sf.setIsKey(0L); if(table.getRegType().intValue()==1) { sf.setRegType(1L); } QueryListInfo<Field> fxList=this.service.getMgClient().getTableFieldList(sf, "property"); for(Field x:fxList.getList()) { if(!DataChange.isEmpty(x.getFkClasss()) && x.getFkClasss().equals(formObj.getClassName()) ) continue; if(BosConstants._fieldV.contains(x.getProperty())) continue; PFormField o=fieldHash.get(x.getProperty()); if(o==null) { if(notV.contains(x.getProperty())) { continue; } o = new PFormField(); o.setFormId(form.getFormId()); o.setClassName(form.getClassName()); o.setProperty(x.getProperty()); o.setDefaultValue(x.getDefaultValue()); if(o.getIsRead()==null) { o.setIsRead(0L); } if(o.getIsNotNuLL()==null) { o.setIsNotNuLL(0L); } if(DataChange.isEmpty(o.getDisType())){ o.setDisType("T"); } o.setFormId(form.getFormId()); o.setDisplay(x._getSimpleDisplay()); o.setValueClass(x.getValueClass()); o.setFkClasss(x.getFkClasss()); o.setDbLen(x.getDbCol()); o.setPropertyType(x.getPropertyType()); fList.getList().add(o); }else { o.setSelected("checked"); if(o.getIsRead()==null) { o.setIsRead(0L); } if(DataChange.isEmpty(o.getDisType())){ o.setDisType("T"); } if(DataChange.isEmpty(o.getIsNotNuLL())){ o.setIsNotNuLL(0L); } o.setFormId(form.getFormId()); o.setDisplay(x._getSimpleDisplay()); o.setValueClass(x.getValueClass()); o.setFkClasss(x.getFkClasss()); o.setDbLen(x.getDbCol()); o.setPropertyType(x.getPropertyType()); } //fHash.put(x.getProperty(), x); } Iterator<String> its=fieldHash.keySet().iterator(); while(its.hasNext()) { PFormField ff=fieldHash.get(its.next()); fList.getList().remove(ff); } super.listToJson(fList, json,BosConstants.getTable(PFormField.class)); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "从表单设置", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/slaveSave", method = RequestMethod.POST) @ResponseBody public JSONObject slaveSave(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } PFormSlave form = json.getObj(PFormSlave.class, "formId,className,orderBy",this.service); Table table=BosConstants.getTable(form.getClassName()); if(table==null) { json.setUnSuccessForNoRecord(Table.class,form.getClassName()); return json.jsonValue(); } if(!DataChange.isEmpty(form.getOrderBy())) { Vector<String> v=Field.split(form.getOrderBy()); for(String x:v) { Field fx=table.getField(x); if(fx==null) { json.setUnSuccess(-1, LabelDisplay.get("排序字段:", json.getLan()) +x+LabelDisplay.get("不存在", json.getLan()),true); return json.jsonValue(); } } } if(DataChange.isEmpty(table.getCodeField())) { form.setCodeFormula(null); form.setCodeScope(null); form.addToMust("codeFormula"); form.addToMust("codeScope"); } Vector<String> ids = json.showIds(); Vector<String> v=Field.split(form.getOrderBy()); for(String s:v) { Field field=table.getField(s); if(field==null) { json.setUnSuccess(-1, LabelDisplay.get("排序字段:", json.getLan()) +s+LabelDisplay.get("不存在", json.getLan()) ,true); return json.jsonValue(); } } PFormField del=new PFormField(); del.setFormId(form.getFormId()); del.setClassName(form.getClassName()); Vector<String> fieldV=this.service.getMgClient().getVector(del, "property",this.service); List<PFormField> list = json.getList(PFormField.class, "property,!disType,!isNotNuLL,!attribute,!condition,!singleLine,!defaultValue",this.service); long seq = 0; for (PFormField x : list) { x.setFormId(form.getFormId()); x.setClassName(form.getClassName()); if (ids.contains(x.getPk())) { fieldV.remove(x.getProperty()); x.setSeq(seq++); if (DataChange.isEmpty(x.getDisType())) { json.setUnSuccess(-1, LabelDisplay.get("属性:" , json.getLan()) + x.getProperty() + LabelDisplay.get("未设置显示方式", json.getLan()) ,true); return json.jsonValue(); } this.service.save(x,ut); BosConstants.debug(x); } } for(String x:fieldV) { del=new PFormField(); del.setFormId(form.getFormId()); del.setClassName(form.getClassName()); del.setProperty(x); this.service.getMgClient().delete(del,ut,this.service); } this.service.save(form,ut); BosConstants.debug(form); BosConstants.getExpireHash().remove(PForm.class, form.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), form.getFormId()); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "删除", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public JSONObject delete(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/delete", PForm.class.getName(), null,true,this.getService()); PForm.delete(id, ut.getMemberId(),this.service); json.setSuccess("删除成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "删除行为操作", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/deleteAction", method = RequestMethod.POST) @ResponseBody public JSONObject deleteAction(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/deleteAction", PFormAction.class.getName(), null,true,this.getService()); PFormAction obj=this.service.getMgClient().getById(id, PFormAction.class); if(obj==null) { json.setUnSuccessForNoRecord(PFormAction.class,id); return json.jsonValue(); } PForm form=this.service.getMgClient().getById(obj.getFormId(), PForm.class); if(form==null) { json.setUnSuccessForNoRecord(PForm.class,obj.getFormId()); return json.jsonValue(); } this.service.getMgClient().deleteByPK(id, PFormAction.class,ut,this.service); BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); json.setSuccess("删除成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "删除自定义操作", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/deleteDiy", method = RequestMethod.POST) @ResponseBody public JSONObject deleteDiy(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/deleteDiy", PFormAction.class.getName(), null,true,this.getService()); PFormDiy obj=this.service.getMgClient().getById(id, PFormDiy.class); if(obj==null) { json.setUnSuccessForNoRecord(PFormAction.class,id); return json.jsonValue(); } PForm form=this.service.getMgClient().getById(obj.getFormId(), PForm.class); if(form==null) { json.setUnSuccessForNoRecord(PForm.class,obj.getFormId()); return json.jsonValue(); } this.service.getMgClient().deleteByPK(id, PFormDiy.class,ut,this.service); BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); json.setSuccess("删除成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "启用", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/enable", method = RequestMethod.POST) @ResponseBody public JSONObject enable(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/enable", PForm.class.getName(), null,true,this.getService()); PForm obj=this.service.getMgClient().getById(id,PForm.class); if(obj==null) { json.setUnSuccessForNoRecord(PForm.class,id); return json.jsonValue(); } BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); obj.setStatus(1L); this.service.save(obj,ut); json.setSuccess("启用成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "清理基础数据菜单", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/clearMenu", method = RequestMethod.POST) @ResponseBody public JSONObject clearMenu(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } // //BOSDYNCHART //Vector<String> v=this.service.getRdClient().getKeys("*"+RdClient.splitChar+"BOSDYMENU"); //for(String x:v) { //this.service.getRdClient().remove(x); //} BosConstants.getExpireHash().removeMatch(RdClient.splitChar+"BOSDYMENU"); new ClassInnerNotice().invoke(ExpiringMap.class.getSimpleName(), RdClient.splitChar+"BOSDYMENU"); json.setSuccess("清理成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "字段的权限显示", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/fieldRoleShow", method = RequestMethod.POST) @ResponseBody public JSONObject fieldRoleShow(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/fieldRoleShow", PFormField.class.getName(), null,true,this.getService()); PFormField obj=this.service.getMgClient().getById(id, PFormField.class); if(obj==null) { json.setUnSuccessForNoRecord(PFormField.class,id); return json.jsonValue(); } PForm form=this.service.getMgClient().getById(obj.getFormId(), PForm.class); if(form==null) { json.setUnSuccessForNoRecord(PForm.class,obj.getFormId()); return json.jsonValue(); } PRoot root=this.service.getMgClient().getById(form.getSys(), PRoot.class); if(root==null) { json.setUnSuccessForNoRecord(PRoot.class,form.getSys()); return json.jsonValue(); } super.objToJson(obj, json); Table table=this.service.getMgClient().getTableById(form.getClassName()); if(table==null) { json.setUnSuccessForNoRecord(Table.class,form.getClassName()); return json.jsonValue(); } if(true) { QueryListInfo<PRole> list=new QueryListInfo<PRole>(); Vector<String> v=MyString.splitBy(obj.getEditRoles(), ","); for(String x:MyString.splitBy(table.getMaintainRole(), ",")) { PRole role=this.service.getMgClient().getById(x, PRole.class); if(role==null) continue; if(v.contains(role.getRoleId())) { role.setSelected(); } list.getList().add(role); } super.listToJson(list, json, BosConstants.getTable(PRole.class)); } if(true) { Vector<String> v=MyString.splitBy(obj.getVisibleRoles(), ","); QueryListInfo<PRole> list=new QueryListInfo<PRole>(); for(String x:MyString.splitBy(table.getViewRoles(), ",")) { PRole role=this.service.getMgClient().getById(x, PRole.class); if(role==null) continue; if(v.contains(role.getRoleId())) { role.setSelected(); } list.getList().add(role); } super.listToJson(list, json, "PRole1", BosConstants.getTable(PRole.class)); } json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "字段的可编辑权限保存", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/fieldRoleSave", method = RequestMethod.POST) @ResponseBody public JSONObject fieldRoleSave(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/fieldRoleShow", PFormField.class.getName(), null,true,this.getService()); PFormField obj=this.service.getMgClient().getById(id, PFormField.class); if(obj==null) { json.setUnSuccessForNoRecord(PFormField.class,id); return json.jsonValue(); } String ids=json.getSimpleData("ids", "可编辑权限", String.class, false,this.getService()); String ids1=json.getSimpleData("ids1", "可视权限", String.class, false,this.getService()); //39|1,30|1,31|1 obj.setEditRoles(ids); obj.addToMust("editRoles"); obj.setVisibleRoles(ids1); obj.addToMust("visibleRoles"); obj.setInnerEdit(null); obj.addToMust("innerEdit"); obj.setInnerVisible(null); obj.addToMust("innerVisible"); this.service.save(obj,ut); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "从表权限设置显示", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/slaveRoleShow", method = RequestMethod.POST) @ResponseBody public JSONObject slaveRoleShow(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/slaveRoleShow", PFormField.class.getName(), null,true,this.getService()); PFormSlave obj=this.service.getMgClient().getById(id, PFormSlave.class); if(obj==null) { json.setUnSuccessForNoRecord(PFormSlave.class,id); return json.jsonValue(); } PForm form=this.service.getMgClient().getById(obj.getFormId(), PForm.class); if(form==null) { json.setUnSuccessForNoRecord(PForm.class,obj.getFormId()); return json.jsonValue(); } PRoot root=this.service.getMgClient().getById(form.getSys(), PRoot.class); if(root==null) { json.setUnSuccessForNoRecord(PRoot.class,form.getSys()); return json.jsonValue(); } Table table=this.service.getMgClient().getTableById(form.getClassName()); if(table==null) { json.setUnSuccessForNoRecord(Table.class,form.getClassName()); return json.jsonValue(); } super.objToJson(obj, json); if(true) { QueryListInfo<PRole> list=new QueryListInfo<PRole>(); Vector<String> v=MyString.splitBy(obj.getAllowAdd(), ","); for(String x:MyString.splitBy(table.getMaintainRole(), ",")) { PRole role=this.service.getMgClient().getById(x, PRole.class); if(role==null) continue; if(v.contains(role.getRoleId())) { role.setSelected(); } list.getList().add(role); } super.listToJson(list, json, BosConstants.getTable(PRole.class)); } if(true) { Vector<String> v=MyString.splitBy(obj.getAllowDelete(), ","); QueryListInfo<PRole> list=new QueryListInfo<PRole>(); for(String x:MyString.splitBy(table.getDeleteRole(), ",")) { PRole role=this.service.getMgClient().getById(x, PRole.class); if(role==null) continue; if(v.contains(role.getRoleId())) { role.setSelected(); } list.getList().add(role); } super.listToJson(list, json, "PRole1", BosConstants.getTable(PRole.class)); } if(true) { Vector<String> v=MyString.splitBy(obj.getAllowVisible(), ","); QueryListInfo<PRole> list=new QueryListInfo<PRole>(); for(String x:MyString.splitBy(table.getViewRoles(), ",")) { PRole role=this.service.getMgClient().getById(x, PRole.class); if(role==null) continue; if(v.contains(role.getRoleId())) { role.setSelected(); } list.getList().add(role); } super.listToJson(list, json, "PRole2", BosConstants.getTable(PRole.class)); } json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "从表权限设置保存", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/slaveRoleSave", method = RequestMethod.POST) @ResponseBody public JSONObject slaveRoleSave(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/slaveRoleShow", PFormField.class.getName(), null,true,this.getService()); PFormSlave obj=this.service.getMgClient().getById(id, PFormSlave.class); if(obj==null) { json.setUnSuccessForNoRecord(PFormField.class,id); return json.jsonValue(); } String ids=json.getSimpleData("ids", "新增权限", String.class, false,this.getService()); String ids1=json.getSimpleData("ids1", "删除权限", String.class, false,this.getService()); String ids2=json.getSimpleData("ids2", "可视权限", String.class, false,this.getService()); obj.setAllowAdd(ids); obj.addToMust("allowAdd"); obj.setAllowDelete(ids1); obj.addToMust("allowDelete"); obj.setAllowVisible(ids2); obj.addToMust("allowVisible"); obj.setInnerAdd(null); obj.addToMust("innerAdd"); obj.setInnerVisible(null); obj.addToMust("innerVisible"); obj.setInnerDelete(null); obj.addToMust("innerDelete"); this.service.save(obj,ut); BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); json.setSuccess("保存成功"); } catch (Exception e) { json.setUnSuccess(e); } return json.jsonValue(); } @Security(accessType = "1", displayName = "禁用", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/disable", method = RequestMethod.POST) @ResponseBody public JSONObject disable(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id = json.getSelectedId(Constants.current_sys, "/dtform/disable", PForm.class.getName(), null,true,this.getService()); PForm obj=this.service.getMgClient().getById(id,PForm.class); if(obj==null) { json.setUnSuccessForNoRecord(PForm.class,id); return json.jsonValue(); } obj.setStatus(0L); this.service.save(obj,ut); BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); json.setSuccess("禁用成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "行记录操作列表", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/rowActionList", method = RequestMethod.POST) @ResponseBody public JSONObject rowActionList(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id=json.getSelectedId(Constants.current_sys, "/dtform/rowActionList", PForm.class.getName(), "", true,this.getService()); PForm obj = this.service.getMgClient().getById(id, PForm.class); if (obj == null) { json.setUnSuccessForNoRecord(PForm.class,id); return json.jsonValue(); } PFormRowAction initAction=new PFormRowAction(); initAction.setFormId(id); QueryListInfo<PFormRowAction> aList=this.service.getMgClient().getList(initAction, "sort",this.service); super.listToJson(aList, json, BosConstants.getTable(PFormRowAction.class.getName())); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "行记录操作列表保存", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "rowActionListSave", method = RequestMethod.POST) @ResponseBody public JSONObject rowActionListSave(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id=json.getSelectedId(Constants.current_sys, "/dtform/rowActionList", PForm.class.getName(), "", true,this.getService()); PForm obj = this.service.getMgClient().getById(id, PForm.class); if (obj == null) { json.setUnSuccessForNoRecord(PForm.class,id); return json.jsonValue(); } List<PFormRowAction> list=json.getList(PFormRowAction.class, "actionName,condition,masterFields",this.service); for(PFormRowAction x:list) { x.setClassName(obj.getClassName()); this.service.save(x,ut); } BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); json.setSuccess("保存成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "行记录操作删除", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/rowActionDelete", method = RequestMethod.POST) @ResponseBody public JSONObject rowActionDelete(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id=json.getSelectedId(Constants.current_sys, "/dtform/rowActionDelete", PFormRowAction.class.getName(), "", true,this.getService()); PFormRowAction obj=this.service.getMgClient().getById(id, PFormRowAction.class); if(obj==null) { json.setUnSuccessForNoRecord(PFormRowAction.class,id); return json.jsonValue(); } this.service.getMgClient().deleteByPK(id, PFormRowAction.class,ut,this.service); BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); json.setSuccess("删除成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "行记录操作显示新增", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/rowActionShowAdd", method = RequestMethod.POST) @ResponseBody public JSONObject rowActionShowAdd(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String formId=json.getSelectedId(Constants.current_sys, "/dtform/rowActionList", PForm.class.getName(), "", true,this.getService()); PForm form = this.service.getMgClient().getById(formId, PForm.class); if (form == null) { json.setUnSuccessForNoRecord(PForm.class,formId); return json.jsonValue(); } if(DataChange.isEmpty(form.getClassName())) { json.setUnSuccess(-1, "请设置模板的类对象"); return json.jsonValue(); } PFormRowAction obj=new PFormRowAction(); obj.setActionId(PFormRowAction.next()); obj.setFormId(formId); super.objToJson(obj, json); if(true) { SelectBidding data=new SelectBidding(); PDiyUri dpu=new PDiyUri(); dpu.setClassName(form.getClassName()); dpu.setExport(0L); QueryListInfo<PDiyUri> dpuList=this.service.getMgClient().getList(dpu,"uri",this.service); BosConstants.debug("PDiyUri "+obj.getClassName()+" export=1 size="+dpuList.size()); for(PDiyUri x:dpuList.getList()) { data.put(x.getUri(), x.getUri()+"["+x.getDisplay()+"]"); } super.selectToJson(data, json, PFormRowAction.class, "diyUri"); } //查询字段列表 Field sf = new Field(); sf.setClassName(form.getClassName()); sf.setRegType(1L); sf.setIsKey(0L); QueryListInfo<Field> fxList=this.service.getMgClient().getTableFieldList(sf, "property"); super.listToJson(fxList, json, BosConstants.getTable(Field.class.getName())); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "行记录操作详情", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/rowActionInfo", method = RequestMethod.POST) @ResponseBody public JSONObject rowActionInfo(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String id=json.getSelectedId(Constants.current_sys, "/dtform/rowActionInfo", PFormRowAction.class.getName(), "", true,this.getService()); PFormRowAction obj=this.service.getMgClient().getById(id, PFormRowAction.class); if(obj==null) { json.setUnSuccessForNoRecord(PFormRowAction.class,id); return json.jsonValue(); } if(obj.getDiyService()==null) { obj.setDiyService(0L); } PForm form = this.service.getMgClient().getById(obj.getFormId(), PForm.class); if (form == null) { json.setUnSuccessForNoRecord(PForm.class,obj.getFormId()); return json.jsonValue(); } if(DataChange.isEmpty(form.getClassName())) { json.setUnSuccess(-1, "请设置模板的类对象"); return json.jsonValue(); } super.objToJson(obj, json); if(true) { SelectBidding data=new SelectBidding(); PDiyUri dpu=new PDiyUri(); dpu.setClassName(form.getClassName()); dpu.setExport(0L); QueryListInfo<PDiyUri> dpuList=this.service.getMgClient().getList(dpu,"uri",this.service); BosConstants.debug("PDiyUri "+obj.getClassName()+" export=1 size="+dpuList.size()); for(PDiyUri x:dpuList.getList()) { data.put(x.getUri(), x.getUri()+"["+x.getDisplay()+"]"); } super.selectToJson(data, json, PFormRowAction.class, "diyUri"); } Field sf = new Field(); sf.setClassName(form.getClassName()); sf.setRegType(1L); sf.setIsKey(0L); QueryListInfo<Field> fxList=this.service.getMgClient().getTableFieldList(sf, "property"); super.listToJson(fxList, json, BosConstants.getTable(Field.class.getName())); json.setSuccess(); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } @Security(accessType = "1", displayName = "行记录操作单个保存", needLogin = true, isEntAdmin = false, isSysAdmin = false,roleId=BosConstants.role_tech) @RequestMapping(value = "/rowActionSave", method = RequestMethod.POST) @ResponseBody public JSONObject rowActionSave(@RequestBody HttpEntity json,HttpServletRequest request) throws Exception{ try { UserToken ut = super.securityCheck(json,request); if (ut == null) { return json.jsonValue(); } String formId=json.getSelectedId(Constants.current_sys, "/dtform/rowActionList", PForm.class.getName(), "", true,this.getService()); PForm form = this.service.getMgClient().getById(formId, PForm.class); if (form == null) { json.setUnSuccessForNoRecord(PForm.class,formId); return json.jsonValue(); } PFormRowAction obj=json.getObj(PFormRowAction.class, "actionName,condition,masterFields,!initScript,!submitScript,!remark,!diyUri",this.service); if(DataChange.isEmpty(obj.getDiyUri())) { obj.setDiyService(0L); }else { obj.setDiyService(1L); } obj.setClassName(obj.getClassName()); obj.setFormId(formId); this.service.save(obj,ut); BosConstants.getExpireHash().remove(PForm.class, obj.getFormId()); new ClassInnerNotice().invoke(PForm.class.getSimpleName(), obj.getFormId()); json.setSuccess("保存成功"); } catch (Exception e) { json.setUnSuccess(e); return json.jsonValue(); } return json.jsonValue(); } public ServiceInf getService() throws Exception { // TODO Auto-generated method stub return this.service; } }
28.529724
188
0.669768
cdf7762dcf8faeadac7406075fc9239a358a0e3c
3,265
package de.hpi.des.hdes.engine.operation; import de.hpi.des.hdes.engine.AData; import de.hpi.des.hdes.engine.ADataWatermark; import de.hpi.des.hdes.engine.udf.Aggregator; import de.hpi.des.hdes.engine.udf.TimestampExtractor; import de.hpi.des.hdes.engine.window.WatermarkGenerator; import de.hpi.des.hdes.engine.window.Window; import de.hpi.des.hdes.engine.window.assigner.WindowAssigner; import java.util.HashMap; import java.util.LinkedList; import java.util.List; /** * Operator that aggregates a Stream * * @param <IN> the type of the input elements * @param <STATE> the type of the state elements * @param <OUT> the type of the output elements */ public class StreamAggregation<IN, STATE, OUT> extends AbstractTopologyElement<OUT> implements OneInputOperator<IN, OUT> { private final Aggregator<IN, STATE, OUT> aggregator; private final WindowAssigner<? extends Window> windowAssigner; private final WatermarkGenerator<OUT> watermarkGenerator; private final TimestampExtractor<OUT> timestampExtractor; private final HashMap<Window, STATE> windowToState; private long latestTimestamp = 0; public StreamAggregation(final Aggregator<IN, STATE, OUT> aggregator, final WindowAssigner<? extends Window> windowAssigner, final WatermarkGenerator<OUT> watermarkGenerator, final TimestampExtractor<OUT> timestampExtractor) { this.aggregator = aggregator; this.windowAssigner = windowAssigner; this.windowToState = new HashMap<>(); this.watermarkGenerator = watermarkGenerator; this.timestampExtractor = timestampExtractor; aggregator.initialize(); } @Override public void process(final AData<IN> in) { final List<? extends Window> activeWindows = this.windowAssigner .assignWindows(in.getEventTime()); final IN input = in.getValue(); // Add the input to the windows it belongs to for (final Window window : activeWindows) { final STATE state = this.windowToState .computeIfAbsent(window, w -> this.aggregator.initialize()); this.windowToState.put(window, this.aggregator.add(state, input)); } this.processWatermark(in); } private void processWatermark(final AData<IN> in) { if (in.isWatermark()) { final long newTimestamp = ((ADataWatermark) (in)).getWatermarkTimestamp(); if (newTimestamp <= this.latestTimestamp) { return; } else { this.latestTimestamp = newTimestamp; } } else { return; } final List<Window> removableWindows = new LinkedList<>(); for (final Window window : this.windowToState.keySet()) { if (window.getMaxTimestamp() < this.latestTimestamp) { final STATE state = this.windowToState.get(window); this.emitEvent(this.aggregator.getResult(state)); removableWindows.add(window); } } for (final Window window : removableWindows) { this.windowToState.remove(window); } } private void emitEvent(final OUT event) { final long timestamp = this.timestampExtractor.apply(event); final AData<OUT> wrappedEvent = new AData<>(event, timestamp, false); final AData<OUT> watermarkedEvent = this.watermarkGenerator.apply(wrappedEvent); this.collector.collect(watermarkedEvent); } }
36.685393
94
0.721286
4eb6bb6bde2a88be35f21eec14412cb8a8debdf3
1,723
/** * Nov 22, 2004 * * Copyright 2004 uitags * * 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 net.sf.uitags.tagutil.i18n; import javax.servlet.jsp.PageContext; import net.sf.uitags.util.UiString; /** * A message finder with no I18N support. It does not perform message * look up; it simply returns whatever string is given to it. * * @author jonni * @version $Id$ */ public final class I18nIgnorantMessageFinder implements MessageFinder { private static final long serialVersionUID = 100L; /** * Default constructor. */ public I18nIgnorantMessageFinder() { super(); } /** {@inheritDoc} */ public void setPageContext(PageContext pageContext) { // Do nothing } /** {@inheritDoc} */ public String get(String key) { return key; } /** {@inheritDoc} */ public String get(String key, Object arg0) { return UiString.simpleConstruct(key, new String[] { String.valueOf(arg0) }); } /** {@inheritDoc} */ public String get(String key, Object[] args) { String[] params = new String[args.length]; for (int i = 0; i < args.length; i++) { params[i] = String.valueOf(args[i]); } return UiString.simpleConstruct(key, params); } }
26.507692
80
0.686013
4c789197ed0660611b62df3fde838bfe9b43ade3
16,123
// mc-dev import package net.minecraft.world.level.chunk.storage; import com.google.common.annotations.VisibleForTesting; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import javax.annotation.Nullable; import net.minecraft.SystemUtils; import net.minecraft.world.level.ChunkCoordIntPair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class RegionFile implements AutoCloseable { private static final Logger LOGGER = LogManager.getLogger(); private static final int SECTOR_BYTES = 4096; @VisibleForTesting protected static final int SECTOR_INTS = 1024; private static final int CHUNK_HEADER_SIZE = 5; private static final int HEADER_OFFSET = 0; private static final ByteBuffer PADDING_BUFFER = ByteBuffer.allocateDirect(1); private static final String EXTERNAL_FILE_EXTENSION = ".mcc"; private static final int EXTERNAL_STREAM_FLAG = 128; private static final int EXTERNAL_CHUNK_THRESHOLD = 256; private static final int CHUNK_NOT_PRESENT = 0; private final FileChannel file; private final Path externalFileDir; final RegionFileCompression version; private final ByteBuffer header; private final IntBuffer offsets; private final IntBuffer timestamps; @VisibleForTesting protected final RegionFileBitSet usedSectors; public RegionFile(Path path, Path path1, boolean flag) throws IOException { this(path, path1, RegionFileCompression.VERSION_DEFLATE, flag); } public RegionFile(Path path, Path path1, RegionFileCompression regionfilecompression, boolean flag) throws IOException { this.header = ByteBuffer.allocateDirect(8192); this.usedSectors = new RegionFileBitSet(); this.version = regionfilecompression; if (!Files.isDirectory(path1, new LinkOption[0])) { throw new IllegalArgumentException("Expected directory, got " + path1.toAbsolutePath()); } else { this.externalFileDir = path1; this.offsets = this.header.asIntBuffer(); ((java.nio.Buffer) this.offsets).limit(1024); // CraftBukkit - decompile error ((java.nio.Buffer) this.header).position(4096); // CraftBukkit - decompile error this.timestamps = this.header.asIntBuffer(); if (flag) { this.file = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.DSYNC); } else { this.file = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE); } this.usedSectors.force(0, 2); ((java.nio.Buffer) this.header).position(0); // CraftBukkit - decompile error int i = this.file.read(this.header, 0L); if (i != -1) { if (i != 8192) { RegionFile.LOGGER.warn("Region file {} has truncated header: {}", path, i); } long j = Files.size(path); for (int k = 0; k < 1024; ++k) { int l = this.offsets.get(k); if (l != 0) { int i1 = getSectorNumber(l); int j1 = getNumSectors(l); if (i1 < 2) { RegionFile.LOGGER.warn("Region file {} has invalid sector at index: {}; sector {} overlaps with header", path, k, i1); this.offsets.put(k, 0); } else if (j1 == 0) { RegionFile.LOGGER.warn("Region file {} has an invalid sector at index: {}; size has to be > 0", path, k); this.offsets.put(k, 0); } else if ((long) i1 * 4096L > j) { RegionFile.LOGGER.warn("Region file {} has an invalid sector at index: {}; sector {} is out of bounds", path, k, i1); this.offsets.put(k, 0); } else { this.usedSectors.force(i1, j1); } } } } } } private Path getExternalChunkPath(ChunkCoordIntPair chunkcoordintpair) { String s = "c." + chunkcoordintpair.x + "." + chunkcoordintpair.z + ".mcc"; return this.externalFileDir.resolve(s); } @Nullable public synchronized DataInputStream getChunkDataInputStream(ChunkCoordIntPair chunkcoordintpair) throws IOException { int i = this.getOffset(chunkcoordintpair); if (i == 0) { return null; } else { int j = getSectorNumber(i); int k = getNumSectors(i); int l = k * 4096; ByteBuffer bytebuffer = ByteBuffer.allocate(l); this.file.read(bytebuffer, (long) (j * 4096)); ((java.nio.Buffer) bytebuffer).flip(); // CraftBukkit - decompile error if (bytebuffer.remaining() < 5) { RegionFile.LOGGER.error("Chunk {} header is truncated: expected {} but read {}", chunkcoordintpair, l, bytebuffer.remaining()); return null; } else { int i1 = bytebuffer.getInt(); byte b0 = bytebuffer.get(); if (i1 == 0) { RegionFile.LOGGER.warn("Chunk {} is allocated, but stream is missing", chunkcoordintpair); return null; } else { int j1 = i1 - 1; if (isExternalStreamChunk(b0)) { if (j1 != 0) { RegionFile.LOGGER.warn("Chunk has both internal and external streams"); } return this.createExternalChunkInputStream(chunkcoordintpair, getExternalChunkVersion(b0)); } else if (j1 > bytebuffer.remaining()) { RegionFile.LOGGER.error("Chunk {} stream is truncated: expected {} but read {}", chunkcoordintpair, j1, bytebuffer.remaining()); return null; } else if (j1 < 0) { RegionFile.LOGGER.error("Declared size {} of chunk {} is negative", i1, chunkcoordintpair); return null; } else { return this.createChunkInputStream(chunkcoordintpair, b0, createStream(bytebuffer, j1)); } } } } } private static int getTimestamp() { return (int) (SystemUtils.getEpochMillis() / 1000L); } private static boolean isExternalStreamChunk(byte b0) { return (b0 & 128) != 0; } private static byte getExternalChunkVersion(byte b0) { return (byte) (b0 & -129); } @Nullable private DataInputStream createChunkInputStream(ChunkCoordIntPair chunkcoordintpair, byte b0, InputStream inputstream) throws IOException { RegionFileCompression regionfilecompression = RegionFileCompression.fromId(b0); if (regionfilecompression == null) { RegionFile.LOGGER.error("Chunk {} has invalid chunk stream version {}", chunkcoordintpair, b0); return null; } else { return new DataInputStream(regionfilecompression.wrap(inputstream)); } } @Nullable private DataInputStream createExternalChunkInputStream(ChunkCoordIntPair chunkcoordintpair, byte b0) throws IOException { Path path = this.getExternalChunkPath(chunkcoordintpair); if (!Files.isRegularFile(path, new LinkOption[0])) { RegionFile.LOGGER.error("External chunk path {} is not file", path); return null; } else { return this.createChunkInputStream(chunkcoordintpair, b0, Files.newInputStream(path)); } } private static ByteArrayInputStream createStream(ByteBuffer bytebuffer, int i) { return new ByteArrayInputStream(bytebuffer.array(), bytebuffer.position(), i); } private int packSectorOffset(int i, int j) { return i << 8 | j; } private static int getNumSectors(int i) { return i & 255; } private static int getSectorNumber(int i) { return i >> 8 & 16777215; } private static int sizeToSectors(int i) { return (i + 4096 - 1) / 4096; } public boolean doesChunkExist(ChunkCoordIntPair chunkcoordintpair) { int i = this.getOffset(chunkcoordintpair); if (i == 0) { return false; } else { int j = getSectorNumber(i); int k = getNumSectors(i); ByteBuffer bytebuffer = ByteBuffer.allocate(5); try { this.file.read(bytebuffer, (long) (j * 4096)); ((java.nio.Buffer) bytebuffer).flip(); // CraftBukkit - decompile error if (bytebuffer.remaining() != 5) { return false; } else { int l = bytebuffer.getInt(); byte b0 = bytebuffer.get(); if (isExternalStreamChunk(b0)) { if (!RegionFileCompression.isValidVersion(getExternalChunkVersion(b0))) { return false; } if (!Files.isRegularFile(this.getExternalChunkPath(chunkcoordintpair), new LinkOption[0])) { return false; } } else { if (!RegionFileCompression.isValidVersion(b0)) { return false; } if (l == 0) { return false; } int i1 = l - 1; if (i1 < 0 || i1 > 4096 * k) { return false; } } return true; } } catch (IOException ioexception) { return false; } } } public DataOutputStream getChunkDataOutputStream(ChunkCoordIntPair chunkcoordintpair) throws IOException { return new DataOutputStream(this.version.wrap((OutputStream) (new RegionFile.ChunkBuffer(chunkcoordintpair)))); } public void flush() throws IOException { this.file.force(true); } public void clear(ChunkCoordIntPair chunkcoordintpair) throws IOException { int i = getOffsetIndex(chunkcoordintpair); int j = this.offsets.get(i); if (j != 0) { this.offsets.put(i, 0); this.timestamps.put(i, getTimestamp()); this.writeHeader(); Files.deleteIfExists(this.getExternalChunkPath(chunkcoordintpair)); this.usedSectors.free(getSectorNumber(j), getNumSectors(j)); } } protected synchronized void write(ChunkCoordIntPair chunkcoordintpair, ByteBuffer bytebuffer) throws IOException { int i = getOffsetIndex(chunkcoordintpair); int j = this.offsets.get(i); int k = getSectorNumber(j); int l = getNumSectors(j); int i1 = bytebuffer.remaining(); int j1 = sizeToSectors(i1); int k1; RegionFile.b regionfile_b; if (j1 >= 256) { Path path = this.getExternalChunkPath(chunkcoordintpair); RegionFile.LOGGER.warn("Saving oversized chunk {} ({} bytes} to external file {}", chunkcoordintpair, i1, path); j1 = 1; k1 = this.usedSectors.allocate(j1); regionfile_b = this.writeToExternalFile(path, bytebuffer); ByteBuffer bytebuffer1 = this.createExternalStub(); this.file.write(bytebuffer1, (long) (k1 * 4096)); } else { k1 = this.usedSectors.allocate(j1); regionfile_b = () -> { Files.deleteIfExists(this.getExternalChunkPath(chunkcoordintpair)); }; this.file.write(bytebuffer, (long) (k1 * 4096)); } this.offsets.put(i, this.packSectorOffset(k1, j1)); this.timestamps.put(i, getTimestamp()); this.writeHeader(); regionfile_b.run(); if (k != 0) { this.usedSectors.free(k, l); } } private ByteBuffer createExternalStub() { ByteBuffer bytebuffer = ByteBuffer.allocate(5); bytebuffer.putInt(1); bytebuffer.put((byte) (this.version.getId() | 128)); ((java.nio.Buffer) bytebuffer).flip(); // CraftBukkit - decompile error return bytebuffer; } private RegionFile.b writeToExternalFile(Path path, ByteBuffer bytebuffer) throws IOException { Path path1 = Files.createTempFile(this.externalFileDir, "tmp", (String) null); FileChannel filechannel = FileChannel.open(path1, StandardOpenOption.CREATE, StandardOpenOption.WRITE); try { ((java.nio.Buffer) bytebuffer).position(5); // CraftBukkit - decompile error filechannel.write(bytebuffer); } catch (Throwable throwable) { if (filechannel != null) { try { filechannel.close(); } catch (Throwable throwable1) { throwable.addSuppressed(throwable1); } } throw throwable; } if (filechannel != null) { filechannel.close(); } return () -> { Files.move(path1, path, StandardCopyOption.REPLACE_EXISTING); }; } private void writeHeader() throws IOException { ((java.nio.Buffer) this.header).position(0); // CraftBukkit - decompile error this.file.write(this.header, 0L); } private int getOffset(ChunkCoordIntPair chunkcoordintpair) { return this.offsets.get(getOffsetIndex(chunkcoordintpair)); } public boolean hasChunk(ChunkCoordIntPair chunkcoordintpair) { return this.getOffset(chunkcoordintpair) != 0; } private static int getOffsetIndex(ChunkCoordIntPair chunkcoordintpair) { return chunkcoordintpair.getRegionLocalX() + chunkcoordintpair.getRegionLocalZ() * 32; } public void close() throws IOException { try { this.padToFullSector(); } finally { try { this.file.force(true); } finally { this.file.close(); } } } private void padToFullSector() throws IOException { int i = (int) this.file.size(); int j = sizeToSectors(i) * 4096; if (i != j) { ByteBuffer bytebuffer = RegionFile.PADDING_BUFFER.duplicate(); ((java.nio.Buffer) bytebuffer).position(0); // CraftBukkit - decompile error this.file.write(bytebuffer, (long) (j - 1)); } } private class ChunkBuffer extends ByteArrayOutputStream { private final ChunkCoordIntPair pos; public ChunkBuffer(ChunkCoordIntPair chunkcoordintpair) { super(8096); super.write(0); super.write(0); super.write(0); super.write(0); super.write(RegionFile.this.version.getId()); this.pos = chunkcoordintpair; } public void close() throws IOException { ByteBuffer bytebuffer = ByteBuffer.wrap(this.buf, 0, this.count); bytebuffer.putInt(0, this.count - 5 + 1); RegionFile.this.write(this.pos, bytebuffer); } } private interface b { void run() throws IOException; } }
37.235566
155
0.578676