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
335f40ba11e52553d3ba0a3c8df9790ef41951ca
1,650
/** * Copyright (c) 2011-2014, hubin ([email protected]). * * 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.baomidou.framework.exception; /** * <p> * web 层异常 * </p> * * @author hubin * @Date 2016-03-15 */ public class WebException extends RuntimeException { private static final long serialVersionUID = 8604424364318396626L; /** * 异常代码 */ private String code; /** * 异常说明 */ private String desc; public WebException() { super(); } public WebException( String message ) { super(message); this.desc = message; } public WebException( String code, String desc ) { this.code = code; this.desc = desc; } public WebException( String code, String desc, Throwable cause ) { super(cause); this.code = code; this.desc = desc; } public WebException( String code, String desc, String message ) { super(message); this.code = code; this.desc = desc; } public String getCode() { return code; } public String getDesc() { return desc; } @Override public String getMessage() { if ( super.getMessage() == null ) { return desc; } return super.getMessage(); } }
17.934783
80
0.677576
3fe01db33eba1856de3ab3d72792fa39476e4d05
2,090
package mage.cards.h; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.AsThoughEffectImpl; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.AsThoughEffectType; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; import mage.game.Game; /** * * @author fireshoes */ public final class HeartwoodDryad extends CardImpl { public HeartwoodDryad(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{G}"); this.subtype.add(SubType.DRYAD); this.power = new MageInt(2); this.toughness = new MageInt(1); // Heartwood Dryad can block creatures with shadow as though Heartwood Dryad had shadow. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new CanBlockAsThoughtIthadShadowEffect(Duration.WhileOnBattlefield))); } public HeartwoodDryad(final HeartwoodDryad card) { super(card); } @Override public HeartwoodDryad copy() { return new HeartwoodDryad(this); } } class CanBlockAsThoughtIthadShadowEffect extends AsThoughEffectImpl { public CanBlockAsThoughtIthadShadowEffect(Duration duration) { super(AsThoughEffectType.BLOCK_SHADOW, duration, Outcome.Benefit); staticText = "{this} can block creatures with shadow as though {this} had shadow"; } public CanBlockAsThoughtIthadShadowEffect(final CanBlockAsThoughtIthadShadowEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { return true; } @Override public CanBlockAsThoughtIthadShadowEffect copy() { return new CanBlockAsThoughtIthadShadowEffect(this); } @Override public boolean applies(UUID sourceId, Ability source, UUID affectedControllerId, Game game) { return sourceId.equals(source.getSourceId()); } }
29.43662
136
0.734928
0d5670760a60618cda5663485572cc4020048b08
602
package com.adaptris.jmx.remote.provider.activemq; import java.io.IOException; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorProvider; import javax.management.remote.JMXServiceURL; import com.adaptris.jmx.remote.jms.JmsJmxConnectorClient; public class ClientProvider implements JMXConnectorProvider { @Override public JMXConnector newJMXConnector(JMXServiceURL url, Map<String, ?> environment) throws IOException { return new JmsJmxConnectorClient(url, environment, new ActiveMqJmsConnectionFactory(environment, url)); } }
31.684211
107
0.825581
50a37b60cbcfcd183771f17b4bc3671b01beca21
3,878
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.v4.app; import android.os.Parcel; import android.os.Parcelable; // Referenced classes of package android.support.v4.app: // bb class FragmentTabHost$SavedState extends android.view.View.BaseSavedState { public String toString() { StringBuilder stringbuilder = new StringBuilder(); // 0 0:new #35 <Class StringBuilder> // 1 3:dup // 2 4:invokespecial #36 <Method void StringBuilder()> // 3 7:astore_1 stringbuilder.append("FragmentTabHost.SavedState{"); // 4 8:aload_1 // 5 9:ldc1 #38 <String "FragmentTabHost.SavedState{"> // 6 11:invokevirtual #42 <Method StringBuilder StringBuilder.append(String)> // 7 14:pop stringbuilder.append(Integer.toHexString(System.identityHashCode(((Object) (this))))); // 8 15:aload_1 // 9 16:aload_0 // 10 17:invokestatic #48 <Method int System.identityHashCode(Object)> // 11 20:invokestatic #54 <Method String Integer.toHexString(int)> // 12 23:invokevirtual #42 <Method StringBuilder StringBuilder.append(String)> // 13 26:pop stringbuilder.append(" curTab="); // 14 27:aload_1 // 15 28:ldc1 #56 <String " curTab="> // 16 30:invokevirtual #42 <Method StringBuilder StringBuilder.append(String)> // 17 33:pop stringbuilder.append(a); // 18 34:aload_1 // 19 35:aload_0 // 20 36:getfield #29 <Field String a> // 21 39:invokevirtual #42 <Method StringBuilder StringBuilder.append(String)> // 22 42:pop stringbuilder.append("}"); // 23 43:aload_1 // 24 44:ldc1 #58 <String "}"> // 25 46:invokevirtual #42 <Method StringBuilder StringBuilder.append(String)> // 26 49:pop return stringbuilder.toString(); // 27 50:aload_1 // 28 51:invokevirtual #60 <Method String StringBuilder.toString()> // 29 54:areturn } public void writeToParcel(Parcel parcel, int i) { super.writeToParcel(parcel, i); // 0 0:aload_0 // 1 1:aload_1 // 2 2:iload_2 // 3 3:invokespecial #64 <Method void android.view.View$BaseSavedState.writeToParcel(Parcel, int)> parcel.writeString(a); // 4 6:aload_1 // 5 7:aload_0 // 6 8:getfield #29 <Field String a> // 7 11:invokevirtual #68 <Method void Parcel.writeString(String)> // 8 14:return } public static final android.os.Parcelable.Creator CREATOR = new bb(); String a; static { // 0 0:new #12 <Class bb> // 1 3:dup // 2 4:invokespecial #15 <Method void bb()> // 3 7:putstatic #17 <Field android.os.Parcelable$Creator CREATOR> //* 4 10:return } FragmentTabHost$SavedState(Parcel parcel) { super(parcel); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #21 <Method void android.view.View$BaseSavedState(Parcel)> a = parcel.readString(); // 3 5:aload_0 // 4 6:aload_1 // 5 7:invokevirtual #27 <Method String Parcel.readString()> // 6 10:putfield #29 <Field String a> // 7 13:return } FragmentTabHost$SavedState(Parcelable parcelable) { super(parcelable); // 0 0:aload_0 // 1 1:aload_1 // 2 2:invokespecial #32 <Method void android.view.View$BaseSavedState(Parcelable)> // 3 5:return } }
36.242991
108
0.571429
bb7257b55d4172906b894e4a7d85336539aa8fc4
7,020
package mekanism.client.gui; import java.io.IOException; import mekanism.api.Coord4D; import mekanism.client.gui.element.GuiEnergyInfo; import mekanism.client.gui.element.GuiFluidGauge; import mekanism.client.gui.element.GuiGasGauge; import mekanism.client.gui.element.GuiGauge; import mekanism.client.gui.element.GuiPowerBar; import mekanism.client.gui.element.GuiProgress; import mekanism.client.gui.element.GuiProgress.IProgressInfoHandler; import mekanism.client.gui.element.GuiProgress.ProgressBar; import mekanism.client.gui.element.GuiRedstoneControl; import mekanism.client.gui.element.GuiSecurityTab; import mekanism.client.gui.element.GuiSlot; import mekanism.client.gui.element.GuiSlot.SlotOverlay; import mekanism.client.gui.element.GuiSlot.SlotType; import mekanism.client.gui.element.GuiUpgradeTab; import mekanism.client.sound.SoundHandler; import mekanism.common.Mekanism; import mekanism.common.base.TileNetworkList; import mekanism.common.inventory.container.ContainerElectrolyticSeparator; import mekanism.common.network.PacketTileEntity.TileEntityMessage; import mekanism.common.tile.TileEntityElectrolyticSeparator; import mekanism.common.tile.TileEntityGasTank; import mekanism.common.util.LangUtils; import mekanism.common.util.ListUtils; import mekanism.common.util.MekanismUtils; import mekanism.common.util.MekanismUtils.ResourceType; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.SoundEvents; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.opengl.GL11; @SideOnly(Side.CLIENT) public class GuiElectrolyticSeparator extends GuiMekanism { public TileEntityElectrolyticSeparator tileEntity; public GuiElectrolyticSeparator(InventoryPlayer inventory, TileEntityElectrolyticSeparator tentity) { super(tentity, new ContainerElectrolyticSeparator(inventory, tentity)); tileEntity = tentity; guiElements.add(new GuiRedstoneControl(this, tileEntity, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"))); guiElements.add(new GuiUpgradeTab(this, tileEntity, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"))); guiElements.add(new GuiEnergyInfo(() -> { String usage = MekanismUtils.getEnergyDisplay(tileEntity.clientEnergyUsed); return ListUtils.asList(LangUtils.localize("gui.using") + ": " + usage + "/t", LangUtils.localize("gui.needed") + ": " + MekanismUtils.getEnergyDisplay(tileEntity.getMaxEnergy()-tileEntity.getEnergy())); }, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"))); guiElements.add(new GuiFluidGauge(() -> tileEntity.fluidTank, GuiGauge.Type.STANDARD, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 5, 10)); guiElements.add(new GuiGasGauge(() -> tileEntity.leftTank, GuiGauge.Type.SMALL, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 58, 18)); guiElements.add(new GuiGasGauge(() -> tileEntity.rightTank, GuiGauge.Type.SMALL, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 100, 18)); guiElements.add(new GuiPowerBar(this, tileEntity, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 164, 15)); guiElements.add(new GuiSecurityTab(this, tileEntity, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"))); guiElements.add(new GuiSlot(SlotType.NORMAL, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 25, 34)); guiElements.add(new GuiSlot(SlotType.NORMAL, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 58, 51)); guiElements.add(new GuiSlot(SlotType.NORMAL, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 100, 51)); guiElements.add(new GuiSlot(SlotType.NORMAL, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 142, 34).with(SlotOverlay.POWER)); guiElements.add(new GuiProgress(new IProgressInfoHandler() { @Override public double getProgress() { return tileEntity.isActive ? 1 : 0; } }, ProgressBar.BI, this, MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png"), 78, 29)); } @Override protected void mouseClicked(int x, int y, int button) throws IOException { super.mouseClicked(x, y, button); int xAxis = (x - (width - xSize) / 2); int yAxis = (y - (height - ySize) / 2); if(xAxis > 8 && xAxis < 17 && yAxis > 73 && yAxis < 82) { TileNetworkList data = TileNetworkList.withContents((byte)0); Mekanism.packetHandler.sendToServer(new TileEntityMessage(Coord4D.get(tileEntity), data)); SoundHandler.playSound(SoundEvents.UI_BUTTON_CLICK); } else if(xAxis > 160 && xAxis < 169 && yAxis > 73 && yAxis < 82) { TileNetworkList data = TileNetworkList.withContents((byte)1); Mekanism.packetHandler.sendToServer(new TileEntityMessage(Coord4D.get(tileEntity), data)); SoundHandler.playSound(SoundEvents.UI_BUTTON_CLICK); } } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { fontRenderer.drawString(tileEntity.getName(), 45, 6, 0x404040); String name = chooseByMode(tileEntity.dumpLeft, LangUtils.localize("gui.idle"), LangUtils.localize("gui.dumping"), LangUtils.localize("gui.dumping_excess")); renderScaledText(name, 21, 73, 0x404040, 66); name = chooseByMode(tileEntity.dumpRight, LangUtils.localize("gui.idle"), LangUtils.localize("gui.dumping"), LangUtils.localize("gui.dumping_excess")); renderScaledText(name, 156-(int)(fontRenderer.getStringWidth(name)*getNeededScale(name, 66)), 73, 0x404040, 66); super.drawGuiContainerForegroundLayer(mouseX, mouseY); } @Override protected void drawGuiContainerBackgroundLayer(float partialTick, int mouseX, int mouseY) { mc.renderEngine.bindTexture(MekanismUtils.getResource(ResourceType.GUI, "GuiElectrolyticSeparator.png")); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); int guiWidth = (width - xSize) / 2; int guiHeight = (height - ySize) / 2; drawTexturedModalRect(guiWidth, guiHeight, 0, 0, xSize, ySize); int displayInt = chooseByMode(tileEntity.dumpLeft, 52, 60, 68); drawTexturedModalRect(guiWidth + 8, guiHeight + 73, 176, displayInt, 8, 8); displayInt = chooseByMode(tileEntity.dumpRight, 52, 60, 68); drawTexturedModalRect(guiWidth + 160, guiHeight + 73, 176, displayInt, 8, 8); super.drawGuiContainerBackgroundLayer(partialTick, mouseX, mouseY); } private <T> T chooseByMode(TileEntityGasTank.GasMode dumping, T idleOption, T dumpingOption, T dumpingExcessOption) { if(dumping.equals(TileEntityGasTank.GasMode.IDLE)) { return idleOption; } else if(dumping.equals(TileEntityGasTank.GasMode.DUMPING)) { return dumpingOption; } else if(dumping.equals(TileEntityGasTank.GasMode.DUMPING_EXCESS)) { return dumpingExcessOption; } return idleOption; //should not happen; } }
46.490066
215
0.781197
1d3a664ab63eb36697c0c9ecf792bddb7723d75d
2,018
/* * 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.engine.processing.bpmn.behavior; import io.zeebe.engine.processing.bpmn.BpmnElementContext; import io.zeebe.engine.processing.common.ErrorEventHandler; import io.zeebe.engine.processing.streamprocessor.writers.TypedStreamWriter; import io.zeebe.engine.state.ZeebeState; import io.zeebe.engine.state.instance.ElementInstance; import io.zeebe.engine.state.instance.ElementInstanceState; import org.agrona.DirectBuffer; public final class BpmnEventPublicationBehavior { private final ErrorEventHandler errorEventHandler; private final TypedStreamWriter streamWriter; private final ElementInstanceState elementInstanceState; public BpmnEventPublicationBehavior( final ZeebeState zeebeState, final TypedStreamWriter streamWriter) { final var workflowState = zeebeState.getWorkflowState(); final var keyGenerator = zeebeState.getKeyGenerator(); elementInstanceState = workflowState.getElementInstanceState(); errorEventHandler = new ErrorEventHandler(workflowState, keyGenerator); this.streamWriter = streamWriter; } /** * Throws an error event that must be caught somewhere in the scope hierarchy. * * @return {@code true} if the error event is thrown and caught by an catch event * @see ErrorEventHandler#throwErrorEvent(DirectBuffer, ElementInstance, TypedStreamWriter) */ public boolean throwErrorEvent(final DirectBuffer errorCode, final BpmnElementContext context) { final var flowScopeInstance = elementInstanceState.getInstance(context.getFlowScopeKey()); return errorEventHandler.throwErrorEvent(errorCode, flowScopeInstance, streamWriter); } }
45.863636
98
0.806244
72f78b893544564726e81c2e12564d6bf4940f32
5,474
package fr.bletrazer.mailbox.sql; import java.io.ByteArrayInputStream; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.bukkit.craftbukkit.libs.org.apache.commons.io.output.ByteArrayOutputStream; import org.bukkit.inventory.ItemStack; import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import fr.bletrazer.mailbox.DataManager.Data; import fr.bletrazer.mailbox.DataManager.ItemData; import fr.bletrazer.mailbox.DataManager.factories.DataFactory; public class ItemDataSQL extends BaseSQL<ItemData> { private static final String TABLE_NAME = "MailBox_ItemData"; private static ItemDataSQL INSTANCE = new ItemDataSQL(); public static ItemDataSQL getInstance() { return INSTANCE; } private ItemDataSQL() { super(); if (this.getSqlConnection().isConnected()) { try { PreparedStatement query = this.getSqlConnection().getConnection() .prepareStatement("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (id BIGINT, uuid VARCHAR(255), durationInSeconds BIGINT, itemStack TEXT, PRIMARY KEY(id))"); query.executeUpdate(); query.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * Tente de transformer un ItemStack en String */ private String toBase64(ItemStack itemstack) { String res = null; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); dataOutput.writeObject(itemstack); dataOutput.close(); res = Base64Coder.encodeLines(outputStream.toByteArray()); } catch (Exception e) { e.printStackTrace(); } return res; } /** * Tente de transformer un String en ItemStack */ private ItemStack fromBase64(String str) { ItemStack res = null; try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(str)); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); res = (ItemStack) dataInput.readObject(); dataInput.close(); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } return res; } /* * table name format ?: - [id: int] [uuid: String] [duration: Long] [itemStack: * String(?)] * */ @Override protected ItemData onCreate(ItemData obj) { ItemData res = null; ItemData temp = obj.clone(); Data data = DataSQL.getInstance().onCreate(temp); if (data != null) { temp.setId(data.getId()); temp.setCreationDate(data.getCreationDate()); try { PreparedStatement query = this.getSqlConnection().getConnection().prepareStatement("INSERT INTO " + TABLE_NAME + " (id, uuid, durationInSeconds, itemStack) VALUES(?, ?, ?, ?)"); query.setLong(1, temp.getId()); query.setString(2, temp.getOwnerUuid().toString()); query.setLong(3, temp.getDuration().getSeconds()); query.setString(4, toBase64(temp.getItem())); query.execute(); query.close(); res = temp; } catch (SQLException e) { e.printStackTrace(); } } return res; } @Override protected List<ItemData> onFind(UUID uuid) { List<ItemData> res = null; List<ItemData> temp = new ArrayList<>(); List<Data> dataList = DataSQL.getInstance().onFind(uuid); if (dataList != null) { try { PreparedStatement query = this.getSqlConnection().getConnection().prepareStatement("SELECT * FROM " + TABLE_NAME + " WHERE uuid = ?"); query.setString(1, uuid.toString()); ResultSet resultset = query.executeQuery(); while (resultset.next()) { ItemStack itemstack = fromBase64(resultset.getString("itemStack")); Duration duration = Duration.ofSeconds(resultset.getLong("durationInSeconds")); Long id = resultset.getLong("id"); Data tData = dataList.stream().filter(e -> e.getId() == id).findAny().orElse(new DataFactory()); temp.add(new ItemData(tData, itemstack, duration)); } query.close(); res = temp; } catch (SQLException e) { e.printStackTrace(); } } return res; } @Override protected ItemData onUpdate(Long id, ItemData obj) { ItemData res = null; ItemData temp = obj.clone(); Data uData = DataSQL.getInstance().onUpdate(id, obj); if (uData != null) { try { PreparedStatement query = this.getSqlConnection().getConnection().prepareStatement("UPDATE " + TABLE_NAME + " SET uuid = ?, itemStack = ?, durationInSeconds = ? WHERE id = ?"); query.setString(1, obj.getOwnerUuid().toString()); query.setString(2, toBase64(obj.getItem())); query.setLong(3, obj.getDuration().toMillis() / 1000); query.setLong(4, obj.getId()); query.executeUpdate(); query.close(); temp.setId(id); res = temp; } catch (SQLException e) { e.printStackTrace(); } } return res; } @Override protected Boolean onDelete(ItemData obj) { Boolean res = false; if (DataSQL.getInstance().delete(obj)) { try { PreparedStatement query = this.getSqlConnection().getConnection().prepareStatement("DELETE FROM " + TABLE_NAME + " WHERE id = ?"); query.setLong(1, obj.getId()); query.execute(); query.close(); res = true; } catch (SQLException e) { e.printStackTrace(); } } return res; } }
26.965517
181
0.694191
b8f3db6e11c1e5aa6c29e2055ad00939217427d7
106
class TypeParameters<T> { <T> T m() { } } class TypeParameters<T, S> { <S> S m() { } }
8.833333
28
0.443396
5d80e71a4088eb8d46aad2f60b8213e298f86b59
2,985
/** * This class is part of the Programming the Internet of Things * project, and is available via the MIT License, which can be * found in the LICENSE file at the top level of this repository. * * Copyright (c) 2020 by Andrew D. King */ package programmingtheiot.gda.connection; import programmingtheiot.common.IDataMessageListener; import programmingtheiot.common.ResourceNameEnum; /** * Interface contract for pub/sub clients. * */ public interface IPubSubClient { /*** * Connects to the pub/sub broker / server using configuration parameters * specified by the sub-class. * * @return bool True on success, False otherwise. */ public boolean connectClient(); /** * Disconnects from the pub/sub broker / server if the client is already connected. * If not, this call is ignored, but will return a False. * * @return bool True on success, False otherwise. */ public boolean disconnectClient(); /** * Attempts to publish a message to the given topic with the given qos * to the pub/sub broker / server. If not already connected, the sub-class * implementation should either throw an exception, or handle the exception * and log a message, and return False. * * @param topicEnum The topic Enum containing the topic value to publish the message to. * @param msg The message to publish. This is expected to be well-formed JSON. * @param qos The QoS level. This is expected to be 0 - 2. * @return bool True on success, False otherwise. */ public boolean publishMessage(ResourceNameEnum topicName, String msg, int qos); /** * Attempts to subscribe to a topic with the given qos hosted by the * pub/sub broker / server. If not already connected, the sub-class * implementation should either throw an exception, or handle the exception * and log a message, and return False. * * @param topicEnum The topic Enum containing the topic value to subscribe to. * @param qos The QoS level. This is expected to be 0 - 2. * @return bool True on success, False otherwise. */ public boolean subscribeToTopic(ResourceNameEnum topicName, int qos); /** * Attempts to unsubscribe from a topic hosted by the pub/sub broker / server. * If not already connected, the sub-class implementation should either * throw an exception, or handle the exception and log a message, and return False. * * @param topicEnum The topic Enum containing the topic value to unsubscribe from. * @return bool True on success, False otherwise. */ public boolean unsubscribeFromTopic(ResourceNameEnum topicName); /** * Sets the data message listener reference, assuming listener is non-null. * * @param listener The data message listener instance to use for passing relevant * messages, such as those received from a subscription event. * @return bool True on success (if listener is non-null will always be the case), False otherwise. */ public boolean setDataMessageListener(IDataMessageListener listener); }
37.3125
100
0.737353
3571cfb084f0222ddaa674347e850269823058f5
5,248
/** * generated by Xtext 2.23.0 */ package org.sodalite.sdl.ansible.ui.wizard; import com.google.common.collect.Iterables; import java.util.Collections; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.JavaCore; import org.eclipse.xtend2.lib.StringConcatenation; import org.eclipse.xtext.ui.XtextProjectHelper; import org.eclipse.xtext.ui.util.PluginProjectFactory; import org.eclipse.xtext.ui.wizard.template.AbstractProjectTemplate; import org.eclipse.xtext.ui.wizard.template.BooleanTemplateVariable; import org.eclipse.xtext.ui.wizard.template.GroupTemplateVariable; import org.eclipse.xtext.ui.wizard.template.IProjectGenerator; import org.eclipse.xtext.ui.wizard.template.ProjectTemplate; import org.eclipse.xtext.ui.wizard.template.StringTemplateVariable; import org.eclipse.xtext.xbase.lib.CollectionLiterals; import org.eclipse.xtext.xbase.lib.ObjectExtensions; import org.eclipse.xtext.xbase.lib.Procedures.Procedure1; @ProjectTemplate(label = "Hello World", icon = "project_template.png", description = "<p><b>Hello World</b></p>\n<p>This is a hello world for AnsibleDsl.</p>") @SuppressWarnings("all") public final class HelloWorldProject extends AbstractProjectTemplate { private final BooleanTemplateVariable advanced = this.check("Advanced:", false); private final GroupTemplateVariable advancedGroup = this.group("Properties"); private final StringTemplateVariable path = this.text("Package:", "mydsl", "The package path to place the files in", this.advancedGroup); protected void updateVariables() { this.path.setEnabled(this.advanced.getValue()); boolean _value = this.advanced.getValue(); boolean _not = (!_value); if (_not) { this.path.setValue("ans"); } } protected IStatus validate() { Status _xifexpression = null; boolean _matches = this.path.getValue().matches("[a-z][a-z0-9_]*(/[a-z][a-z0-9_]*)*"); if (_matches) { _xifexpression = null; } else { _xifexpression = new Status(IStatus.ERROR, "Wizard", (("\'" + this.path) + "\' is not a valid package name")); } return _xifexpression; } public void generateProjects(final IProjectGenerator generator) { PluginProjectFactory _pluginProjectFactory = new PluginProjectFactory(); final Procedure1<PluginProjectFactory> _function = new Procedure1<PluginProjectFactory>() { public void apply(final PluginProjectFactory it) { it.setProjectName(HelloWorldProject.this.getProjectInfo().getProjectName()); it.setLocation(HelloWorldProject.this.getProjectInfo().getLocationPath()); List<String> _projectNatures = it.getProjectNatures(); Iterables.<String>addAll(_projectNatures, Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList(JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature", XtextProjectHelper.NATURE_ID))); List<String> _builderIds = it.getBuilderIds(); Iterables.<String>addAll(_builderIds, Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList(JavaCore.BUILDER_ID, XtextProjectHelper.BUILDER_ID))); List<String> _folders = it.getFolders(); _folders.add("src"); StringConcatenation _builder = new StringConcatenation(); _builder.append("src/"); _builder.append(HelloWorldProject.this.path); _builder.append("/Model.ans"); StringConcatenation _builder_1 = new StringConcatenation(); _builder_1.append("/*"); _builder_1.newLine(); _builder_1.append(" "); _builder_1.append("* This is an example model"); _builder_1.newLine(); _builder_1.append(" "); _builder_1.append("*/"); _builder_1.newLine(); _builder_1.append("playbook_name: \"hello world playbook\""); _builder_1.newLine(); _builder_1.append("plays:"); _builder_1.newLine(); _builder_1.append("\t"); _builder_1.append("play:"); _builder_1.newLine(); _builder_1.append("\t\t"); _builder_1.append("play_name: \"hello world play\""); _builder_1.newLine(); _builder_1.append("\t\t"); _builder_1.append("hosts: \"all\""); _builder_1.newLine(); _builder_1.append("\t\t"); _builder_1.append("tasks_list:"); _builder_1.newLine(); _builder_1.append("\t\t\t"); _builder_1.append("task_to_execute:"); _builder_1.newLine(); _builder_1.append("\t\t\t\t"); _builder_1.append("task_name: \"hello world task\""); _builder_1.newLine(); _builder_1.append("\t\t\t\t"); _builder_1.append("module: \"debug\""); _builder_1.newLine(); _builder_1.append("\t\t\t\t\t"); _builder_1.append("parameters:"); _builder_1.newLine(); _builder_1.append("\t\t\t\t\t\t"); _builder_1.append("msg: \"Hello world!\""); _builder_1.newLine(); HelloWorldProject.this.addFile(it, _builder, _builder_1); } }; PluginProjectFactory _doubleArrow = ObjectExtensions.<PluginProjectFactory>operator_doubleArrow(_pluginProjectFactory, _function); generator.generate(_doubleArrow); } }
44.854701
211
0.699123
15d30412cd0e139ceaf4acac43dd5eea7bd62c3b
3,947
package io.takari.jdkget.it; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.stream.Stream; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Ignore; import org.junit.Test; import io.takari.jdkget.Arch; import io.takari.jdkget.CachingOutput; import io.takari.jdkget.ITransport; import io.takari.jdkget.JdkGetter; import io.takari.jdkget.model.JCE; import io.takari.jdkget.model.BinaryType; import io.takari.jdkget.model.JdkRelease; import io.takari.jdkget.model.JdkReleases; import io.takari.jdkget.model.JdkVersion; public class LoadAllIT { @Test @Ignore public void testDownloadUnpack() throws Exception { String ver = "9+181"; JdkReleases releases = JdkReleases.readFromClasspath(); ITransport transport = releases.createTransportFactory().createTransport(); JdkRelease r = releases.select(JdkVersion.parse(ver)); boolean failed = downloadUnpack(releases, r, Arch.WIN_64, true, transport); assertFalse(failed); } @Test public void testDownloadAndUnpackAll() throws IOException { String startWith = System.getProperty("io.takari.jdkget.startWith"); JdkReleases releases = JdkReleases.readFromClasspath(); ITransport transport = releases.createTransportFactory().createTransport(); JdkVersion start = null; if (StringUtils.isNotBlank(startWith)) { start = releases.select(JdkVersion.parse(startWith)).getVersion(); } boolean failed = false; for (JdkRelease r : releases.getReleases()) { if (start != null && r.getVersion().compareTo(start) > 0) { continue; } failed |= downloadUnpack(releases, r, null, true, transport); } assertFalse(failed); } private boolean downloadUnpack(JdkReleases releases, JdkRelease rel, Arch selArch, boolean unrestrictJce, ITransport transport) { JdkVersion ver = rel.getVersion(); System.out.println(ver.longBuild() + " / " + ver.shortBuild() + (rel.isPsu() ? " PSU" : "")); Stream<Arch> a = selArch != null ? Stream.of(selArch) : rel.getArchs(BinaryType.JDK).parallelStream(); boolean[] failed = new boolean[] {false}; a.forEach(arch -> { for (BinaryType bt : BinaryType.values()) { CachingOutput o = new CachingOutput(); try { JCE jce = null; if (unrestrictJce) { jce = releases.getJCE(rel.getVersion()); } File jdktmp = new File("target/tmp/" + bt + "_" + arch); if (jdktmp.exists()) { FileUtils.forceDelete(jdktmp); } FileUtils.forceMkdir(jdktmp); if (rel.getUnpackableBinary(bt, arch) == null) { continue; } JdkGetter jdkGet = new JdkGetter(transport, o); jdkGet.setRemoveDownloads(false); jdkGet.get(rel, jce, arch, bt, jdktmp); System.out.println(" " + bt + " / " + arch + " >> OK"); } catch (Throwable e) { failed[0] = true; System.err.println(" " + bt + " / " + arch + " >> FAIL"); e.printStackTrace(); o.error("", e); o.output(System.err); try (PrintStream out = new PrintStream(new File("target/tmp/" + rel.getVersion().toString() + "_" + bt + "_" + arch + "_error.log"))) { o.output(out); } catch (IOException ee) { ee.printStackTrace(); } } } }); Runtime rt = Runtime.getRuntime(); long total = rt.totalMemory(); long free = rt.freeMemory(); long occBefore = total - free; System.gc(); total = rt.totalMemory(); free = rt.freeMemory(); long occ = total - free; System.out.println(" MEM: " + (occ / 1024L / 1024L) + " (" + (occBefore / 1024L / 1024L) + ")"); return failed[0]; } }
30.596899
126
0.630099
258ea8936c936040bc9f8348e76df8badcf1994d
1,129
package me.fixeddev.ezchat.replacer; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; public abstract class PlaceholderReplacer { private static PlaceholderReplacer instance; private static Lock lock = new ReentrantLock(); public static PlaceholderReplacer getInstance() { if (instance == null) { lock.lock(); if (instance == null) { if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { Bukkit.getLogger().log(Level.INFO, "[EzChat] Successfully hooked with PlaceholderAPI"); instance = new PlaceholderApiReplacer(); } else { instance = new DummyReplacer(); } } lock.unlock(); } return instance; } public abstract String replacePlaceholders(Player player, String toReplace); public abstract String replaceRelational(Player player, Player playerTwo, String toReplace); }
30.513514
107
0.64039
851127814ca5c7b19bb5e7379fe0fbe7a3a596df
3,114
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package DECL|package|org.apache.hadoop.fs.swift.util package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|swift operator|. name|util package|; end_package begin_class DECL|class|Duration specifier|public class|class name|Duration block|{ DECL|field|started specifier|private specifier|final name|long name|started decl_stmt|; DECL|field|finished specifier|private name|long name|finished decl_stmt|; DECL|method|Duration () specifier|public name|Duration parameter_list|() block|{ name|started operator|= name|time argument_list|() expr_stmt|; name|finished operator|= name|started expr_stmt|; block|} DECL|method|time () specifier|private name|long name|time parameter_list|() block|{ return|return name|System operator|. name|currentTimeMillis argument_list|() return|; block|} DECL|method|finished () specifier|public name|void name|finished parameter_list|() block|{ name|finished operator|= name|time argument_list|() expr_stmt|; block|} DECL|method|getDurationString () specifier|public name|String name|getDurationString parameter_list|() block|{ return|return name|humanTime argument_list|( name|value argument_list|() argument_list|) return|; block|} DECL|method|humanTime (long time) specifier|public specifier|static name|String name|humanTime parameter_list|( name|long name|time parameter_list|) block|{ name|long name|seconds init|= operator|( name|time operator|/ literal|1000 operator|) decl_stmt|; name|long name|minutes init|= operator|( name|seconds operator|/ literal|60 operator|) decl_stmt|; return|return name|String operator|. name|format argument_list|( literal|"%d:%02d:%03d" argument_list|, name|minutes argument_list|, name|seconds operator|% literal|60 argument_list|, name|time operator|% literal|1000 argument_list|) return|; block|} annotation|@ name|Override DECL|method|toString () specifier|public name|String name|toString parameter_list|() block|{ return|return name|getDurationString argument_list|() return|; block|} DECL|method|value () specifier|public name|long name|value parameter_list|() block|{ return|return name|finished operator|- name|started return|; block|} block|} end_class end_unit
18.210526
826
0.782595
f08543a6fe944e84e8ad7cfc36ee57914e0bc95f
3,518
package org.apache.commons.lang3.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public abstract class BackgroundInitializer<T> implements ConcurrentInitializer<T> { private ExecutorService executor; private ExecutorService externalExecutor; private Future<T> future; /* access modifiers changed from: protected */ public int getTaskCount() { return 1; } /* access modifiers changed from: protected */ public abstract T initialize() throws Exception; protected BackgroundInitializer() { this((ExecutorService) null); } protected BackgroundInitializer(ExecutorService executorService) { setExternalExecutor(executorService); } public final synchronized ExecutorService getExternalExecutor() { return this.externalExecutor; } public synchronized boolean isStarted() { return this.future != null; } public final synchronized void setExternalExecutor(ExecutorService executorService) { if (!isStarted()) { this.externalExecutor = executorService; } else { throw new IllegalStateException("Cannot set ExecutorService after start()!"); } } public synchronized boolean start() { ExecutorService executorService; if (isStarted()) { return false; } ExecutorService externalExecutor2 = getExternalExecutor(); this.executor = externalExecutor2; if (externalExecutor2 == null) { executorService = createExecutor(); this.executor = executorService; } else { executorService = null; } this.future = this.executor.submit(createTask(executorService)); return true; } public T get() throws ConcurrentException { try { return getFuture().get(); } catch (ExecutionException e) { ConcurrentUtils.handleCause(e); return null; } catch (InterruptedException e2) { Thread.currentThread().interrupt(); throw new ConcurrentException(e2); } } public synchronized Future<T> getFuture() { if (this.future != null) { } else { throw new IllegalStateException("start() must be called first!"); } return this.future; } /* access modifiers changed from: protected */ public final synchronized ExecutorService getActiveExecutor() { return this.executor; } private Callable<T> createTask(ExecutorService executorService) { return new InitializationTask(executorService); } private ExecutorService createExecutor() { return Executors.newFixedThreadPool(getTaskCount()); } private class InitializationTask implements Callable<T> { private final ExecutorService execFinally; InitializationTask(ExecutorService executorService) { this.execFinally = executorService; } public T call() throws Exception { try { return BackgroundInitializer.this.initialize(); } finally { ExecutorService executorService = this.execFinally; if (executorService != null) { executorService.shutdown(); } } } } }
30.591304
89
0.640421
6e71fbfbddc0a82e313a47a07efb0ebcee16f5e6
252
package org.jsmart.zerocode.core.report; public interface ZeroCodeReportGenerator { void generateCsvReport(); /** * Spike chat is disabled by default * */ void generateHighChartReport(); void generateExtentReport(); }
18
42
0.68254
af9109da0a36e8edbabbfb99cc72feee79136360
1,320
package com.andcreations.ae.studio.plugins.text.editor; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; /** * @author Mikolaj Gucki */ @SuppressWarnings("serial") class TextEditorDocument extends RSyntaxDocument { /** */ private TextEditorDocumentListener listener; /** */ TextEditorDocument(String syntaxStyle,TextEditorDocumentListener listener) { super(syntaxStyle); this.listener = listener; } /** */ int getLineStartOffset(int line) throws BadLocationException { Element map = getDefaultRootElement(); if (line < 0) { throw new BadLocationException("Negative line",-1); } else if (line >= map.getElementCount()) { throw new BadLocationException("No such line",getLength() + 1); } else { Element lineElement = map.getElement(line); return lineElement.getStartOffset(); } } /** */ @Override public void remove(int offset,int length) throws BadLocationException { String text = getText(offset,length); listener.removingText(offset,length,text); super.remove(offset,length); } }
29.333333
81
0.625
f1c681681a6d1aa071416a4ecb4bc5ac92b7cee5
108
package br.dao; import br.model.Disciplina; public class DisciplinaDAO extends GenericDAO<Disciplina> { }
15.428571
59
0.796296
653de49a51dcec49dd566e250cb8810a43147a78
1,056
package org.magic.api.notifiers.impl; import java.io.IOException; import javax.swing.JOptionPane; import org.magic.api.beans.MTGNotification; import org.magic.api.beans.MTGNotification.FORMAT_NOTIFICATION; import org.magic.api.beans.MTGNotification.MESSAGE_TYPE; import org.magic.api.interfaces.abstracts.AbstractMTGNotifier; public class SwingNotifier extends AbstractMTGNotifier { @Override public FORMAT_NOTIFICATION getFormat() { return FORMAT_NOTIFICATION.TEXT; } @Override public void send(MTGNotification notification) throws IOException { JOptionPane.showMessageDialog(null, notification.getMessage(), notification.getTitle(), convert(notification.getType())); } private int convert(MESSAGE_TYPE type) { switch(type) { case ERROR : return JOptionPane.ERROR_MESSAGE; case INFO : return JOptionPane.INFORMATION_MESSAGE; case WARNING : return JOptionPane.WARNING_MESSAGE; case NONE : return 0; default: return JOptionPane.INFORMATION_MESSAGE; } } @Override public String getName() { return "Swing"; } }
25.756098
123
0.785985
f6b77dcdeef9fdbc356e64ef17ba09c228e08a0c
803
package edu.ucla.cs.cs144; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ItemServlet extends HttpServlet implements Servlet { public ItemServlet() {} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // your codes here Item item = null; String xml = AuctionSearchClient.getXMLDataForItemId(request.getParameter("id")); if (xml != "" && xml != null) { item = ParseXML.parseXML(xml); } request.setAttribute("item", item); request.getRequestDispatcher("/item.jsp").forward(request, response); } }
32.12
117
0.753425
ae30bb724c359cc5434f0a266b35500fb1737dca
283
package com.outbrain.swinfra.config.provider; import java.util.Map; /** * Implement this API to be able to provide configuration properties to our projects ;) * * @author Eran Harel */ public interface ConfigurationProvider { public Map<Object, Object> getConfiguration(); }
21.769231
87
0.75265
292c17fd1602bce0055b908ce01f092af81c7041
906
package no.ntnu.idi.apollo69server.game_engine.entity_systems; import com.badlogic.ashley.core.Engine; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.utils.ImmutableArray; import no.ntnu.idi.apollo69server.game_engine.components.NetworkPlayerComponent; public class SpawnSystem extends EntitySystem { private ImmutableArray<Entity> entities; public SpawnSystem(int priority) { super(priority); } @Override public void addedToEngine(Engine engine) { entities = engine.getEntitiesFor(Family.all(NetworkPlayerComponent.class).get()); } @Override public void update(float deltaTime) { for (Entity entity : entities) { NetworkPlayerComponent networkPlayerComponent = NetworkPlayerComponent.MAPPER.get(entity); } } }
27.454545
102
0.746137
99f703a6af028ec57f10ad5f8f1f9aece10be164
266
package com.qingshop.mall.modules.mall.service; import com.baomidou.mybatisplus.extension.service.IService; import com.qingshop.mall.modules.mall.entity.MallShipFree; /** * 指定条件包邮表 服务类 */ public interface IMallShipFreeService extends IService<MallShipFree> { }
22.166667
70
0.804511
324ff3a2ba43d73acc02e80b2d2444fe6ab01add
1,091
package lexicon.levenshtein; import org.apache.commons.text.similarity.LevenshteinDistance; public class LevenshteinTest { private final LevenshteinDistance levenshteinDistance; public LevenshteinTest() { levenshteinDistance = new LevenshteinDistance(); } public String distance(String word1, String word2) { return "'" + word1 + "' matches to '" + word2 + "' with distance of " + levenshteinDistance.apply(word1, word2); } public static void main(String[] args) { LevenshteinTest levenshteinTest = new LevenshteinTest(); System.out.println(levenshteinTest.distance("shit", "shit")); System.out.println(levenshteinTest.distance("Shit", "shit")); System.out.println(levenshteinTest.distance("shit", "shiit")); System.out.println(levenshteinTest.distance("sheet", "shit")); System.out.println(levenshteinTest.distance("sit", "shit")); System.out.println(levenshteinTest.distance("pass", "piss")); System.out.println(levenshteinTest.distance("shot", "shit")); } }
38.964286
120
0.679193
23ea1620b9c2dd75388dd56712f6738baabd6e98
3,055
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package lab.pkg6_brauliocalix; import java.util.ArrayList; /** * * @author User */ public class Series { /* Nombre, tiempo de duración en minutos por capítulos, categorías(tiene libertad para poner las categorías que quiera) , actores principales , numero de temporadas , productora , idioma original , si tiene doblaje y si tiene subtítulos al español. */ private String nombre; private String Tiempo; private String categoria; private String actores; private String temps; private String productora; private String idiomaorigi; private String doblaje; private String subtitulo; public Series() { } public Series(String nombre, String Tiempo, String categoria, String actores, String temps, String productora, String idiomaorigi, String doblaje, String subtitulo) { this.nombre = nombre; this.Tiempo = Tiempo; this.categoria = categoria; this.actores = actores; this.temps = temps; this.productora = productora; this.idiomaorigi = idiomaorigi; this.doblaje = doblaje; this.subtitulo = subtitulo; } public String getActores() { return actores; } public void setActores(String actores) { this.actores = actores; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getTiempo() { return Tiempo; } public void setTiempo(String Tiempo) { this.Tiempo = Tiempo; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public String getTemps() { return temps; } public void setTemps(String temps) { this.temps = temps; } public String getProductora() { return productora; } public void setProductora(String productora) { this.productora = productora; } public String getIdiomaorigi() { return idiomaorigi; } public void setIdiomaorigi(String idiomaorigi) { this.idiomaorigi = idiomaorigi; } public String getDoblaje() { return doblaje; } public void setDoblaje(String doblaje) { this.doblaje = doblaje; } public String getSubtitulo() { return subtitulo; } public void setSubtitulo(String subtitulo) { this.subtitulo = subtitulo; } @Override public String toString() { return "Series{" + "nombre=" + nombre + ", Tiempo=" + Tiempo + ", categoria=" + categoria + ", actores=" + actores + ", temps=" + temps + ", productora=" + productora + ", idiomaorigi=" + idiomaorigi + ", doblaje=" + doblaje + ", subtitulo=" + subtitulo + '}'; } }
24.055118
268
0.628151
ebd7d82dafd242185a7c5f673bdeccc6c0e17bdc
2,960
package org.mybatis.generator.extend; import java.text.SimpleDateFormat; import java.util.Date; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.dom.java.CompilationUnit; import org.mybatis.generator.api.dom.java.Field; import org.mybatis.generator.api.dom.java.InnerClass; import org.mybatis.generator.api.dom.java.Method; public interface MyPlugin { /** * 是否添加xml的注释 */ boolean IS_ADD_XML_COMMENT = false; /** * 是否使用自定义的文件注释 */ boolean IS_MY_FILE_COMMENT = true; /** * 是否使用自定义的类主食 */ boolean IS_MY_CLASS_COMMENT = true; /** * 是否使用自定义的属性注释 */ boolean IS_MY_FIELD_COMMENT = true; /** * 是否使用自定义的Get方法注释 */ boolean IS_MY_GETTER_COMMENT = true; /** * 是否使用自定义的Set方法注释 */ boolean IS_MY_SETTER_COMMENT = true; /** * * 自定义文件类 * * @param compilationUnit */ static void addFileDoc(CompilationUnit compilationUnit) { if (IS_MY_FIELD_COMMENT) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); compilationUnit.addFileCommentLine("/*"); compilationUnit.addFileCommentLine(" * " + compilationUnit.getType().getShortName() + ".java"); compilationUnit.addFileCommentLine(" * Copyright(C) 2017 飞羽company "); compilationUnit.addFileCommentLine(" * createTime : " + sdf.format(new Date())); compilationUnit.addFileCommentLine(" */"); } } static void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) { if (IS_MY_CLASS_COMMENT) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); innerClass.addJavaDocLine("/*"); innerClass.addJavaDocLine(" * " + "备注"); innerClass.addJavaDocLine(" * "); innerClass.addJavaDocLine(" * @author feiyu127"); innerClass.addJavaDocLine(" * @version 1.0 " + sdf.format(new Date())); innerClass.addJavaDocLine(" */"); } } static boolean addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { if (IS_MY_FIELD_COMMENT) { field.addJavaDocLine("/*"); field.addJavaDocLine(" * " + introspectedColumn.getRemarks()); field.addJavaDocLine(" */"); } return IS_MY_FIELD_COMMENT; } static boolean addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { if (IS_MY_GETTER_COMMENT) { method.addJavaDocLine("/*"); method.addJavaDocLine(" * 获取 " + introspectedColumn.getRemarks()); method.addJavaDocLine(" */"); } return IS_MY_GETTER_COMMENT; } static boolean addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { if (IS_MY_SETTER_COMMENT) { method.addJavaDocLine("/*"); method.addJavaDocLine(" * 设置 " + introspectedColumn.getRemarks()); method.addJavaDocLine(" */"); } return IS_MY_SETTER_COMMENT; } }
29.306931
99
0.705743
f76bbee843f1ac7a4eef3f3411189b793de53d17
3,655
package com.disruptor.netty.common; <<<<<<< HEAD /** * Created with IntelliJ IDEA. * Description: * User: kkc * Email: [email protected] * Date: 2018-11-01 * Time: 上午9:57 */ ======= >>>>>>> e34cfaaf75c090c83b307d83bb7c1c8af07acefb import io.netty.handler.codec.marshalling.DefaultMarshallerProvider; import io.netty.handler.codec.marshalling.DefaultUnmarshallerProvider; import io.netty.handler.codec.marshalling.MarshallerProvider; import io.netty.handler.codec.marshalling.MarshallingDecoder; import io.netty.handler.codec.marshalling.MarshallingEncoder; import io.netty.handler.codec.marshalling.UnmarshallerProvider; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.MarshallingConfiguration; /** * Marshalling工厂 */ public final class MarshallingCodeCFactory { /** * 创建Jboss Marshalling解码器MarshallingDecoder * @return MarshallingDecoder */ public static MarshallingDecoder buildMarshallingDecoder() { <<<<<<< HEAD //首先通过Marshalling工具类的精通方法获取Marshalling实例对象 参数serial标识创建的是java序列化工厂对象。 final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial"); //创建了MarshallingConfiguration对象,配置了版本号为5 final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setVersion(5); //根据marshallerFactory和configuration创建provider UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration); //构建Netty的MarshallingDecoder对象,俩个参数分别为provider和单个消息序列化后的最大长度 MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024 * 1024 * 1); return decoder; ======= //首先通过Marshalling工具类的精通方法获取Marshalling实例对象 参数serial标识创建的是java序列化工厂对象。 final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial"); //创建了MarshallingConfiguration对象,配置了版本号为5 final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setVersion(5); //根据marshallerFactory和configuration创建provider UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration); //构建Netty的MarshallingDecoder对象,俩个参数分别为provider和单个消息序列化后的最大长度 MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024 * 1024 * 1); return decoder; >>>>>>> e34cfaaf75c090c83b307d83bb7c1c8af07acefb } /** * 创建Jboss Marshalling编码器MarshallingEncoder * @return MarshallingEncoder */ public static MarshallingEncoder buildMarshallingEncoder() { <<<<<<< HEAD final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial"); final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setVersion(5); MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration); //构建Netty的MarshallingEncoder对象,MarshallingEncoder用于实现序列化接口的POJO对象序列化为二进制数组 MarshallingEncoder encoder = new MarshallingEncoder(provider); return encoder; } } ======= final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial"); final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setVersion(5); MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration); //构建Netty的MarshallingEncoder对象,MarshallingEncoder用于实现序列化接口的POJO对象序列化为二进制数组 MarshallingEncoder encoder = new MarshallingEncoder(provider); return encoder; } } >>>>>>> e34cfaaf75c090c83b307d83bb7c1c8af07acefb
42.011494
106
0.78933
9d363dce52faee98bdc2a935eb26f291ac186fb4
4,783
package org.k2.util.reflection; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import org.k2.util.reflection.exception.MissingAnnotationError; import org.k2.util.reflection.exception.ReflectionError; public class ReflectionUtils { public static Field getAnnotatedField( Class<?> cls, Class<? extends Annotation> annType) throws MissingAnnotationError { for (Field field : cls.getDeclaredFields()) { for (Annotation ann : field.getAnnotations()) { if (ann.annotationType().equals(annType)) { return field; } } } throw new MissingAnnotationError(cls, annType, "on fields"); } public static Field getAnnotatedField( Class<?> cls, Class<? extends Annotation> annType, Class<?> fieldType) throws ReflectionError, MissingAnnotationError { for (Field field : cls.getDeclaredFields()) { for (Annotation ann : field.getAnnotations()) { if (ann.annotationType().equals(annType)) { if (field.getType().isAssignableFrom(fieldType)) { return field; } throw new ReflectionError( cls, "The field annotated with @Key is not of type: "+fieldType.getName()); } } } throw new MissingAnnotationError(cls, annType, "on fields"); } public static Method getAnnotatedMethod( Class<?> cls, Class<? extends Annotation> annType) throws MissingAnnotationError { for (Method method : cls.getDeclaredMethods()) { for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().equals(annType)) { return method; } } } throw new MissingAnnotationError(cls, annType, "on methods"); } public static Method getAnnotatedMethod( Class<?> cls, Class<? extends Annotation> annType, Class<?> ... argTypes) throws MissingAnnotationError { for (Method method : cls.getDeclaredMethods()) { if (method.getParameterCount() == argTypes.length) { if (Arrays.asList(argTypes).equals(Arrays.asList(method.getParameterTypes()))) { for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().equals(annType)) { return method; } } } } } throw new MissingAnnotationError(cls, annType, "on methods with parameters: "+Arrays.asList(argTypes).toString()); } public static Method getAnnotatedMethod( Class<?> cls, Class<? extends Annotation> annType, int argCount) throws MissingAnnotationError { for (Method method : cls.getDeclaredMethods()) { if (method.getParameterCount() == argCount) { for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().equals(annType)) { return method; } } } } throw new MissingAnnotationError(cls, annType, "on methods with "+argCount+" parameters"); } public static Method getAnnotatedMethodReturnsType( Class<?> cls, Class<? extends Annotation> annType, Class<?> returnType, Class<?> ... argTypes) throws ReflectionError, MissingAnnotationError { for (Method method : cls.getDeclaredMethods()) { if (method.getParameterCount() == argTypes.length) { if (Arrays.asList(argTypes).equals(Arrays.asList(method.getParameterTypes()))) { for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().equals(annType)) { if (method.getReturnType().isAssignableFrom(returnType) || (method.getReturnType() == void.class && (returnType.equals(Void.class) || returnType.equals(void.class)))) { return method; } throw new ReflectionError( cls, "The method annotated with @Key does not return type: "+returnType.getName()); } } } } } throw new MissingAnnotationError(cls, annType, "on methods returning: "+returnType.getName()+" with parameters: "+Arrays.asList(argTypes).toString()); } public static Method getAnnotatedMethodReturnsType( Class<?> cls, Class<? extends Annotation> annType, Class<?> returnType, int argCount) throws ReflectionError, MissingAnnotationError { for (Method method : cls.getDeclaredMethods()) { if (method.getParameterCount() == argCount) { for (Annotation ann : method.getAnnotations()) { if (ann.annotationType().equals(annType)) { if (method.getReturnType().isAssignableFrom(returnType) || (method.getReturnType() == void.class && (returnType.equals(Void.class) || returnType.equals(void.class)))) { return method; } throw new ReflectionError( cls, "The method annotated with @Key does not return type: "+returnType.getName()); } } } } throw new MissingAnnotationError(cls, annType, "on methods returning: "+returnType.getName()+" with "+argCount+" parameters"); } }
33.447552
152
0.680535
2a16beae135a48fb07162f188968bdc4ceef0496
4,679
package com.medicapital.server.util; import static com.medicapital.server.log.Tracer.tracer; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.medicapital.common.dao.ServerException; public class EmailService { private Session session; private Transport transport; private String serverUser; private String serverPassword; private String transportProtocol; private String smtpHost; private int smtpPort; private boolean authentication; private boolean debug; private String socketFactoryClass; private boolean socketFactoryFallback; public void init() throws ServerException { try { final Properties props = new Properties(); props.put("mail.transport.protocol", transportProtocol); props.put("mail.smtp.host", smtpHost); props.put("mail.host", smtpHost); props.put("mail.auth", authentication); props.put("mail.smtp.auth", authentication); props.put("mail.smtp.port", smtpPort); props.put("mail.debug", debug); props.put("mail.smtp.socketFactory.port", smtpPort); props.put("mail.smtp.socketFactory.class", socketFactoryClass); props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback); session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverUser, serverPassword); } }); session.setDebug(true); transport = session.getTransport(); transport.connect(serverUser, serverPassword); } catch (final MessagingException e) { throw new ServerException("Init e-Mail service error", e); } } public void send(final String to, final String subject, final String body) throws ServerException { try { tracer(this).debug("Sending e-mail to: " + to + ", subject: " + subject); final InternetAddress addressFrom = new InternetAddress(serverUser); final MimeMessage message = new MimeMessage(session); message.setSender(addressFrom); message.setSubject(subject); message.setContent(body, "text/plain"); final InternetAddress[] addressTo = new InternetAddress[1]; addressTo[0] = new InternetAddress(to); message.setRecipients(Message.RecipientType.TO, addressTo); message.setSentDate(new Date()); transport.sendMessage(message, message.getAllRecipients()); tracer(this).debug("E-mail to: " + to + " sent successfully"); } catch (final MessagingException e) { tracer(this).error("E-mail to: " + to + " not sent - error: " + e.getMessage(), e); throw new ServerException("E-Mail service error", e); } } public void close() throws ServerException { try { if (transport != null) { transport.close(); transport = null; } } catch (final MessagingException e) { throw new ServerException("Error occured while closing e-mail service", e); } } public String getServerUser() { return serverUser; } public void setServerUser(String serverUser) { this.serverUser = serverUser; } public String getServerPassword() { return serverPassword; } public void setServerPassword(String serverPassword) { this.serverPassword = serverPassword; } public String getTransportProtocol() { return transportProtocol; } public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; } public String getSmtpHost() { return smtpHost; } public void setSmtpHost(String smtpHost) { this.smtpHost = smtpHost; } public int getSmtpPort() { return smtpPort; } public void setSmtpPort(int smtpPort) { this.smtpPort = smtpPort; } public boolean isAuthentication() { return authentication; } public void setAuthentication(boolean authentication) { this.authentication = authentication; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } public String getSocketFactoryClass() { return socketFactoryClass; } public void setSocketFactoryClass(String socketFactoryClass) { this.socketFactoryClass = socketFactoryClass; } public boolean isSocketFactoryFallback() { return socketFactoryFallback; } public void setSocketFactoryFallback(boolean socketFactoryFallback) { this.socketFactoryFallback = socketFactoryFallback; } }
29.062112
101
0.722163
97be1e7db364fdec4aefa0cac6b2c418ec7e98b5
241
package by.htp.classWork; public class T2000 extends Terminator{ public T2000(Target target) { super(target); } public void showTarget(){ System.out.println(T2000.class.getSimpleName() + " target: "); super.showTarget(); } }
16.066667
64
0.697095
5224a25693c979fab2cea348c2c8946b87f99ba2
2,390
/******************************************************************************* * Copyright 2016 Jalian Systems Pvt. Ltd. * * 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.sourceforge.marathon.javafxagent.css; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import net.sourceforge.marathon.javafxagent.IJavaFXElement; public class AttributeFilter implements SelectorFilter { public static final Logger LOGGER = Logger.getLogger(AttributeFilter.class.getName()); private String name; private Argument arg; private String op; public AttributeFilter(String name, Argument arg, String op) { this.name = name; this.arg = arg; this.op = op; } @Override public String toString() { if (op == null) { return "[" + name + "]"; } return "[" + name + " " + op + " " + arg + "]"; } @Override public List<IJavaFXElement> match(IJavaFXElement je) { if (doesMatch(je)) { return Arrays.asList(je); } return new ArrayList<IJavaFXElement>(); } public boolean doesMatch(IJavaFXElement je) { if (arg == null) { return je.hasAttribue(name); } String expected = je.getAttribute(name); if (expected == null) { return false; } if (op.equals("startsWith")) { return expected.startsWith(arg.getStringValue()); } else if (op.equals("endsWith")) { return expected.endsWith(arg.getStringValue()); } else if (op.equals("contains")) { return expected.contains(arg.getStringValue()); } else { return expected.equals(arg.getStringValue()); } } }
32.297297
90
0.591213
21b2938405e44a14b0f9f73918c437ad8c0b82c1
1,011
package man.survey; import java.util.List; public class Section implements QuestionFormatter { private int id; private List<Question> questions; public Section(int id, List<Question> questions) { this.id = id; this.questions = questions; } public Section() {} public List<Question> getQuestions() { return questions; } public void setQuestions(List<Question> questions) { this.questions = questions; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Question getQuestionById(int id){ for(Question question : questions){ if(question.getId()==id){ return question; } } return null; } @Override public void clearAnswer() { questions.forEach(q->q.clearAnswer()); } @Override public void setScale(int scale) { questions.forEach(q->q.setScale(scale)); } }
19.442308
56
0.580613
fedd26186077b3d1d115b428f428b0c1ead23132
2,981
package Base; import javafx.fxml.*; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; public class Base { //Stage mainWindow; //Scene sceneProduct, sceneSupplier; // @FXML // void AllCustomerMouseClick(MouseEvent event) { // try { // FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../Customer/customerPage.fxml")); // Parent root = (Parent) fxmlLoader.load(); // Stage stage = new Stage(); // stage.setTitle("Dashboard"); // stage.setScene(new Scene(root, 1000, 700)); // stage.show(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // @FXML // void AllPackagesMouseClick(MouseEvent event) { // try { // FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../Package/Package.fxml")); // Parent root = (Parent) fxmlLoader.load(); // Stage stage = new Stage(); // stage.setTitle("Dashboard"); // stage.setScene(new Scene(root, 1000, 700)); // stage.show(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // @FXML // void AllProductsMouseClick(MouseEvent event) { // // try { // FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../Product/productPage.fxml")); // Parent root = (Parent) fxmlLoader.load(); // Stage stage = new Stage(); // stage.setTitle("Dashboard"); // stage.setScene(new Scene(root, 1000, 700)); // stage.show(); // } catch (IOException e) { // e.printStackTrace(); // } // // // //Parent root = new FXMLLoader(getClass().getResource("basePage.fxml")); // //primaryStage.setTitle("Dashboard"); // //primaryStage.setScene(new Scene(root, 650, 400)); // //primaryStage.show(); // // // } // // @FXML // void AllSuppliersMouseClick(MouseEvent event) { // try { // FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../Supplier/supplierPage.fxml")); // Parent root = (Parent) fxmlLoader.load(); // Stage stage = new Stage(); // stage.setTitle("Dashboard"); // stage.setScene(new Scene(root, 1000, 700)); // stage.show(); // } catch (IOException e) { // e.printStackTrace(); // } // } //public void startBase(Stage Base) throws Exception { // Parent root = FXMLLoader.load(getClass().getResource("productPage.fxml")); //Base.setTitle("Dashboard"); //Base.setScene(new Scene(root, 650, 400)); //Base.show(); //AnchorPane pane = FXMLLoader.load(getClass().getResource("../Supplier/SupplierPage.fxml")); //} }
32.053763
110
0.56055
049c1a2785f563e9fd0af7042c0cd835ef9137bd
2,283
package io.github.sdwfqin.widget; import android.content.Context; import android.content.res.TypedArray; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.AttributeSet; import androidx.appcompat.widget.AppCompatEditText; /** * 描述:Double类型的EditText * * @author 张钦 * @date 2018/1/22 */ public class DecimalEditText extends AppCompatEditText implements TextWatcher { /** * 小数的位数 */ private int DECIMAL_DIGITS = 2; public DecimalEditText(Context context) { this(context, null); } public DecimalEditText(Context context, AttributeSet attrs) { super(context, attrs); this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); this.setBackgroundResource(0); if (attrs != null) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DecimalEditText); DECIMAL_DIGITS = typedArray.getInteger(R.styleable.DecimalEditText_quick_decimalLength, 2); typedArray.recycle(); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().contains(".")) { if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) { s = s.toString().subSequence(0, s.toString().indexOf(".") + DECIMAL_DIGITS + 1); this.setText(s); this.setSelection(s.length()); } } if (".".equals(s.toString().trim().substring(0))) { s = "0" + s; this.setText(s); this.setSelection(2); } if (s.toString().startsWith("0") && s.toString().trim().length() > 1) { if (!".".equals(s.toString().substring(1, 2))) { this.setText(s.subSequence(0, 1)); this.setSelection(1); return; } } } @Override public void afterTextChanged(Editable s) { } public void setDecimalLength(int decimalLength) { DECIMAL_DIGITS = decimalLength; } }
28.185185
103
0.59965
9cbda7e320ac9a9c318a5ccd5c2a34ee747ab41d
2,041
/* * Copyright (C) 2016 The Android Open Source Project * * 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.example.android.miwok; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; public class PhrasesActivity extends AppCompatActivity { protected ArrayList<Word> phrases; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.word_list); // Colors array phrases = new ArrayList<>(); phrases.add(new Word("Where are you going?", "Minto wuksus")); phrases.add(new Word("What is your name?", "Tinne oyaase'ne")); phrases.add(new Word("My name is ...", "oyaaset ...")); phrases.add(new Word("How are you feeling?", "michekses?")); phrases.add(new Word("I am feeling good.", "kuchi achit")); phrases.add(new Word("Are you coming?", "eenes'aa?")); phrases.add(new Word("Yes, I am coming.", "hee'eenem")); phrases.add(new Word("I'm coming.", "eenem")); phrases.add(new Word("Let's go.", "yoowutis")); phrases.add(new Word("Come here.", "enni'nem")); // Array adapter for numbers array WordAdapter itemsAdapter = new WordAdapter(this, phrases, R.color.category_phrases); // listView to display list of numbers ListView listView = findViewById(R.id.list); listView.setAdapter(itemsAdapter); } }
37.109091
92
0.678099
b22332170d28ae806c948073d292678217a09bec
1,691
package dailydiary.handlers; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.amazon.ask.model.Slot; import com.amazon.ask.response.ResponseBuilder; import dailydiary.extension.DateTimeExtenstion; import dailydiary.models.Event; public class GetLastEventHandler extends GetEventsHandler { // Text public static final String TXT_REPROMPT = "Erstelle zuerst einen neuen Eintrag."; public static final String TXT_EVENT_FOUND = "Der letzte Eintrag war %s und fand am %s um %s statt."; public static final String TXT_NO_EVENT_FOUND = "Es wurde noch kein Eintrag angelegt."; @Override public List<Event> searchEvents(Map<String, Slot> slots) { List<Event> list = new ArrayList<>(); Event lstEvent = diary.getLastEvent(); if (lstEvent != null) list.add(lstEvent); return list; } @Override public void assembleResponseFound(ResponseBuilder responseBuilder, List<Event> events) { Event lstEvent = events.get(0); String date = DateTimeExtenstion.getFormaterDate().format(lstEvent.getDate()); String time = DateTimeExtenstion.getFormaterTime().format(lstEvent.getDate()); String result = String.format(TXT_EVENT_FOUND, lstEvent.getName(), date, time); responseBuilder .withSimpleCard(DailyDiaryRequestHandler.RESPONSE_CARD_TITLE, result) .withSpeech(result); } @Override public void assembleResponseNotFound(ResponseBuilder responseBuilder) { responseBuilder .withSimpleCard(DailyDiaryRequestHandler.RESPONSE_CARD_TITLE, TXT_NO_EVENT_FOUND) .withSpeech(TXT_NO_EVENT_FOUND) .withReprompt(TXT_REPROMPT); } }
33.156863
105
0.735068
c1211b4335b74ad0043d3f3910e20f077d46ef3a
421
package com.netcracker.ncstore.dto; import lombok.AllArgsConstructor; import lombok.Getter; import java.time.Instant; import java.util.Locale; /** * DTO used for transferring information about discount */ @AllArgsConstructor @Getter public class DiscountPriceRegionDTO { private final double price; private final Locale region; private final Instant startUtcTime; private final Instant endUtcTime; }
21.05
55
0.781473
3681a0ec97609eb300afad54b1870a7d874bb430
4,984
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ____ _ _____ _ * / ___| _ __ _ __(_)_ __ __ |_ _| _ _ __| |__ ___ * \___ \| '_ \| '__| | '_ \ / _` || || | | | '__| '_ \ / _ \ * ___) | |_) | | | | | | | (_| || || |_| | | | |_) | (_) | * |____/| .__/|_| |_|_| |_|\__, ||_| \__,_|_| |_.__/ \___/ * |_| |___/ https://github.com/yingzhuo/spring-turbo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package spring.turbo.bean; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import spring.turbo.bean.function.DayRangePartitionor; import spring.turbo.util.*; import java.io.Serializable; import java.util.*; import java.util.stream.Stream; /** * @author 应卓 * @see DateUtils * @see DatePair * @since 1.0.13 */ public final class DayRange implements Serializable, Iterable<Date> { public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd"; private final Date leftInclude; private final Date rightInclude; public DayRange(String left, String right) { this(DEFAULT_DATE_PATTERN, left, right); } public DayRange(String datePattern, String left, String right) { this(DateParseUtils.parse(left, datePattern), DateParseUtils.parse(right, datePattern)); } public DayRange(Date leftInclude, Date rightInclude) { Asserts.notNull(leftInclude); Asserts.notNull(rightInclude); this.leftInclude = DateUtils.truncate(leftInclude, Calendar.DATE); this.rightInclude = DateUtils.truncate(rightInclude, Calendar.DATE); if (this.leftInclude.after(this.rightInclude)) { throw new IllegalArgumentException("left is after right"); } } public Date getLeftInclude() { return leftInclude; } public Date getRightInclude() { return rightInclude; } @Override public Iterator<Date> iterator() { return new DayRangeIterator(leftInclude, rightInclude); } public Stream<Date> toStream() { return StreamFactories.newStream(iterator()); } /** * 分区 * * @param partitionor 分区器实例 * @return 分区结果 (可变集合) * @see DayRangePartitionor * @see spring.turbo.bean.function.DayRangePartitionorFactories */ public Map<String, List<Date>> partition(DayRangePartitionor partitionor) { Asserts.notNull(partitionor); final MultiValueMap<String, Date> list = new LinkedMultiValueMap<>(); for (Date date : this) { final String partitionName = partitionor.test(date); if (partitionName != null) { list.add(partitionName, date); } } return list; } public Map<String, Set<Date>> partitionAsSet(DayRangePartitionor partitionor) { final Map<String, Set<Date>> set = new HashMap<>(); final Map<String, List<Date>> ps = this.partition(partitionor); for (final String partitionName : ps.keySet()) { final List<Date> list = ps.get(partitionName); set.put(partitionName, new HashSet<>(list)); } return set; } // ----------------------------------------------------------------------------------------------------------------- @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DayRange dates = (DayRange) o; return leftInclude.equals(dates.leftInclude) && rightInclude.equals(dates.rightInclude); } @Override public int hashCode() { return Objects.hash(leftInclude, rightInclude); } @Override public String toString() { return StringFormatter.format("{} @@ {}", DateUtils.format(leftInclude, "yyyy-MM-dd"), DateUtils.format(rightInclude, "yyyy-MM-dd") ); } // ----------------------------------------------------------------------------------------------------------------- private final static class DayRangeIterator implements Iterator<Date> { private final Date last; private Date it; public DayRangeIterator(Date it, Date last) { this.it = DateUtils.addDays(it, -1); this.last = last; } @Override public boolean hasNext() { Date nextDay = DateUtils.addDays(it, 1); return nextDay.before(last) || DateUtils.isSameDay(last, nextDay); } @Override public Date next() { if (!hasNext()) { throw new NoSuchElementException("no such day"); } Date nextDay = DateUtils.addDays(it, 1); it = nextDay; return nextDay; } } }
32.575163
121
0.536517
c723fa57335244d2ded3f06257fd228336ef4c35
1,916
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.codeInsight.daemon.quickFix; import com.intellij.JavaTestUtil; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.util.PsiUtil; import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.builders.JavaModuleFixtureBuilder; import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase; /** * @author nik */ public class IncreaseLanguageLevelFixTest extends JavaCodeInsightFixtureTestCase { @Override protected String getTestDataPath() { return JavaTestUtil.getJavaTestDataPath() + "/codeInsight/daemonCodeAnalyzer/quickFix/increaseLanguageLevel/"; } @Override protected void tuneFixture(JavaModuleFixtureBuilder moduleBuilder) throws Exception { moduleBuilder.setLanguageLevel(LanguageLevel.JDK_1_6); moduleBuilder.addJdk(IdeaTestUtil.getMockJdk18Path().getPath()); } public void testLambda() throws Exception { myFixture.configureByFile("Lambda.java"); assertEquals(LanguageLevel.JDK_1_6, PsiUtil.getLanguageLevel(myFixture.getFile())); IntentionAction fix = myFixture.findSingleIntention("Set language level"); myFixture.launchAction(fix); assertEquals(LanguageLevel.JDK_1_8, PsiUtil.getLanguageLevel(myFixture.getFile())); } }
39.102041
114
0.788622
828c4929a839b8b397af13cd310c3639b00b89de
916
/** Describes a quantity of an article to purchase. */ public class LineItem { private int quantity; private Product theProduct; /** Constructs an item from the product and quantity. @param aProduct the product @param aQuantity the item quantity */ public LineItem(Product aProduct, int aQuantity) { theProduct = aProduct; quantity = aQuantity; } /** Computes the total cost of this line item. @return the total price */ public double getTotalPrice() { return theProduct.getPrice() * quantity; } /** Formats this item. @return a formatted string of this item */ public String format() { return String.format("%-30s%8.2f%5d%8.2f", theProduct.getDescription(), theProduct.getPrice(), quantity, getTotalPrice()); } }
22.9
65
0.585153
b6a404cdbf49b0ae04aa6ee94c1e3dbe5c0e9aab
494
package com.alibaba.chaosblade.exec.plugin.http; import com.alibaba.chaosblade.exec.common.aop.Plugin; import com.alibaba.chaosblade.exec.common.model.ModelSpec; import com.alibaba.chaosblade.exec.plugin.http.model.HttpModelSpec; /** * @Author yuhan * @package: com.alibaba.chaosblade.exec.plugin.restTemplate * @Date 2019-05-10 10:25 */ public abstract class HttpPlugin implements Plugin { @Override public ModelSpec getModelSpec() { return new HttpModelSpec(); } }
26
67
0.753036
ec342e0b2f0ef55060047d15d35ba4947510a498
2,984
/* * Copyright (c) 2005, The JUNG Authors * All rights reserved. * * This software is open-source under the BSD license; see either "license.txt" * or https://github.com/tomnelson/jungrapht-visualization/blob/master/LICENSE for a description. * * * Created on Apr 12, 2005 */ package org.jungrapht.visualization.layout.util; import java.util.ConcurrentModificationException; import org.jungrapht.visualization.layout.model.LayoutModel; import org.jungrapht.visualization.layout.model.Point; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Simple implementation of PickSupport that returns the vertex or edge that is closest to the * specified location. This implementation provides the same picking options that were available in * previous versions of * * <p>No element will be returned that is farther away than the specified maximum distance. * * @author Tom Nelson * @author Joshua O'Madadhain */ public class RadiusVertexAccessor<V> implements VertexAccessor<V> { private static final Logger log = LoggerFactory.getLogger(RadiusVertexAccessor.class); protected double maxDistance; /** Creates an instance with an effectively infinite default maximum distance. */ public RadiusVertexAccessor() { this(Math.sqrt(Double.MAX_VALUE - 1000)); } /** * Creates an instance with the specified default maximum distance. * * @param maxDistance the maximum distance at which any element can be from a specified location * and still be returned */ public RadiusVertexAccessor(double maxDistance) { this.maxDistance = maxDistance; } /** * @param layoutModel * @param p the pick point * @return the vertex associated with location p */ @Override public V getVertex(LayoutModel<V> layoutModel, Point p) { return getVertex(layoutModel, p.x, p.y); } /** * Gets the vertex nearest to the location of the (x,y) location selected, within a distance of * {@code this.maxDistance}. Iterates through all visible vertices and checks their distance from * the location. Override this method to provide a more efficient implementation. * * @param x the x coordinate of the location * @param y the y coordinate of the location * @return a vertex which is associated with the location {@code (x,y)} as given by {@code layout} */ @Override public V getVertex(LayoutModel<V> layoutModel, double x, double y) { double minDistance = maxDistance * maxDistance * maxDistance; V closest = null; while (true) { try { for (V vertex : layoutModel.getGraph().vertexSet()) { Point p = layoutModel.apply(vertex); double dx = p.x - x; double dy = p.y - y; double dist = dx * dx + dy * dy; if (dist < minDistance) { minDistance = dist; closest = vertex; } } break; } catch (ConcurrentModificationException cme) { } } return closest; } }
32.434783
100
0.694705
45ae7502971037251d55c0920831a4f9f2fafcd2
1,429
package org.jessenpan.leetcode.backtracking; import java.util.ArrayList; import java.util.List; /** * @author jessenpan * tag:backtracing */ public class S93RestoreIPAddresses { private List<String> ips = new ArrayList<>(); public List<String> restoreIpAddresses(String s) { findValidIpAddress(s, 0, "", 0); return ips; } private void findValidIpAddress(String originStr, int index, String subIp, int position) { if (index == 4) { if (position == originStr.length()) { ips.add(subIp); } return; } index++; for (int i = 1; i <= 3; i++) { if (position + i > originStr.length()) { continue; } String segment = originStr.substring(position, position + i); if (isValidSegment(segment)) { String newSubIp = (index != 1) ? (subIp + "." + segment) : subIp + segment; findValidIpAddress(originStr, index, newSubIp, position + i); } } } private boolean isValidSegment(String segment) { Integer num = Integer.parseInt(segment); if (num == 0) { return segment.length() == 1; } int compared = (int) Math.pow(10, segment.length() - 1); if (num < compared) { return false; } return num >= 0 && num <= 255; } }
27.480769
94
0.530441
a2e55ecde34a66ce94e990423d06ebd6e02a1749
4,374
package com.example.demo.controller; import com.example.demo.entity.Register; import com.example.demo.service.RegisterService; import lombok.extern.java.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @Log @RestController @RequestMapping("/register") @CrossOrigin(origins = "*", allowedHeaders = "*") public class RegisterController { @Autowired private RegisterService service; @PostMapping("/register") public ResponseEntity register(@Validated @RequestBody Register register) throws Exception { log.info("Controller Register"); boolean TF = service.register(register); if(TF) { log.info("Register ok"); return new ResponseEntity(HttpStatus.OK); } log.info("Register no"); return new ResponseEntity(HttpStatus.NO_CONTENT); } @PostMapping("/overlapID") public ResponseEntity<String> overlapID(@Validated @RequestBody Register register) throws Exception { log.info("Controller overlapID"); Boolean TF = false; TF = service.overlapID(register); if (TF) { log.info("ok"); return new ResponseEntity<>(HttpStatus.OK); } else { log.info("No"); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } @PostMapping("/overlapNN") public ResponseEntity<String> overlapNN(@Validated @RequestBody Register register) throws Exception { log.info("Controller overlapNN"); Boolean TF = false; TF = service.overlapNN(register); if (TF) { log.info("ok"); return new ResponseEntity<>(HttpStatus.OK); } else { log.info("No"); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } @PostMapping("/findid") public ResponseEntity<Register> findid(@Validated @RequestBody Register register) throws Exception { log.info("Controller Find Id"); Register getid; getid = service.findID(register); if (getid == null) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else { return new ResponseEntity<>(getid, HttpStatus.OK); } } @PostMapping("/findpw") public ResponseEntity<Register> findpw(@Validated @RequestBody Register register) throws Exception { log.info("Controller Find Pw"); Register getforid; getforid = service.findPw(register); if (getforid != null) { return new ResponseEntity<>(getforid,HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } @PostMapping("uplodpw") public ResponseEntity uplodepw(@Validated @RequestBody Register register) throws Exception { log.info("Controller Up Lod PW" ); boolean TF = service.uplodPw(register); if(TF) { return new ResponseEntity(HttpStatus.OK); } return new ResponseEntity(HttpStatus.NO_CONTENT); } @PostMapping("/login") public ResponseEntity<Register> login(@Validated @RequestBody Register register) throws Exception { log.info("Controller Login"); Register getid; getid = service.login(register); if (getid != null) { return new ResponseEntity<>(getid, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } @PostMapping("/phonnum") public ResponseEntity<Register> phonnum(@Validated @RequestBody Register register) throws Exception { log.info("Controller Phone Num"); Register num; num = service.getNum(register); if (num != null) { return new ResponseEntity<>(num, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } } @PostMapping("/placeupdata") public ResponseEntity placeupdata(@Validated @RequestBody Register register) throws Exception { log.info("Controller Place Updata"); service.uplodPl(register); return new ResponseEntity(HttpStatus.OK); } }
32.4
105
0.63946
10f8f040b9aa041b48e7224b2a379f623fb774df
659
package com.amos.flyinn.summoner; import android.view.MotionEvent; import com.amos.shared.TouchEvent; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; public class FakeInputSender { private ObjectOutputStream output; public FakeInputSender() { } public void connect() throws Exception { Socket socket = new Socket("127.0.0.1", 1337); this.output = new ObjectOutputStream(socket.getOutputStream()); } public void sendMotionEvent(MotionEvent e) throws IOException { this.output.writeObject(new TouchEvent(e.getX(), e.getY(), e.getAction(), e.getDownTime())); } }
24.407407
100
0.713202
6ad87d0cd022671aa5e5e49130089050bb95d576
41,957
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.kit.datamanager.metastore2.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import edu.kit.datamanager.entities.Identifier; import edu.kit.datamanager.entities.PERMISSION; import edu.kit.datamanager.exceptions.ResourceNotFoundException; import edu.kit.datamanager.metastore2.configuration.MetastoreConfiguration; import edu.kit.datamanager.metastore2.dao.ILinkedMetadataRecordDao; import edu.kit.datamanager.metastore2.domain.MetadataRecord; import edu.kit.datamanager.metastore2.domain.MetadataSchemaRecord; import edu.kit.datamanager.metastore2.domain.ResourceIdentifier; import edu.kit.datamanager.repo.configuration.RepoBaseConfiguration; import edu.kit.datamanager.repo.dao.IAllIdentifiersDao; import edu.kit.datamanager.repo.dao.IContentInformationDao; import edu.kit.datamanager.repo.dao.IDataResourceDao; import edu.kit.datamanager.repo.domain.ContentInformation; import edu.kit.datamanager.repo.domain.DataResource; import edu.kit.datamanager.repo.domain.Date; import edu.kit.datamanager.repo.domain.RelatedIdentifier; import edu.kit.datamanager.repo.domain.ResourceType; import edu.kit.datamanager.repo.domain.Title; import edu.kit.datamanager.repo.service.IContentInformationService; import java.io.ByteArrayInputStream; import java.nio.file.attribute.AclEntry; import java.nio.file.attribute.AclEntryPermission; import java.time.Instant; import java.util.function.Function; import org.javers.core.Javers; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.mock.web.MockMultipartFile; import org.springframework.restdocs.JUnitRestDocumentation; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener; import org.springframework.security.web.FilterChainProxy; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import org.springframework.test.context.web.ServletTestExecutionListener; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.multipart.MultipartFile; /** * * Test for exceptions */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //RANDOM_PORT) @EntityScan("edu.kit.datamanager") @EnableJpaRepositories("edu.kit.datamanager") @ComponentScan({"edu.kit.datamanager"}) @AutoConfigureMockMvc @TestExecutionListeners(listeners = {ServletTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class, WithSecurityContextTestExecutionListener.class}) @ActiveProfiles("test") @TestPropertySource(properties = {"spring.datasource.url=jdbc:h2:mem:db_util;DB_CLOSE_DELAY=-1"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class MetadataRecordUtilTest { private final static String TEMP_DIR_4_ALL = "/tmp/metastore2/"; private final static String TEMP_DIR_4_SCHEMAS = TEMP_DIR_4_ALL + "schema/"; private final static String TEMP_DIR_4_METADATA = TEMP_DIR_4_ALL + "metadata/"; private static final String METADATA_RECORD_ID = "test_id"; private static final String PID = "anyPID"; private static final String PRINCIPAL = "principal"; private static final String SCHEMA_ID = "my_dc"; private static final String INVALID_SCHEMA = "invalid_dc"; private static final ResourceIdentifier RELATED_RESOURCE = ResourceIdentifier.factoryInternalResourceIdentifier("anyResourceId"); private static final ResourceIdentifier RELATED_RESOURCE_2 = ResourceIdentifier.factoryInternalResourceIdentifier("anyOtherResourceId"); private MockMvc mockMvc; @Autowired private WebApplicationContext context; @Autowired private FilterChainProxy springSecurityFilterChain; @Autowired private ILinkedMetadataRecordDao metadataRecordDao; @Autowired private IDataResourceDao dataResourceDao; @Autowired private IContentInformationDao contentInformationDao; @Autowired private IAllIdentifiersDao allIdentifiersDao; @Autowired private MetastoreConfiguration metadataConfig; @Autowired Javers javers = null; @Rule public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); public MetadataRecordUtilTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { System.out.println("------MetadataControllerTest--------------------------"); System.out.println("------" + this.metadataConfig); System.out.println("------------------------------------------------------"); contentInformationDao.deleteAll(); dataResourceDao.deleteAll(); metadataRecordDao.deleteAll(); allIdentifiersDao.deleteAll(); // setup mockMvc this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .addFilters(springSecurityFilterChain) .apply(documentationConfiguration(this.restDocumentation)) .build(); } @After public void tearDown() { } /** * Constructor */ @Test public void testConstructor() { assertNotNull(new MetadataRecordUtil()); } /** * Test of createMetadataRecord method, of class MetadataRecordUtil. */ @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption1() { System.out.println("createMetadataRecord"); // all null MetastoreConfiguration applicationProperties = null; MultipartFile recordDocument = null; MultipartFile document = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption2() { // valid MetastoreConfiguration System.out.println("createMetadataRecord"); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile recordDocument = null; MultipartFile document = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption3() { System.out.println("createMetadataRecord"); // empty record document MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", (byte[]) null); MultipartFile document = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption3a() { System.out.println("createMetadataRecord"); // invalid record document MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", new String("{nonsense}").getBytes()); MultipartFile document = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } //////////////////////////////////////////////////////////////////////// // Test with invalid records //////////////////////////////////////////////////////////////////////// @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption4() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); // set schema to null record.setSchema(null); record.setRelatedResource(ResourceIdentifier.factoryInternalResourceIdentifier("any")); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption4a() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); // set schema identifier to null record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(null)); record.setRelatedResource(ResourceIdentifier.factoryInternalResourceIdentifier("any")); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption4b() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); // set related resource to null record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(null); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption4c() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); // set related resource identifier to null record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(ResourceIdentifier.factoryInternalResourceIdentifier(null)); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption4d() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); // set id which is not allowed for create record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setSchemaVersion(1l); record.setRelatedResource(RELATED_RESOURCE); record.setId("anyId"); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } //////////////////////////////////////////////////////////////////////// // Test with invalid document //////////////////////////////////////////////////////////////////////// @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption5() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; // empty document MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", (byte[]) null);; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption5a() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", new String("{nonsense}").getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption6() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(null)); record.setRelatedResource(null); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption6a() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(null)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption6b() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(null); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.UnprocessableEntityException.class) public void testCreateMetadataRecordExeption6c() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption7() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = null; MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption8() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", (byte[]) null); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption9() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", SCHEMA_ID.getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", (byte[]) null);; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption10() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); // record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", (byte[]) null);; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption11() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); // set schema identifier to null record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(null)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", (byte[]) null);; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testCreateMetadataRecordExeption12() throws JsonProcessingException { System.out.println("createMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setId(SCHEMA_ID); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", mapper.writeValueAsString(record).getBytes()); MetastoreConfiguration applicationProperties = metadataConfig; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", (byte[]) null);; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.createMetadataRecord(applicationProperties, recordDocument, document); fail("Don't reach this line!"); } /** * Test of updateMetadataRecord method, of class MetadataRecordUtil. */ @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testUpdateMetadataRecord1() { System.out.println("updateMetadataRecord"); MetastoreConfiguration applicationProperties = null; String resourceId = ""; String eTag = ""; MultipartFile recordDocument = null; MultipartFile document = null; Function<String, String> supplier = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.updateMetadataRecord(applicationProperties, resourceId, eTag, recordDocument, document, supplier); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("Don't reach this line!"); } /** * Test of updateMetadataRecord method, of class MetadataRecordUtil. */ @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testUpdateMetadataRecord2() { System.out.println("updateMetadataRecord"); MetastoreConfiguration applicationProperties = null; String resourceId = ""; String eTag = ""; MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", (byte[]) null); MultipartFile document = null; Function<String, String> supplier = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.updateMetadataRecord(applicationProperties, resourceId, eTag, recordDocument, document, supplier); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("Don't reach this line!"); } /** * Test of updateMetadataRecord method, of class MetadataRecordUtil. */ @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testUpdateMetadataRecord3() throws JsonProcessingException { System.out.println("updateMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MetastoreConfiguration applicationProperties = null; String resourceId = ""; String eTag = ""; MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", new String().getBytes()); MultipartFile document = null; Function<String, String> supplier = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.updateMetadataRecord(applicationProperties, resourceId, eTag, recordDocument, document, supplier); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("Don't reach this line!"); } /** * Test of updateMetadataRecord method, of class MetadataRecordUtil. */ @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testUpdateMetadataRecord4() throws JsonProcessingException { System.out.println("updateMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MetastoreConfiguration applicationProperties = null; String resourceId = ""; String eTag = ""; MockMultipartFile recordDocument = null; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", (byte[]) null); Function<String, String> supplier = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.updateMetadataRecord(applicationProperties, resourceId, eTag, recordDocument, document, supplier); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("Don't reach this line!"); } /** * Test of updateMetadataRecord method, of class MetadataRecordUtil. */ @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testUpdateMetadataRecord5() throws JsonProcessingException { System.out.println("updateMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MetastoreConfiguration applicationProperties = null; String resourceId = ""; String eTag = ""; MockMultipartFile recordDocument = null; MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", new String().getBytes()); Function<String, String> supplier = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.updateMetadataRecord(applicationProperties, resourceId, eTag, recordDocument, document, supplier); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("Don't reach this line!"); } /** * Test of updateMetadataRecord method, of class MetadataRecordUtil. */ @Test(expected = edu.kit.datamanager.exceptions.BadArgumentException.class) public void testUpdateMetadataRecord6() throws JsonProcessingException { System.out.println("updateMetadataRecord"); MetadataRecord record = new MetadataRecord(); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); ObjectMapper mapper = new ObjectMapper(); MetastoreConfiguration applicationProperties = null; String resourceId = ""; String eTag = ""; MockMultipartFile recordDocument = new MockMultipartFile("record", "metadata-record.json", "application/json", SCHEMA_ID.getBytes()); MultipartFile document = new MockMultipartFile("document", "metadata.xml", "application/xml", mapper.writeValueAsString(record).getBytes()); Function<String, String> supplier = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.updateMetadataRecord(applicationProperties, resourceId, eTag, recordDocument, document, supplier); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("Don't reach this line!"); } // // /** // * Test of deleteMetadataRecord method, of class MetadataRecordUtil. // */ // @Test // public void testDeleteMetadataRecord() { // System.out.println("deleteMetadataRecord"); // MetastoreConfiguration applicationProperties = null; // String id = ""; // String eTag = ""; // Function<String, String> supplier = null; // MetadataRecordUtil.deleteMetadataRecord(applicationProperties, id, eTag, supplier); // // TODO review the generated test code and remove the default call to fail. // fail("Don't reach this line!"); // } // /** * Test of migrateToDataResource method, of class MetadataRecordUtil. */ @Test(expected = ResourceNotFoundException.class) public void testMigrateToDataResource() { System.out.println("migrateToDataResource"); MetadataRecord record = new MetadataRecord(); record.setId("08/15"); record.setRecordVersion(1l); record.setCreatedAt(Instant.now()); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); record.setRelatedResource(RELATED_RESOURCE); RepoBaseConfiguration applicationProperties = metadataConfig; DataResource expResult = null; DataResource result = MetadataRecordUtil.migrateToDataResource(applicationProperties, record); fail("Don't reach this line!"); } /** * Test of migrateToMetadataRecord method, of class MetadataRecordUtil. */ @Test public void testMigrateToMetadataRecord() { System.out.println("migrateToMetadataRecord"); RepoBaseConfiguration applicationProperties = metadataConfig; DataResource dataResource = null; MetadataRecord expResult = new MetadataRecord(); MetadataRecord result = MetadataRecordUtil.migrateToMetadataRecord(applicationProperties, dataResource, false); assertEquals(expResult, result); dataResource = DataResource.factoryNewDataResource(); dataResource.getAlternateIdentifiers().clear(); // Test with id & PrimaryIdentifier result = MetadataRecordUtil.migrateToMetadataRecord(applicationProperties, dataResource, false); assertNotNull(result.getId()); assertEquals("Id should be the same!", result.getId(), dataResource.getId()); assertEquals("Version should be '1'", Long.valueOf(1l), result.getRecordVersion()); assertTrue("ACL should be empty", result.getAcl().isEmpty()); assertNull("PID should be empty", result.getPid()); assertNull("Create date should be empty!", result.getCreatedAt()); assertNull("Last update date should be empty!", result.getLastUpdate()); // Test with one (internal) alternate identifier. dataResource = DataResource.factoryNewDataResource(); dataResource.getDates().add(Date.factoryDate(Instant.now(), Date.DATE_TYPE.ISSUED)); result = MetadataRecordUtil.migrateToMetadataRecord(applicationProperties, dataResource, false); assertNotNull(result.getId()); assertEquals("Id should be the same!", result.getId(), dataResource.getId()); assertEquals("Version should be '1'", Long.valueOf(1l), result.getRecordVersion()); assertTrue("ACL should be empty", result.getAcl().isEmpty()); assertNull("PID should be empty", result.getPid()); assertNull("Create date should be empty!", result.getCreatedAt()); assertNull("Last update date should be empty!", result.getLastUpdate()); // Test migration of PID with two alternate identifiers (internal & UPC) dataResource.getAlternateIdentifiers().add(Identifier.factoryIdentifier(PID, Identifier.IDENTIFIER_TYPE.UPC)); result = MetadataRecordUtil.migrateToMetadataRecord(applicationProperties, dataResource, false); assertNotNull(result.getId()); assertEquals("Id should be the same!", result.getId(), dataResource.getId()); assertEquals("Version should be '1'", Long.valueOf(1l), result.getRecordVersion()); assertTrue("ACL should be empty", result.getAcl().isEmpty()); assertNull("Create date should be empty!", result.getCreatedAt()); assertNull("Last update date should be empty!", result.getLastUpdate()); // PID should be set assertNotNull("PID shouldn't be NULL", result.getPid()); assertEquals(PID, result.getPid().getIdentifier()); assertEquals(ResourceIdentifier.IdentifierType.UPC, result.getPid().getIdentifierType()); // Add schemaID, resourceType, relatedIdentifier for schema //@ToDo Make this working again // dataResource.getTitles().add(Title.factoryTitle(SCHEMA_ID)); // dataResource.setResourceType(ResourceType.createResourceType(SCHEMA_ID)); // RelatedIdentifier relId = RelatedIdentifier.factoryRelatedIdentifier(RelatedIdentifier.RELATION_TYPES.IS_DERIVED_FROM, SCHEMA_ID, null, null); // relId.setIdentifierType(Identifier.IDENTIFIER_TYPE.INTERNAL); // dataResource.getRelatedIdentifiers().add(relId); // // dataResourceService adds ACL // dataResource = applicationProperties.getDataResourceService().create(dataResource, PRINCIPAL); // IContentInformationService contentInformationService = applicationProperties.getContentInformationService(); // MetadataSchemaRecord msr = new MetadataSchemaRecord(); // msr.setSchemaId(SCHEMA_ID); // msr.setSchemaVersion(1l); // msr.setType(MetadataSchemaRecord.SCHEMA_TYPE.XML); // DataResource dr_schema = MetadataSchemaRecordUtil.migrateToDataResource(applicationProperties, msr); // applicationProperties.getDataResourceService().create(dr_schema, PRINCIPAL); // contentInformationService.create(ContentInformation.createContentInformation("anyFile"), dataResource, SCHEMA_ID, new ByteArrayInputStream(SCHEMA_ID.getBytes()), true); // result = MetadataRecordUtil.migrateToMetadataRecord(applicationProperties, dataResource, false); // assertNotNull(result.getId()); // assertEquals("Id should be the same!", result.getId(), dataResource.getId()); // assertEquals("Version should be '1'", Long.valueOf(1l), result.getRecordVersion()); // assertFalse("ACL shouldn't be empty", result.getAcl().isEmpty()); // assertEquals("ACL should contain one entry for 'SELF'", 1, result.getAcl().size()); // edu.kit.datamanager.repo.domain.acl.AclEntry next = result.getAcl().iterator().next(); // assertEquals("SID should be principal set before!'", PRINCIPAL, next.getSid()); // assertEquals("Persmission should be 'ADMINISTRATE'", PERMISSION.ADMINISTRATE, next.getPermission()); // // Dates should be set bei content information service. // assertNotNull("Create date should be set!", result.getCreatedAt()); // assertNotNull("Last update date should be set!", result.getLastUpdate()); // // PID should be set // assertEquals(PID, result.getPid().getIdentifier()); // assertEquals(ResourceIdentifier.IdentifierType.UPC, result.getPid().getIdentifierType()); } /** * Test of mergeRecords method, of class MetadataRecordUtil. */ @Test public void testMergeRecords() { System.out.println("mergeRecords"); MetadataRecord managed = null; MetadataRecord provided = null; MetadataRecord expResult = null; MetadataRecord result = MetadataRecordUtil.mergeRecords(managed, provided); assertEquals(expResult, result); provided = new MetadataRecord(); result = MetadataRecordUtil.mergeRecords(managed, provided); assertNotNull(result); assertEquals(provided, result); managed = provided; provided = null; result = MetadataRecordUtil.mergeRecords(managed, provided); assertNotNull(result); assertEquals(managed, result); managed = new MetadataRecord(); provided = new MetadataRecord(); provided.setPid(ResourceIdentifier.factoryInternalResourceIdentifier(SCHEMA_ID)); result = MetadataRecordUtil.mergeRecords(managed, provided); assertNotNull(result); assertEquals(provided, result); managed = new MetadataRecord(); provided = new MetadataRecord(); provided.getAcl().add(new edu.kit.datamanager.repo.domain.acl.AclEntry(SCHEMA_ID, PERMISSION.WRITE)); result = MetadataRecordUtil.mergeRecords(managed, provided); assertNotNull(result); provided.setPid(result.getPid()); assertEquals(provided, result); managed = new MetadataRecord(); provided = new MetadataRecord(); provided.setRelatedResource(RELATED_RESOURCE); result = MetadataRecordUtil.mergeRecords(managed, provided); assertNotNull(result); provided.setPid(result.getPid()); assertEquals(provided, result); } /** * Test of setToken method, of class MetadataRecordUtil. */ @Test public void testSetToken() { System.out.println("setToken"); String bearerToken = ""; MetadataRecordUtil.setToken(bearerToken); } }
52.380774
174
0.769621
e4a00a9e4134efccc5b7140ddae91544ce61a0c0
665
package org.rosen.automation.project.screenplay.interactions; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.Interaction; import net.serenitybdd.screenplay.actions.Click; import org.rosen.automation.project.screenplay.pages.Main; import static net.serenitybdd.screenplay.Tasks.instrumented; public class ClickInBlousesSubmenuOption implements Interaction { @Override public <T extends Actor> void performAs(T actor) { actor.attemptsTo(Click.on(Main.BLOUSES_SUBMENU_OPTION)); } public static ClickInBlousesSubmenuOption submenuOption() { return instrumented(ClickInBlousesSubmenuOption.class); } }
33.25
65
0.796992
6f9d47a01f3b8dfa33c0797127b491492d55f634
1,086
package io.github.micansid.guiautomation.control.screen; import io.github.micansid.guiautomation.algorithm.find.ImagePositionFinder; import io.github.micansid.guiautomation.algorithm.find.SimpleFinder; import io.github.micansid.guiautomation.control.awt.AwtScreenshotSupplier; import io.github.micansid.guiautomation.util.helper.Ensure; import io.github.micansid.guiautomation.util.image.Image; import java.util.function.Supplier; import lombok.AccessLevel; import lombok.Getter; @Getter(AccessLevel.PUBLIC) public class ScreenBuilder { private Supplier<Image> screenSupplier = new AwtScreenshotSupplier(); private ImagePositionFinder finder = new SimpleFinder(); public Screen build() { return new Screen(getFinder(), getScreenSupplier()); } public ScreenBuilder setScreenSupplier(final Supplier<Image> screenSupplier) { Ensure.notNull(screenSupplier); this.screenSupplier = screenSupplier; return this; } public ScreenBuilder setFinder(final ImagePositionFinder finder) { Ensure.notNull(finder); this.finder = finder; return this; } }
32.909091
80
0.794659
59e3051f57589f213145c8b6191544a3a97ca818
1,187
/* * Copyright (c) 2011-2017 OpenDDR LLC and others. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package mobi.openddr.example.gwtcanvasdemo.client; public class SpringObject { public static final double springStrength = 0.1; public static final double friction = 0.8; public Vector pos, vel, goal; public SpringObject(Vector start) { this.pos = new Vector(start); this.vel = new Vector(0, 0); this.goal = new Vector(start); } public void update() { Vector d = Vector.sub(goal, pos); d.mult(springStrength); vel.add(d); vel.mult(friction); pos.add(vel); } }
31.236842
81
0.682393
5da29f0e022fd93070d83e0aa6fd3586a7aef14c
8,181
/* * Copyright 2012-2019 MarkLogic Corporation * * 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.marklogic.client.admin; import com.marklogic.client.util.RequestLogger; import com.marklogic.client.util.RequestParameters; import com.marklogic.client.io.Format; import com.marklogic.client.io.marker.StructureReadHandle; import com.marklogic.client.io.marker.TextReadHandle; import com.marklogic.client.io.marker.TextWriteHandle; /** * A Resource Extensions Manager supports writing, reading, and deleting * a Resource Services extension as well as listing the installed * Resource Services extensions. A Resource Services extension implements * server operations on a kind of database resource not supported * by default. */ public interface ResourceExtensionsManager { /** * Reads the list of resource service extensions installed on the server * in a JSON or XML representation provided as an object of an IO class. * * The IO class must have been registered before creating the database client. * By default, the provided handles that implement * {@link com.marklogic.client.io.marker.ContentHandle ContentHandle} are registered. * * <a href="../../../../overview-summary.html#ShortcutMethods">Learn more about shortcut methods</a> * * @param format whether to provide the list in a JSON or XML representation * @param as the IO class for reading the list of resource service extensions * @param <T> the type of object that will be returned by the handle registered for it * @return an object of the IO class with the list of resource service extensions */ <T> T listServicesAs(Format format, Class<T> as); /** * Reads the list of resource service extensions installed on the server * in a JSON or XML representation provided as an object of an IO class. * * The IO class must have been registered before creating the database client. * By default, the provided handles that implement * {@link com.marklogic.client.io.marker.ContentHandle ContentHandle} are registered. * * <a href="../../../../overview-summary.html#ShortcutMethods">Learn more about shortcut methods</a> * * @param format whether to provide the list in a JSON or XML representation * @param as the IO class for reading the list of resource service extensions * @param refresh whether to parse metadata from the extension source * @param <T> the type of object that will be returned by the handle registered for it * @return an object of the IO class with the list of resource service extensions */ <T> T listServicesAs(Format format, Class<T> as, boolean refresh); /** * Reads the list of resource service extensions installed on the server. * @param listHandle a handle on a JSON or XML representation of the list * @param <T> the type of StructureReadHandle to return * @return the list handle */ <T extends StructureReadHandle> T listServices(T listHandle); /** * Reads the list of resource service extensions installed on the server, * specifying whether to refresh the metadata about each extension by parsing * the extension source. * @param listHandle a handle on a JSON or XML representation of the list * @param refresh whether to parse metadata from the extension source * @param <T> the type of StructureReadHandle to return * @return the list handle */ <T extends StructureReadHandle> T listServices(T listHandle, boolean refresh); /** * Reads the XQuery implementation of the services for a resource * in a textual representation provided as an object of an IO class. * * The IO class must have been registered before creating the database client. * By default, the provided handles that implement * {@link com.marklogic.client.io.marker.ContentHandle ContentHandle} are registered. * * <a href="../../../../overview-summary.html#ShortcutMethods">Learn more about shortcut methods</a> * * @param resourceName the name of the resource * @param as the IO class for reading the source code as text * @param <T> the type of object that will be returned by the handle registered for it * @return an object of the IO class with the source code for the service */ <T> T readServicesAs(String resourceName, Class<T> as); /** * Reads the XQuery implementation of the services for a resource. * @param resourceName the name of the resource * @param sourceHandle a handle for reading the text of the XQuery implementation. * @param <T> the type of TextReadHandle to return * @return the XQuery source code */ <T extends TextReadHandle> T readServices(String resourceName, T sourceHandle); /** * Installs the services that implement a resource * in a textual representation provided as an object of an IO class. * * The IO class must have been registered before creating the database client. * By default, the provided handles that implement * {@link com.marklogic.client.io.marker.ContentHandle ContentHandle} are registered. * * <a href="../../../../overview-summary.html#ShortcutMethods">Learn more about shortcut methods</a> * * @param resourceName the name of the resource * @param source an IO representation of the source code * @param metadata the metadata about the resource services * @param methodParams a declaration of the parameters for the services */ void writeServicesAs( String resourceName, Object source, ExtensionMetadata metadata, MethodParameters... methodParams ); /** * Installs the services that implement a resource. * @param resourceName the name of the resource * @param sourceHandle a handle on the source for the XQuery implementation * @param metadata the metadata about the resource services * @param methodParams a declaration of the parameters for the services */ void writeServices(String resourceName, TextWriteHandle sourceHandle, ExtensionMetadata metadata, MethodParameters... methodParams); /** * Uninstalls the services that implement a resource. * @param resourceName the name of the resource */ void deleteServices(String resourceName); /** * Starts debugging client requests. You can suspend and resume debugging output * using the methods of the logger. * * @param logger the logger that receives debugging output */ void startLogging(RequestLogger logger); /** * Stops debugging client requests. */ void stopLogging(); /** * Method Parameters declare the parameters accepted * by the Resource Services extension. */ public class MethodParameters extends RequestParameters { private MethodType method; /** * Declares the parameters for a method the provides services for a resource. * @param method the method type */ public MethodParameters(MethodType method) { super(); this.method = method; } /** * Returns the method for the parameters. * @return the method type */ public MethodType getMethod() { return method; } /** * Returns the hash code for the method. */ @Override public int hashCode() { return getMethod().hashCode(); } /** * Returns whether the method declaration is the same. */ @Override public boolean equals(Object other) { if (other == null) return false; if (!(other instanceof MethodParameters)) return false; MethodParameters otherParam = (MethodParameters) other; if (!getMethod().equals(otherParam.getMethod())) return false; return super.equals(otherParam); } } }
39.907317
134
0.721428
fdd9709e47226224db8a4ae6c84766c3145fd4f6
3,217
/* * 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. */ /** * Codecs API: API for customization of the encoding and structure of the index. * * <p>The Codec API allows you to customise the way the following pieces of index information are * stored: * * <ul> * <li>Postings lists - see {@link org.apache.lucene.codecs.PostingsFormat} * <li>DocValues - see {@link org.apache.lucene.codecs.DocValuesFormat} * <li>Stored fields - see {@link org.apache.lucene.codecs.StoredFieldsFormat} * <li>Term vectors - see {@link org.apache.lucene.codecs.TermVectorsFormat} * <li>Points - see {@link org.apache.lucene.codecs.PointsFormat} * <li>FieldInfos - see {@link org.apache.lucene.codecs.FieldInfosFormat} * <li>SegmentInfo - see {@link org.apache.lucene.codecs.SegmentInfoFormat} * <li>Norms - see {@link org.apache.lucene.codecs.NormsFormat} * <li>Live documents - see {@link org.apache.lucene.codecs.LiveDocsFormat} * </ul> * * For some concrete implementations beyond Lucene's official index format, see the <a * href="{@docRoot}/../codecs/overview-summary.html">Codecs module</a>. * * <p>Codecs are identified by name through the Java Service Provider Interface. To create your own * codec, extend {@link org.apache.lucene.codecs.Codec} and pass the new codec's name to the super() * constructor: * * <pre class="prettyprint"> * public class MyCodec extends Codec { * * public MyCodec() { * super("MyCodecName"); * } * * ... * } * </pre> * * You will need to register the Codec class so that the {@link java.util.ServiceLoader * ServiceLoader} can find it, by including a META-INF/services/org.apache.lucene.codecs.Codec file * on your classpath that contains the package-qualified name of your codec. * * <p>If you just want to customise the {@link org.apache.lucene.codecs.PostingsFormat}, or use * different postings formats for different fields, then you can register your custom postings * format in the same way (in META-INF/services/org.apache.lucene.codecs.PostingsFormat), and then * extend the default codec and override {@code * org.apache.lucene.codecs.luceneMN.LuceneMNCodec#getPostingsFormatForField(String)} to return your * custom postings format. * * <p>Similarly, if you just want to customise the {@link org.apache.lucene.codecs.DocValuesFormat} * per-field, have a look at {@code LuceneMNCodec.getDocValuesFormatForField(String)}. */ package org.apache.lucene.codecs;
46.623188
100
0.734535
184bf976c6ae0423618586b5c942256fb670ec4e
5,481
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui; import com.intellij.ide.dnd.*; import com.intellij.ide.dnd.aware.DnDAwareTree; import com.intellij.openapi.Disposable; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.ui.ComponentUtil; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.dnd.DnDConstants; import java.util.ArrayList; import java.util.List; public abstract class ChangesTreeDnDSupport implements DnDDropHandler, DnDTargetChecker { @NotNull protected final ChangesTree myTree; public ChangesTreeDnDSupport(@NotNull ChangesTree tree) { myTree = tree; } public void install(@NotNull Disposable disposable) { DnDSupport.createBuilder(myTree) .setTargetChecker(this) .setDropHandler(this) .setImageProvider(this::createDraggedImage) .setBeanProvider(this::createDragStartBean) .setDisposableParent(disposable) .install(); } @NotNull protected DnDImage createDraggedImage(@NotNull DnDActionInfo info) { int count = getSelectionCount(myTree); String imageText = VcsBundle.message("vcs.dnd.image.text.n.files", count); return createDragImage(myTree, imageText); } @Nullable protected abstract DnDDragStartBean createDragStartBean(@NotNull DnDActionInfo info); protected abstract boolean canHandleDropEvent(@NotNull DnDEvent aEvent, @Nullable ChangesBrowserNode<?> dropNode); @Override public boolean update(DnDEvent aEvent) { aEvent.hideHighlighter(); aEvent.setDropPossible(false, ""); ChangesBrowserNode<?> dropNode = getDropRootNode(myTree, aEvent); boolean canHandle = canHandleDropEvent(aEvent, dropNode); if (!canHandle) return true; highlightDropNode(aEvent, dropNode); aEvent.setDropPossible(true); return false; } private void highlightDropNode(@NotNull DnDEvent aEvent, @Nullable ChangesBrowserNode<?> dropNode) { final Rectangle tableCellRect; if (dropNode == null) { if (myTree.getRowCount() == 0) { tableCellRect = new Rectangle(0, 0, JBUI.scale(300), JBUI.scale(25)); } else { Rectangle lastRowRect = myTree.getRowBounds(myTree.getRowCount() - 1); int y = lastRowRect.y + lastRowRect.height; tableCellRect = new Rectangle(0, y, JBUI.scale(300), lastRowRect.height); } } else { tableCellRect = myTree.getPathBounds(new TreePath(dropNode.getPath())); } if (tableCellRect != null && fitsInBounds(tableCellRect)) { aEvent.setHighlighting(new RelativeRectangle(myTree, tableCellRect), DnDEvent.DropTargetHighlightingType.RECTANGLE); } } @Nullable public static ChangesBrowserNode<?> getDropRootNode(@NotNull ChangesTree tree, @NotNull DnDEvent event) { RelativePoint dropPoint = event.getRelativePoint(); Point onTree = dropPoint.getPoint(tree); TreePath dropPath = TreeUtil.getPathForLocation(tree, onTree.x, onTree.y); if (dropPath == null) return null; ChangesBrowserNode<?> dropNode = (ChangesBrowserNode<?>)dropPath.getLastPathComponent(); while (!dropNode.getParent().isRoot()) { dropNode = dropNode.getParent(); } return dropNode; } public static boolean isCopyAction(@NotNull DnDEvent aEvent) { DnDAction eventAction = aEvent.getAction(); return eventAction != null && eventAction.getActionId() == DnDConstants.ACTION_COPY; } private boolean fitsInBounds(final Rectangle rect) { JScrollPane pane = ComponentUtil.getScrollPane(myTree); if (pane != null) { Rectangle rectangle = SwingUtilities.convertRectangle(myTree, rect, pane.getParent()); return pane.getBounds().contains(rectangle); } return true; } @NotNull public static DnDImage createDragImage(@NotNull Tree tree, @NotNull @Nls String imageText) { Image image = DnDAwareTree.getDragImage(tree, imageText, null).getFirst(); return new DnDImage(image, new Point(-image.getWidth(null), -image.getHeight(null))); } public static int getSelectionCount(@NotNull ChangesTree tree) { TreePath[] paths = tree.getSelectionModel().getSelectionPaths(); List<ChangesBrowserNode<?>> parents = new ArrayList<>(); for (TreePath path : paths) { ChangesBrowserNode<?> node = (ChangesBrowserNode<?>)path.getLastPathComponent(); if (!node.isLeaf()) { parents.add(node); } } int count = 0; outer: for (TreePath path : paths) { ChangesBrowserNode<?> node = (ChangesBrowserNode<?>)path.getLastPathComponent(); for (ChangesBrowserNode<?> parent : parents) { if (isChildNode(parent, node)) continue outer; } count += node.getFileCount(); } return count; } private static boolean isChildNode(ChangesBrowserNode<?> parent, ChangesBrowserNode<?> node) { ChangesBrowserNode<?> nodeParent = node.getParent(); while (nodeParent != null) { if (nodeParent == parent) return true; nodeParent = nodeParent.getParent(); } return false; } }
34.471698
140
0.719577
c4f51c9f32a43c0b1bbe6b868556471bd5f9d28c
2,620
package de.idrinth.waraddonclient.model; import de.idrinth.waraddonclient.Config; import de.idrinth.waraddonclient.service.FileLogger; import de.idrinth.waraddonclient.service.Request; import de.idrinth.waraddonclient.service.XmlParser; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import javax.json.JsonArray; public abstract class AddonList implements Runnable { protected final HashMap<String, ActualAddon> list = new HashMap<>(); protected final ArrayList<ActualAddon> rows = new ArrayList<>(); protected final Request client; protected final FileLogger logger; private final XmlParser parser; private final Config config; public AddonList(Request client, FileLogger logger, XmlParser parser, Config config) { this.client = client; this.logger = logger; this.parser = parser; this.config = config; } public ActualAddon get(int position) { return rows.get(position); } public ActualAddon get(String name) { return list.get(name); } /** * amount of addons handled * * @return int */ public int size() { return list.size(); } /** * adds an addon to the global list * * @param addon */ public void add(de.idrinth.waraddonclient.model.ActualAddon addon) { list.put(addon.getName(), addon); rows.add(addon); } public class JsonProcessor { private final javax.json.JsonArray json; public JsonProcessor(JsonArray parse) { json = parse; } public void run() throws IOException { if (json == null) { throw new IOException("no content in json"); } for (int counter = json.size(); counter > 0; counter--) { try { processJsonAddon(new ActualAddon(json.getJsonObject(counter - 1), client, logger, parser, config)); } catch (ActualAddon.InvalidArgumentException ex) { logger.error(ex); } } } protected void newAddon(ActualAddon addon) { add(addon); } private void processJsonAddon(de.idrinth.waraddonclient.model.ActualAddon addon) { if (list.containsKey(addon.getName())) { existingAddon(addon); return; } newAddon(addon); } protected void existingAddon(ActualAddon addon) { list.get(addon.getName()).update(addon); } } }
26.734694
119
0.6
fc0fb9dc665f593041ea0e2140d601675d12fea0
2,317
package org.snpeff.outputFormatter; import java.util.HashSet; import org.snpeff.interval.Gene; import org.snpeff.interval.Marker; import org.snpeff.interval.Regulation; import org.snpeff.interval.Variant; import org.snpeff.snpEffect.VariantEffect; /** * Formats: Show all annotations that intersect the BED input file. * * WARNING: In this format, the output are annotations (instead of input intervals) * * @author pcingola */ public class BedAnnotationOutputFormatter extends BedOutputFormatter { public BedAnnotationOutputFormatter() { super(); outOffset = 0; // Bed format is zero-based } /** * Show all effects */ @Override public String toString() { Variant variant = (Variant) section; String variantName = variant.getChromosomeName() + ":" + (variant.getStart() + outOffset); // Show results HashSet<String> chEffs = new HashSet<>(); for (VariantEffect changeEffect : variantEffects) { // If it is not filtered out by changeEffectResutFilter => Show it if ((variantEffectResutFilter == null) || (!variantEffectResutFilter.filter(changeEffect))) { String ann = null; Marker m = changeEffect.getMarker(); if (m != null) { // Get gene name (if any) String geneName = null; Gene gene = changeEffect.getGene(); if (gene != null) geneName = (useGeneId ? gene.getId() : gene.getGeneName()); // Get annotation type String type = m.getType().toString(); // Show complete regulation info if (m instanceof Regulation) { Regulation r = (Regulation) m; type += "|" + r.getName() + "|" + r.getRegulationType(); } // Add BED line ann = m.getChromosomeName() + "\t" // + "\t" + (m.getStart() + outOffset) // + "\t" + (m.getEnd() + outOffset + 1) // + "\t" + variantName + ";" + type // + (geneName != null ? ":" + geneName : "") // ; } if (ann != null) chEffs.add(ann); } } // Show all StringBuilder sb = new StringBuilder(); for (String chEff : chEffs) sb.append(chEff + "\n"); return sb.toString(); } /** * Show header */ @Override public String toStringHeader() { return "# SnpEff version " + version + "\n" // + "# Command line: " + commandLineStr + "\n" // + "# Chromo\tStart\tEnd\tVariant;Annotation\tScore"; } }
26.329545
96
0.633578
1e6b55fde839414769acb7afd070d5a9382669ff
352
package br.com.kek.tictactoe.enums; public enum OptionMoveEnum { MOVE_X("X"), MOVE_O("O"); private String value; private OptionMoveEnum(String value) { this.value = value; } public String getValue() { return value; } public OptionMoveEnum getReversePlayer() { return this.getValue().equals(MOVE_X.getValue()) ? MOVE_O : MOVE_X; } }
16.761905
69
0.704545
a4a078652d44abc63a1570fe8f155e97b1521156
10,049
package malcjohn; public class Aufgabe_2 { /** * @param args */ public static void main(String[] args) { /** * * Das ist die 1 Unteraufgabe */ // Neuer Anfang mir Docs // beliebig - meine "grossen Zahlen" int grosseZahl = (Integer.MAX_VALUE / 2); // 1073741823 int grosseZahl2 = (Integer.MAX_VALUE / 3); // 715827882 // Zuweisung zu float float neuZahlZuweisung = (int) grosseZahl; float neuZahlZuweisung2 = (int) grosseZahl2; // Zuweisung zu double double neuZahlZuweisung3 = (int) grosseZahl; double neuZahlZuweisung4 = (int) grosseZahl2; // Nicht sicher wie genau, ich mache noch umgekehrt // Entweder int-int oder int-float // Kommt das gleiche wie bei grosseZahl > Irrelevant // int neuZahlZuweisung3 = (int) grosseZahl; // int neuZahlZuweisung4 = (int) grosseZahl2; // Uberprufen ob int max value/2-3 existriert System.out.println(grosseZahl); System.out.println(grosseZahl2); // Float and double value zahlen System.out.println(neuZahlZuweisung + " > Float in int"); // 1.07374182E9 System.out.println(neuZahlZuweisung2 + " > Zweite float in int"); // 7.158279E8 System.out.println(neuZahlZuweisung3 + " > Double in int"); // 1.073741823E9 System.out.println(neuZahlZuweisung4 + " > Zweite double int"); // 7.15827882E8 System.out.println(); System.out.println(Integer.MAX_VALUE + " grossete max value of int"); System.out.println(Integer.MIN_VALUE + " kleinste min value of int"); System.out.println(); /* * * Die 2 Unteraufgabe Moglich ? > Ja typecasting nicht notig, also (int) * muss nicht geschrieben sein */ float zuweisung3 = Integer.MAX_VALUE; double zuweissung2 = Integer.MAX_VALUE; // nur fur vorletzte aufgabe mit min value float zuweisungMinus = Integer.MIN_VALUE; double zuweissungMinus = Integer.MIN_VALUE; System.out.println(zuweisung3 + " Zugewiesen float zu int"); // 2.14748365E9 System.out.println(zuweissung2 + " Zugewiesen double zu int"); // 2.147483647E9 System.out.println(); System.out.println(); /* * * Die 3 Unteraufgabe Umwandlung von float und double varianten in int * wieder */ int WiederUmwandlung = (int) zuweisung3; int WiederUmwandlung2 = (int) zuweissung2; // Kriegt man die Max. Value von int System.out.println(WiederUmwandlung); // 2147483647 System.out.println(WiederUmwandlung2); // 2147483647 System.out.println(); System.out.println(); /* * Die 4 Unteraufgabe Ziehen Sie von den Fließkommavariablen 1 ab und * wandeln Sie wieder zurück, Machen Sie das Entsprechende mit * Subtraktion von 10, Division durch 10 und schließlich mit Subtraktion * und Division nacheinander. */ System.out.print(Float.MIN_VALUE); // Vorsichtig here, nicht in negativ // geht, sondern 0.000... float EinsAbziehen = zuweisung3 - 1; System.out.println(EinsAbziehen); // 2.14748365E9 int EinsAbziehen2 = (int) EinsAbziehen; System.out.println(EinsAbziehen2); // 2147483647 System.out.println(" 1 abziehen"); System.out.println(); float EinsAbziehen3 = zuweisung3 - 10; System.out.println(EinsAbziehen3); // 2.14748365E9 int EinsAbziehen4 = (int) EinsAbziehen; System.out.println(EinsAbziehen4); // 2147483647 System.out.println("-10 "); System.out.println(); float EinsAbziehen5 = zuweisung3 / 10; System.out.println(EinsAbziehen5); // 2.14748368E8 int EinsAbziehen6 = (int) EinsAbziehen; System.out.println(EinsAbziehen6); // 2147483647 System.out.println("/10"); System.out.println(); float EinsAbziehen7 = (zuweisung3 - 10) / 10; System.out.println(EinsAbziehen7); // 2.14748368E8 int EinsAbziehen8 = (int) EinsAbziehen; System.out.println(EinsAbziehen8); // 2147483647 System.out.println("-10 /10"); System.out.println(); System.out.println(" Ab jetzt mit double"); double EinsAbziehen9 = zuweissung2 - 1; System.out.println(EinsAbziehen9); // 2.147483646E9 int EinsAbziehen10 = (int) EinsAbziehen; System.out.println(EinsAbziehen10); // 2147483647 System.out.println(" 1 abziehen"); System.out.println(); double EinsAbziehen11 = zuweissung2 - 10; System.out.println(EinsAbziehen11); // 2.147483637E9 int EinsAbziehen12 = (int) EinsAbziehen; System.out.println(EinsAbziehen12); // 2147483647 System.out.println("-10 "); System.out.println(); double EinsAbziehen13 = zuweissung2 / 10; System.out.println(EinsAbziehen13); // 2.147483647E8 int EinsAbziehen14 = (int) EinsAbziehen; System.out.println(EinsAbziehen14); // 2147483647 System.out.println("/10"); System.out.println(); double EinsAbziehen15 = (zuweissung2 - 10) / 10; System.out.println(EinsAbziehen15); // 2.147483637E8 int EinsAbziehen16 = (int) EinsAbziehen; System.out.println(EinsAbziehen16); // 2147483647 System.out.println("-10 /10"); System.out.println(); // Ab jetzt mit min value // Genommen von der 2 Unteraufgabe System.out.println("Ab jetzt mit min value"); float EinsAbziehen17 = zuweisungMinus + 1; System.out.println(EinsAbziehen17); // -2.14748365E9 int EinsAbziehen18 = (int) EinsAbziehen; System.out.println(EinsAbziehen18); // 2147483647 System.out.println(" 1 abziehen"); System.out.println(); float EinsAbziehen19 = zuweisungMinus + 10; System.out.println(EinsAbziehen19); // -2.14748365E9 int EinsAbziehen20 = (int) EinsAbziehen; System.out.println(EinsAbziehen20); // 2147483647 System.out.println("-10 "); System.out.println(); float EinsAbziehen21 = zuweisungMinus / 10; System.out.println(EinsAbziehen21); // -2.14748368E8 int EinsAbziehen22 = (int) EinsAbziehen; System.out.println(EinsAbziehen22); // 2147483647 System.out.println("/10"); System.out.println(); float EinsAbziehen23 = (zuweisungMinus + 10) / 10; System.out.println(EinsAbziehen23); // -2.14748368E8 int EinsAbziehen24 = (int) EinsAbziehen; System.out.println(EinsAbziehen24); // 2147483647 System.out.println("-10 /10"); System.out.println(); System.out.println(" Ab jetzt mit double"); double EinsAbziehen25 = zuweissungMinus + 1; System.out.println(EinsAbziehen25); // -2.147483647E9 int EinsAbziehen26 = (int) EinsAbziehen; System.out.println(EinsAbziehen26); // 2147483647 System.out.println(" 1 abziehen"); System.out.println(); double EinsAbziehen27 = zuweissungMinus + 10; System.out.println(EinsAbziehen27); // -2.147483638E9 int EinsAbziehen28 = (int) EinsAbziehen; System.out.println(EinsAbziehen28); // 2147483647 System.out.println("-10 "); System.out.println(); double EinsAbziehen29 = zuweissungMinus / 10; System.out.println(EinsAbziehen29); // -2.147483648E8 int EinsAbziehen30 = (int) EinsAbziehen; System.out.println(EinsAbziehen30); // 2147483647 System.out.println("/10"); System.out.println(); double EinsAbziehen31 = (zuweissungMinus + 10) / 10; System.out.println(EinsAbziehen31); // -2.147483638E8 int EinsAbziehen32 = (int) EinsAbziehen; System.out.println(EinsAbziehen32); // 2147483647 System.out.println("-10 /10"); System.out.println(); System.out.println(); System.out.println(); /** * * Besorgen Sie sich die größte darstellbare long-Zahl und * multiplizieren Sie sie zuerst als float und dann als double mit 10, * entsprechend die kleinste darstellbare (negativer Exponent) dividiert * durch 10. */ System.out.println("// 5th. Sentence [the last part]"); long sj = Long.MAX_VALUE; long sd = Long.MIN_VALUE; // System.out.println(sd); float fr = (float) sj; // for max value double re = (double) sj; // for max value System.out.println(fr * 10); // 9.223372E19 System.out.println(re * 10); // 9.223372036854776E19 float fg = (float) sd; // for min value double ft = (double) sd; // for min value System.out.println(fg / 10); // -9.2233722E17 System.out.println(ft / 10); // -9.2233720368547763E17 System.out.println(); System.out.println(); // Wahrscheinlich richtig, aber ich nutze nur den letzten Teil mit Long /* * System.out.println("// 1st. Sentence"); int a = 2_000_000; int d = * 500_000; double b = 54.85; double c = 989787.845664; * System.out.println(a+b+c+d); // basic sum * * System.out.println("// 2nd. Sentence"); double r = * 6445641689494.6546; // random float t = (float) 65464654646.4; // * random * * float by = Integer.MAX_VALUE; // this is right double dy = * Integer.MAX_VALUE; // this is right * * int g = Integer.MAX_VALUE; double y = g+t+r; // or comment this in * and change println to g+r+t * * System.out.println(by); // another sum, this time converted to * double/float System.out.println(dy); * * * System.out.println("// 3rd. Sentence"); int w = (int) y; int q = * (int) r; int qw = (int) t; System.out.println(w); // just takes the * max value from integer System.out.println(q); // in general there ist * always the same number of int System.out.println(qw); // it's * max_value of that; 10 numbers * * System.out.println("// 4th. Sentence"); float byt = by - 1; float duk * = by - 10; float buk = by / 10 ; float puk = (by -10) / 10; * System.out.println(byt); int tuk = (int) byt; * System.out.println(duk); System.out.println(buk); * System.out.println(tuk); System.out.println(puk); * * System.out.println("// 5th. Sentence [the last part]"); long sj = * Long.MAX_VALUE; long sd = Long.MIN_VALUE; * * float fr = (float) sj; // for max value double re = (double) sj; // * for max value * * System.out.println(fr * 10); System.out.println(re * 10); * * float fg = (float) sd; // for min value double ft = (double) sd; // * for min value * * System.out.println(fg / 10); System.out.println(ft / 10); */ } }
35.259649
82
0.668823
64564b0c4f019a1abe422c85f8455fae28b0b8f6
32,816
/*! * Copyright 2010 - 2015 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.pentaho.di.ui.repository.pur.repositoryexplorer.model; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.Workspace; import javax.jcr.security.AccessControlException; import org.apache.commons.io.FileUtils; import org.apache.jackrabbit.api.JackrabbitWorkspace; import org.apache.jackrabbit.api.security.authorization.PrivilegeManager; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.plugins.JobEntryPluginType; import org.pentaho.di.core.plugins.StepPluginType; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.RepositoryDirectoryInterface; import org.pentaho.di.repository.RepositoryTestBase; import org.pentaho.di.repository.UserInfo; import org.pentaho.di.repository.pur.PurRepository; import org.pentaho.di.repository.pur.PurRepositoryConnector; import org.pentaho.di.repository.pur.PurRepositoryMeta; import org.pentaho.di.ui.repository.pur.services.IAclService; import org.pentaho.platform.api.engine.IAuthorizationPolicy; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.api.engine.security.userroledao.IPentahoRole; import org.pentaho.platform.api.engine.security.userroledao.IPentahoUser; import org.pentaho.platform.api.engine.security.userroledao.IUserRoleDao; import org.pentaho.platform.api.mt.ITenant; import org.pentaho.platform.api.mt.ITenantManager; import org.pentaho.platform.api.mt.ITenantedPrincipleNameResolver; import org.pentaho.platform.api.repository2.unified.IBackingRepositoryLifecycleManager; import org.pentaho.platform.api.repository2.unified.IUnifiedRepository; import org.pentaho.platform.api.repository2.unified.RepositoryFile; import org.pentaho.platform.api.repository2.unified.RepositoryFileAcl; import org.pentaho.platform.api.repository2.unified.RepositoryFileAcl.Builder; import org.pentaho.platform.api.repository2.unified.RepositoryFilePermission; import org.pentaho.platform.api.repository2.unified.RepositoryFileSid; import org.pentaho.platform.api.repository2.unified.RepositoryFileSid.Type; import org.pentaho.platform.core.mt.Tenant; import org.pentaho.platform.engine.core.system.PentahoSessionHolder; import org.pentaho.platform.engine.core.system.StandaloneSession; import org.pentaho.platform.repository2.ClientRepositoryPaths; import org.pentaho.platform.repository2.unified.IRepositoryFileDao; import org.pentaho.platform.repository2.unified.ServerRepositoryPaths; import org.pentaho.platform.repository2.unified.jcr.JcrTenantUtils; import org.pentaho.platform.repository2.unified.jcr.PentahoJcrConstants; import org.pentaho.platform.repository2.unified.jcr.RepositoryFileProxyFactory; import org.pentaho.platform.repository2.unified.jcr.SimpleJcrTestUtils; import org.pentaho.platform.repository2.unified.jcr.jackrabbit.security.TestPrincipalProvider; import org.pentaho.platform.repository2.unified.jcr.sejcr.CredentialsStrategy; import org.pentaho.platform.security.policy.rolebased.IRoleAuthorizationPolicyRoleBindingDao; import org.pentaho.platform.security.userroledao.DefaultTenantedPrincipleNameResolver; import org.pentaho.test.platform.engine.core.MicroPlatform; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.extensions.jcr.JcrCallback; import org.springframework.extensions.jcr.JcrTemplate; import org.springframework.extensions.jcr.SessionFactory; import org.springframework.security.Authentication; import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.providers.UsernamePasswordAuthenticationToken; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; @RunWith( SpringJUnit4ClassRunner.class ) @ContextConfiguration( locations = { "classpath:/repository.spring.xml", "classpath:/repository-test-override.spring.xml" } ) public class UIEERepositoryDirectoryIT extends RepositoryTestBase implements ApplicationContextAware, java.io.Serializable { static final long serialVersionUID = 2064159405078106703L; /* EESOURCE: UPDATE SERIALVERUID */ private IUnifiedRepository repo; private ITenantedPrincipleNameResolver userNameUtils = new DefaultTenantedPrincipleNameResolver(); private ITenantedPrincipleNameResolver roleNameUtils = new DefaultTenantedPrincipleNameResolver( DefaultTenantedPrincipleNameResolver.ALTERNATE_DELIMETER ); private ITenantManager tenantManager; private ITenant systemTenant; private IRoleAuthorizationPolicyRoleBindingDao roleBindingDaoTarget; private String repositoryAdminUsername; private JcrTemplate testJcrTemplate; private MicroPlatform mp; IUserRoleDao testUserRoleDao; IUserRoleDao userRoleDao; private String singleTenantAdminRoleName; private String tenantAuthenticatedRoleName; private String sysAdminUserName; private String superAdminRoleName; private TransactionTemplate txnTemplate; private IRepositoryFileDao repositoryFileDao; private final String TENANT_ID_ACME = "acme"; private IBackingRepositoryLifecycleManager repositoryLifecyleManager; private final String TENANT_ID_DUFF = "duff"; private static IAuthorizationPolicy authorizationPolicy; // ~ Methods ========================================================================================================= @BeforeClass public static void setUpClass() throws Exception { System.out.println( "Repository: " + UIEERepositoryDirectoryIT.class.getClassLoader().getResource( "repository.spring.xml" ).getPath() ); // folder cannot be deleted at teardown shutdown hooks have not yet necessarily completed // parent folder must match jcrRepository.homeDir bean property in repository-test-override.spring.xml FileUtils.deleteDirectory( new File( "/tmp/jackrabbit-test-TRUNK" ) ); PentahoSessionHolder.setStrategyName( PentahoSessionHolder.MODE_GLOBAL ); } @AfterClass public static void tearDownClass() throws Exception { PentahoSessionHolder.setStrategyName( PentahoSessionHolder.MODE_INHERITABLETHREADLOCAL ); } @Before public void setUp() throws Exception { loginAsRepositoryAdmin(); SimpleJcrTestUtils.deleteItem( testJcrTemplate, ServerRepositoryPaths.getPentahoRootFolderPath() ); mp = new MicroPlatform(); // used by DefaultPentahoJackrabbitAccessControlHelper mp.defineInstance( "tenantedUserNameUtils", userNameUtils ); mp.defineInstance( "tenantedRoleNameUtils", roleNameUtils ); mp.defineInstance( IAuthorizationPolicy.class, authorizationPolicy ); mp.defineInstance( ITenantManager.class, tenantManager ); mp.defineInstance( "roleAuthorizationPolicyRoleBindingDaoTarget", roleBindingDaoTarget ); mp.defineInstance( "repositoryAdminUsername", repositoryAdminUsername ); mp.defineInstance( "RepositoryFileProxyFactory", new RepositoryFileProxyFactory( testJcrTemplate, repositoryFileDao ) ); mp.defineInstance( "useMultiByteEncoding", new Boolean( false ) ); mp.defineInstance( IAclService.class, new Boolean( false ) ); // Start the micro-platform mp.start(); loginAsRepositoryAdmin(); setAclManagement(); systemTenant = tenantManager.createTenant( null, ServerRepositoryPaths.getPentahoRootFolderName(), singleTenantAdminRoleName, tenantAuthenticatedRoleName, "Anonymous" ); userRoleDao.createUser( systemTenant, sysAdminUserName, "password", "", new String[] { singleTenantAdminRoleName } ); logout(); super.setUp(); KettleEnvironment.init(); // programmatically register plugins, annotation based plugins do not get loaded unless // they are in kettle's plugins folder. JobEntryPluginType.getInstance().registerCustom( JobEntryAttributeTesterJobEntry.class, "test", "JobEntryAttributeTester", "JobEntryAttributeTester", "JobEntryAttributeTester", "" ); StepPluginType.getInstance().registerCustom( TransStepAttributeTesterTransStep.class, "test", "StepAttributeTester", "StepAttributeTester", "StepAttributeTester", "" ); repositoryMeta = new PurRepositoryMeta(); repositoryMeta.setName( "JackRabbit" ); repositoryMeta.setDescription( "JackRabbit test repository" ); userInfo = new UserInfo( EXP_LOGIN, "password", EXP_USERNAME, "Apache Tomcat user", true ); repository = new PurRepository(); repository.init( repositoryMeta ); login( sysAdminUserName, systemTenant, new String[] { singleTenantAdminRoleName, tenantAuthenticatedRoleName } ); ITenant tenantAcme = tenantManager.createTenant( systemTenant, EXP_TENANT, singleTenantAdminRoleName, tenantAuthenticatedRoleName, "Anonymous" ); userRoleDao.createUser( tenantAcme, EXP_LOGIN, "password", "", new String[] { singleTenantAdminRoleName } ); logout(); setUpUser(); PurRepository purRep = (PurRepository) repository; final PurRepositoryConnector purRepositoryConnector = new PurRepositoryConnector( purRep, (PurRepositoryMeta) repositoryMeta, purRep.getRootRef() ); purRep.setPurRepositoryConnector( purRepositoryConnector ); purRep.setTest( repo ); repository.connect( EXP_LOGIN, "password" ); login( EXP_LOGIN, tenantAcme, new String[] { singleTenantAdminRoleName, tenantAuthenticatedRoleName } ); System.out.println( "PUR NAME!!!: " + repo.getClass().getCanonicalName() ); RepositoryFile repositoryFile = repo.getFile( ClientRepositoryPaths.getPublicFolderPath() ); Serializable repositoryFileId = repositoryFile.getId(); List<RepositoryFile> files = repo.getChildren( repositoryFileId ); StringBuilder buf = new StringBuilder(); for ( RepositoryFile file : files ) { buf.append( "\n" ).append( file ); } assertTrue( "files not deleted: " + buf, files.isEmpty() ); } private void setAclManagement() { testJcrTemplate.execute( new JcrCallback() { @Override public Object doInJcr( Session session ) throws IOException, RepositoryException { PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants( session ); Workspace workspace = session.getWorkspace(); PrivilegeManager privilegeManager = ( (JackrabbitWorkspace) workspace ).getPrivilegeManager(); try { privilegeManager.getPrivilege( pentahoJcrConstants.getPHO_ACLMANAGEMENT_PRIVILEGE() ); } catch ( AccessControlException ace ) { privilegeManager.registerPrivilege( pentahoJcrConstants.getPHO_ACLMANAGEMENT_PRIVILEGE(), false, new String[0] ); } session.save(); return null; } } ); } private void setUpUser() { StandaloneSession pentahoSession = new StandaloneSession( userInfo.getLogin() ); pentahoSession.setAuthenticated( userInfo.getLogin() ); pentahoSession.setAttribute( IPentahoSession.TENANT_ID_KEY, "/pentaho/" + EXP_TENANT ); final GrantedAuthority[] authorities = new GrantedAuthority[2]; authorities[0] = new GrantedAuthorityImpl( "Authenticated" ); authorities[1] = new GrantedAuthorityImpl( "acme_Authenticated" ); final String password = "ignored"; //$NON-NLS-1$ UserDetails userDetails = new User( userInfo.getLogin(), password, true, true, true, true, authorities ); Authentication authentication = new UsernamePasswordAuthenticationToken( userDetails, password, authorities ); // next line is copy of SecurityHelper.setPrincipal pentahoSession.setAttribute( "SECURITY_PRINCIPAL", authentication ); PentahoSessionHolder.setSession( pentahoSession ); SecurityContextHolder.setStrategyName( SecurityContextHolder.MODE_GLOBAL ); SecurityContextHolder.getContext().setAuthentication( authentication ); repositoryLifecyleManager.newTenant(); repositoryLifecyleManager.newUser(); } private void loginAsRepositoryAdmin() { StandaloneSession pentahoSession = new StandaloneSession( repositoryAdminUsername ); pentahoSession.setAuthenticated( repositoryAdminUsername ); final GrantedAuthority[] repositoryAdminAuthorities = new GrantedAuthority[] { new GrantedAuthorityImpl( superAdminRoleName ) }; final String password = "ignored"; UserDetails repositoryAdminUserDetails = new User( repositoryAdminUsername, password, true, true, true, true, repositoryAdminAuthorities ); Authentication repositoryAdminAuthentication = new UsernamePasswordAuthenticationToken( repositoryAdminUserDetails, password, repositoryAdminAuthorities ); PentahoSessionHolder.setSession( pentahoSession ); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication( repositoryAdminAuthentication ); } private void logout() { PentahoSessionHolder.removeSession(); SecurityContextHolder.getContext().setAuthentication( null ); } /** * Logs in with given username. * * @param username * username of user * @param tenantId * tenant to which this user belongs * @tenantAdmin true to add the tenant admin authority to the user's roles */ private void login( final String username, final ITenant tenant, String[] roles ) { StandaloneSession pentahoSession = new StandaloneSession( username ); pentahoSession.setAuthenticated( tenant.getId(), username ); PentahoSessionHolder.setSession( pentahoSession ); pentahoSession.setAttribute( IPentahoSession.TENANT_ID_KEY, tenant.getId() ); final String password = "password"; List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); for ( String roleName : roles ) { authList.add( new GrantedAuthorityImpl( roleName ) ); } GrantedAuthority[] authorities = authList.toArray( new GrantedAuthority[0] ); UserDetails userDetails = new User( username, password, true, true, true, true, authorities ); Authentication auth = new UsernamePasswordAuthenticationToken( userDetails, password, authorities ); PentahoSessionHolder.setSession( pentahoSession ); // this line necessary for Spring Security's MethodSecurityInterceptor SecurityContextHolder.getContext().setAuthentication( auth ); createUserHomeFolder( tenant, username ); } private ITenant getTenant( String principalId, boolean isUser ) { ITenant tenant = null; ITenantedPrincipleNameResolver nameUtils = isUser ? userNameUtils : roleNameUtils; if ( nameUtils != null ) { tenant = nameUtils.getTenant( principalId ); } if ( tenant == null || tenant.getId() == null ) { tenant = getCurrentTenant(); } return tenant; } private ITenant getCurrentTenant() { if ( PentahoSessionHolder.getSession() != null ) { String tenantId = (String) PentahoSessionHolder.getSession().getAttribute( IPentahoSession.TENANT_ID_KEY ); return tenantId != null ? new Tenant( tenantId, true ) : null; } else { return null; } } private String getPrincipalName( String principalId, boolean isUser ) { String principalName = null; ITenantedPrincipleNameResolver nameUtils = isUser ? userNameUtils : roleNameUtils; if ( nameUtils != null ) { principalName = nameUtils.getPrincipleName( principalId ); } return principalName; } private void createUserHomeFolder( final ITenant theTenant, final String theUsername ) { IPentahoSession origPentahoSession = PentahoSessionHolder.getSession(); Authentication origAuthentication = SecurityContextHolder.getContext().getAuthentication(); StandaloneSession pentahoSession = new StandaloneSession( repositoryAdminUsername ); pentahoSession.setAuthenticated( null, repositoryAdminUsername ); PentahoSessionHolder.setSession( pentahoSession ); try { txnTemplate.execute( new TransactionCallbackWithoutResult() { public void doInTransactionWithoutResult( final TransactionStatus status ) { Builder aclsForUserHomeFolder = null; Builder aclsForTenantHomeFolder = null; ITenant tenant = null; String username = null; if ( theTenant == null ) { tenant = getTenant( username, true ); username = getPrincipalName( theUsername, true ); } else { tenant = theTenant; username = theUsername; } if ( tenant == null || tenant.getId() == null ) { tenant = getCurrentTenant(); } if ( tenant == null || tenant.getId() == null ) { tenant = JcrTenantUtils.getDefaultTenant(); } RepositoryFile userHomeFolder = null; String userId = userNameUtils.getPrincipleId( theTenant, username ); final RepositoryFileSid userSid = new RepositoryFileSid( userId ); RepositoryFile tenantHomeFolder = null; RepositoryFile tenantRootFolder = null; // Get the Tenant Root folder. If the Tenant Root folder does not exist then exit. tenantRootFolder = repositoryFileDao.getFileByAbsolutePath( ServerRepositoryPaths.getTenantRootFolderPath( theTenant ) ); if ( tenantRootFolder != null ) { // Try to see if Tenant Home folder exist tenantHomeFolder = repositoryFileDao.getFileByAbsolutePath( ServerRepositoryPaths.getTenantHomeFolderPath( theTenant ) ); if ( tenantHomeFolder == null ) { String ownerId = userNameUtils.getPrincipleId( theTenant, username ); RepositoryFileSid ownerSid = new RepositoryFileSid( ownerId, Type.USER ); String tenantAuthenticatedRoleId = roleNameUtils.getPrincipleId( theTenant, tenantAuthenticatedRoleName ); RepositoryFileSid tenantAuthenticatedRoleSid = new RepositoryFileSid( tenantAuthenticatedRoleId, Type.ROLE ); aclsForTenantHomeFolder = new RepositoryFileAcl.Builder( userSid ).ace( tenantAuthenticatedRoleSid, EnumSet .of( RepositoryFilePermission.READ ) ); aclsForUserHomeFolder = new RepositoryFileAcl.Builder( userSid ).ace( ownerSid, EnumSet.of( RepositoryFilePermission.ALL ) ); tenantHomeFolder = repositoryFileDao.createFolder( tenantRootFolder.getId(), new RepositoryFile.Builder( ServerRepositoryPaths.getTenantHomeFolderName() ).folder( true ).build(), aclsForTenantHomeFolder .build(), "tenant home folder" ); } else { String ownerId = userNameUtils.getPrincipleId( theTenant, username ); RepositoryFileSid ownerSid = new RepositoryFileSid( ownerId, Type.USER ); aclsForUserHomeFolder = new RepositoryFileAcl.Builder( userSid ).ace( ownerSid, EnumSet.of( RepositoryFilePermission.ALL ) ); } // now check if user's home folder exist userHomeFolder = repositoryFileDao.getFileByAbsolutePath( ServerRepositoryPaths.getUserHomeFolderPath( theTenant, username ) ); if ( userHomeFolder == null ) { userHomeFolder = repositoryFileDao.createFolder( tenantHomeFolder.getId(), new RepositoryFile.Builder( username ) .folder( true ).build(), aclsForUserHomeFolder.build(), "user home folder" ); //$NON-NLS-1$ } } } } ); } finally { // Switch our identity back to the original user. PentahoSessionHolder.setSession( origPentahoSession ); SecurityContextHolder.getContext().setAuthentication( origAuthentication ); } } private void cleanupUserAndRoles( final ITenant tenant ) { loginAsRepositoryAdmin(); for ( IPentahoRole role : testUserRoleDao.getRoles( tenant ) ) { testUserRoleDao.deleteRole( role ); } for ( IPentahoUser user : testUserRoleDao.getUsers( tenant ) ) { testUserRoleDao.deleteUser( user ); } } @After public void tearDown() throws Exception { // null out fields to get back memory authorizationPolicy = null; login( sysAdminUserName, systemTenant, new String[] { singleTenantAdminRoleName, tenantAuthenticatedRoleName } ); ITenant tenant = tenantManager.getTenant( "/" + ServerRepositoryPaths.getPentahoRootFolderName() + "/" + TENANT_ID_ACME ); if ( tenant != null ) { cleanupUserAndRoles( tenant ); } login( sysAdminUserName, systemTenant, new String[] { singleTenantAdminRoleName, tenantAuthenticatedRoleName } ); tenant = tenantManager.getTenant( "/" + ServerRepositoryPaths.getPentahoRootFolderName() + "/" + TENANT_ID_DUFF ); if ( tenant != null ) { cleanupUserAndRoles( tenant ); } cleanupUserAndRoles( systemTenant ); SimpleJcrTestUtils.deleteItem( testJcrTemplate, ServerRepositoryPaths.getPentahoRootFolderPath() ); logout(); repositoryAdminUsername = null; singleTenantAdminRoleName = null; tenantAuthenticatedRoleName = null; // roleBindingDao = null; authorizationPolicy = null; testJcrTemplate = null; // null out fields to get back memory tenantManager = null; repo = null; mp.stop(); } @Override protected void delete( ObjectId id ) { if ( id != null ) { repo.deleteFile( id.getId(), true, null ); } } /** * Tries twice to delete files. By not failing outright on the first pass, we hopefully eliminate files that are * holding references to the files we cannot delete. */ protected void safelyDeleteAll( final ObjectId[] ids ) throws Exception { Exception firstException = null; List<String> frozenIds = new ArrayList<String>(); for ( ObjectId id : ids ) { frozenIds.add( id.getId() ); } List<String> remainingIds = new ArrayList<String>(); for ( ObjectId id : ids ) { remainingIds.add( id.getId() ); } try { for ( int i = 0; i < frozenIds.size(); i++ ) { repo.deleteFile( frozenIds.get( i ), true, null ); remainingIds.remove( frozenIds.get( i ) ); } } catch ( Exception e ) { e.printStackTrace(); } if ( !remainingIds.isEmpty() ) { List<String> frozenIds2 = remainingIds; List<String> remainingIds2 = new ArrayList<String>(); for ( String id : frozenIds2 ) { remainingIds2.add( id ); } try { for ( int i = 0; i < frozenIds2.size(); i++ ) { repo.deleteFile( frozenIds2.get( i ), true, null ); remainingIds2.remove( frozenIds2.get( i ) ); } } catch ( Exception e ) { if ( firstException == null ) { firstException = e; } } if ( !remainingIds2.isEmpty() ) { throw firstException; } } } @Override public void setApplicationContext( final ApplicationContext applicationContext ) throws BeansException { SessionFactory jcrSessionFactory = (SessionFactory) applicationContext.getBean( "jcrSessionFactory" ); testJcrTemplate = new JcrTemplate( jcrSessionFactory ); testJcrTemplate.setAllowCreate( true ); testJcrTemplate.setExposeNativeSession( true ); repositoryAdminUsername = (String) applicationContext.getBean( "repositoryAdminUsername" ); superAdminRoleName = (String) applicationContext.getBean( "superAdminAuthorityName" ); sysAdminUserName = (String) applicationContext.getBean( "superAdminUserName" ); tenantAuthenticatedRoleName = (String) applicationContext.getBean( "singleTenantAuthenticatedAuthorityName" ); singleTenantAdminRoleName = (String) applicationContext.getBean( "singleTenantAdminAuthorityName" ); tenantManager = (ITenantManager) applicationContext.getBean( "tenantMgrProxy" ); roleBindingDaoTarget = (IRoleAuthorizationPolicyRoleBindingDao) applicationContext .getBean( "roleAuthorizationPolicyRoleBindingDaoTarget" ); authorizationPolicy = (IAuthorizationPolicy) applicationContext.getBean( "authorizationPolicy" ); repo = (IUnifiedRepository) applicationContext.getBean( "unifiedRepository" ); userRoleDao = (IUserRoleDao) applicationContext.getBean( "userRoleDao" ); repositoryFileDao = (IRepositoryFileDao) applicationContext.getBean( "repositoryFileDao" ); testUserRoleDao = userRoleDao; repositoryLifecyleManager = (IBackingRepositoryLifecycleManager) applicationContext.getBean( "defaultBackingRepositoryLifecycleManager" ); txnTemplate = (TransactionTemplate) applicationContext.getBean( "jcrTransactionTemplate" ); TestPrincipalProvider.userRoleDao = testUserRoleDao; TestPrincipalProvider.adminCredentialsStrategy = (CredentialsStrategy) applicationContext.getBean( "jcrAdminCredentialsStrategy" ); TestPrincipalProvider.repository = (Repository) applicationContext.getBean( "jcrRepository" ); } @Override protected RepositoryDirectoryInterface loadStartDirectory() throws Exception { RepositoryDirectoryInterface rootDir = repository.loadRepositoryDirectoryTree(); RepositoryDirectoryInterface startDir = rootDir.findDirectory( "public" ); assertNotNull( startDir ); return startDir; } /** * Allow PentahoSystem to create this class but it in turn delegates to the authorizationPolicy fetched from Spring's * ApplicationContext. */ public static class DelegatingAuthorizationPolicy implements IAuthorizationPolicy { public List<String> getAllowedActions( final String actionNamespace ) { return authorizationPolicy.getAllowedActions( actionNamespace ); } public boolean isAllowed( final String actionName ) { return authorizationPolicy.isAllowed( actionName ); } } @Test public void testUiDelete() throws Exception { RepositoryDirectoryInterface rootDir = repository.loadRepositoryDirectoryTree(); final String startDirName = "home"; final String testDirName = "testdir"; final String startDirPath = "/" + startDirName; final String testDirPath = startDirPath + "/" + testDirName; RepositoryDirectoryInterface startDir = rootDir.findDirectory( startDirName ); final RepositoryDirectoryInterface testDirCreated = repository.createRepositoryDirectory( startDir, testDirName ); assertNotNull( testDirCreated ); assertNotNull( testDirCreated.getObjectId() ); rootDir = repository.loadRepositoryDirectoryTree(); final RepositoryDirectoryInterface startDirFound = repository.findDirectory( startDirPath ); final RepositoryDirectoryInterface testDirFound = repository.findDirectory( testDirPath ); Assert.assertNotNull( testDirFound ); final UIEERepositoryDirectory startDirUi = new UIEERepositoryDirectory( startDirFound, null, repository ); final UIEERepositoryDirectory testDirUi = new UIEERepositoryDirectory( testDirFound, startDirUi, repository ); testDirUi.delete( true ); RepositoryDirectoryInterface testDirFound2 = repository.findDirectory( testDirPath ); Assert.assertNull( testDirFound2 ); } @Test public void testUiDeleteNotEmpty() throws Exception { RepositoryDirectoryInterface rootDir = repository.loadRepositoryDirectoryTree(); final String startDirName = "home"; final String testDirName = "testdir"; final String testDir2Name = "testdir2"; final String startDirPath = "/" + startDirName; final String testDirPath = startDirPath + "/" + testDirName; final String testDir2Path = testDirPath + "/" + testDir2Name; RepositoryDirectoryInterface startDir = rootDir.findDirectory( startDirName ); final RepositoryDirectoryInterface testDirCreated = repository.createRepositoryDirectory( startDir, testDirName ); final RepositoryDirectoryInterface testDir2Created = repository.createRepositoryDirectory( testDirCreated, testDir2Name ); assertNotNull( testDirCreated ); assertNotNull( testDirCreated.getObjectId() ); assertNotNull( testDir2Created ); rootDir = repository.loadRepositoryDirectoryTree(); startDir = rootDir.findDirectory( startDirName ); final RepositoryDirectoryInterface startDirFound = repository.findDirectory( startDirPath ); final RepositoryDirectoryInterface testDirFound = repository.findDirectory( testDirPath ); Assert.assertNotNull( testDirFound ); final RepositoryDirectoryInterface testDir2Found = repository.findDirectory( testDir2Path ); Assert.assertNotNull( testDir2Found ); final UIEERepositoryDirectory startDirUi = new UIEERepositoryDirectory( startDirFound, null, repository ); final UIEERepositoryDirectory testDirUi = new UIEERepositoryDirectory( testDirFound, startDirUi, repository ); testDirUi.delete( true ); RepositoryDirectoryInterface testDirFound2 = repository.findDirectory( testDirPath ); Assert.assertNull( testDirFound2 ); } @Override @Test @Ignore public void testVarious() throws Exception { } @Override @Test @Ignore public void testDirectories() throws Exception { } @Override @Test @Ignore public void testJobs() throws Exception { } @Override @Test @Ignore public void testTransformations() throws Exception { } @Override @Test @Ignore public void testPartitionSchemas() throws Exception { } @Override @Test @Ignore public void testClusterSchemas() throws Exception { } @Override @Test @Ignore public void testDatabases() throws Exception { } @Override @Test @Ignore public void testSlaves() throws Exception { } @Override @Test @Ignore public void testRenameAndUndelete() throws Exception { } @Override @Test @Ignore public void testVersions() throws Exception { } @Override @Test @Ignore public void testGetSecurityProvider() throws Exception { } @Override @Test @Ignore public void testGetVersionRegistry() throws Exception { } @Override @Test @Ignore public void testInsertJobEntryDatabase() throws Exception { } @Override @Test @Ignore public void testInsertLogEntry() throws Exception { } @Override @Test @Ignore public void testInsertStepDatabase() throws Exception { } @Override @Test @Ignore public void testLoadConditionFromStepAttribute() throws Exception { } @Override @Test @Ignore public void testLoadDatabaseMetaFromJobEntryAttribute() throws Exception { } @Override @Test @Ignore public void testLoadDatabaseMetaFromStepAttribute() throws Exception { } @Override @Test @Ignore public void testReadJobMetaSharedObjects() throws Exception { } @Override @Test @Ignore public void testReadTransSharedObjects() throws Exception { } @Override @Test @Ignore public void testSaveConditionStepAttribute() throws Exception { } @Override @Test @Ignore public void testGetAcl() throws Exception { } @Override @Test @Ignore public void testSetAcl() throws Exception { } @Override @Test @Ignore public void testSaveDatabaseMetaJobEntryAttribute() throws Exception { } @Override @Test @Ignore public void testSaveDatabaseMetaStepAttribute() throws Exception { } }
40.563659
121
0.740553
ff5e2aef1d505ce6ebc678c975fb37f468277880
370
package io.renren.modules.house.service; import com.baomidou.mybatisplus.service.IService; import io.renren.common.utils.PageUtils; import io.renren.modules.house.entity.TmMbodycardEntity; import java.util.List; import java.util.Map; public interface TmMbodycardService extends IService<TmMbodycardEntity> { PageUtils queryEntity(Map<String, Object> params); }
24.666667
73
0.813514
285d8fe67f621e5c7ed573bc4e55cb25a132be6a
1,068
/* */ package com.cyc.baseclient.inference.metrics; import com.cyc.base.inference.InferenceParameterValue; import com.cyc.base.inference.metrics.InferenceMetric; import com.cyc.base.inference.metrics.InferenceMetricsI; import java.util.HashSet; import com.cyc.base.cycobject.CycList; import com.cyc.base.cycobject.CycSymbolI; import com.cyc.baseclient.cycobject.CycArrayList; /** * The preferred value type for the :METRICS inference parameter. * See {@link com.cyc.baseclient.inference.params.InferenceParameters#setMetrics(com.cyc.baseclient.inference.metrics.InferenceMetrics)} * * @author baxter */ public class InferenceMetrics extends HashSet<InferenceMetric> implements InferenceMetricsI { @Override public String stringApiValue() { return cycListApiValue().stringApiValue(); } @Override public CycList cycListApiValue() { final CycList cyclistApiValue = new CycArrayList<CycSymbolI>(this.size()); for (final InferenceMetric metric : this) { cyclistApiValue.add(metric.getName()); } return cyclistApiValue; } }
28.864865
136
0.773408
9046647b9526f6b683addbb521e66cf7b95db32e
2,336
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.dingtalkindustry_1_0.models; import com.aliyun.tea.*; public class QueryUserExtInfoResponseBody extends TeaModel { // 扩展属性 @NameInMap("content") public java.util.List<QueryUserExtInfoResponseBodyContent> content; public static QueryUserExtInfoResponseBody build(java.util.Map<String, ?> map) throws Exception { QueryUserExtInfoResponseBody self = new QueryUserExtInfoResponseBody(); return TeaModel.build(map, self); } public QueryUserExtInfoResponseBody setContent(java.util.List<QueryUserExtInfoResponseBodyContent> content) { this.content = content; return this; } public java.util.List<QueryUserExtInfoResponseBodyContent> getContent() { return this.content; } public static class QueryUserExtInfoResponseBodyContent extends TeaModel { // 扩展属性Key @NameInMap("userExtendKey") public String userExtendKey; // 扩展属性值 @NameInMap("userExtendValue") public String userExtendValue; // 扩展属性描述 @NameInMap("userExtendDisplayName") public String userExtendDisplayName; public static QueryUserExtInfoResponseBodyContent build(java.util.Map<String, ?> map) throws Exception { QueryUserExtInfoResponseBodyContent self = new QueryUserExtInfoResponseBodyContent(); return TeaModel.build(map, self); } public QueryUserExtInfoResponseBodyContent setUserExtendKey(String userExtendKey) { this.userExtendKey = userExtendKey; return this; } public String getUserExtendKey() { return this.userExtendKey; } public QueryUserExtInfoResponseBodyContent setUserExtendValue(String userExtendValue) { this.userExtendValue = userExtendValue; return this; } public String getUserExtendValue() { return this.userExtendValue; } public QueryUserExtInfoResponseBodyContent setUserExtendDisplayName(String userExtendDisplayName) { this.userExtendDisplayName = userExtendDisplayName; return this; } public String getUserExtendDisplayName() { return this.userExtendDisplayName; } } }
33.855072
113
0.687072
149e43951bd32b9825b294b4de646ee029268011
778
package org.deuce.benchmark.stmbench7.impl.backend; import java.util.ArrayList; import org.deuce.benchmark.stmbench7.annotations.ContainedInAtomic; import org.deuce.benchmark.stmbench7.backend.ImmutableCollection; /** * A simple implementation of a small-size set * (used by Assembly and AtomicPart objects). */ @ContainedInAtomic public class SmallSetImpl<E> extends ArrayList<E> { private static final long serialVersionUID = 8608574819902616324L; public SmallSetImpl() { super(); } public SmallSetImpl(SmallSetImpl<E> source) { super(source); } public boolean add(E element) { if(contains(element)) return false; super.add(element); return true; } public ImmutableCollection<E> immutableView() { return new ImmutableViewImpl<E>(this); } }
21.611111
67
0.757069
6559507fd65e13ab124fda9d604305c16681109d
1,129
package com.html5parser.constants; public class HTML5Elements { public static final String[] FORMATTING = { "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u" }; public static final String[] SPECIAL = { "address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "isindex", "li", "link", "listing", "main", "marquee", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", "section", "select", "source", "style", "summary", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp", "mi", "mo", "mn", "ms", "mtext", "annotation-xml", "foreignObject", "desc", "title" }; }
47.041667
76
0.534101
b238dff65740fe0e692b05c89dda04f67589816a
2,168
package com.code10.isa.controller; import com.code10.isa.controller.exception.BadRequestException; import com.code10.isa.model.Restaurant; import com.code10.isa.model.dto.EmployeeRegisterDto; import com.code10.isa.model.user.Manager; import com.code10.isa.model.user.Waiter; import com.code10.isa.service.AuthService; import com.code10.isa.service.WaiterService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/waiters") public class WaiterController { private final WaiterService waiterService; private final AuthService authService; @Autowired public WaiterController(WaiterService waiterService, AuthService authService) { this.waiterService = waiterService; this.authService = authService; } @PreAuthorize("hasAuthority('MANAGER')") @PostMapping public ResponseEntity create(@RequestBody EmployeeRegisterDto registerDto) { if (authService.emailTaken(registerDto)) { throw new BadRequestException("Email taken!"); } if (!registerDto.fieldsPopulated()) { throw new BadRequestException("Please enter all fields!"); } if (!registerDto.passwordsMatch()) { throw new BadRequestException("Passwords not matching!"); } Manager manager = (Manager) authService.getCurrentUser(); Restaurant restaurant = manager.getRestaurant(); final Waiter waiter = waiterService.create(registerDto, restaurant); return new ResponseEntity<>(waiter, HttpStatus.CREATED); } @PreAuthorize("hasAuthority('MANAGER')") @GetMapping("/myWaiters") public ResponseEntity findByRestaurant() { Manager manager = (Manager) authService.getCurrentUser(); List<Waiter> waiters = waiterService.findByRestaurant(manager.getRestaurant().getId()); return new ResponseEntity<>(waiters, HttpStatus.OK); } }
33.875
95
0.733395
7ebededa1c7888e31da850d940906290cd5ed0a7
2,419
package de.nx42.maps4cim.util.arr2d; import static org.junit.Assert.fail; import org.junit.Test; public class GapInterpolatorTest { protected static final short g = -9; protected static final short[][] testArr = new short[][]{ { g,1,1,2,2,2 }, { 1,1,g,g,2,2 }, { 1,1,g,2,2,2 }, { 2,2,g,3,3,3 }, { 2,2,2,3,g,3 }, { 2,2,g,3,g,g } }; protected static final short[][] testArr2 = new short[][]{ { 1,1,1,1,1,1,2,2,2,2,2,2 }, { 1,1,1,g,1,1,2,2,2,2,2,2 }, { 1,1,1,g,1,1,2,2,2,2,2,2 }, { 1,1,1,1,1,1,2,g,g,g,g,g }, { g,1,1,1,1,1,2,2,2,2,2,2 }, { g,g,1,1,1,1,2,2,2,2,2,2 }, { g,g,2,2,2,2,3,3,3,3,3,3 }, { g,g,2,2,2,2,3,3,3,3,3,3 }, { g,g,g,2,2,2,3,g,g,g,g,3 }, { g,g,2,2,2,2,g,g,g,g,g,g }, { g,g,2,2,2,2,3,g,g,g,g,3 }, { 2,2,2,2,2,2,3,3,g,g,3,3 } }; protected static final short[][] testArr3 = new short[][]{ { 1,1,1,1,1,1,2,2,2,2,2,2 }, { 1,1,1,g,g,g,g,g,g,g,2,2 }, { 1,1,1,g,g,g,g,g,g,g,2,2 }, { 1,1,1,g,g,g,g,g,g,g,g,g }, { g,1,g,g,g,g,g,g,g,2,2,2 }, { g,g,g,g,g,g,g,g,g,2,2,2 }, { g,g,g,g,g,g,g,g,g,3,3,3 }, { g,g,g,g,g,g,g,g,g,3,3,3 }, { g,g,g,g,g,g,g,g,g,g,g,3 }, { g,g,g,g,g,g,g,g,g,g,g,3 }, { g,g,2,2,2,2,3,g,g,g,g,3 }, { 2,2,2,2,2,2,3,3,g,g,3,3 } }; @Test public void testFullArray() { try { GapInterpolator gip = new GapInterpolator(g); float[][] result = copy(testArr3); for (int y = 0; y < result.length; y++) { for (int x = 0; x < result[0].length; x++) { if(result[y][x] == g) { result[y][x] = gip.star(testArr3, x, y); } } } } catch(Exception e) { fail(e.getMessage()); } } @Test public void testStar() throws Exception { GapInterpolator gip = new GapInterpolator(g); float res = gip.star(testArr, 5, 5); } protected static float[][] copy(short[][] input) { float[][] output = new float[input.length][input[0].length]; for (int i = 0; i < input.length; i++) { for (int j = 0; j < input[0].length; j++) { output[i][j] = input[i][j]; } } return output; } }
28.458824
68
0.424142
4d7ec35f7c38728b873ec71c49824919aa8a8e3a
3,988
package org.bouncycastle.asn1.cmp; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.DERInteger; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.DERSequence; public class CertResponse extends ASN1Encodable { private DERInteger certReqId; private PKIStatusInfo status; private CertifiedKeyPair certifiedKeyPair; private ASN1OctetString rspInfo; private CertResponse(ASN1Sequence seq) { certReqId = DERInteger.getInstance(seq.getObjectAt(0)); status = PKIStatusInfo.getInstance(seq.getObjectAt(1)); if (seq.size() >= 3) { if (seq.size() == 3) { DEREncodable o = seq.getObjectAt(2); if (o instanceof ASN1OctetString) { rspInfo = ASN1OctetString.getInstance(o); } else { certifiedKeyPair = CertifiedKeyPair.getInstance(o); } } else { certifiedKeyPair = CertifiedKeyPair.getInstance(seq.getObjectAt(2)); rspInfo = ASN1OctetString.getInstance(seq.getObjectAt(3)); } } } public static CertResponse getInstance(Object o) { if (o instanceof CertResponse) { return (CertResponse)o; } if (o instanceof ASN1Sequence) { return new CertResponse((ASN1Sequence)o); } throw new IllegalArgumentException("Invalid object: " + o.getClass().getName()); } public CertResponse( DERInteger certReqId, PKIStatusInfo status) { this(certReqId, status, null, null); } public CertResponse( DERInteger certReqId, PKIStatusInfo status, CertifiedKeyPair certifiedKeyPair, ASN1OctetString rspInfo) { if (certReqId == null) { throw new IllegalArgumentException("'certReqId' cannot be null"); } if (status == null) { throw new IllegalArgumentException("'status' cannot be null"); } this.certReqId = certReqId; this.status = status; this.certifiedKeyPair = certifiedKeyPair; this.rspInfo = rspInfo; } public DERInteger getCertReqId() { return certReqId; } public PKIStatusInfo getStatus() { return status; } public CertifiedKeyPair getCertifiedKeyPair() { return certifiedKeyPair; } /** * <pre> * CertResponse ::= SEQUENCE { * certReqId INTEGER, * -- to match this response with corresponding request (a value * -- of -1 is to be used if certReqId is not specified in the * -- corresponding request) * status PKIStatusInfo, * certifiedKeyPair CertifiedKeyPair OPTIONAL, * rspInfo OCTET STRING OPTIONAL * -- analogous to the id-regInfo-utf8Pairs string defined * -- for regInfo in CertReqMsg [CRMF] * } * </pre> * @return a basic ASN.1 object representation. */ public DERObject toASN1Object() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(certReqId); v.add(status); if (certifiedKeyPair != null) { v.add(certifiedKeyPair); } if (rspInfo != null) { v.add(rspInfo); } return new DERSequence(v); } }
28.485714
95
0.545888
7b1250259f333e58898589c9a172e7553dc07b61
4,468
package com.kieferhagin.gravestones; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import net.canarymod.Canary; import net.canarymod.api.chat.ChatComponent; import net.canarymod.api.entity.living.humanoid.Player; import net.canarymod.api.factory.ChatComponentFactory; import net.canarymod.api.inventory.Item; import net.canarymod.api.inventory.PlayerInventory; import net.canarymod.api.world.World; import net.canarymod.api.world.blocks.BlockType; import net.canarymod.api.world.blocks.Chest; import net.canarymod.api.world.blocks.Sign; import net.canarymod.api.world.position.Location; public class Gravestone { private Location location; private Player player; private Chest chest; /** * Create a new gravestone container * @param player The player that the gravestone will contain * @param location The location of the gravestone (the stone stair) */ public Gravestone(Player player, Location location){ this.location = location; this.player = player; } /** * Generate the gravestone in the world and bury the player's items */ public void buryPlayer(ChatComponent causeOfDeath){ this.chest = this.generate(causeOfDeath); this.addPlayerItemsToChest(); } private Chest generate(ChatComponent causeOfDeath){ World world = this.location.getWorld(); // Place the blocks in such a way where the double chest is parallel with the stone stair Location stoneStairLocation = new Location(this.location); Location[] chestLocations = { new Location(stoneStairLocation.getX(), stoneStairLocation.getY()-1, stoneStairLocation.getZ()), new Location(stoneStairLocation.getX(), stoneStairLocation.getY()-1, stoneStairLocation.getZ() - 1) }; Location signLocation = new Location(stoneStairLocation.getX(), stoneStairLocation.getY(), stoneStairLocation.getZ() - 2); this.addSign(signLocation, causeOfDeath); world.setBlockAt(stoneStairLocation, BlockType.StoneBrickStair); for (Location chestLoc : chestLocations){ world.setBlockAt(chestLoc, BlockType.Chest); } return (Chest)(world.getBlockAt(chestLocations[1]).getTileEntity()); } private void addSign(Location signLocation, ChatComponent causeOfDeath){ World world = signLocation.getWorld(); world.setBlockAt(signLocation, BlockType.SignPost); Sign sign = (Sign)(world.getBlockAt(signLocation).getTileEntity()); ChatComponentFactory chatFactory = Canary.factory().getChatComponentFactory(); ChatComponent nameComponent = chatFactory.compileChatComponent(this.player.getName()); ChatComponent timeOfDeathComponent = chatFactory.compileChatComponent(this.getDateNowString()); String fullDeathText = causeOfDeath.getFullText().replace(this.player.getName() + " ", ""); ArrayList<ChatComponent> deathTextLines = new ArrayList<ChatComponent>(); if (fullDeathText.length() > 10){ deathTextLines.add(chatFactory.compileChatComponent(fullDeathText.substring(0, 9))); deathTextLines.add(chatFactory.compileChatComponent(fullDeathText.substring(9))); } else { deathTextLines.add(chatFactory.compileChatComponent(fullDeathText)); } sign.setComponentOnLine(nameComponent, 0); sign.setComponentOnLine(timeOfDeathComponent, 1); sign.setComponentOnLine(deathTextLines.get(0), 2); if (deathTextLines.size() > 1){ sign.setComponentOnLine(deathTextLines.get(1), 3); } } private String getDateNowString(){ Date nowDate = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a"); return dateFormat.format(nowDate); } private void addPlayerItemsToChest(){ PlayerInventory inventory = this.player.getInventory(); // Get the players equipment details, and clear it out to keep it from dropping Item boots = inventory.getBootsSlot(); Item chestplate = inventory.getChestplateSlot(); Item legs = inventory.getLeggingsSlot(); Item helmet = inventory.getHelmetSlot(); inventory.setBootsSlot(null); inventory.setChestPlateSlot(null); inventory.setLeggingsSlot(null); inventory.setHelmetSlot(null); // Add all the equipped and inventory items to the chest Item[] equippedItems = {boots, chestplate, legs, helmet}; Item[] inventoryItems = inventory.clearInventory(); for (Item item : equippedItems){ if (item != null){ chest.addItem(item); } } for (Item item : inventoryItems){ if (item != null){ chest.addItem(item); } } } }
32.613139
97
0.751343
05d1b416798ab8646a33f467851b576e0a2cdc47
121
package crazypants.enderio.item.darksteel; public interface IDarkSteelItem { int getIngotsRequiredForFullRepair(); }
17.285714
42
0.818182
4c6eef6c9d3bb9ebc665e3423843defe9324c61f
5,238
/* * Copyright (c) 2014 Simon Robinson * * 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 qr.cloud.qrpedia; import qr.cloud.util.QRCloudDatabase; import qr.cloud.util.QRCloudProvider; import qr.cloud.util.QRCloudUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import com.actionbarsherlock.app.SherlockListFragment; public class SavedTextListFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { OnSavedTextSelectedListener mCallback; public interface OnSavedTextSelectedListener { public void onSavedTextSelected(long position); } private static final int MESSAGE_LIST_LOADER = 0x01; private SimpleCursorAdapter mCursorAdapter; private boolean mIsInDialog = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // start loading content getLoaderManager().initLoader(MESSAGE_LIST_LOADER, null, this); String[] bindFrom = { QRCloudDatabase.COL_MESSAGE }; int[] bindTo = { R.id.imported_text }; mCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.import_text_row, null, bindFrom, bindTo, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); setListAdapter(mCursorAdapter); } @Override public void onAttach(Activity activity) { super.onAttach(activity); // make sure that the container activity has implemented the callback interface try { mCallback = (OnSavedTextSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement " + OnSavedTextSelectedListener.class.toString()); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // configure the list view ListView listView = getListView(); QRCloudUtils.setListViewEmptyView(listView, getString(R.string.no_saved_messages), R.string.default_font, R.dimen.activity_horizontal_margin, R.dimen.activity_vertical_margin); listView.setSelector(R.drawable.message_row_selector); // override the default selector listView.setDivider(new ColorDrawable(this.getResources().getColor(R.color.list_divider))); listView.setDividerHeight(1); listView.setOnItemLongClickListener(mLongClickListener); if (mIsInDialog && Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // fix black background issue pre-honeycomb listView.setBackgroundColor(Color.WHITE); } } public void setIsInDialog(boolean isInDialog) { mIsInDialog = isInDialog; // for fixing pre-Honeycomb dialog display issue } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { CursorLoader cursorLoader = new CursorLoader(getActivity(), QRCloudProvider.CONTENT_URI_MESSAGES, QRCloudDatabase.PROJECTION_ID_MESSAGE, null, null, QRCloudDatabase.COL_DATE + " DESC"); return cursorLoader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mCursorAdapter.swapCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { mCursorAdapter.swapCursor(null); } @Override public void onListItemClick(ListView list, View view, int position, long id) { mCallback.onSavedTextSelected(id); } private OnItemLongClickListener mLongClickListener = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.clipping_options); builder.setItems(R.array.clipping_options_values, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String chosenValue = getResources().getStringArray(R.array.clipping_options_values)[which]; if (chosenValue.equals(getString(R.string.btn_delete))) { // delete the selected item getActivity().getContentResolver().delete( Uri.withAppendedPath(QRCloudProvider.CONTENT_URI_MESSAGES, String.valueOf(id)), null, null); } } }); builder.show(); return true; } }; }
35.391892
114
0.781405
05bee8cbdd1305963bc91ba5c1c21e2d4390485f
928
// <별점 테러 방지 프로그램 /> // "제품에 대한 별점 중에서 최솟값과 최댓값을 뺀 별점들의 평균값을 구하는 프로그램" public class RatingAverage { public static void main(String[] args) { //[1] Input int[] ratings = { 1, 2, 3, 4, 5 }; // int ratings[] = { 1, 2, 3, 4, 5 }; int max = ratings[0]; // 0번째 인덱스의 값으로 초기화 int min = ratings[0]; // 0번째 인덱스의 값으로 초기화 int sum = ratings[0]; // 0번째 인덱스의 값으로 초기화 //[2] Process: 하나의 for 문으로 합계, 최댓값, 최솟값을 계산 for (int i = 1; i < 5; i++) { // 인덱스를 1부터 시작 주의 sum += ratings[i]; if (ratings[i] > max) { max = ratings[i]; // 최댓값 구하기 } if (ratings[i] < min) { min = ratings[i]; // 최솟값 구하기 } } int rating = (sum - max - min) / (5 - 2); //[3] Output System.out.println("최댓값: " + max + ", 최솟값: " + min); System.out.println("최종 별점: " + rating); } }
32
80
0.449353
de6b5a3e9ee6ce65fb41763f75503d335a04db8e
350
package ro.ase.acs.observer; import java.util.HashMap; public class Website extends Observabil { private HashMap<String, String> newsletters=new HashMap<>(); public void adaugaNewsletter(String subiect, String mesaj) { newsletters.put(subiect, mesaj); } public String getContinut(String subiect) { return newsletters.get(subiect); } }
21.875
61
0.757143
3e68f933717edc937f76193fec253f63008b5771
3,661
package org.jdna.eloaa.server.qmonitor; /* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2016 GwtMaterialDesign * %% * 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% */ import org.jdna.eloaa.shared.model.MovieEntry; import static org.junit.Assert.*; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; /** * Created by seans on 10/08/16. */ public class QueueMonitorTest { @Test public void testFilename() throws Exception { QueueMonitor m = new QueueMonitor(); File source = new File("./dl/123.mkv"); MovieEntry me = new MovieEntry(); me.setTitle("My Title"); me.setYear("2014"); String name = m.filename(me, source); assertEquals("My Title (2014).mkv", name); me.setYear(null); name = m.filename(me, source); assertEquals("My Title.mkv", name); } @Test public void testResolveFile() throws Exception { QueueMonitor q = new QueueMonitor(); deleteDir("target/unittest/"); File dir = new File("target/unittest/dl/test1/"); dir.mkdirs(); Files.write(Paths.get(new File(dir, "m1.mkv").toURI()), "1".getBytes()); Files.write(Paths.get(new File(dir, "m2.mkv").toURI()), "11".getBytes()); Files.write(Paths.get(new File(dir, "m3.mkv").toURI()), "111".getBytes()); File f = q.resolveFile(dir); assertEquals("m3.mkv", f.getName()); assertEquals(3, f.length()); deleteDir("target/unittest/"); } @Test public void testFindLocalFile() throws Exception { QueueMonitor q = new QueueMonitor(); deleteDir("target/unittest/"); File dir = new File("target/unittest/dl/test1/subdir1/"); dir.mkdirs(); Files.write(Paths.get(new File(dir, "m1.mkv").toURI()), "1".getBytes()); File f = q.findLocalFile(new File("target/unittest/dl/test1/"), "/dl/test1/subdir1/m1.mkv"); assertEquals("m1.mkv", f.getName()); deleteDir("target/unittest/"); } @Test public void testStripPath() throws Exception { QueueMonitor q = new QueueMonitor(); String path; assertEquals("b/test.mkv", path=q.stripPath("/a/b/test.mkv")); assertEquals("test.mkv", path=q.stripPath(path)); assertNull(path=q.stripPath(path)); } public static void deleteDir(String dir) { Path directory = Paths.get(dir); try { Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } catch (Throwable t) { } } }
32.114035
107
0.614313
d81da642852a2212455c98c3d25bb9242da36749
1,890
package ml.varpeti.hf04java; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; public class ShowUsersActivity extends AppCompatActivity { FirebaseDatabase database; DatabaseReference reference; RecyclerView rw; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_users); database = FirebaseDatabase.getInstance(); reference = database.getReference("users"); rw = findViewById(R.id.rw); rw.setLayoutManager(new LinearLayoutManager(this)); reference.addValueEventListener(postListener()); } ValueEventListener postListener() { return new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { ArrayList<User> users = new ArrayList<>(); for (DataSnapshot ds: dataSnapshot.getChildren()) { User user = ds.getValue(User.class); Log.i("|||",user.name); users.add(user); } RecyclerView.Adapter adapter = new RecyclerViewAdapter(users); rw.setAdapter(adapter); } @Override public void onCancelled(DatabaseError databaseError) { //TODO } }; } }
28.208955
78
0.648148
328eb59a5aa17b19684b6736e5da8576cd599911
3,382
package com.example.invoke.dao; import com.example.invoke.dto.CommonDto; import com.example.invoke.model.Miui; import com.example.invoke.model.MiuiExample; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; @Repository(value = "miuiMapper") public interface MiuiMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int countByExample(MiuiExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int deleteByExample(MiuiExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int insert(Miui record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int insertSelective(Miui record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ List<Miui> selectByExample(MiuiExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ Miui selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int updateByExampleSelective(@Param("record") Miui record, @Param("example") MiuiExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int updateByExample(@Param("record") Miui record, @Param("example") MiuiExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int updateByPrimaryKeySelective(Miui record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table miui * * @mbggenerated Sat Sep 22 18:45:34 CST 2018 */ int updateByPrimaryKey(Miui record); @Select(value = "SELECT COUNT(author) value1,author category FROM miui GROUP BY author ORDER BY value1 desc limit 0,7") List<CommonDto> topAuthors(); @Select(value = "SELECT COUNT(phone_type) value1,phone_type category FROM miui WHERE phone_type like \"%米%\" GROUP BY phone_type ORDER BY value1 desc limit 0,7") List<CommonDto> topPhoneTypes(); }
32.519231
165
0.679184
c454b260c88a7c5ded91f6f347a9439ea2e4bb87
1,848
package com.heroland.competition.dal.pojo; import java.util.Date; public class HerolandSchoolCourse { private Long id; private String schoolKey; private Long courseId; private Integer obligatory; private Boolean isDeleted; private String creator; private String modifier; private Date gmtCreate; private Date gmtModified; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSchoolKey() { return schoolKey; } public void setSchoolKey(String schoolKey) { this.schoolKey = schoolKey == null ? null : schoolKey.trim(); } public Long getCourseId() { return courseId; } public void setCourseId(Long courseId) { this.courseId = courseId; } public Integer getObligatory() { return obligatory; } public void setObligatory(Integer obligatory) { this.obligatory = obligatory; } public Boolean getIsDeleted() { return isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator == null ? null : creator.trim(); } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier == null ? null : modifier.trim(); } public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } }
19.452632
69
0.622835
aecc754ad50451266b1d470df9769b85da4dbd4d
637
package com.codersoft.cms.wechat.mp.builder; import com.codersoft.cms.wechat.mp.service.WeixinService; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * 功能描述: 处理类 * * @param: * @return: * @auther: Yuanw * @email: [email protected] * @date: 2018年8月24日 上午11:11 */ public abstract class AbstractBuilder { protected final Logger logger = LoggerFactory.getLogger(getClass()); public abstract WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, WeixinService service) ; }
24.5
70
0.759812
85c4eb8eda63c8df82daf3ed18ef7f831c37608f
344
package cn.sy.mapper; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import cn.sy.domain.TbUser; import cn.sy.domain.User; @Mapper public interface TbUserMapper { List<TbUser> findAll(); TbUser findById(@Param("userId") String userId); }
17.2
52
0.744186
10b18f5aeced64eaa726ddee72df1321e7811e85
832
package vlqhoang.project.smartchoice.ProductPriceComparatorService.unitTests.repository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import vlqhoang.project.smartchoice.ProductPriceComparatorService.entity.ProductPriceEntity; import vlqhoang.project.smartchoice.ProductPriceComparatorService.repository.ProductPriceRepository; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @DataJpaTest public class ProductPriceRepositoryTest { @Autowired ProductPriceRepository productPriceRepository; @Test public void testFindAll() { List<ProductPriceEntity> records = productPriceRepository.findAll(); assertEquals(3, records.size()); } }
33.28
100
0.819712
3d36f48634944bf390af810083e0b6b2ccc04526
1,186
package ac.cn.saya.singleton; /** * @Title: SingletonUtil1 * @ProjectName java-utils * @Description: TODO * @Author liunengkai * @Date: 2019-07-10 20:45 * @Description: * 单例模式(懒汉式-线程不安全) */ public class SingletonUtil3 { public static void main(String []args){ for (int i = 0 ; i < 10 ; i++){ new Thread(() -> { System.out.println((SingletonClassUitl3.getInstance()).hashCode()); }).start(); } } } /** * @描述 懒汉式(线程不安全) * @参数 * @返回值 * @创建人 saya.ac.cn-刘能凯 * @创建时间 2019-07-10 * @修改人和其它信息 */ class SingletonClassUitl3{ /** * 本类内部创建对象实例 */ private static SingletonClassUitl3 instance; /** * @描述 构造器私有化 * @参数 * @返回值 * @创建人 saya.ac.cn-刘能凯 * @创建时间 2019-07-10 * @修改人和其它信息 */ private SingletonClassUitl3() { } /** * @描述 提供一个公有的静态方法,当使用到该方法时,才会创建insane * @参数 * @返回值 * @创建人 saya.ac.cn-刘能凯 * @创建时间 2019-07-10 * @修改人和其它信息 */ public static SingletonClassUitl3 getInstance(){ if (instance == null){ instance = new SingletonClassUitl3(); } return instance; } }
17.441176
83
0.53457
3e4b766df61d523d7e3e24ff95ca848f56f795ac
1,752
package MyService; import ProofOfWork.Creator; import Data.FileThread; import java.io.IOException; import java.net.Socket; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; import java.util.logging.Logger; import jdk.net.Sockets; import P2PTransfer.* ; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Dark */ public class Worker { public boolean Add(byte[] file , String title , String desc , String id ) { Creator c = new Creator () ; try { String proof = c.getProof(file) ; FileThread ft = new FileThread( file , proof.getBytes() , ".txt") ; ft.setMeta(title, desc ,id); P2PTransfer.Upload u = new P2PTransfer.Upload() ; u.broadCast((Socket[])LoadSockets.clients.toArray(), ft); P2PTransfer.Receive.save(ft); return true ; } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex); } return false; } public boolean Add(byte []file , FileThread ft ){ ft.Add(file); Upload u = new Upload() ; try { u.broadCast((Socket[])LoadSockets.clients.toArray(), ft); return true ; } catch (IOException ex) { Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex); } return false ; } }
32.444444
82
0.593607
6e1c9146dc367cd41e803428e53ab2e37099fec1
885
package cn.org.imaginary.common.common; import javax.mail.internet.MimeMessage; /** * Author : imaginary * Date : 2017/5/23 16 34 * Version : V1.0 * Desc : */ public interface MimeMessagePreparator { /** * Prepare the given new MimeMessage instance. * @param mimeMessage the message to prepare * @throws javax.mail.MessagingException passing any exceptions thrown by MimeMessage * methods through for automatic conversion to the MailException hierarchy * @throws java.io.IOException passing any exceptions thrown by MimeMessage methods * through for automatic conversion to the MailException hierarchy * @throws Exception if mail preparation failed, for example when a * Velocity template cannot be rendered for the mail text */ void prepare(MimeMessage mimeMessage) throws Exception; }
36.875
90
0.707345
ce5e974d27a6570d59b071b6bd32f358170f194f
1,606
package me.violinsolo.testlibsapp.base; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.viewbinding.ViewBinding; /** * @author violinsolo * @version Boman v0.1 * @createAt 2020/5/20 10:18 AM * @updateAt 2020/5/20 10:18 AM * <p> * Copyright (c) 2020 EmberXu.hack. All rights reserved. */ public abstract class BaseFragment<T extends ViewBinding> extends Fragment { protected T mBinder; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // return super.onCreateView(inflater, container, savedInstanceState); mBinder = onBind(inflater, container); bindListeners(); return mBinder.getRoot(); } /** * need to initilize the ViewBinding Class in every sub activity class. * * @return mBinder the field of view binding handler. Initialize it before use * eg. * mBinder = FragmentXMLNameBinding.inflate(inflater, container, boolean attachToParent = false); */ protected abstract T onBind(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent); /** * bind all listeners here. */ protected abstract void bindListeners(); }
27.689655
132
0.702366
9989a5ba79684a6aaa9718c7267eaed5a44e2ed4
8,109
package scratch.UCERF3.enumTreeBranches; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.dom4j.Document; import org.opensha.commons.util.ExceptionUtils; import org.opensha.commons.util.XMLUtils; import org.opensha.refFaultParamDb.vo.FaultSectionPrefData; import org.opensha.sha.faultSurface.FaultSection; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import scratch.UCERF3.logicTree.LogicTreeBranchNode; import scratch.UCERF3.utils.DeformationModelFetcher; import scratch.UCERF3.utils.FaultSystemIO; import scratch.UCERF3.utils.UCERF3_DataUtils; public enum DeformationModels implements LogicTreeBranchNode<DeformationModels> { // Name ShortName Weight FaultModel File // UCERF2 UCERF2_ALL( "UCERF2 All", "UC2ALL", 0d, FaultModels.FM2_1), UCERF2_NCAL( "UCERF2 NCal", "NCAL", 0d, FaultModels.FM2_1), UCERF2_BAYAREA( "UCERF2 Bay Area", "BAY", 0d, FaultModels.FM2_1), // UCERF3 // AVERAGE BLOCK MODEL ABM( "Average Block Model", "ABM", 0.10d, FaultModels.FM3_1, "ABM_slip_rake_fm_3_1_2013_04_09.csv", FaultModels.FM3_2, "ABM_slip_rake_fm_3_2_2013_04_09.csv"), // GEOBOUNDED INVERSION GEOBOUND( "Geobounded", "GEOB", 0d, FaultModels.FM3_1, "geobound_slip_rake__MAPPED_2012_06_05.csv"), // NEOKINEMA NEOKINEMA( "Neokinema", "NEOK", 0.30d, FaultModels.FM3_1, "neokinema_slip_rake_fm_3_1_2013_04_09.csv", FaultModels.FM3_2, "neokinema_slip_rake_fm_3_2_2013_04_09.csv"), // ZENG ZENG( "Zeng Unbounded", "ZENG", 0.00d, FaultModels.FM3_1, "zeng_slip_rake_fm_3_1_2012_10_11.csv", FaultModels.FM3_2, "zeng_slip_rake_fm_3_2_2012_10_11.csv"), ZENGAB( "Zeng All Bounded", "ZENGAB", 0.00d, FaultModels.FM3_1, "zeng_slip_rake_fm_3_1_all_bounded_2013_01_10.csv", FaultModels.FM3_2, "zeng_slip_rake_fm_3_2_all_bounded_2013_01_10.csv"), ZENGBB( "Zeng B-Fault Bounded", "ZENGBB", 0.30d, FaultModels.FM3_1, "zeng_slip_rake_fm_3_1_b_bounded_2013_04_09.csv", FaultModels.FM3_2, "zeng_slip_rake_fm_3_2_b_bounded_2013_04_09.csv"), // GEOLOGIC GEOLOGIC( "Geologic", "GEOL", 0.30d, FaultModels.FM3_1, "geologic_slip_rake_fm_3_1_2013_04_09.csv", FaultModels.FM3_2, "geologic_slip_rake_fm_3_2_2013_04_09.csv"), GEOLOGIC_UPPER( "Geologic Upper Bound", "GLUP", 0d, FaultModels.FM3_1, "geologic_slip_rake_fm_3_1_upperbound_2013_04_09.csv", FaultModels.FM3_2, "geologic_slip_rake_fm_3_2_upperbound_2013_04_09.csv"), GEOLOGIC_LOWER( "Geologic Lower Bound", "GLLOW", 0d, FaultModels.FM3_1, "geologic_slip_rake_fm_3_1_lowerbound_2013_04_09.csv", FaultModels.FM3_2, "geologic_slip_rake_fm_3_2_lowerbound_2013_04_09.csv"), // GEOLOGIC + ABM GEOLOGIC_PLUS_ABM( "Geologic + ABM", "GLpABM", 0d, FaultModels.FM3_1, "geologic_plus_ABM_slip_rake_fm_3_1_2012_06_08.csv", FaultModels.FM3_2, "geologic_plus_ABM_slip_rake_fm_3_2_2012_06_08.csv"), GEOL_P_ABM_OLD_MAPPED( "Geologic + ABM OLD", "GLpABMOLD",0d, FaultModels.FM3_1, "geologic_plus_ABM_slip_rake__MAPPED_2012_06_05.csv"), MEAN_UCERF3( "Mean UCERF3 DM", "MeanU3DM", 0d, FaultModels.FM3_1, null, FaultModels.FM3_2, null); private List<FaultModels> faultModels; private List<String> fileNames; private String name, shortName; private double weight; private DeformationModels(String name, String shortName, double weight, FaultModels model) { this(name, shortName, weight, Lists.newArrayList(model), null); } private DeformationModels(String name, String shortName, double weight, FaultModels model, String file) { this(name, shortName, weight, Lists.newArrayList(model), Lists.newArrayList(file)); } private DeformationModels(String name, String shortName, double weight, FaultModels model1, String file1, FaultModels model2, String file2) { this(name, shortName, weight, Lists.newArrayList(model1, model2), Lists.newArrayList(file1, file2)); } private DeformationModels(String name, String shortName, double weight, List<FaultModels> faultModels, List<String> fileNames) { Preconditions.checkNotNull(faultModels, "fault models cannot be null!"); Preconditions.checkArgument(!faultModels.isEmpty(), "fault models cannot be empty!"); Preconditions.checkArgument(fileNames == null || fileNames.size() == faultModels.size(), "file names must either be null or the same size as fault models!"); this.faultModels = faultModels; this.fileNames = fileNames; this.name = name; this.shortName = shortName; this.weight = weight; } public String getName() { return name; } public String getShortName() { return shortName; } @Override public String toString() { return name; } public boolean isApplicableTo(FaultModels faultModel) { return faultModels.contains(faultModel); } public List<FaultModels> getApplicableFaultModels() { return Collections.unmodifiableList(faultModels); } public URL getDataFileURL(FaultModels faultModel) { String fileName = getDataFileName(faultModel); if (fileName == null) return null; return UCERF3_DataUtils.locateResource("DeformationModels", fileName); } public String getDataFileName(FaultModels faultModel) { Preconditions.checkState(isApplicableTo(faultModel), "Deformation model "+name()+" isn't applicable to fault model: "+faultModel); if (fileNames == null) return null; return fileNames.get(faultModels.indexOf(faultModel)); } public static List<DeformationModels> forFaultModel(FaultModels fm) { ArrayList<DeformationModels> mods = new ArrayList<DeformationModels>(); for (DeformationModels mod : values()) if (mod.isApplicableTo(fm)) mods.add(mod); return mods; } @Override public double getRelativeWeight(InversionModels im) { return weight; } @Override public String encodeChoiceString() { return getShortName(); } @Override public String getBranchLevelName() { return "Deformation Model"; } private static File getCacheDir() { File scratchDir = UCERF3_DataUtils.DEFAULT_SCRATCH_DATA_DIR; if (scratchDir.exists()) { // eclipse project File dir = new File(scratchDir, "SubSections"); if (!dir.exists()) Preconditions.checkState(dir.mkdir()); return dir; } else { // use home dir String path = System.getProperty("user.home"); File homeDir = new File(path); Preconditions.checkState(homeDir.exists(), "user.home dir doesn't exist: "+path); File openSHADir = new File(homeDir, ".opensha"); if (!openSHADir.exists()) Preconditions.checkState(openSHADir.mkdir(), "Couldn't create OpenSHA store location: "+openSHADir.getAbsolutePath()); File uc3Dir = new File(openSHADir, "ucerf3_sub_sects"); if (!uc3Dir.exists()) Preconditions.checkState(uc3Dir.mkdir(), "Couldn't create UCERF3 ERF store location: "+uc3Dir.getAbsolutePath()); return uc3Dir; } } public static List<? extends FaultSection> loadSubSects(FaultModels fm, DeformationModels dm) { File cacheDir = getCacheDir(); File xmlFile = new File(cacheDir, fm.encodeChoiceString()+"_"+dm.encodeChoiceString()+"_sub_sects.xml"); if (xmlFile.exists()) { try { return FaultModels.loadStoredFaultSections(xmlFile); } catch (Exception e) { ExceptionUtils.throwAsRuntimeException(e); } } System.out.println("No sub section cache exists for "+fm.getShortName()+", "+dm.getShortName()); List<? extends FaultSection> sects = new DeformationModelFetcher( fm, dm, UCERF3_DataUtils.DEFAULT_SCRATCH_DATA_DIR, 0.1).getSubSectionList(); // write to XML Document doc = XMLUtils.createDocumentWithRoot(); FaultSystemIO.fsDataToXML(doc.getRootElement(), FaultModels.XML_ELEMENT_NAME, fm, null, sects); try { XMLUtils.writeDocumentToFile(xmlFile, doc); } catch (IOException e) { System.err.println("WARNING: Couldn't write cache file: "+xmlFile.getAbsolutePath()); e.printStackTrace(); } return sects; } }
40.343284
136
0.739055
eeb364a615967dd43b7aba1c51b750111ee09faf
358
package com.javaguru.shoppinglist.service.validation; import com.javaguru.shoppinglist.domain.Product; public interface ProductValidationRule { void validate(Product product); default void checkNotNull(Product product) { if (product == null) { throw new ProductValidationException("Product must be not null"); } } }
27.538462
77
0.712291
050cbafcbf6e318e4f568b32526819ba04631b9c
4,855
/** * */ package cern.accsoft.steering.aloha.plugin.traj.meas.data; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import Jama.Matrix; import cern.accsoft.steering.aloha.bean.AlohaBeanFactory; import cern.accsoft.steering.aloha.bean.aware.NoiseWeighterAware; import cern.accsoft.steering.aloha.calc.NoiseWeighter; import cern.accsoft.steering.aloha.meas.data.AbstractDynamicData; import cern.accsoft.steering.aloha.meas.data.DynamicDataListener; import cern.accsoft.steering.aloha.model.data.ModelOpticsData; import cern.accsoft.steering.aloha.plugin.traj.meas.TrajectoryMeasurement; import cern.accsoft.steering.util.MatrixUtil; import cern.accsoft.steering.util.meas.data.Plane; /** * @author kfuchsbe * */ public class CombinedTrajectoryDataImpl extends AbstractDynamicData implements CombinedTrajectoryData, NoiseWeighterAware { /** the map which contains the calculated values */ private Map<String, List<Double>> valuesMap = new HashMap<String, List<Double>>(); /** the measurement used for the calculations */ private TrajectoryMeasurement measurement; /** the nois-weighter injected by {@link AlohaBeanFactory} */ private NoiseWeighter noiseWeighter; /** * the listener, which we add to both, the model data and the measurement * data, in order to get notified about changes. */ private DynamicDataListener dataListener = new DynamicDataListener() { @Override public void becameDirty() { setDirty(true); } }; /** * the setter for the measurement-object. * * @param measurement */ public void setMeasurement(TrajectoryMeasurement measurement) { this.measurement = measurement; this.measurement.getData().addListener(this.dataListener); this.measurement.getModelDelegate().getModelOpticsData().addListener( this.dataListener); } /** * this enum just defines prefixes for the hashmap-keys * * @author kfuchsbe * */ private enum KeyPrefix { NOISY_DIFFERENCE, NORMALIZED_DIFFERENCE, NORMALIZED_RMS; } @Override protected void calc() { valuesMap.clear(); ModelOpticsData modelOpticsData = getMeasurement().getModelDelegate() .getModelOpticsData(); for (Plane plane : Plane.values()) { List<Double> diffData = new ArrayList<Double>(); List<Double> normalizeDiffData = new ArrayList<Double>(); List<Double> normalizedRmsData = new ArrayList<Double>(); TrajectoryData dispersionData = getMeasurement().getData(); if (dispersionData != null) { List<Double> posValuesMeas = dispersionData .getMeanValues(plane); List<Double> posRmsMeas = dispersionData.getRmsValues(plane); List<Double> posValuesModel = modelOpticsData .getMonitorPos(plane); List<Double> betas = modelOpticsData.getMonitorBetas(plane); for (int i = 0; i < posValuesMeas.size(); i++) { double value = (posValuesMeas.get(i) - posValuesModel .get(i)); double sqrtBeta = Math.sqrt(betas.get(i)); diffData.add(getNoiseWeighter().calcNoisyValue(value, posRmsMeas.get(i))); normalizeDiffData.add(value / sqrtBeta); normalizedRmsData.add(posRmsMeas.get(i) / sqrtBeta); } } this.valuesMap.put(createKey(KeyPrefix.NOISY_DIFFERENCE, plane), diffData); this.valuesMap.put( createKey(KeyPrefix.NORMALIZED_DIFFERENCE, plane), normalizeDiffData); this.valuesMap.put(createKey(KeyPrefix.NORMALIZED_RMS, plane), normalizedRmsData); } } @Override public List<Double> getMonitorNormalizedPosDiff(Plane plane) { ensureUpToDate(); return getValues(KeyPrefix.NORMALIZED_DIFFERENCE, plane); } @Override public List<Double> getMonitorNormalizedPosRms(Plane plane) { ensureUpToDate(); return getValues(KeyPrefix.NORMALIZED_RMS, plane); } @Override public Matrix getNoisyDifferenceVector() { ensureUpToDate(); List<Double> values = new ArrayList<Double>(); values.addAll(getNoisyMonitorPosDiff(Plane.HORIZONTAL)); values.addAll(getNoisyMonitorPosDiff(Plane.VERTICAL)); return MatrixUtil.createVector(values); } @Override public List<Double> getNoisyMonitorPosDiff(Plane plane) { ensureUpToDate(); return getValues(KeyPrefix.NOISY_DIFFERENCE, plane); } private List<Double> getValues(KeyPrefix prefix, Plane plane) { return this.valuesMap.get(createKey(prefix, plane)); } /** * create a key for the hashmap * * @param prefix * the prefix to use * @param plane * the plane * @return the key */ private String createKey(KeyPrefix prefix, Plane plane) { return prefix + "-" + plane; } private TrajectoryMeasurement getMeasurement() { return measurement; } @Override public void setNoiseWeighter(NoiseWeighter noiseWeighter) { this.noiseWeighter = noiseWeighter; } private NoiseWeighter getNoiseWeighter() { return this.noiseWeighter; } }
28.226744
83
0.739032
74dcfed7367a9976275553fcd640b8ea83f11c59
1,815
package org.talend.designer.esb.webservice; import java.io.IOException; import javax.wsdl.Definition; import javax.wsdl.WSDLException; import org.talend.core.model.repository.IRepositoryViewObject; import org.talend.designer.esb.webservice.ws.wsdlinfo.Function; import org.talend.designer.esb.webservice.ws.wsdlutil.CompressAndEncodeTool; public class ServiceSetting { private String wsdlLocation; private Function function; private Definition definition; private boolean hasRpcOperation; private String port; private IRepositoryViewObject resourceNode; public void setWsdlLocation(String wsdlLocation) { this.wsdlLocation = wsdlLocation; } public String getWsdlLocation() { return wsdlLocation; } public void setFunction(Function function) { this.function = function; } public Function getFunction() { return function; } public void setDefinition(Definition definition) { this.definition = definition; } public Definition getDefinition() { return definition; } /** * Checks if is updated. * If user do nothing about the binding dialog, then is not updated. * @return true, if is updated */ public boolean isUpdated() { return definition != null; } public String getCompressedAndEncodedWSDL() throws IOException, WSDLException { return CompressAndEncodeTool.compressAndEncode(definition); } public void setHasRcpOperation(boolean hasRpcOperation) { this.hasRpcOperation = hasRpcOperation; } public boolean hasRpcOperation() { return hasRpcOperation; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public void setResourceNode(IRepositoryViewObject resourceNode) { this.resourceNode = resourceNode; } public IRepositoryViewObject getResourceNode() { return resourceNode; } }
22.134146
80
0.771901
320be2206d401854047b9eafa7215ef5ed406f6e
5,233
package es.sacyl.gsa.inform.ctrl; import es.sacyl.gsa.inform.bean.UsuarioBean; import ezvcard.Ezvcard; import ezvcard.VCard; import ezvcard.VCardVersion; import ezvcard.property.Email; import ezvcard.property.Label; import ezvcard.property.Organization; import ezvcard.property.StructuredName; import ezvcard.property.Telephone; import ezvcard.property.Title; /** * * @author JuanNieto */ public class UsuarioCtrl { /** * * @param usuario * @param fun * @return Compara el nombre del menu con el SET de funcionalidades que * guarda en textomenu */ public static Boolean tieneLaFuncionalidad(UsuarioBean usuario, String fun) { Boolean laTiene = false; for (String funcionaliad : usuario.getFuncionalidadStrings()) { if (funcionaliad.trim().toUpperCase().equals(fun.trim().toUpperCase())) { laTiene = true; } } return laTiene; } /** * * @param usuario * @param fun * @return */ public static Boolean tieneElGrupoActiveDirectory(UsuarioBean usuario, String fun) { Boolean laTiene = false; for (String grupoAd : usuario.getGruposActiveDirectory()) { if (grupoAd.trim().toUpperCase().equals(fun.trim().toUpperCase())) { laTiene = true; } } return laTiene; } public static String toHtml(UsuarioBean usuario, String separador) { String cadena = "<b>"; cadena = cadena.concat(toTxtSeparador(usuario, separador)); /* if (dni != null) { cadena = cadena.concat(dni); } else { cadena = cadena.concat(" "); } cadena = cadena.concat(separador); cadena = cadena.concat("Apellidos: "); cadena = cadena.concat(getApellidosNombre()); cadena = cadena.concat(separador); cadena = cadena.concat("Telefonos: "); if (telefono != null) { cadena = cadena.concat(telefono); } else { cadena = cadena.concat(" "); } if (movilUsuario != null) { cadena = cadena.concat(movilUsuario); } else { cadena = cadena.concat(" "); } cadena = cadena.concat(separador); cadena = cadena.concat("Correo: "); if (mail != null) { cadena = cadena.concat(mail); } else { cadena = cadena.concat(" "); } cadena = cadena.concat(separador); cadena = cadena.concat("Categoria: "); if (categoria != null) { cadena = cadena.concat(categoria.getNombre()); } else { cadena = cadena.concat(" "); } cadena = cadena.concat("</b>"); */ return cadena; } public static String toTxtSeparador(UsuarioBean usuario, String separador) { String cadena = ""; cadena = cadena.concat("Dni: "); if (usuario.getDni() != null) { cadena = cadena.concat(usuario.getDni()); } else { cadena = cadena.concat(" "); } cadena = cadena.concat(separador); cadena = cadena.concat("Apellidos: "); cadena = cadena.concat(usuario.getApellidosNombre()); cadena = cadena.concat(separador); cadena = cadena.concat("Telefonos: "); if (usuario.getTelefono() != null) { cadena = cadena.concat(usuario.getTelefono()); } else { cadena = cadena.concat(" "); } if (usuario.getMovilUsuario() != null) { cadena = cadena.concat(usuario.getMovilUsuario()); } else { cadena = cadena.concat(" "); } cadena = cadena.concat(separador); cadena = cadena.concat("Correo: "); if (usuario.getMail() != null) { cadena = cadena.concat(usuario.getMail()); } else { cadena = cadena.concat(" "); } cadena = cadena.concat(separador); cadena = cadena.concat("Categoria: "); if (usuario.getCategoria() != null && usuario.getCategoria().getNombre() != null) { cadena = cadena.concat(usuario.getCategoria().getNombre()); } else { cadena = cadena.concat(" "); } return cadena; } public static String getVard(UsuarioBean usuario) { VCard vcard = new VCard(); Email mail = new Email(usuario.getMail()); vcard.addEmail(mail); Label label = new Label("Vcard profesional"); Telephone telephone = new Telephone(usuario.getTelefono()); vcard.addTelephoneNumber(telephone); Organization organization = new Organization(); organization.addParameter("Servicio/Unidad", usuario.getGfh().getDescripcion()); vcard.addOrganization(organization); Title title = new Title(usuario.getCategoria().getNombre()); vcard.addTitle(title); StructuredName n = new StructuredName(); n.setFamily(usuario.getApellidos()); n.setGiven(usuario.getNombre()); vcard.setStructuredName(n); String text = Ezvcard.write(vcard).version(VCardVersion.V3_0).go(); return text; } }
30.424419
91
0.572329
1e28b1a2044269e0d000f71698c3ed84347f2792
7,678
package com.tasdemir.tasklist; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import model.Task; import model.User; import utils.HibernateUtil; import utils.Utils; @Controller public class TaskController { SessionFactory sf = HibernateUtil.getSessionFactory(); // Task list page @SuppressWarnings("unchecked") @RequestMapping(value = "/tasklist", method = RequestMethod.GET) public String taskList(Model model, HttpServletRequest req) { model.addAttribute("filter", 1); // Filter dropdown menu activate // Check the session boolean log = req.getSession().getAttribute("id") != null; if (log) { int id = (Integer) req.getSession().getAttribute("id"); // Set the user ID Session sesi = sf.openSession(); List<Task> taskarr = new ArrayList<Task>(); // Create a list for tasks try { // Fill the task list with tasks taskarr = sesi.createQuery("from Task where task_user_id = '" + id + "' order by task_id desc").list(); model.addAttribute("ls", taskarr); // Create a model for the task list } catch (Exception e) { System.err.println("Databse error: " + e); } return "tasklist"; } else { return "redirect:/"; } } // Task add page @RequestMapping(value = "/taskadd", method = RequestMethod.GET) public String taskAddPage(HttpServletRequest req, Model model) { // Check errors boolean error = req.getSession().getAttribute("error") != null; if (error) { String err = "" + req.getSession().getAttribute("error"); // Convert error object to string model.addAttribute("error", err); // Set error model req.getSession().removeAttribute("error"); // Clear error object } return Utils.loginControl(req, "redirect:/", "taskadd"); } // Task create action @RequestMapping(value = "/addtask", method = RequestMethod.POST) public String addTask(Task task, HttpServletRequest req, @RequestParam String startDate, @RequestParam String dueDate) { // Check required fields if (task.getTaskName().equals("") || task.getTaskDescription().equals("") || startDate.equals("") || dueDate.equals("")) { req.getSession().setAttribute("error", "All fields are required!"); return "redirect:/taskadd"; } // Check the sessions boolean log = req.getSession().getAttribute("id") != null; if (log) { int id = (Integer) req.getSession().getAttribute("id"); // Standart user ID // Date formatter (String -> Date) SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date sd = new Date(); Date dd = new Date(); try { sd = formatter.parse(startDate); dd = formatter.parse(dueDate); } catch (ParseException e) { System.err.println("Date parse error: " + e); } // New task creating Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); task.setTaskId(Integer.MAX_VALUE); // Set task id task.setTaskUserId(id); // Set task user id task.setTaskStartDate(sd); // Set task start date task.setTaskDueDate(dd); // Set task due date sesi.save(task); // Save task tr.commit(); sesi.close(); return "redirect:/tasklist"; } else { return "redirect:/"; } } int tid; // Selected task id // Task edit page @SuppressWarnings("unchecked") @RequestMapping(value = "/taskedit/{id}", method = RequestMethod.GET) public String taskEditPage(@PathVariable Integer id, Model model, HttpServletRequest req) { tid = id; // Set task ID for update operations User user = (User) req.getSession().getAttribute("user"); // Get the user's attributes Session sesi = sf.openSession(); // Create a list and fill it with the task List<Task> ls = sesi.createQuery("from Task where taskId = '" + id + "' ").setMaxResults(1).list(); // Check the user's ID for validation if (ls.get(0).getTaskUserId() != user.getUserId()) { model.addAttribute("error", "User is not validated!"); } else { model.addAttribute("ls", ls); // Create a model for the task sesi.close(); } return Utils.loginControl(req, "redirect:/", "taskedit"); } // Task edit action @RequestMapping(value = "/updatetask", method = RequestMethod.POST) public String updateTask(Task task, HttpServletRequest req, @RequestParam String startDate, @RequestParam String dueDate) { // Check required fields if (task.getTaskName().equals("") || task.getTaskDescription().equals("") || startDate.equals("") || dueDate.equals("")) { req.getSession().setAttribute("error", "All fields are required!"); return "redirect:/taskedit/" + tid; } // Check the session boolean log = req.getSession().getAttribute("id") != null; if (log) { int id = (Integer) req.getSession().getAttribute("id"); // Standart user ID // Date formatter (String -> Date) SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date sd = new Date(); Date dd = new Date(); try { sd = formatter.parse(startDate); dd = formatter.parse(dueDate); } catch (ParseException e) { System.err.println("Date parse error: " + e); } // New task creating Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); task.setTaskId(tid); // Set the task id task.setTaskUserId(id); // Set the task user ID task.setTaskStartDate(sd); // Set the task start date task.setTaskDueDate(dd); // Set the task due date sesi.update(task); // Update the task tr.commit(); sesi.close(); return "redirect:/tasklist"; } else { return "redirect:/"; } } // Task delete from list (ajax) @ResponseBody @RequestMapping(value = "/taskdelete", method = RequestMethod.POST) public String taskDelete(@RequestParam String id, @RequestParam String idName, @RequestParam String tableName) { try { Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); // Delete operation String q = "delete from " + tableName + " where " + idName + " = " + id; sesi.createNativeQuery(q).executeUpdate(); tr.commit(); sesi.close(); return id; } catch (Exception e) { return ""; } } // Task filtering @SuppressWarnings("unchecked") @RequestMapping(value = "/tasklist/{fid}", method = RequestMethod.GET) public String taskFilter(@PathVariable Integer fid, HttpServletRequest req, Model model) { model.addAttribute("filter", 1); // Filter dropdown menu activate // Check the session boolean log = req.getSession().getAttribute("id") != null; if (log) { int id = (Integer) req.getSession().getAttribute("id"); // Get the user's ID Session sesi = sf.openSession(); List<Task> ftaskarr = new ArrayList<Task>(); // Create a list for the filtered tasks try { // Fill the list with the filtered tasks ftaskarr = sesi .createQuery("from Task where task_user_id = '" + id + "' and task_status = '" + fid + "' order by task_id desc") .list(); model.addAttribute("ls", ftaskarr); // Create a model for the list } catch (Exception e) { System.err.println("Databse error: " + e); } return "tasklist"; } else { return "redirect:/"; } } }
33.823789
119
0.685725
22d30ebf791a700c9be229f7b8d2fed5504b72db
12,515
/* * 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.tinkerpop.gremlin.server.op.session; import org.apache.tinkerpop.gremlin.driver.Tokens; import org.apache.tinkerpop.gremlin.driver.message.RequestMessage; import org.apache.tinkerpop.gremlin.driver.message.ResponseMessage; import org.apache.tinkerpop.gremlin.driver.message.ResponseStatusCode; import org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyCompilerGremlinPlugin; import org.apache.tinkerpop.gremlin.process.traversal.TraversalSource; import org.apache.tinkerpop.gremlin.server.Context; import org.apache.tinkerpop.gremlin.server.GremlinServer; import org.apache.tinkerpop.gremlin.server.OpProcessor; import org.apache.tinkerpop.gremlin.server.Settings; import org.apache.tinkerpop.gremlin.server.handler.StateKey; import org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor; import org.apache.tinkerpop.gremlin.server.op.OpProcessorException; import org.apache.tinkerpop.gremlin.server.util.MetricManager; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.util.function.ThrowingConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.Bindings; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier; import static com.codahale.metrics.MetricRegistry.name; /** * Simple {@link OpProcessor} implementation that handles {@code ScriptEngine} script evaluation in the context of * a session. Note that this processor will also take a "close" op to kill the session and rollback any incomplete transactions. * * @author Stephen Mallette (http://stephen.genoprime.com) */ public class SessionOpProcessor extends AbstractEvalOpProcessor { private static final Logger logger = LoggerFactory.getLogger(SessionOpProcessor.class); public static final String OP_PROCESSOR_NAME = "session"; /** * Script engines are evaluated in a per session context where imports/scripts are isolated per session. */ protected static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>(); static { MetricManager.INSTANCE.getGuage(sessions::size, name(GremlinServer.class, "sessions")); } /** * Configuration setting for how long a session will be available before it times out. */ public static final String CONFIG_SESSION_TIMEOUT = "sessionTimeout"; /** * Configuration setting for how long to wait in milliseconds for each configured graph to close any open * transactions when the session is killed. */ public static final String CONFIG_PER_GRAPH_CLOSE_TIMEOUT = "perGraphCloseTimeout"; /** * Configuration setting that behaves as an override to the global script engine setting of the same name that is * provided to the {@link GroovyCompilerGremlinPlugin}. */ public static final String CONFIG_GLOBAL_FUNCTION_CACHE_ENABLED = "globalFunctionCacheEnabled"; /** * Default timeout for a session is eight hours. */ public static final long DEFAULT_SESSION_TIMEOUT = 28800000; /** * Default amount of time to wait in milliseconds for each configured graph to close any open transactions when * the session is killed. */ public static final long DEFAULT_PER_GRAPH_CLOSE_TIMEOUT = 10000; static final Settings.ProcessorSettings DEFAULT_SETTINGS = new Settings.ProcessorSettings(); static { DEFAULT_SETTINGS.className = SessionOpProcessor.class.getCanonicalName(); DEFAULT_SETTINGS.config = new HashMap<String, Object>() {{ put(CONFIG_SESSION_TIMEOUT, DEFAULT_SESSION_TIMEOUT); put(CONFIG_PER_GRAPH_CLOSE_TIMEOUT, DEFAULT_PER_GRAPH_CLOSE_TIMEOUT); put(CONFIG_MAX_PARAMETERS, DEFAULT_MAX_PARAMETERS); put(CONFIG_GLOBAL_FUNCTION_CACHE_ENABLED, true); }}; } public SessionOpProcessor() { super(false); } @Override public String getName() { return OP_PROCESSOR_NAME; } @Override public void init(final Settings settings) { this.maxParameters = (int) settings.optionalProcessor(SessionOpProcessor.class).orElse(DEFAULT_SETTINGS).config. getOrDefault(CONFIG_MAX_PARAMETERS, DEFAULT_MAX_PARAMETERS); } /** * Session based requests accept a "close" operator in addition to "eval". A close will trigger the session to be * killed and any uncommitted transaction to be rolled-back. */ @Override public Optional<ThrowingConsumer<Context>> selectOther(final RequestMessage requestMessage) throws OpProcessorException { if (requestMessage.getOp().equals(Tokens.OPS_CLOSE)) { // this must be an in-session request if (!requestMessage.optionalArgs(Tokens.ARGS_SESSION).isPresent()) { final String msg = String.format("A message with an [%s] op code requires a [%s] argument", Tokens.OPS_CLOSE, Tokens.ARGS_SESSION); throw new OpProcessorException(msg, ResponseMessage.build(requestMessage).code(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS).statusMessage(msg).create()); } final boolean force = requestMessage.<Boolean>optionalArgs(Tokens.ARGS_FORCE).orElse(false); return Optional.of(rhc -> { final Session sessionToClose = sessions.get(requestMessage.getArgs().get(Tokens.ARGS_SESSION).toString()); if (null != sessionToClose) { sessionToClose.manualKill(force); } // send back a confirmation of the close rhc.writeAndFlush(ResponseMessage.build(requestMessage) .code(ResponseStatusCode.NO_CONTENT) .create()); }); } else { return Optional.empty(); } } @Override public ThrowingConsumer<Context> getEvalOp() { return this::evalOp; } @Override protected Optional<ThrowingConsumer<Context>> validateEvalMessage(final RequestMessage message) throws OpProcessorException { super.validateEvalMessage(message); if (!message.optionalArgs(Tokens.ARGS_SESSION).isPresent()) { final String msg = String.format("A message with an [%s] op code requires a [%s] argument", Tokens.OPS_EVAL, Tokens.ARGS_SESSION); throw new OpProcessorException(msg, ResponseMessage.build(message).code(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS).statusMessage(msg).create()); } return Optional.empty(); } @Override public void close() throws Exception { sessions.values().forEach(session -> session.manualKill(false)); } protected void evalOp(final Context context) throws OpProcessorException { final RequestMessage msg = context.getRequestMessage(); final Session session = getSession(context, msg); // check if the session is still accepting requests - if not block further requests if (!session.acceptingRequests()) { final String sessionClosedMessage = String.format("Session %s is no longer accepting requests as it has been closed", session.getSessionId()); final ResponseMessage response = ResponseMessage.build(msg).code(ResponseStatusCode.SERVER_ERROR) .statusMessage(sessionClosedMessage).create(); throw new OpProcessorException(sessionClosedMessage, response); } // place the session on the channel context so that it can be used during serialization. in this way // the serialization can occur on the same thread used to execute the gremlin within the session. this // is important given the threadlocal nature of Graph implementation transactions. context.getChannelHandlerContext().channel().attr(StateKey.SESSION).set(session); evalOpInternal(context, session::getGremlinExecutor, getBindingMaker(session).apply(context)); } /** * Examines the {@link RequestMessage} and extracts the session token. The session is then either found or a new * one is created. */ protected static Session getSession(final Context context, final RequestMessage msg) { final String sessionId = (String) msg.getArgs().get(Tokens.ARGS_SESSION); logger.debug("In-session request {} for eval for session {} in thread {}", msg.getRequestId(), sessionId, Thread.currentThread().getName()); final Session session = sessions.computeIfAbsent(sessionId, k -> new Session(k, context, sessions)); session.touch(); return session; } /** * A useful method for those extending this class, where the means for binding construction can be supplied * to this class. This function is used in {@link #evalOp(Context)} to create the final argument to * {@link AbstractEvalOpProcessor#evalOpInternal(Context, Supplier, BindingSupplier)}. * In this way an extending class can use the default {@link AbstractEvalOpProcessor.BindingSupplier} * which carries a lot of re-usable functionality or provide a new one to override the existing approach. */ protected Function<Context, BindingSupplier> getBindingMaker(final Session session) { return context -> () -> { final RequestMessage msg = context.getRequestMessage(); final Bindings bindings = session.getBindings(); // alias any global bindings to a different variable if (msg.getArgs().containsKey(Tokens.ARGS_ALIASES)) { final Map<String, String> aliases = (Map<String, String>) msg.getArgs().get(Tokens.ARGS_ALIASES); for (Map.Entry<String,String> aliasKv : aliases.entrySet()) { boolean found = false; // first check if the alias refers to a Graph instance final Graph graph = context.getGraphManager().getGraph(aliasKv.getValue()); if (null != graph) { bindings.put(aliasKv.getKey(), graph); found = true; } // if the alias wasn't found as a Graph then perhaps it is a TraversalSource - it needs to be // something if (!found) { final TraversalSource ts = context.getGraphManager().getTraversalSource(aliasKv.getValue()); if (null != ts) { bindings.put(aliasKv.getKey(), ts); found = true; } } // this validation is important to calls to GraphManager.commit() and rollback() as they both // expect that the aliases supplied are valid if (!found) { final String error = String.format("Could not alias [%s] to [%s] as [%s] not in the Graph or TraversalSource global bindings", aliasKv.getKey(), aliasKv.getValue(), aliasKv.getValue()); throw new OpProcessorException(error, ResponseMessage.build(msg) .code(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS).statusMessage(error).create()); } } } // add any bindings to override any other supplied Optional.ofNullable((Map<String, Object>) msg.getArgs().get(Tokens.ARGS_BINDINGS)).ifPresent(bindings::putAll); return bindings; }; } }
47.226415
184
0.68366
25141d5b0cff20975a4ac80a5b61034b52c6ef56
1,410
package com.sethholloway.sorts; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import com.sethholloway.sorts.*; public class SortTest { Sort qs; Sort ss; Sort ms; List<Integer> sortedList; List<Integer> unsortedList; @Before public void setUp() throws Exception { qs = new Quicksort(); ss = new SelectionSort(); ms = new MergeSort(); sortedList = new ArrayList<Integer>(); unsortedList = new ArrayList<Integer>(); sortedList.add(0); sortedList.add(1); sortedList.add(2); sortedList.add(3); sortedList.add(4); unsortedList.add(0); unsortedList.add(4); unsortedList.add(3); unsortedList.add(2); unsortedList.add(1); } @Test public void test_single_element_list_is_sorted() { List<Integer> l = new ArrayList<Integer>(); l.add(1); assertTrue(l.equals(qs.sort(l))); assertTrue(l.equals(ss.sort(l))); assertTrue(l.equals(ms.sort(l))); } @Test public void test_quicksort() { List<Integer> afterSort = qs.sort(unsortedList); assertTrue(sortedList.equals(afterSort)); } @Test public void test_selectionsort() { List<Integer> afterSort = ss.sort(unsortedList); assertTrue(sortedList.equals(afterSort)); } @Test public void test_mergesort() { List<Integer> afterSort = ms.sort(unsortedList); assertTrue(sortedList.equals(afterSort)); } }
21.692308
51
0.712057
159dff4429b53c185ed96bf6559eabb330e3baf5
3,977
package org.waal70.canbus.util; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginElement; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import javax.swing.*; import java.util.ArrayList; import static javax.swing.SwingUtilities.invokeLater; import static org.apache.logging.log4j.core.config.Property.EMPTY_ARRAY; import static org.apache.logging.log4j.core.layout.PatternLayout.createDefaultLayout; @Plugin(name = "JTextAreaAppender", category = "Core", elementType = "appender", printObject = true) public class TextAreaAppender extends AbstractAppender { private static volatile ArrayList<JTextArea> textAreas = new ArrayList<>(); private int maxLines; private TextAreaAppender(String name, Layout<?> layout, Filter filter, int maxLines, boolean ignoreExceptions) { super(name, filter, layout, ignoreExceptions, EMPTY_ARRAY); this.maxLines = maxLines; } @SuppressWarnings("unused") @PluginFactory public static TextAreaAppender createAppender(@PluginAttribute("name") String name, @PluginAttribute("maxLines") int maxLines, @PluginAttribute("ignoreExceptions") boolean ignoreExceptions, @PluginElement("Layout") Layout<?> layout, @PluginElement("Filters") Filter filter) { if (name == null) { LOGGER.error("No name provided for JTextAreaAppender"); return null; } if (layout == null) { layout = createDefaultLayout(); } return new TextAreaAppender(name, layout, filter, maxLines, ignoreExceptions); } // Add the target JTextArea to be populated and updated by the logging information. public static void addLog4j2TextAreaAppender(final JTextArea textArea) { TextAreaAppender.textAreas.add(textArea); } @Override public void append(LogEvent event) { String message = new String(this.getLayout().toByteArray(event)); // Append formatted message to text area using the Thread. try { invokeLater(() -> { for (JTextArea textArea : textAreas) { try { if (textArea != null) { if (textArea.getText().length() == 0) { textArea.setText(message); } else { textArea.append("\n" + message); if (maxLines > 0 & textArea.getLineCount() > maxLines + 1) { int endIdx = textArea.getDocument().getText(0, textArea.getDocument().getLength()).indexOf("\n"); textArea.getDocument().remove(0, endIdx + 1); } } String content = textArea.getText(); textArea.setText(content.substring(0, content.length() - 1)); } } catch (Throwable throwable) { throwable.printStackTrace(); } } }); } catch (IllegalStateException exception) { exception.printStackTrace(); } } }
38.990196
133
0.548403
93b90ee72143e14c47513b54c7ffc03dc2b7590a
8,591
/* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/ // for license please see accompanying LICENSE.txt file (available also at http://www.xmlpull.org/) package org.xmlpull.v1.util; import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; /** * Handy functions that combines XmlPull API into higher level functionality. * * @author <a href="http://www.extreme.indiana.edu/~aslom/">Aleksander Slominski</a> * @author Naresh Bhatia */ public class XmlPullUtil { public static final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"; private XmlPullUtil() {} /** * Return value of attribute with given name and no namespace. */ public static String getAttributeValue(XmlPullParser pp, String name) { return pp.getAttributeValue(XmlPullParser.NO_NAMESPACE, name); } /** * Return PITarget from Processing Instruction (PI) as defined in * XML 1.0 Section 2.6 Processing Instructions * <code>[16] PI ::= '&lt;?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'</code> */ public static String getPITarget(XmlPullParser pp) throws IllegalStateException { int eventType; try { eventType = pp.getEventType(); } catch(XmlPullParserException ex) { // should never happen ... throw new IllegalStateException( "could not determine parser state: "+ex+pp.getPositionDescription()); } if( eventType != XmlPullParser.PROCESSING_INSTRUCTION ) { throw new IllegalStateException( "parser must be on processing instruction and not " +XmlPullParser.TYPES[ eventType ]+pp.getPositionDescription()); } final String PI = pp.getText(); for (int i = 0; i < PI.length(); i++) { if( isS(PI.charAt(i)) ) { // assert i > 0 return PI.substring(0,i); } } return PI; } /** * Return everything past PITarget and S from Processing Instruction (PI) as defined in * XML 1.0 Section 2.6 Processing Instructions * <code>[16] PI ::= '&lt;?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'</code> * * <p><b>NOTE:</b> if there is no PI data it returns empty string. */ public static String getPIData(XmlPullParser pp) throws IllegalStateException { int eventType; try { eventType = pp.getEventType(); } catch(XmlPullParserException ex) { // should never happen ... throw new IllegalStateException( "could not determine parser state: "+ex+pp.getPositionDescription()); } if( eventType != XmlPullParser.PROCESSING_INSTRUCTION ) { throw new IllegalStateException( "parser must be on processing instruction and not " +XmlPullParser.TYPES[ eventType ]+pp.getPositionDescription()); } final String PI = pp.getText(); int pos = -1; for (int i = 0; i < PI.length(); i++) { if( isS(PI.charAt(i)) ) { pos = i; } else if(pos > 0) { return PI.substring(i); } } return ""; } /** * Return true if chacters is S as defined in XML 1.0 * <code>S ::= (#x20 | #x9 | #xD | #xA)+</code> */ private static boolean isS(char ch) { return (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'); } /** * Skip sub tree that is currently porser positioned on. * <br>NOTE: parser must be on START_TAG and when funtion returns * parser will be positioned on corresponding END_TAG */ public static void skipSubTree(XmlPullParser pp) throws XmlPullParserException, IOException { pp.require(XmlPullParser.START_TAG, null, null); int level = 1; while(level > 0) { int eventType = pp.next(); if(eventType == XmlPullParser.END_TAG) { --level; } else if(eventType == XmlPullParser.START_TAG) { ++level; } } } /** * call parser nextTag() and check that it is START_TAG, throw exception if not. */ public static void nextStartTag(XmlPullParser pp) throws XmlPullParserException, IOException { if(pp.nextTag() != XmlPullParser.START_TAG) { throw new XmlPullParserException( "expected START_TAG and not "+pp.getPositionDescription()); } } /** * combine nextTag(); pp.require(pp.START_TAG, null, name); */ public static void nextStartTag(XmlPullParser pp, String name) throws XmlPullParserException, IOException { pp.nextTag(); pp.require(XmlPullParser.START_TAG, null, name); } /** * combine nextTag(); pp.require(pp.START_TAG, namespace, name); */ public static void nextStartTag(XmlPullParser pp, String namespace, String name) throws XmlPullParserException, IOException { pp.nextTag(); pp.require(XmlPullParser.START_TAG, namespace, name); } /** * combine nextTag(); pp.require(pp.END_TAG, namespace, name); */ public static void nextEndTag(XmlPullParser pp, String namespace, String name) throws XmlPullParserException, IOException { pp.nextTag(); pp.require(XmlPullParser.END_TAG, namespace, name); } /** * Read text content of element ith given namespace and name * (use null namespace do indicate that nemspace should not be checked) */ public static String nextText(XmlPullParser pp, String namespace, String name) throws IOException, XmlPullParserException { if(name == null) { throw new XmlPullParserException("name for element can not be null"); } pp.require(XmlPullParser.START_TAG, namespace, name); return pp.nextText(); } /** * Read attribute value and return it or throw exception if * current element does not have such attribute. */ public static String getRequiredAttributeValue(XmlPullParser pp, String namespace, String name) throws IOException, XmlPullParserException { String value = pp.getAttributeValue(namespace, name); if (value == null) { throw new XmlPullParserException("required attribute "+name+" is not present"); } else { return value; } } /** * Call parser nextTag() and check that it is END_TAG, throw exception if not. */ public static void nextEndTag(XmlPullParser pp) throws XmlPullParserException, IOException { if(pp.nextTag() != XmlPullParser.END_TAG) { throw new XmlPullParserException( "expected END_TAG and not"+pp.getPositionDescription()); } } /** * Tests if the current event is of the given type and if the namespace and name match. * null will match any namespace and any name. If the test passes a true is returned * otherwise a false is returned. */ public static boolean matches(XmlPullParser pp, int type, String namespace, String name) throws XmlPullParserException { boolean matches = type == pp.getEventType() && (namespace == null || namespace.equals (pp.getNamespace())) && (name == null || name.equals (pp.getName ())); return matches; } /** * Writes a simple element such as <username>johndoe</username>. The namespace * and elementText are allowed to be null. If elementText is null, an xsi:nil="true" * will be added as an attribute. */ public static void writeSimpleElement(XmlSerializer serializer, String namespace, String elementName, String elementText) throws IOException, XmlPullParserException { if (elementName == null) { throw new XmlPullParserException("name for element can not be null"); } serializer.startTag(namespace, elementName); if (elementText == null) { serializer.attribute(XSI_NS, "nil", "true"); } else { serializer.text(elementText); } serializer.endTag(namespace, elementName); } }
33.428016
100
0.594692
6149f75a29594ec4e699f62fd1693012da99627c
5,283
/** * Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET * (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije * informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE * COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp., * INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM * ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC)) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. 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 HOLDER 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. */ package org.societies.personalisation.socialprofiler.datamodel; import org.neo4j.graphdb.Traverser; import org.societies.personalisation.socialprofiler.datamodel.behaviour.Profile; public interface SocialPerson { public final String ROOT = "ROOT"; /** * Set a new profile in the Person Behaviour * @param profile Settings */ public void addProfile(Profile profile); /** * Returns the percentage of a profile * this tell an idea about how narcissist the person is * @return String percentage * */ public String getProfilePercentage(Profile.Type profileType); /** * Set the current Percentage value for a specific Profile * @param profileType profile identifier * @param numberOfActions related to this Profile */ public void setProfilePercentage(Profile.Type profileType, String numberOfActions); /** * returns the total number of actions this user realized on the Social Network * this may be taken into consideration when comparing 2 users with similar percentages * @return String total number */ public String getTotalNumberOfActions(); /** * sets the total number of actions this user realized on a Social Network * @param totalActions * number of actions realized */ void setTotalNumberOfActions( String totalActions ); /** * returns the name of the person * @return person name */ public String getName(); /** * Sets the person name. * @param name * name of person */ void setName( String name ); /** * returns the friends of the person * @return listFriends */ public Traverser getFriends(); /** * returns the friends of the person+friends of the friends till depth n * @return listFriends */ public Traverser getFriends(final Integer depth); /** * returns the betweeness parameter of the person * @return double - Betweeness_parameter */ public double getParamBetweenessCentr (); /** * sets the betweeness parameter of the person * the first time it will be set with undefined in order not to have null error execption * or notFOundException * @param value */ public void setParamBetweenessCentr (double value); /** * returns the eigenvetor centrality parameter of the person * @return double - eigenvector_parameter */ public double getParamEigenVectorCentr (); /** * sets the eigenvector parameter of the person * the first time it will be set with undefined in order not to have null error execption * or notFOundException * @param value */ public void setParamEigenVectorCentr (double value); /** * returns the closeness centrality parameter of the person * @return double - eigenvector_parameter */ public int getParamClosenessCentr (); /** * sets the closeness parameter of the person * the first time it will be set with undefined in order not to have null error execption * or notFOundException * @param value */ public void setParamClosenessCentr (int value); }
33.649682
131
0.707553
9f94edb9339c8557cd6878d65bb76d124593fe0d
2,760
package com.cubeio.thriftwrapjdbc; import java.util.Map; import java.util.Optional; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import io.cube.utils.Tracing; import io.jaegertracing.internal.JaegerSpan; import io.jaegertracing.internal.JaegerTracer; import io.cube.tracing.thriftjava.JaegerMeshDThriftSpanConverter; import io.cube.tracing.thriftjava.Span; import io.opentracing.Scope; import io.opentracing.Tracer; import io.opentracing.tag.Tags; import io.opentracing.util.GlobalTracer; public class ThriftWrapJDBCClient { public static Scope startClientSpan(String operationName) { Tracer tracer = GlobalTracer.get(); Tracer.SpanBuilder spanBuilder = tracer.buildSpan(operationName); return spanBuilder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT) .startActive(true); } public static void main(String[] args) { String MYSQL_HOST = "sakila2.cnt3lftdrpew.us-west-2.rds.amazonaws.com"; // "localhost"; String MYSQL_PORT = "3306"; String MYSQL_DBNAME = "sakila"; String MYSQL_USERNAME = "cube"; String MYSQL_PWD = "cubeio12"; // AWS RDS pwd String jdbcHost = "jdbc:mysql://" + MYSQL_HOST + ":" + MYSQL_PORT + "/sakila"; TTransport transport = new TSocket("localhost", 9090); JaegerTracer tracer = Tracing.init("MIThrift"); GlobalTracer.register(tracer); try (Scope scope = startClientSpan("ThriftQuery");) { System.out.println("Current Span Is :: " + scope.span().toString()); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); ThriftWrapJDBC.Client client = new ThriftWrapJDBC.Client(protocol); String result = ""; String queryString = "select film.film_id as film_id, film.title as title, group_concat(" + "actor_film_count.first_name) as actors_firstnames, group_concat(actor_film_count.last_name)" + " as actors_lastnames, group_concat(actor_film_count.film_count) as film_counts from film," + " film_actor, actor_film_count where film.film_id = film_actor.film_id and " + "film_actor.actor_id = actor_film_count.actor_id and title = ? group by film.film_id, film.title"; JaegerSpan span = (JaegerSpan) scope.span(); Span thriftSpan = JaegerMeshDThriftSpanConverter.convertSpan(span); thriftSpan.setBaggage(Map.of("intent", "record")); String queryParams = "[{\"index\":1,\"type\":\"string\",\"value\":\"GONE TROUBLE\"}]"; result = client.query(queryString, queryParams, thriftSpan); System.out.println(result); transport.close(); } catch (TException e) { e.printStackTrace(); } } }
36.8
117
0.736594
15064a98365079141620699afe1e4914514b0b11
854
package com.lorne.alipay.test.controller; import com.lorne.alipay.test.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * Created by houcunlu on 2017/10/19. */ @RestController @RequestMapping("/test") public class TestController { @Autowired private TestService testService; /** * 当面付 : 条码支付 * @param * @return */ @RequestMapping("/barcodePay") public String barcodePay(@RequestParam("orderNo") String orderNo , @RequestParam("payCode") String payCode , @RequestParam("storeId") String storeId ) { return testService.barcodePay(orderNo , payCode , storeId); } }
23.081081
156
0.73185
42e5c257c493465a1ec51ed83905a10f6ad4db0a
121
package org.apache.lucene.luke.app.desktop.util.lang; @FunctionalInterface public interface Callable { void call(); }
17.285714
53
0.77686
629945f22c7e984adab0adfe56cb19ade0a063c6
4,049
package im.actor.runtime.js.webrtc; import com.google.gwt.core.client.JavaScriptObject; import im.actor.runtime.js.entity.JsClosure; import im.actor.runtime.js.entity.JsClosureError; public class JsPeerConnection extends JavaScriptObject { public static native JsPeerConnection create(JsPeerConnectionConfig config)/*-{ var peerConnectionClass = $wnd.RTCPeerConnection || $wnd.mozRTCPeerConnection || $wnd.webkitRTCPeerConnection || $wnd.msRTCPeerConnection; return {peerConnection: new peerConnectionClass(config)}; }-*/; protected JsPeerConnection() { } public final native void addStream(JsMediaStream stream)/*-{ this.peerConnection.addStream(stream); }-*/; public final native void addIceCandidate(int label, String candidate)/*-{ this.peerConnection.addIceCandidate(new RTCIceCandidate({sdpMLineIndex: label, candidate: candidate})); }-*/; public final native void close()/*-{ this.peerConnection.close(); }-*/; public final native void createOffer(JsSessionDescriptionCallback callback)/*-{ var sdpConstraints = { 'mandatory': { 'OfferToReceiveAudio': true, 'OfferToReceiveVideo': false } }; this.peerConnection.createOffer(function(offer) { callback.@im.actor.runtime.js.webrtc.JsSessionDescriptionCallback::onOfferCreated(*)(offer); }, function(error) { $wnd.console.warn(error); callback.@im.actor.runtime.js.webrtc.JsSessionDescriptionCallback::onOfferFailure(*)(); }, sdpConstraints); }-*/; public final native void createAnswer(JsSessionDescriptionCallback callback)/*-{ var sdpConstraints = { 'mandatory': { 'OfferToReceiveAudio': true, 'OfferToReceiveVideo': false } }; this.peerConnection.createAnswer(function(offer) { callback.@im.actor.runtime.js.webrtc.JsSessionDescriptionCallback::onOfferCreated(*)(offer); }, function(error) { $wnd.console.warn(error); callback.@im.actor.runtime.js.webrtc.JsSessionDescriptionCallback::onOfferFailure(*)(); }, sdpConstraints); }-*/; public final native void setRemoteDescription(JsSessionDescription description, JsClosure closure, JsClosureError error)/*-{ this.peerConnection.setRemoteDescription(description, function() { [email protected]::callback(*)(); }, function(e) { $wnd.console.warn(e); [email protected]::onError(*)(e); }); }-*/; public final native void setLocalDescription(JsSessionDescription description, JsClosure closure, JsClosureError error)/*-{ this.peerConnection.setLocalDescription(description, function() { [email protected]::callback(*)(); }, function(e) { $wnd.console.warn(e); [email protected]::onError(*)(e); }); }-*/; public final native void setListener(JsPeerConnectionListener listener)/*-{ this.peerConnection.onicecandidate = function(candidate) { if (candidate.candidate != null) { [email protected]::onIceCandidate(*)(candidate.candidate); } }; this.peerConnection.onaddstream = function(event) { [email protected]::onStreamAdded(*)(event.stream); } this.peerConnection.onremovestream = function(event) { [email protected]::onStreamRemoved(*)(event.stream); } this.peerConnection.onnegotiationneeded = function(event) { [email protected]::onRenegotiationNeeded(*)(); } }-*/; }
39.31068
128
0.653989
02222e87795e12651a330b21c6ba5c0267af3d3c
2,332
package net.sf.jabb.cache; import static org.junit.Assert.*; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import net.sf.ehcache.CacheException; import net.sf.ehcache.CacheManager; import org.junit.Test; public class AbstractEhCachedKeyValueRepositoryTest { @Test public void testDeletion() throws InterruptedException { final AtomicInteger values = new AtomicInteger(0); final AtomicBoolean refreshNeeded = new AtomicBoolean(false); AbstractEhCachedKeyValueRepository<Integer, Integer> cachedRepo = new AbstractEhCachedKeyValueRepository<Integer, Integer>(){ @Override public String getValueScope() { return ""; } @Override public String getCacheName() { return "OrganizationIdByApiKeyCache"; } @Override public Integer getDirectly(Integer key) throws Exception { if (key < 1000){ int result = values.getAndIncrement(); if (result == 4){ return null; } else if (result == 3 || result == 5) { throw new RuntimeException("purposefully generated"); }else{ return result; } }else{ return null; } } @Override protected boolean refreshAheadNeeded(long accessTime, long createdTime, long expirationTime){ return refreshNeeded.get(); } }; cachedRepo.cacheManager = CacheManager.newInstance(); cachedRepo.threadPool = Executors.newCachedThreadPool(); cachedRepo.initializeCache(); // 0 load assertEquals(Integer.valueOf(0), cachedRepo.get(100)); assertNull(cachedRepo.get(1001)); // 1 reload cachedRepo.onValueChanged(100); assertEquals(Integer.valueOf(1), cachedRepo.get(100)); // 2 reload cachedRepo.onValueChanged(100); assertEquals(Integer.valueOf(2), cachedRepo.get(100)); refreshNeeded.set(true); // 3 failed to update cachedRepo.onValueChanged(100); Thread.sleep(500); assertEquals(Integer.valueOf(2), cachedRepo.get(100)); Thread.sleep(500); refreshNeeded.set(false); // 4 deleted cachedRepo.onValueChanged(100); Thread.sleep(500); assertNull(cachedRepo.get(100)); Thread.sleep(500); // 5 failed to load try{ assertNull(cachedRepo.get(100)); fail("should throw CacheException"); }catch(CacheException e){ // good } } }
24.808511
127
0.711407
4f879011de39260eaede0de578707111511e8021
2,475
package com.netease.edu.sample.parameter; public class WhiteboardG2RecordFileInfoCallbackParam { private String eventType; private RecordFileData data; public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public RecordFileData getData() { return data; } public void setData(RecordFileData data) { this.data = data; } public static class RecordFileData { /** * 点播文件id,注意白板录制文件(gz)无此字段。通过该参数可以调用点播接口查询相关信息。 */ private String vid; /** * 文件名,直接存储,混合录制文件filename带有"-mix"标记 */ private String fileName; private Long recordTime; private Long size; private String channelName; private String channelId; private String url; private String md5; private Long timestamp; public String getVid() { return vid; } public void setVid(String vid) { this.vid = vid; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public Long getRecordTime() { return recordTime; } public void setRecordTime(Long recordTime) { this.recordTime = recordTime; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } public String getChannelName() { return channelName; } public void setChannelName(String channelName) { this.channelName = channelName; } public String getChannelId() { return channelId; } public void setChannelId(String channelId) { this.channelId = channelId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public Long getTimestamp() { return timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } } }
19.8
56
0.536162
0604ec6ef91f61fcca8cd0955762b8bfce78a22e
7,458
/* * Copyright (c) 2010-2017 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.provisioning.ucf.api; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import java.util.Collection; /** * @author Radovan Semancik * */ public final class Change implements DebugDumpable { /* * Object identification: these values should be reasonably filled-in on Change object creation. */ private Object primaryIdentifierRealValue; // we might reconsider this in the future private Collection<ResourceAttribute<?>> identifiers; private ObjectClassComplexTypeDefinition objectClassDefinition; /* * Usually either of the following two should be present. An exception is a notification-only change event. */ /** * This starts as a (converted) resource object. Gradually it gets augmented with shadow information, * but the process needs to be clarified. See MID-5834. */ private PrismObject<ShadowType> currentResourceObject; /** * Delta from the resource - if known. Substantial e.g. for asynchronous updates. */ private ObjectDelta<ShadowType> objectDelta; /** * Token is used only in live synchronization process. */ private PrismProperty<?> token; /** * Original value of the corresponding shadow stored in repository. * * This is usually filled-in during change processing in provisioning module. (Except for notifyChange calls: TBD.) */ private PrismObject<ShadowType> oldRepoShadow; /** * This means that the change is just a notification that a resource object has changed. To know about its state * it has to be fetched. For notification-only changes both objectDelta and currentResourceObject have to be null. * (And this flag is introduced to distinguish intentional notification-only changes from malformed ones that have * both currentResourceObject and objectDelta missing.) */ private boolean notificationOnly; /** * When token is present. */ public Change(Object primaryIdentifierRealValue, Collection<ResourceAttribute<?>> identifiers, PrismObject<ShadowType> currentResourceObject, ObjectDelta<ShadowType> delta, PrismProperty<?> token) { this.primaryIdentifierRealValue = primaryIdentifierRealValue; this.identifiers = identifiers; this.currentResourceObject = currentResourceObject; this.objectDelta = delta; this.token = token; } /** * When token is not present. */ public Change(Object primaryIdentifierRealValue, Collection<ResourceAttribute<?>> identifiers, PrismObject<ShadowType> currentResourceObject, ObjectDelta<ShadowType> delta) { this.primaryIdentifierRealValue = primaryIdentifierRealValue; this.identifiers = identifiers; this.currentResourceObject = currentResourceObject; this.objectDelta = delta; } private Change() { } public ObjectDelta<ShadowType> getObjectDelta() { return objectDelta; } public void setObjectDelta(ObjectDelta<ShadowType> change) { this.objectDelta = change; } public Collection<ResourceAttribute<?>> getIdentifiers() { return identifiers; } public void setIdentifiers(Collection<ResourceAttribute<?>> identifiers) { this.identifiers = identifiers; } public ObjectClassComplexTypeDefinition getObjectClassDefinition() { return objectClassDefinition; } public void setObjectClassDefinition(ObjectClassComplexTypeDefinition objectClassDefinition) { this.objectClassDefinition = objectClassDefinition; } public PrismProperty<?> getToken() { return token; } public void setToken(PrismProperty<?> token) { this.token = token; } public PrismObject<ShadowType> getOldRepoShadow() { return oldRepoShadow; } public void setOldRepoShadow(PrismObject<ShadowType> oldRepoShadow) { this.oldRepoShadow = oldRepoShadow; } public PrismObject<ShadowType> getCurrentResourceObject() { return currentResourceObject; } public void setCurrentResourceObject(PrismObject<ShadowType> currentResourceObject) { this.currentResourceObject = currentResourceObject; } public void setNotificationOnly(boolean notificationOnly) { this.notificationOnly = notificationOnly; } public boolean isNotificationOnly() { return notificationOnly; } public boolean isDelete() { return objectDelta != null && objectDelta.isDelete(); } // todo what if delta is null, oldShadow is null, current is not null? public boolean isAdd() { return objectDelta != null && objectDelta.isAdd(); } @Override public String toString() { return "Change(uid=" + primaryIdentifierRealValue + ",identifiers=" + identifiers + ", objectDelta=" + objectDelta + ", token=" + token + ", oldRepoShadow=" + oldRepoShadow + ", currentResourceObject=" + currentResourceObject + ")"; } @Override public String debugDump() { return debugDump(0); } @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); DebugUtil.indentDebugDump(sb, 0); sb.append("Change"); if (notificationOnly) { sb.append(" (notification only)"); } sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, "primaryIdentifierValue", String.valueOf(primaryIdentifierRealValue), indent + 1); sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, "identifiers", identifiers, indent + 1); sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, "objectDelta", objectDelta, indent + 1); sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, "objectClassDefinition", objectClassDefinition, indent + 1); sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, "token", token, indent + 1); sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, "oldRepoShadow", oldRepoShadow, indent + 1); sb.append("\n"); DebugUtil.debugDumpWithLabel(sb, "currentResourceObject", currentResourceObject, indent + 1); return sb.toString(); } public String getOid() { if (objectDelta != null && objectDelta.getOid() != null) { return objectDelta.getOid(); } else if (currentResourceObject.getOid() != null) { return currentResourceObject.getOid(); } else if (oldRepoShadow.getOid() != null) { return oldRepoShadow.getOid(); } else { throw new IllegalArgumentException("No oid value defined for the object to synchronize."); } } public Object getPrimaryIdentifierRealValue() { return primaryIdentifierRealValue; } }
35.179245
143
0.687316
cf2f1e6d1e9e81cdd8b6b0c399aa0c2eabc4c931
1,455
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.auth.api.accounttransfer; import android.os.RemoteException; import com.google.android.gms.internal.auth.zzaf; import com.google.android.gms.internal.auth.zzz; // Referenced classes of package com.google.android.gms.auth.api.accounttransfer: // AccountTransferClient final class zzd extends AccountTransferClient.zzc { zzd(AccountTransferClient accounttransferclient, zzaf zzaf) { zzao = zzaf; // 0 0:aload_0 // 1 1:aload_2 // 2 2:putfield #10 <Field zzaf zzao> super(((zzc) (null))); // 3 5:aload_0 // 4 6:aconst_null // 5 7:invokespecial #13 <Method void AccountTransferClient$zzc(zzc)> // 6 10:return } protected final void zza(zzz zzz1) throws RemoteException { zzz1.zza(((com.google.android.gms.internal.auth.zzx) (zzax)), zzao); // 0 0:aload_1 // 1 1:aload_0 // 2 2:getfield #22 <Field com.google.android.gms.internal.auth.zzy zzax> // 3 5:aload_0 // 4 6:getfield #10 <Field zzaf zzao> // 5 9:invokeinterface #27 <Method void zzz.zza(com.google.android.gms.internal.auth.zzx, zzaf)> // 6 14:return } private final zzaf zzao; }
32.333333
104
0.63299
eefd66612dfad29ecfc33d545d6d555d47de6fe4
4,226
package tech.heartin.books.serverlesscookbook; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.BufferedReader; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import org.json.simple.JSONObject; import org.json.simple.parser.ParseException; import org.json.simple.parser.JSONParser; /** * Proxy Stream Handler. */ public class ProxyStreamHandlerLambda implements RequestStreamHandler { /** * handleRequest implementation. * @param inputStream - Input stream from API Gateway. * @param outputStream - Output stream to API Gateway. * @param context - Context. * @throws IOException - If something goes wrong. */ public final void handleRequest(final InputStream inputStream, final OutputStream outputStream, final Context context) throws IOException { LambdaLogger logger = context.getLogger(); context.getLogger().log("Inside Proxy Stream Handler."); final String greeting = generateGreetingFromInputStream(inputStream); final JSONObject responseJson = generateResponseJson(greeting); logger.log(responseJson.toJSONString()); OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); writer.write(responseJson.toJSONString()); writer.close(); } private String generateGreetingFromInputStream(final InputStream inputStream) { final JSONParser parser = new JSONParser(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String name = "User"; String application = ""; String time = "Day"; String userAgent = ""; try { final JSONObject event = (JSONObject) parser.parse(reader); if (event.get("pathParameters") != null) { JSONObject pathParams = (JSONObject) event.get("pathParameters"); if (pathParams.get("proxy") != null) { application = (String) pathParams.get("proxy"); } } if (event.get("queryStringParameters") != null) { JSONObject queryParams = (JSONObject) event.get("queryStringParameters"); if (queryParams.get("name") != null) { name = (String) queryParams.get("name"); } } if (event.get("body") != null) { JSONObject body = (JSONObject) parser.parse((String) event.get("body")); if (body.get("time") != null) { time = (String) body.get("time"); } } if (event.get("headers") != null) { JSONObject headers = (JSONObject) event.get("headers"); if (headers.get("User-Agent") != null) { userAgent = (String) headers.get("User-Agent"); } } } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } String greeting = "Good " + time + ", " + name + ". "; greeting += "Welcome to " + application + ". "; if (!userAgent.equals("")) { greeting += "Client User-Agent is " + userAgent + "."; } return greeting; } private JSONObject generateResponseJson(final String greeting) { JSONObject responseBody = new JSONObject(); responseBody.put("message", greeting); JSONObject headers = new JSONObject(); //Not required, shown to demo the possibility. headers.put("Content-Type", "application/json"); JSONObject responseJson = new JSONObject(); responseJson.put("isBase64Encoded", false); responseJson.put("statusCode", "200"); responseJson.put("headers", headers); responseJson.put("body", responseBody.toString()); return responseJson; } }
34.92562
93
0.604591