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
f049c54e425cc6588f450637e3adcb201415d78a
4,434
package org.factcast.client.grpc; import static io.grpc.stub.ClientCalls.*; import java.util.List; import java.util.Optional; import java.util.OptionalLong; import java.util.UUID; import java.util.stream.Collectors; import org.factcast.core.Fact; import org.factcast.core.store.FactStore; import org.factcast.core.subscription.Subscription; import org.factcast.core.subscription.SubscriptionImpl; import org.factcast.core.subscription.SubscriptionRequestTO; import org.factcast.core.subscription.observer.FactObserver; import org.factcast.grpc.api.conv.ProtoConverter; import org.factcast.grpc.api.gen.FactStoreProto; import org.factcast.grpc.api.gen.FactStoreProto.MSG_Fact; import org.factcast.grpc.api.gen.FactStoreProto.MSG_Facts; import org.factcast.grpc.api.gen.FactStoreProto.MSG_Notification; import org.factcast.grpc.api.gen.FactStoreProto.MSG_OptionalFact; import org.factcast.grpc.api.gen.FactStoreProto.MSG_SubscriptionRequest; import org.factcast.grpc.api.gen.RemoteFactStoreGrpc; import org.factcast.grpc.api.gen.RemoteFactStoreGrpc.RemoteFactStoreBlockingStub; import org.factcast.grpc.api.gen.RemoteFactStoreGrpc.RemoteFactStoreStub; import org.springframework.beans.factory.annotation.Autowired; import com.google.common.annotations.VisibleForTesting; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.stub.StreamObserver; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import net.devh.springboot.autoconfigure.grpc.client.AddressChannelFactory; /** * Adapter that implements a FactStore by calling a remote one via GRPC. * * @author [email protected] * */ @Slf4j class GrpcFactStore implements FactStore { static final String CHANNEL_NAME = "factstore"; final RemoteFactStoreBlockingStub blockingStub; final RemoteFactStoreStub stub; final ProtoConverter converter = new ProtoConverter(); @Autowired GrpcFactStore(AddressChannelFactory channelFactory) { this(channelFactory.createChannel(CHANNEL_NAME)); } @VisibleForTesting GrpcFactStore(@NonNull Channel channel) { this(RemoteFactStoreGrpc.newBlockingStub(channel), RemoteFactStoreGrpc.newStub(channel)); } @VisibleForTesting GrpcFactStore(@NonNull RemoteFactStoreBlockingStub newBlockingStub, @NonNull RemoteFactStoreStub newStub) { this.blockingStub = newBlockingStub; this.stub = newStub; } @Override public Optional<Fact> fetchById(UUID id) { log.trace("fetching {} from remote store", id); MSG_OptionalFact fetchById = blockingStub.fetchById(converter.toProto(id)); if (!fetchById.getPresent()) { return Optional.empty(); } else { return converter.fromProto(fetchById); } } @Override public void publish(@NonNull List<? extends Fact> factsToPublish) { try { log.trace("publishing {} facts to remote store", factsToPublish.size()); List<MSG_Fact> mf = factsToPublish.stream().map(converter::toProto).collect(Collectors .toList()); MSG_Facts mfs = MSG_Facts.newBuilder().addAllFact(mf).build(); blockingStub.publish(mfs); } catch (Exception e) { log.warn("failed to publish {} facts: {}", factsToPublish.size(), e); } } @Override public Subscription subscribe(@NonNull SubscriptionRequestTO req, @NonNull FactObserver observer) { SubscriptionImpl<Fact> subscription = SubscriptionImpl.on(observer); StreamObserver<FactStoreProto.MSG_Notification> responseObserver = new ClientStreamObserver( subscription); ClientCall<MSG_SubscriptionRequest, MSG_Notification> call = stub.getChannel().newCall( RemoteFactStoreGrpc.METHOD_SUBSCRIBE, stub.getCallOptions() .withWaitForReady() .withCompression("gzip")); asyncServerStreamingCall(call, converter.toProto(req), responseObserver); return subscription.onClose(() -> { cancel(call); }); } private void cancel(final ClientCall<MSG_SubscriptionRequest, MSG_Notification> call) { call.cancel("Client is no longer interested", null); } @Override public OptionalLong serialOf(@NonNull UUID l) { return converter.fromProto(blockingStub.serialOf(converter.toProto(l))); } }
35.190476
100
0.723049
de21c291c9dfaace5b9f1adda81b36233c0155f4
1,055
package seedu.address.commons.core; /** * Container for user visible messages. */ public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MULTIPLE_INPUT_FOR_SAME_PREFIX = "There should be no more than one input for each prefix!"; public static final String MESSAGE_INVALID_CLIENT_DISPLAYED_ID = "The client ID provided is invalid"; public static final String MESSAGE_INVALID_HAIRDRESSER_DISPLAYED_ID = "The hairdresser ID provided is invalid"; public static final String MESSAGE_HAIRDRESSER_LISTED_OVERVIEW = "%1$d hairdressers listed!"; public static final String MESSAGE_CLIENT_LISTED_OVERVIEW = "%1$d clients listed!"; public static final String MESSAGE_APPOINTMENT_LISTED_OVERVIEW = "%1$d appointments listed!"; public static final String MESSAGE_INVALID_APPOINTMENT_DISPLAYED_ID = "The appointment ID provided is invalid"; }
52.75
115
0.772512
8678c020d283434e7e6f9af5e730a76e696e2838
3,071
package meteorapegaso.meteorus.util; import meteorapegaso.meteorus.achievements.AchievementManager; import meteorapegaso.meteorus.blocks.MeteorusBlockHandler; import meteorapegaso.meteorus.items.MeteorusItemHandler; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import cpw.mods.fml.common.ICraftingHandler; public class CraftingHandler implements ICraftingHandler{ @Override public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix) { //ProjectCarved for(int i=0; i < craftMatrix.getSizeInventory(); i++) { if(craftMatrix.getStackInSlot(i) != null) { ItemStack j = craftMatrix.getStackInSlot(i); if(j.getItem() != null && j.getItem() == MeteorusItemHandler.ProjectCarvedStone) { ItemStack k = new ItemStack(MeteorusItemHandler.ProjectCarvedStone.itemID, 2, (j.getItemDamage() + 2)); if(k.getItemDamage() >= k.getMaxDamage()){ k.stackSize--; } craftMatrix.setInventorySlotContents(i, k); } } } //Chisel for(int i=0; i < craftMatrix.getSizeInventory(); i++) { if(craftMatrix.getStackInSlot(i) != null) { ItemStack j = craftMatrix.getStackInSlot(i); if(j.getItem() != null && j.getItem() == MeteorusItemHandler.Chisel) { ItemStack k = new ItemStack(MeteorusItemHandler.Chisel.itemID, 2, (j.getItemDamage() + 2)); if(k.getItemDamage() >= k.getMaxDamage()){ k.stackSize--; } craftMatrix.setInventorySlotContents(i, k); } } } //Hammer for(int i=0; i < craftMatrix.getSizeInventory(); i++) { if(craftMatrix.getStackInSlot(i) != null) { ItemStack j = craftMatrix.getStackInSlot(i); if(j.getItem() != null && j.getItem() == MeteorusItemHandler.Hammer) { ItemStack k = new ItemStack(MeteorusItemHandler.Hammer.itemID, 2, (j.getItemDamage() + 1)); if(k.getItemDamage() >= k.getMaxDamage()){ k.stackSize--; } craftMatrix.setInventorySlotContents(i, k); } } } //Achievement if (item.itemID == MeteorusBlockHandler.ColoredStones.blockID) { player.addStat(AchievementManager.TIME_OF_DECORATIONS, 1); } if (item.itemID == MeteorusBlockHandler.ColoredStoneBricks.blockID) { player.addStat(AchievementManager.BRICKS_COLORS, 1); } if (item.itemID == MeteorusBlockHandler.ColoredStoneCarvedBricks.blockID) { player.addStat(AchievementManager.BRICKS_CHISELED, 1); } if (item.itemID == MeteorusBlockHandler.ProjectTable.blockID) { player.addStat(AchievementManager.PROJECT_TABLE, 1); } } @Override public void onSmelting(EntityPlayer player, ItemStack item) { if (item.itemID == MeteorusBlockHandler.ColoredStones.blockID) { player.addStat(AchievementManager.TIME_OF_DECORATIONS, 1); } } }
32.326316
114
0.650277
94abee0bd40d2da0a9bc9ae8500ccd15b84719e2
526
/** * */ package com.airsltd.core.data; /** * The block data has not been set up correctly. This is a coding issue. * * @author Jon Boley * */ public class AirsExtBlockInializationException extends RuntimeException { /** * */ private static final long serialVersionUID = -5947686206032548272L; public <T extends IBlockDataExt<? extends IBlockData>> AirsExtBlockInializationException(Class<T> p_class) { super("Unable to find IComplexDataHooks for class: " + p_class.getName()); } }
21.916667
110
0.692015
287e05b4dc54d1f3c653242bf1fa799c3b13dc14
6,642
package com.github.tonywills.xkcdviewer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.ShareActionProvider; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.github.tonywills.xkcdviewer.api.XkcdService; import com.github.tonywills.xkcdviewer.api.model.Comic; import com.google.gson.Gson; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; public class ViewComicFragment extends Fragment { private static final String TAG = "ViewComicFragment"; public static final int MODE_RANDOM = 0x0457; public static final int MODE_LATEST = 0x1745; public static final int MODE_SPECIFIC = 0x0473; private static final String ARG_MODE = "mode"; private static final String ARG_COMIC = "comic"; private static final String ARG_HAS_PARENT = "hasParent"; @BindView(R.id.image_view) ImageView imageView; private ComicViewerListener listener; private Comic comic; private int mode; private boolean hasParent; private ShareActionProvider shareActionProvider; public static ViewComicFragment newInstance(int mode) { ViewComicFragment fragment = new ViewComicFragment(); Bundle args = new Bundle(); args.putInt(ARG_MODE, mode); fragment.setArguments(args); return fragment; } public static ViewComicFragment newInstance(Comic comic) { ViewComicFragment fragment = new ViewComicFragment(); Bundle args = new Bundle(); args.putInt(ARG_MODE, MODE_SPECIFIC); args.putString(ARG_COMIC, new Gson().toJson(comic)); args.putBoolean(ARG_HAS_PARENT, true); fragment.setArguments(args); return fragment; } public ViewComicFragment() { // Required empty public constructor } @Override public void onAttach(Context context) { super.onAttach(context); attachListener(context); } @SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) { super.onAttach(activity); attachListener(activity); } private void attachListener(Context context) { listener = (ComicViewerListener) context; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mode = getArguments().getInt(ARG_MODE, 0); hasParent = getArguments().getBoolean(ARG_HAS_PARENT, false); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) { return inflater.inflate(R.layout.fragment_view_comic, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, getActivity()); loadComic(); } @Override public void onResume() { super.onResume(); try { ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); assert actionBar != null; actionBar.setDisplayHomeAsUpEnabled(hasParent); } catch (ClassCastException | NullPointerException e) { Log.d(TAG, "onCreate: Couldn't set home button"); } } private void loadComic() { switch (mode) { case MODE_LATEST: listener.setTitleFromComicViewer("Latest"); XkcdService.getInstance(getContext()).getLatestComic(comicCallback); break; case MODE_RANDOM: listener.setTitleFromComicViewer("Random Comic"); XkcdService.getInstance(getContext()).getRandomComic(comicCallback); break; case MODE_SPECIFIC: comicCallback.complete( new Gson().fromJson(getArguments().getString(ARG_COMIC), Comic.class)); break; default: Log.w(TAG, "onViewCreated: No mode selected", new Exception("No mode set")); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.comic, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (getActivity() != null) { getActivity().onBackPressed(); } return true; case R.id.action_share: shareComic(); return true; case R.id.action_star: XkcdService.getInstance(getContext()).setComicFavourite(comic, !comic.isFavourite()); item.setIcon(comic.isFavourite() ? R.drawable.ic_star_filled : R.drawable.ic_star_outline); return true; default: return super.onOptionsItemSelected(item); } } private XkcdService.ComicCallback comicCallback = new XkcdService.ComicCallback() { @Override public void complete(@Nullable Comic comic) { if (comic != null) { ViewComicFragment.this.comic = comic; listener.setTitleFromComicViewer(comic.getTitle()); imageView.setContentDescription(comic.getAlt()); Context context = getContext(); if (context != null) { Picasso.with(context) .load(comic.getImg()) .into(imageView); } } } }; private void shareComic() { if (comic == null) { return; } Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TITLE, comic.getTitle()); shareIntent.putExtra(Intent.EXTRA_TEXT, comic.getImg()); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, "Share with...")); } public interface ComicViewerListener { void setTitleFromComicViewer(String title); } }
35.329787
107
0.651009
81a64ce7194b0cbc5eb993c19df70ee85ccb900b
308
/* * Copyright (c) 2014 xxworkshop. All rights reserved. * Created by Broche Xu on 4/22/14 5:42 PM. */ package com.xxworkshop.common.formatter; public enum Anchor { LeftTop, CenterTop, RightTop, LeftCenter, Center, RightCenter, LeftBottom, CenterBottom, RightBottom }
17.111111
54
0.665584
c71ae499737d417b17bcc72b094b8be0fc87e3f7
4,791
/* * Copyright 2014-2016 Media for Mobile * * 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.m4m.samples; import android.content.Context; import android.util.Log; import org.m4m.android.AndroidMediaObjectFactory; import org.m4m.android.AudioFormatAndroid; import org.m4m.android.VideoFormatAndroid; import java.io.IOException; public class VideoCapture { private static final String TAG = "VideoCapture"; private int width = 1280; private int height = 720; private static final int frameRate = 30; private static final int iFrameInterval = 1; private static final int bitRate = 3000; private static final String codec = "video/avc"; private static final Object syncObject = new Object(); private org.m4m.VideoFormat videoFormat; private org.m4m.GLCapture capture; private boolean isStarted; private boolean isConfigured; private Context context; private org.m4m.IProgressListener progressListener; public VideoCapture(Context context, org.m4m.IProgressListener progressListener, int width, int height) { this.width = width; this.height = height; this.context = context; this.progressListener = progressListener; initVideoFormat(); } public void start(String videoPath) throws IOException { Log.i(TAG, "start"); if (isStarted()) { throw new IllegalStateException(TAG + " already started!"); } capture = new org.m4m.GLCapture(new AndroidMediaObjectFactory(context), progressListener); Log.i(TAG, "start2 " + videoFormat.getVideoCodec() + " " + videoFormat.getMimeType() + " " + videoFormat.toString()); capture.setTargetFile(videoPath); capture.setTargetVideoFormat(videoFormat); Log.i(TAG, "start3"); org.m4m.AudioFormat audioFormat = new AudioFormatAndroid("audio/mp4a-latm", 44100, 1); Log.i(TAG, "start3_1"); capture.setTargetAudioFormat(audioFormat); Log.i(TAG, "start4"); capture.start(); Log.i(TAG, "start5"); isStarted = true; isConfigured = false; } public void start(org.m4m.StreamingParameters params) throws IOException { if (isStarted()) { throw new IllegalStateException(TAG + " already started!"); } capture = new org.m4m.GLCapture(new AndroidMediaObjectFactory(context), progressListener); capture.setTargetConnection(params); capture.setTargetVideoFormat(videoFormat); capture.start(); isStarted = true; isConfigured = false; } public void stop() { if (!isStarted()) { throw new IllegalStateException(TAG + " not started or already stopped!"); } capture.stop(); capture = null; isConfigured = false; } private boolean configure() { if (isConfigured()) { return true; } try { capture.setSurfaceSize(width, height); isConfigured = true; } catch (Exception ex) { Log.e("VideoCapture", ex.getMessage(), ex); } return isConfigured; } public boolean beginCaptureFrame() { if (!isStarted()) { return false; } if (!isConfigured()) { if (!configure()) { return false; } } capture.beginCaptureFrame(); return true; } public void endCaptureFrame() { if (!isStarted()) { return; } if (!isConfigured()) { return; } capture.endCaptureFrame(); } public boolean isStarted() { if (capture == null) { return false; } return isStarted; } public boolean isConfigured() { return isConfigured; } public int getFrameWidth() { return width; } public int getFrameHeight() { return height; } private void initVideoFormat() { videoFormat = new VideoFormatAndroid(codec, width, height); videoFormat.setVideoBitRateInKBytes(bitRate); videoFormat.setVideoFrameRate(frameRate); videoFormat.setVideoIFrameInterval(iFrameInterval); } }
27.067797
125
0.628261
2376efe267636808665b5d142ed357df458ed989
929
package android.support.v4.widget; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /* renamed from: android.support.v4.widget.u */ public abstract class C0386u extends C0362f { private int f701j; private int f702k; private LayoutInflater f703l; @Deprecated public C0386u(Context context, int i, Cursor cursor, boolean z) { super(context, cursor, z); this.f702k = i; this.f701j = i; this.f703l = (LayoutInflater) context.getSystemService("layout_inflater"); } public View m1820a(Context context, Cursor cursor, ViewGroup viewGroup) { return this.f703l.inflate(this.f701j, viewGroup, false); } public View m1821b(Context context, Cursor cursor, ViewGroup viewGroup) { return this.f703l.inflate(this.f702k, viewGroup, false); } }
29.967742
82
0.709365
9b112cf394da6da397e6f4a484ef81099c4ab153
679
package cn.lueans.lueansread; import android.app.Application; import android.support.v7.app.AppCompatDelegate; import com.raizlabs.android.dbflow.config.FlowManager; import im.fir.sdk.FIR; /** * Created by 24277 on 2017/2/23. */ public class App extends Application { private static App mContext; @Override public void onCreate() { FlowManager.init(this); FIR.init(this); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); super.onCreate(); } //单例模式 public static App getInstance(){ if (mContext == null) { mContext = new App(); } return mContext; } }
20.575758
80
0.655376
f79dd20291da74990626802ed200a898d7150a78
1,654
package me.StevenLawson.TotalFreedomMod.commands; import org.apache.commons.lang3.StringUtils; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; @CommandPermissions(level = AdminLevel.ALL, source = SourceType.BOTH) @CommandParameters(description = "Show all commands for all server plugins.", usage = "/<command>") public class Command_cmdlist extends FreedomCommand { @Override public boolean run(CommandSender sender, org.bukkit.entity.Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { List<String> commands = new ArrayList<String>(); for (Plugin targetPlugin : server.getPluginManager().getPlugins()) { try { PluginDescriptionFile desc = targetPlugin.getDescription(); Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) desc.getCommands(); if (map != null) { for (Entry<String, Map<String, Object>> entry : map.entrySet()) { String command_name = (String) entry.getKey(); commands.add(command_name); } } } catch (Throwable ex) { } } Collections.sort(commands); sender.sendMessage(StringUtils.join(commands, ",")); return true; } }
34.458333
155
0.628174
ac7f9dfd619b7f353a0f5b5b7d288997911c3f92
77
package org.subra.aem.commons.helpers; public interface ActivatonHelper { }
15.4
38
0.805195
db6bfa11c114c7929e66839b1dd2f95ede610918
3,221
package org.springframework.roo.project; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.roo.support.util.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Unit test of the {@link Execution} class * * @author Andrew Swan * @since 1.2.0 */ public class ExecutionTest extends XmlTestCase { private static final String EXECUTION_CONFIGURATION_XML = " <configuration>\n" + " <sources>\n" + " <source>src/main/groovy</source>\n" + " </sources>\n" + " </configuration>\n"; private static final String GOAL_1 = "lock"; private static final String GOAL_2 = "load"; private static final String[] GOALS = { GOAL_1, GOAL_2 }; private static final String ID = "some-id"; private static final String PHASE = "test"; private static final String EXECUTION_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<execution>\n" + " <id>" + ID + "</id>\n" + " <phase>" + PHASE + "</phase>\n" + " <goals>\n" + " <goal>" + GOAL_1 + "</goal>\n" + " <goal>" + GOAL_2 + "</goal>\n" + " </goals>\n" + EXECUTION_CONFIGURATION_XML + "</execution>"; // Fixture @Mock private Configuration mockConfiguration; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testExecutionWithConfigurationDoesNotEqualOneWithout() { // Set up final Execution execution1 = new Execution(ID, PHASE, GOALS); final Execution execution2 = new Execution(ID, PHASE, mockConfiguration, GOALS); // Invoke assertFalse(execution1.equals(execution2)); assertFalse(execution2.equals(execution1)); } @Test public void testGetElementForMinimalExecution() throws Exception { // Set up final Document document = DOCUMENT_BUILDER.newDocument(); final Configuration mockConfiguration = mock(Configuration.class); when(mockConfiguration.getConfiguration()).thenReturn( XmlUtils.stringToElement(EXECUTION_CONFIGURATION_XML)); final Execution execution = new Execution(ID, PHASE, mockConfiguration, GOALS); // Invoke final Element element = execution.getElement(document); // Check assertXmlEquals(EXECUTION_XML, element); } @Test public void testIdenticalExecutionsAreEqual() { assertEquals(new Execution(ID, PHASE, mockConfiguration, GOALS), new Execution(ID, PHASE, mockConfiguration, GOALS)); } @Test public void testIdenticalExecutionsWithNoConfigurationAreEqual() { assertEquals(new Execution(ID, PHASE, GOALS), new Execution(ID, PHASE, GOALS)); } }
32.535354
94
0.613474
4e7549fac421f6a5c30c515c8a7dd674bb56a53f
1,498
/* Soot - a J*va Optimization Framework * Copyright (C) 2002 Sable Research Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ package soot.util.dot; /** * A class for specifying Dot graph attributes. * * @author Feng Qian */ public class DotGraphAttribute { String id; String value; public DotGraphAttribute(String id, String v){ this.id = id; this.value = v; } public String toString(){ StringBuffer line = new StringBuffer(); line.append(this.id); line.append("="); line.append(this.value); return new String(line); } }
29.372549
74
0.71028
36036e4728e0588bc3c833a3917a064cf4951b0e
25,484
package io.github.humbleui.skija; import java.lang.ref.*; import org.jetbrains.annotations.*; import io.github.humbleui.skija.impl.*; import io.github.humbleui.types.*; public class Paint extends Managed { static { Library.staticLoad(); } @ApiStatus.Internal public static class _FinalizerHolder { public static final long PTR = _nGetFinalizer(); } @ApiStatus.Internal public Paint(long ptr, boolean managed) { super(ptr, _FinalizerHolder.PTR, managed); } /** * Constructs SkPaint with default values. * * @see <a href="https://fiddle.skia.org/c/@Paint_empty_constructor">https://fiddle.skia.org/c/@Paint_empty_constructor</a> */ public Paint() { super(_nMake(), _FinalizerHolder.PTR); Stats.onNativeCall(); } /** * <p>Makes a shallow copy of Paint. PathEffect, Shader, * MaskFilter, ColorFilter, and ImageFilter are shared * between the original paint and the copy.</p> * * <p>The referenced objects PathEffect, Shader, MaskFilter, ColorFilter, * and ImageFilter cannot be modified after they are created.</p> * * @return shallow copy of paint * * @see <a href="https://fiddle.skia.org/c/@Paint_copy_const_SkPaint">https://fiddle.skia.org/c/@Paint_copy_const_SkPaint</a> */ @NotNull @Contract("-> new") public Paint makeClone() { try { Stats.onNativeCall(); return new Paint(_nMakeClone(_ptr), true); } finally { Reference.reachabilityFence(this); } } @ApiStatus.Internal @Override public boolean _nativeEquals(Native other) { try { return _nEquals(_ptr, Native.getPtr(other)); } finally { Reference.reachabilityFence(this); Reference.reachabilityFence(other); } } /** * Sets all Paint contents to their initial values. This is equivalent to replacing * Paint with the result of Paint(). * * @see <a href="https://fiddle.skia.org/c/@Paint_reset">https://fiddle.skia.org/c/@Paint_reset</a> */ @NotNull @Contract("-> this") public Paint reset() { Stats.onNativeCall(); _nReset(_ptr); return this; } /** * Returns true if pixels on the active edges of Path may be drawn with partial transparency. * * @return antialiasing state */ public boolean isAntiAlias() { try { Stats.onNativeCall(); return _nIsAntiAlias(_ptr); } finally { Reference.reachabilityFence(this); } } /** * Requests, but does not require, that edge pixels draw opaque or with partial transparency. * * @param value setting for antialiasing */ @NotNull @Contract("_ -> this") public Paint setAntiAlias(boolean value) { Stats.onNativeCall(); _nSetAntiAlias(_ptr, value); return this; } /** * @return true if color error may be distributed to smooth color transition. */ public boolean isDither() { try { Stats.onNativeCall(); return _nIsDither(_ptr); } finally { Reference.reachabilityFence(this); } } /** * Requests, but does not require, to distribute color error. * * @param value setting for ditering * @return this */ @NotNull @Contract("_ -> this") public Paint setDither(boolean value) { Stats.onNativeCall(); _nSetDither(_ptr, value); return this; } /** * @return whether the geometry is filled, stroked, or filled and stroked. */ @NotNull public PaintMode getMode() { try { Stats.onNativeCall(); return PaintMode._values[_nGetMode(_ptr)]; } finally { Reference.reachabilityFence(this); } } /** * Sets whether the geometry is filled, stroked, or filled and stroked. * * @see <a href="https://fiddle.skia.org/c/@Paint_setStyle">https://fiddle.skia.org/c/@Paint_setStyle</a> * @see <a href="https://fiddle.skia.org/c/@Stroke_Width">https://fiddle.skia.org/c/@Stroke_Width</a> */ @NotNull @Contract("!null -> this; null -> fail") public Paint setMode(@NotNull PaintMode style) { assert style != null : "Paint::setMode expected style != null"; Stats.onNativeCall(); _nSetMode(_ptr, style.ordinal()); return this; } /** * Set paint's mode to STROKE if true, or FILL if false. * * @param value stroke or fill * @return this */ @NotNull @Contract("_ -> this") public Paint setStroke(boolean value) { return setMode(value ? PaintMode.STROKE : PaintMode.FILL); } /** * Retrieves alpha and RGB, unpremultiplied, packed into 32 bits. * Use helpers {@link Color#getA(int)}, {@link Color#getR(int)}, {@link Color#getG(int)}, and {@link Color#getB(int)} to extract * a color component. * * @return unpremultiplied ARGB */ public int getColor() { try { Stats.onNativeCall(); return _nGetColor(_ptr); } finally { Reference.reachabilityFence(this); } } /** * Retrieves alpha and RGB, unpremultiplied, as four floating point values. RGB are * extended sRGB values (sRGB gamut, and encoded with the sRGB transfer function). * * @return unpremultiplied RGBA */ @NotNull public Color4f getColor4f() { try { Stats.onNativeCall(); return _nGetColor4f(_ptr); } finally { Reference.reachabilityFence(this); } } /** * Sets alpha and RGB used when stroking and filling. The color is a 32-bit value, * unpremultiplied, packing 8-bit components for alpha, red, blue, and green. * * @param color unpremultiplied ARGB * * @see <a href="https://fiddle.skia.org/c/@Paint_setColor">https://fiddle.skia.org/c/@Paint_setColor</a> */ @NotNull @Contract("_ -> this") public Paint setColor(int color) { Stats.onNativeCall(); _nSetColor(_ptr, color); return this; } /** * Sets alpha and RGB used when stroking and filling. The color is four floating * point values, unpremultiplied. The color values are interpreted as being in sRGB. * * @param color unpremultiplied RGBA * @return this */ @NotNull @Contract("!null -> this; null -> fail") public Paint setColor4f(@NotNull Color4f color) { return setColor4f(color, null); } /** * Sets alpha and RGB used when stroking and filling. The color is four floating * point values, unpremultiplied. The color values are interpreted as being in * the colorSpace. If colorSpace is nullptr, then color is assumed to be in the * sRGB color space. * * @param color unpremultiplied RGBA * @param colorSpace SkColorSpace describing the encoding of color * @return this */ @NotNull @Contract("!null, _ -> this; null, _ -> fail") public Paint setColor4f(@NotNull Color4f color, @Nullable ColorSpace colorSpace) { try { assert color != null : "Paint::setColor4f expected color != null"; Stats.onNativeCall(); _nSetColor4f(_ptr, color.getR(), color.getG(), color.getB(), color.getA(), Native.getPtr(colorSpace)); return this; } finally { Reference.reachabilityFence(colorSpace); } } /** * Retrieves alpha from the color used when stroking and filling. * * @return alpha ranging from 0f, fully transparent, to 1f, fully opaque */ public float getAlphaf() { return getColor4f().getA(); } /** * Retrieves alpha from the color used when stroking and filling. * * @return alpha ranging from 0, fully transparent, to 255, fully opaque */ public int getAlpha() { return Math.round(getAlphaf() * 255f); } /** * <p>Replaces alpha, leaving RGB unchanged. An out of range value triggers * an assert in the debug build. a is a value from 0f to 1f.</p> * * <p>a set to zero makes color fully transparent; a set to 1.0 makes color * fully opaque.</p> * * @param a alpha component of color * @return this */ @NotNull @Contract("_ -> this") public Paint setAlphaf(float a) { return setColor4f(getColor4f().withA(a)); } /** * <p>Replaces alpha, leaving RGB unchanged. An out of range value triggers * an assert in the debug build. a is a value from 0 to 255.</p> * * <p>a set to zero makes color fully transparent; a set to 255 makes color * fully opaque.</p> * * @param a alpha component of color * @return this */ @NotNull @Contract("_ -> this") public Paint setAlpha(int a) { return setAlphaf(a / 255f); } /** * Sets color used when drawing solid fills. The color components range from 0 to 255. * The color is unpremultiplied; alpha sets the transparency independent of RGB. * * @param a amount of alpha, from fully transparent (0) to fully opaque (255) * @param r amount of red, from no red (0) to full red (255) * @param g amount of green, from no green (0) to full green (255) * @param b amount of blue, from no blue (0) to full blue (255) * * @see <a href="https://fiddle.skia.org/c/@Paint_setARGB">https://fiddle.skia.org/c/@Paint_setARGB</a> */ @NotNull @Contract("_, _, _, _ -> this") public Paint setARGB(int a, int r, int g, int b) { Stats.onNativeCall(); _nSetColor4f(_ptr, r / 255f, g / 255f, b / 255f, a / 255f, 0); return this; } /** * Returns the thickness of the pen used by Paint to outline the shape. * * @return zero for hairline, greater than zero for pen thickness */ public float getStrokeWidth() { try { Stats.onNativeCall(); return _nGetStrokeWidth(_ptr); } finally { Reference.reachabilityFence(this); } } /** * Sets the thickness of the pen used by the paint to outline the shape. * A stroke-width of zero is treated as "hairline" width. Hairlines are always exactly one * pixel wide in device space (their thickness does not change as the canvas is scaled). * Negative stroke-widths are invalid; setting a negative width will have no effect. * * @param width zero thickness for hairline; greater than zero for pen thickness * * @see <a href="https://fiddle.skia.org/c/@Miter_Limit">https://fiddle.skia.org/c/@Miter_Limit</a> * @see <a href="https://fiddle.skia.org/c/@Paint_setStrokeWidth">https://fiddle.skia.org/c/@Paint_setStrokeWidth</a> */ @NotNull @Contract("_ -> this") public Paint setStrokeWidth(float width) { Stats.onNativeCall(); _nSetStrokeWidth(_ptr, width); return this; } /** * Returns the limit at which a sharp corner is drawn beveled. * * @return zero and greater miter limit */ public float getStrokeMiter() { try { Stats.onNativeCall(); return _nGetStrokeMiter(_ptr); } finally { Reference.reachabilityFence(this); } } /** * Sets the limit at which a sharp corner is drawn beveled. * Valid values are zero and greater. * Has no effect if miter is less than zero. * * @param miter zero and greater miter limit * @return this * * @see <a href="https://fiddle.skia.org/c/@Paint_setStrokeMiter">https://fiddle.skia.org/c/@Paint_setStrokeMiter</a> */ @NotNull @Contract("_ -> this") public Paint setStrokeMiter(float miter) { Stats.onNativeCall(); _nSetStrokeMiter(_ptr, miter); return this; } /** * @return the geometry drawn at the beginning and end of strokes. */ @NotNull @Contract("-> this") public PaintStrokeCap getStrokeCap() { try { Stats.onNativeCall(); return PaintStrokeCap._values[_nGetStrokeCap(_ptr)]; } finally { Reference.reachabilityFence(this); } } /** * Sets the geometry drawn at the beginning and end of strokes. * * @return this * * @see <a href="https://fiddle.skia.org/c/@Paint_setStrokeCap_a">https://fiddle.skia.org/c/@Paint_setStrokeCap_a</a> * @see <a href="https://fiddle.skia.org/c/@Paint_setStrokeCap_b">https://fiddle.skia.org/c/@Paint_setStrokeCap_b</a> */ @NotNull @Contract("!null -> this; null -> fail") public Paint setStrokeCap(@NotNull PaintStrokeCap cap) { assert cap != null : "Paint::setStrokeCap expected cap != null"; Stats.onNativeCall(); _nSetStrokeCap(_ptr, cap.ordinal()); return this; } /** * @return the geometry drawn at the corners of strokes. */ @NotNull @Contract("-> this") public PaintStrokeJoin getStrokeJoin() { try { Stats.onNativeCall(); return PaintStrokeJoin._values[_nGetStrokeJoin(_ptr)]; } finally { Reference.reachabilityFence(this); } } /** * Sets the geometry drawn at the corners of strokes. * * @return this * * @see <a href="https://fiddle.skia.org/c/@Paint_setStrokeJoin">https://fiddle.skia.org/c/@Paint_setStrokeJoin</a> */ @NotNull @Contract("!null -> this; null -> fail") public Paint setStrokeJoin(@NotNull PaintStrokeJoin join) { assert join != null : "Paint::setStrokeJoin expected join != null"; Stats.onNativeCall(); _nSetStrokeJoin(_ptr, join.ordinal()); return this; } /** * Returns the filled equivalent of the stroked path. * * @param src Path read to create a filled version * @return resulting Path */ @NotNull @Contract("!null -> new; null -> fail") public Path getFillPath(@NotNull Path src) { return getFillPath(src, null, 1); } /** * Returns the filled equivalent of the stroked path. * * @param src Path read to create a filled version * @param cull Optional limit passed to PathEffect * @param resScale if &gt; 1, increase precision, else if (0 &lt; resScale &lt; 1) reduce precision * to favor speed and size * @return resulting Path */ @NotNull @Contract("!null, _, _ -> new; null, _, _ -> fail") public Path getFillPath(@NotNull Path src, @Nullable Rect cull, float resScale) { try { assert src != null : "Paint::getFillPath expected src != null"; Stats.onNativeCall(); if (cull == null) return new Path(_nGetFillPath(_ptr, Native.getPtr(src), resScale)); else return new Path(_nGetFillPathCull(_ptr, Native.getPtr(src), cull._left, cull._top, cull._right, cull._bottom, resScale)); } finally { Reference.reachabilityFence(this); Reference.reachabilityFence(src); } } /** * @return {@link Shader} or null * @see <a href="https://fiddle.skia.org/c/@Paint_refShader">https://fiddle.skia.org/c/@Paint_refShader</a> */ @Nullable public Shader getShader() { try { Stats.onNativeCall(); long shaderPtr = _nGetShader(_ptr); return shaderPtr == 0 ? null : new Shader(shaderPtr); } finally { Reference.reachabilityFence(this); } } /** * @param shader how geometry is filled with color; if null, color is used instead * * @see <a href="https://fiddle.skia.org/c/@Color_Filter_Methods">https://fiddle.skia.org/c/@Color_Filter_Methods</a> * @see <a href="https://fiddle.skia.org/c/@Paint_setShader">https://fiddle.skia.org/c/@Paint_setShader</a> */ @NotNull @Contract("_ -> this") public Paint setShader(@Nullable Shader shader) { try { Stats.onNativeCall(); _nSetShader(_ptr, Native.getPtr(shader)); return this; } finally { Reference.reachabilityFence(shader); } } /** * @return {@link ColorFilter} or null * @see <a href="https://fiddle.skia.org/c/@Paint_refColorFilter">https://fiddle.skia.org/c/@Paint_refColorFilter</a> */ @Nullable public ColorFilter getColorFilter() { try { Stats.onNativeCall(); long colorFilterPtr = _nGetColorFilter(_ptr); return colorFilterPtr == 0 ? null : new ColorFilter(colorFilterPtr); } finally { Reference.reachabilityFence(this); } } /** * @param colorFilter {@link ColorFilter} to apply to subsequent draw * * @see <a href="https://fiddle.skia.org/c/@Blend_Mode_Methods">https://fiddle.skia.org/c/@Blend_Mode_Methods</a> * @see <a href="https://fiddle.skia.org/c/@Paint_setColorFilter">https://fiddle.skia.org/c/@Paint_setColorFilter</a> */ @NotNull @Contract("_ -> this") public Paint setColorFilter(@Nullable ColorFilter colorFilter) { try { Stats.onNativeCall(); _nSetColorFilter(_ptr, Native.getPtr(colorFilter)); return this; } finally { Reference.reachabilityFence(colorFilter); } } /** * Returns BlendMode. By default, returns {@link BlendMode#SRC_OVER}. * * @return mode used to combine source color with destination color */ @Nullable public BlendMode getBlendMode() { try { Stats.onNativeCall(); return BlendMode._values[_nGetBlendMode(_ptr)]; } finally { Reference.reachabilityFence(this); } } /** * @return true if BlendMode is BlendMode.SRC_OVER, the default. */ public boolean isSrcOver() { return getBlendMode() == BlendMode.SRC_OVER; } /** * Sets SkBlendMode to mode. Does not check for valid input. * * @param mode BlendMode used to combine source color and destination * @return this */ @NotNull @Contract("!null -> this; null -> fail") public Paint setBlendMode(@NotNull BlendMode mode) { assert mode != null : "Paint::setBlendMode expected mode != null"; Stats.onNativeCall(); _nSetBlendMode(_ptr, mode.ordinal()); return this; } /** * @return {@link PathEffect} or null * @see <a href="https://fiddle.skia.org/c/@Paint_refPathEffect">https://fiddle.skia.org/c/@Paint_refPathEffect</a> */ @Nullable public PathEffect getPathEffect() { try { Stats.onNativeCall(); long pathEffectPtr = _nGetPathEffect(_ptr); return pathEffectPtr == 0 ? null : new PathEffect(pathEffectPtr); } finally { Reference.reachabilityFence(this); } } /** * @param p replace {@link Path} with a modification when drawn * * @see <a href="https://fiddle.skia.org/c/@Mask_Filter_Methods">https://fiddle.skia.org/c/@Mask_Filter_Methods</a> * @see <a href="https://fiddle.skia.org/c/@Paint_setPathEffect">https://fiddle.skia.org/c/@Paint_setPathEffect</a> */ @NotNull @Contract("_ -> this") public Paint setPathEffect(@Nullable PathEffect p) { try { Stats.onNativeCall(); _nSetPathEffect(_ptr, Native.getPtr(p)); return this; } finally { Reference.reachabilityFence(p); } } /** * @return {@link MaskFilter} if previously set, null otherwise * @see <a href="https://fiddle.skia.org/c/@Paint_refMaskFilter">https://fiddle.skia.org/c/@Paint_refMaskFilter</a> */ @Nullable public MaskFilter getMaskFilter() { try { Stats.onNativeCall(); long maskFilterPtr = _nGetMaskFilter(_ptr); return maskFilterPtr == 0 ? null : new MaskFilter(maskFilterPtr); } finally { Reference.reachabilityFence(this); } } /** * @param maskFilter modifies clipping mask generated from drawn geometry * @return this * * @see <a href="https://fiddle.skia.org/c/@Paint_setMaskFilter">https://fiddle.skia.org/c/@Paint_setMaskFilter</a> * @see <a href="https://fiddle.skia.org/c/@Typeface_Methods">https://fiddle.skia.org/c/@Typeface_Methods</a> */ @NotNull @Contract("_ -> this") public Paint setMaskFilter(@Nullable MaskFilter maskFilter) { try { Stats.onNativeCall(); _nSetMaskFilter(_ptr, Native.getPtr(maskFilter)); return this; } finally { Reference.reachabilityFence(maskFilter); } } /** * @return {@link ImageFilter} or null * @see <a href="https://fiddle.skia.org/c/@Paint_refImageFilter">https://fiddle.skia.org/c/@Paint_refImageFilter</a> */ @Nullable public ImageFilter getImageFilter() { try { Stats.onNativeCall(); long imageFilterPtr = _nGetImageFilter(_ptr); return imageFilterPtr == 0 ? null : new ImageFilter(imageFilterPtr); } finally { Reference.reachabilityFence(this); } } /** * @param imageFilter how SkImage is sampled when transformed * * @see <a href="https://fiddle.skia.org/c/@Draw_Looper_Methods">https://fiddle.skia.org/c/@Draw_Looper_Methods</a> * @see <a href="https://fiddle.skia.org/c/@Paint_setImageFilter">https://fiddle.skia.org/c/@Paint_setImageFilter</a> */ @NotNull @Contract("_ -> this") public Paint setImageFilter(@Nullable ImageFilter imageFilter) { try { Stats.onNativeCall(); _nSetImageFilter(_ptr, Native.getPtr(imageFilter)); return this; } finally { Reference.reachabilityFence(imageFilter); } } /** * <p>Returns true if Paint prevents all drawing; * otherwise, the Paint may or may not allow drawing.</p> * * <p>Returns true if, for example, BlendMode combined with alpha computes a * new alpha of zero.</p> * * @return true if Paint prevents all drawing * * @see <a href="https://fiddle.skia.org/c/@Paint_nothingToDraw">https://fiddle.skia.org/c/@Paint_nothingToDraw</a> */ public boolean hasNothingToDraw() { try { Stats.onNativeCall(); return _nHasNothingToDraw(_ptr); } finally { Reference.reachabilityFence(this); } } public static native long _nGetFinalizer(); public static native long _nMake(); public static native long _nMakeClone(long ptr); public static native boolean _nEquals(long ptr, long otherPtr); public static native void _nReset(long ptr); public static native boolean _nIsAntiAlias(long ptr); public static native void _nSetAntiAlias(long ptr, boolean value); public static native boolean _nIsDither(long ptr); public static native void _nSetDither(long ptr, boolean value); public static native int _nGetMode(long ptr); public static native void _nSetMode(long ptr, int value); public static native int _nGetColor(long ptr); public static native Color4f _nGetColor4f(long ptr); public static native void _nSetColor(long ptr, int argb); public static native void _nSetColor4f(long ptr, float r, float g, float b, float a, long colorSpacePtr); public static native float _nGetStrokeWidth(long ptr); public static native void _nSetStrokeWidth(long ptr, float value); public static native float _nGetStrokeMiter(long ptr); public static native void _nSetStrokeMiter(long ptr, float value); public static native int _nGetStrokeCap(long ptr); public static native void _nSetStrokeCap(long ptr, int value); public static native int _nGetStrokeJoin(long ptr); public static native void _nSetStrokeJoin(long ptr, int value); public static native long _nGetFillPath(long ptr, long path, float resScale); public static native long _nGetFillPathCull(long ptr, long path, float left, float top, float right, float bottom, float resScale); public static native long _nGetShader(long ptr); public static native void _nSetShader(long ptr, long shaderPtr); public static native long _nGetColorFilter(long ptr); public static native void _nSetColorFilter(long ptr, long colorFilterPtr); public static native int _nGetBlendMode(long ptr); public static native void _nSetBlendMode(long ptr, int mode); public static native long _nGetPathEffect(long ptr); public static native void _nSetPathEffect(long ptr, long pathEffectPtr); public static native long _nGetMaskFilter(long ptr); public static native void _nSetMaskFilter(long ptr, long filterPtr); public static native long _nGetImageFilter(long ptr); public static native void _nSetImageFilter(long ptr, long filterPtr); public static native boolean _nHasNothingToDraw(long ptr); }
35.198895
137
0.61258
9eb0c8fa73319957b5162dcb61caae7aa7192092
143
package id.ac.ui.pusilkom.odontogram.enums; /** * Created by fahri on 4/24/17. */ public enum HLinePart { HALF_RIGHT, HALF_LEFT, FULL }
15.888889
43
0.692308
986a226c358b3f537d642d37fc909989f8815f41
90
/** * orm4j8で使用するクラスをまとめたパッケージ * * @author 417.72KI */ package jp.natsukishina.orm4j8;
15
31
0.711111
a1503437b7f4f42baed528232eea037969f4147a
1,602
/* * 0blivi0n-cache * ============== * Java REST Client * * Copyright (C) 2015 Joaquim Rocha <[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 net.uiqui.oblivion.client.api.model; public class Node { private String node = null; private boolean online = true; private String server = null; private int port = 0; private int broadcast = 0; private int http = 0; public String getNode() { return node; } public void setNode(String node) { this.node = node; } public boolean isOnline() { return online; } public void setOnline(boolean online) { this.online = online; } public String getServer() { return server; } public void setServer(String server) { this.server = server; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public int getBroadcast() { return broadcast; } public void setBroadcast(int broadcast) { this.broadcast = broadcast; } public int getHttp() { return http; } public void setHttp(int http) { this.http = http; } }
20.538462
76
0.687266
41d8a5d2aad2e9eb35b17c710f9dc270b7138a75
8,304
package com.medialink.submission4.view; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.snackbar.Snackbar; import com.medialink.submission4.Const; import com.medialink.submission4.FavoriteMovieContract; import com.medialink.submission4.R; import com.medialink.submission4.database.FavoriteHelper; import com.medialink.submission4.helper.MappingHelper; import com.medialink.submission4.model.FavoriteItem; import com.medialink.submission4.model.movie.MovieItem; import com.medialink.submission4.presenter.FavoritePresenter; import com.medialink.submission4.view.adapter.MovieFavoriteAdapter; import java.lang.ref.WeakReference; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; /** * A simple {@link Fragment} subclass. */ public class MovieFavoriteFragment extends Fragment implements LoadMovieFavCallback, FavoriteMovieContract.ViewInterface { private Unbinder unbinder; private final static String TAG = MovieFavoriteFragment.class.getSimpleName(); @BindView(R.id.progress_fav_movie) ProgressBar progressFavMovie; @BindView(R.id.rv_fav_movie) RecyclerView rvFavMovie; @BindView(R.id.movie_layout) CoordinatorLayout movieLayout; private FavoritePresenter mPresenter; private MovieFavoriteAdapter adapter; private FavoriteHelper favoriteHelper; private static final String EXTRA_STATE = "extra_state"; public MovieFavoriteFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_movie_favorite, container, false); unbinder = ButterKnife.bind(this, view); mPresenter = new FavoritePresenter(this, getContext()); rvFavMovie.setLayoutManager(new LinearLayoutManager(getContext())); rvFavMovie.addItemDecoration(new DividerItemDecoration(getContext(), RecyclerView.VERTICAL)); rvFavMovie.setHasFixedSize(true); adapter = new MovieFavoriteAdapter(getContext(), this); rvFavMovie.setAdapter(adapter); favoriteHelper = FavoriteHelper.getInstance(getContext()); favoriteHelper.open(); // proses ambil data if (savedInstanceState == null) { // proses ambil data new LoadFavoriteAsync(favoriteHelper, this).execute(); } else { ArrayList<FavoriteItem> list = savedInstanceState.getParcelableArrayList(EXTRA_STATE); if (list != null) { adapter.setFavItem(list); } progressFavMovie.setVisibility(View.GONE); } return view; } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelableArrayList(EXTRA_STATE, adapter.getFavItem()); } @Override public void onDestroy() { super.onDestroy(); unbinder.unbind(); } @Override public void preExecute() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { progressFavMovie.setVisibility(View.VISIBLE); } }); } @Override public void postExecute(ArrayList<FavoriteItem> favList) { progressFavMovie.setVisibility(View.GONE); if (favList.size() > 0) { adapter.setFavItem(favList); } else { adapter.setFavItem(new ArrayList<FavoriteItem>()); showSnackbarMessage("Tidak ada data saat ini"); } } @Override public void setMovie(ArrayList<MovieItem> list) { } @Override public void itemFavoriteClick(FavoriteItem movie, int position) { Intent i = new Intent(getContext(), DetailActivity.class); i.putExtra(Const.KEY_ID, movie.getMovie_id()); i.putExtra(Const.KEY_TYPE, Const.INTENT_MOVIE); i.putExtra("POSITION", position); startActivityForResult(i, 103); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (data != null) { if (requestCode == 103) { if (resultCode == 1031) { int position = data.getIntExtra("POSITION", 0); adapter.removeItem(position); showSnackbarMessage("Satu item berhasil dihapus"); } } } } @Override public void itemDelete(String id, int position) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext()); alertDialogBuilder.setTitle("Hapus Favorite"); alertDialogBuilder .setMessage("Anda Yakin Ingin Hapus Favorite Ini?") .setCancelable(false) .setPositiveButton("Ya", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { mPresenter.itemDelete(id, position); Log.d(TAG, "itemDelete: hapus disini"); } }) .setNegativeButton("Tidak", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } @Override public void setError(String msg) { } @Override public void showMessage(String msg) { Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } @Override public void refreshAddItem(FavoriteItem favItem) { adapter.addItem(favItem); } @Override public void refreshUpdateItem(int position, FavoriteItem favItem) { adapter.updateItem(position, favItem); } @Override public void refreshRemoveItem(int position) { adapter.removeItem(position); } private static class LoadFavoriteAsync extends AsyncTask<Void, Void, ArrayList<FavoriteItem>> { private final WeakReference<FavoriteHelper> weakFavoriteHelper; private final WeakReference<LoadMovieFavCallback> weakCallback; public LoadFavoriteAsync(FavoriteHelper favHelper, LoadMovieFavCallback callback) { this.weakFavoriteHelper = new WeakReference<>(favHelper); this.weakCallback = new WeakReference<>(callback); } @Override protected void onPreExecute() { super.onPreExecute(); weakCallback.get().preExecute(); } @Override protected ArrayList<FavoriteItem> doInBackground(Void... voids) { Cursor dataCursor = weakFavoriteHelper.get().queryAll(Const.MOVIE_TYPE); return MappingHelper.mapCursorToArrayList(dataCursor); } @Override protected void onPostExecute(ArrayList<FavoriteItem> favoriteItems) { super.onPostExecute(favoriteItems); weakCallback.get().postExecute(favoriteItems); } } private void showSnackbarMessage(String message) { Snackbar.make(rvFavMovie, message, Snackbar.LENGTH_SHORT).show(); } } interface LoadMovieFavCallback { void preExecute(); void postExecute(ArrayList<FavoriteItem> notes); }
32.822134
101
0.67329
f59c777bba2945de2d26788d8b32835edc36513f
1,425
/* * Copyright 2016 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.bot.spring.boot.common; import java.util.ArrayList; import java.util.List; public class ErrCheck { private static List<String> ERR_WORDS; static { ERR_WORDS = new ArrayList<String>(); ERR_WORDS.add("神"); ERR_WORDS.add("お題"); ERR_WORDS.add("お題取得"); ERR_WORDS.add("題"); ERR_WORDS.add("配布"); ERR_WORDS.add("ヘルプ"); } /** * エラーの時true. */ public static boolean checkOdai(String odai) { boolean result = false; if (odai == null) { return true; } try { Integer.parseInt(odai); result = true; } catch (NumberFormatException e) { for (String tmp : ERR_WORDS) { if (tmp.equals(odai)) { result = true; break; } } } return result; } }
23.360656
78
0.649825
93d413f1116999ae009ddad3904e75c93155368f
572
/** * Title: BasicFrame.java * Description: My first basic AWT (Windows Programming) frame. * Copyright: Copyright (c) 2015 * Student No: C00137009 * @author Daniel Hayden * @version 1.0 */ import java.awt.*; import java.awt.event.*; @SuppressWarnings("serial") class BasicFrame extends Frame{ public BasicFrame(){ setSize(200, 150); setTitle("This is My Frame"); setBackground(Color.lightGray); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0);}}); } }
23.833333
63
0.65035
51b508f90c823b52b6c89b6989ab292bf6c5a2b3
4,268
/* * Copyright 2019 IIT Software GmbH * * IIT Software GmbH licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.swiftmq.impl.scheduler.standard; import com.swiftmq.mgmt.Entity; import com.swiftmq.mgmt.EntityList; import com.swiftmq.swiftlet.SwiftletManager; import com.swiftmq.swiftlet.log.LogSwiftlet; import com.swiftmq.swiftlet.queue.QueueManager; import com.swiftmq.swiftlet.threadpool.ThreadpoolSwiftlet; import com.swiftmq.swiftlet.timer.TimerSwiftlet; import com.swiftmq.swiftlet.topic.TopicManager; import com.swiftmq.swiftlet.trace.TraceSpace; import com.swiftmq.swiftlet.trace.TraceSwiftlet; public class SwiftletContext { public static final String JOBGROUP = "Scheduler"; public static final String JOBNAME = "Message Sender"; public static final String PARM = "ID"; public static final String PROP_SCHED_ID = "JMS_SWIFTMQ_SCHEDULER_ID"; public static final String PROP_SCHED_DEST = "JMS_SWIFTMQ_SCHEDULER_DESTINATION"; public static final String PROP_SCHED_DEST_TYPE = "JMS_SWIFTMQ_SCHEDULER_DESTINATION_TYPE"; public static final String PROP_SCHED_CALENDAR = "JMS_SWIFTMQ_SCHEDULER_CALENDAR"; public static final String PROP_SCHED_TIME = "JMS_SWIFTMQ_SCHEDULER_TIME_EXPRESSION"; public static final String PROP_SCHED_EXPIRATION = "JMS_SWIFTMQ_SCHEDULER_EXPIRATION"; public static final String PROP_SCHED_FROM = "JMS_SWIFTMQ_SCHEDULER_DATE_FROM"; public static final String PROP_SCHED_TO = "JMS_SWIFTMQ_SCHEDULER_DATE_TO"; public static final String PROP_SCHED_ENABLE_LOGGING = "JMS_SWIFTMQ_SCHEDULER_ENABLE_LOGGING"; public static final String PROP_SCHED_MAY_EXPIRE = "JMS_SWIFTMQ_SCHEDULER_MAY_EXPIRE_WHILE_ROUTER_DOWN"; public static final String REQUEST_QUEUE = "swiftmqscheduler"; public static final String INTERNAL_QUEUE = "sys$scheduler"; public static final String QUEUE = "queue"; public static final String TOPIC = "topic"; public SchedulerSwiftletImpl schedulerSwiftlet = null; public TraceSwiftlet traceSwiftlet = null; public TraceSpace traceSpace = null; public LogSwiftlet logSwiftlet = null; public TimerSwiftlet timerSwiftlet = null; public ThreadpoolSwiftlet threadpoolSwiftlet = null; public QueueManager queueManager = null; public TopicManager topicManager = null; public Entity root = null; public EntityList jobGroupList = null; public EntityList activeScheduleList = null; public EntityList activeMessageScheduleList = null; public Scheduler scheduler = null; public SwiftletContext(SchedulerSwiftletImpl schedulerSwiftlet, Entity root) throws Exception { this.schedulerSwiftlet = schedulerSwiftlet; this.root = root; traceSwiftlet = (TraceSwiftlet) SwiftletManager.getInstance().getSwiftlet("sys$trace"); logSwiftlet = (LogSwiftlet) SwiftletManager.getInstance().getSwiftlet("sys$log"); timerSwiftlet = (TimerSwiftlet) SwiftletManager.getInstance().getSwiftlet("sys$timer"); threadpoolSwiftlet = (ThreadpoolSwiftlet) SwiftletManager.getInstance().getSwiftlet("sys$threadpool"); queueManager = (QueueManager) SwiftletManager.getInstance().getSwiftlet("sys$queuemanager"); topicManager = (TopicManager) SwiftletManager.getInstance().getSwiftlet("sys$topicmanager"); traceSpace = traceSwiftlet.getTraceSpace(TraceSwiftlet.SPACE_KERNEL); jobGroupList = (EntityList) root.getEntity("usage").getEntity("job-groups"); activeScheduleList = (EntityList) root.getEntity("usage").getEntity("active-job-schedules"); activeMessageScheduleList = (EntityList) root.getEntity("usage").getEntity("active-message-schedules"); } public void close() throws Exception { } }
52.691358
111
0.772259
ac914ad1d8ffed4611f73a201fa734914750af76
4,303
package com.mobgen.halo.android.sdk.core.internal.startup; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.mobgen.halo.android.framework.common.annotations.Api; import com.mobgen.halo.android.framework.common.helpers.logger.Halog; import com.mobgen.halo.android.framework.common.utils.AssertionUtils; import com.mobgen.halo.android.sdk.api.Halo; import com.mobgen.halo.android.sdk.core.internal.startup.callbacks.HaloInstallationListener; import com.mobgen.halo.android.sdk.core.internal.startup.callbacks.ProcessListener; import com.mobgen.halo.android.sdk.core.internal.startup.processes.StartupProcess; import com.mobgen.halo.android.sdk.core.internal.startup.processes.StartupRunnableAdapter; import java.util.concurrent.atomic.AtomicInteger; /** * Manages the startup process to handle the different actions that should be performed * in the sdk. */ public class StartupManager implements ProcessListener { /** * The core. */ private Halo mHalo; /** * The callback to notify results. */ private HaloInstallationListener mInstallationListener; /** * Counter for pending processes. */ private AtomicInteger mCounter; /** * Checks if the manager has started. */ private boolean mIsRunning; /** * Checks if the startup process is finished. */ private boolean mIsFinished; /** * The handler for the main thread. */ private Handler mHandler; /** * The startup manager constructor that can handle the startup process. * * @param halo The halo instance. */ public StartupManager(@NonNull Halo halo) { AssertionUtils.notNull(halo, "halo"); mHalo = halo; mCounter = new AtomicInteger(0); mHandler = new Handler(Looper.getMainLooper()); } /** * Tells if the process has finished. * * @return True if finished, false otherwise. */ @Api(1.3) public boolean isRunning() { return mIsRunning; } /** * Tells if the startup process has finished. * * @return True if finished, false otherwise. */ @Api(1.3) public boolean hasFinished() { return mIsFinished; } /** * Adds an installation listener to handle the process of the installation. * * @param listener The listener. */ @Api(2.0) public void setInstallationListener(@Nullable HaloInstallationListener listener) { mInstallationListener = listener; } /** * Starts the process of the startup. * * @param processes The processes to execute. */ @Api(1.3) public synchronized void execute(@Nullable StartupProcess... processes) { if (processes == null || processes.length == 0) { notifyFinished(); } else { runProcesses(processes); } } @Override public synchronized void onProcessFinished() { Halog.d(getClass(), "Process finished"); if (mCounter.decrementAndGet() == 0) { mHandler.post(new Runnable() { @Override public void run() { notifyFinished(); } }); } } /** * Notifies the callbacks and clears the callbacks to avoid keeping references * from them. */ private synchronized void notifyFinished() { if (!mIsFinished) { mIsFinished = true; mIsRunning = false; mInstallationListener.onFinishedInstallation(); Halog.d(getClass(), "--- HALO SETUP FINISHED ---"); } } /** * Runs the processes stored. */ private synchronized void runProcesses(@NonNull StartupProcess... processes) { mIsFinished = false; mIsRunning = true; for (StartupProcess process : processes) { mCounter.incrementAndGet(); //Set listener process.setProcessListener(this); //Run StartupRunnableAdapter runnable = new StartupRunnableAdapter(mHalo, process); mHalo.framework().toolbox().queue().enqueue(process.getThreadPolicy(), runnable); } } }
29.272109
93
0.633976
a3e75fb9aa3d18dd7209b728ecf08f7b11120aa4
4,106
/******************************************************************************* * Copyright (c) 1991, 2021 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ package com.ibm.j9ddr.vm29.structure; /** * Structure: MM_MemorySubSpace * * This stub class represents a class that can return in memory offsets * to VM C and C++ structures. * * This particular implementation exists only to allow StructurePointer code to * compile at development time. This is never loaded at run time. * * At runtime generated byte codes returning actual offset values from the core file * will be loaded by the StructureClassLoader. */ public final class MM_MemorySubSpace { // VM Constants public static final long SIZEOF; // Offsets public static final int __allocationFailureStatsOffset_; public static final int __childrenOffset_; public static final int __collectorOffset_; public static final int __concurrentCollectableOffset_; public static final int __contractionSizeOffset_; public static final int __counterBalanceChainOffset_; public static final int __counterBalanceChainHeadOffset_; public static final int __counterBalanceSizeOffset_; public static final int __counterBalanceTypeOffset_; public static final int __currentSizeOffset_; public static final int __expansionSizeOffset_; public static final int __extensionsOffset_; public static final int __initialSizeOffset_; public static final int __isAllocatableOffset_; public static final int __lockOffset_; public static final int __maximumSizeOffset_; public static final int __memorySpaceOffset_; public static final int __memoryTypeOffset_; public static final int __minimumSizeOffset_; public static final int __nextOffset_; public static final int __objectFlagsOffset_; public static final int __parentOffset_; public static final int __physicalSubArenaOffset_; public static final int __previousOffset_; public static final int __regionListOffset_; public static final int __uniqueIDOffset_; public static final int __usesGlobalCollectorOffset_; // Static Initializer private static final boolean RUNTIME = false; static { if (!RUNTIME) { throw new IllegalArgumentException("This stub class should not be on your classpath"); } SIZEOF = 0; __allocationFailureStatsOffset_ = 0; __childrenOffset_ = 0; __collectorOffset_ = 0; __concurrentCollectableOffset_ = 0; __contractionSizeOffset_ = 0; __counterBalanceChainOffset_ = 0; __counterBalanceChainHeadOffset_ = 0; __counterBalanceSizeOffset_ = 0; __counterBalanceTypeOffset_ = 0; __currentSizeOffset_ = 0; __expansionSizeOffset_ = 0; __extensionsOffset_ = 0; __initialSizeOffset_ = 0; __isAllocatableOffset_ = 0; __lockOffset_ = 0; __maximumSizeOffset_ = 0; __memorySpaceOffset_ = 0; __memoryTypeOffset_ = 0; __minimumSizeOffset_ = 0; __nextOffset_ = 0; __objectFlagsOffset_ = 0; __parentOffset_ = 0; __physicalSubArenaOffset_ = 0; __previousOffset_ = 0; __regionListOffset_ = 0; __uniqueIDOffset_ = 0; __usesGlobalCollectorOffset_ = 0; } }
36.660714
135
0.754993
6c7ccb448c37f1deedefb013feaff096908a1fcd
5,561
/* * Copyright (c) 2019 The StreamX Project * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.streamxhub.streamx.console.core.runner; import com.streamxhub.streamx.common.conf.ConfigConst; import com.streamxhub.streamx.common.util.HdfsUtils; import com.streamxhub.streamx.console.base.util.WebUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import java.io.File; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author benjobs */ @Order @Slf4j @Component public class EnvInitializeRunner implements ApplicationRunner { @Autowired private ApplicationContext context; private String PROD_ENV_NAME = "prod"; @Override public void run(ApplicationArguments args) throws Exception { System.getProperties().setProperty( ConfigConst.KEY_STREAMX_HDFS_WORKSPACE(), context.getEnvironment().getProperty( ConfigConst.KEY_STREAMX_HDFS_WORKSPACE(), ConfigConst.STREAMX_HDFS_WORKSPACE_DEFAULT() ) ); String profiles = context.getEnvironment().getActiveProfiles()[0]; if (profiles.equals(PROD_ENV_NAME)) { String appUploads = ConfigConst.APP_UPLOADS(); if (!HdfsUtils.exists(appUploads)) { log.info("mkdir {} starting ...", appUploads); HdfsUtils.mkdirs(appUploads); } String appWorkspace = ConfigConst.APP_WORKSPACE(); if (!HdfsUtils.exists(appWorkspace)) { log.info("mkdir {} starting ...", appWorkspace); HdfsUtils.mkdirs(appWorkspace); } String appBackups = ConfigConst.APP_BACKUPS(); if (!HdfsUtils.exists(appBackups)) { log.info("mkdir {} starting ...", appBackups); HdfsUtils.mkdirs(appBackups); } String appSavePoints = ConfigConst.APP_SAVEPOINTS(); if (!HdfsUtils.exists(appSavePoints)) { log.info("mkdir {} starting ...", appSavePoints); HdfsUtils.mkdirs(appSavePoints); } String appJars = ConfigConst.APP_JARS(); if (!HdfsUtils.exists(appJars)) { log.info("mkdir {} starting ...", appJars); HdfsUtils.mkdirs(appJars); } String appPlugins = ConfigConst.APP_PLUGINS(); if (HdfsUtils.exists(appPlugins)) { HdfsUtils.delete(appPlugins); } HdfsUtils.mkdirs(appPlugins); String keepFile = ".gitkeep"; File plugins = new File(WebUtils.getAppDir("plugins")); for (File file : Objects.requireNonNull(plugins.listFiles())) { String plugin = appPlugins.concat("/").concat(file.getName()); if (!HdfsUtils.exists(plugin) && !keepFile.equals(file.getName())) { log.info("load plugin:{} to {}", file.getName(), appPlugins); HdfsUtils.upload(file.getAbsolutePath(), appPlugins, false, true); } } String appShims = ConfigConst.APP_SHIMS(); if (HdfsUtils.exists(appShims)) { HdfsUtils.delete(appShims); } String regex = "^streamx-flink-shims_flink-(1.12|1.13)-(.*).jar$"; Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); File[] shims = new File(WebUtils.getAppDir("lib")).listFiles(pathname -> pathname.getName().matches(regex)); for (File file : Objects.requireNonNull(shims)) { Matcher matcher = pattern.matcher(file.getName()); if (!keepFile.equals(file.getName()) && matcher.matches()) { String version = matcher.group(1); String shimsPath = appShims.concat("/flink-").concat(version); if (!HdfsUtils.exists(shimsPath)) { HdfsUtils.mkdirs(shimsPath); } log.info("load shims:{} to {}", file.getName(), shimsPath); HdfsUtils.upload(file.getAbsolutePath(), shimsPath, false, true); } } } else { log.warn("The local test environment is only used in the development phase to provide services to the console web, and many functions will not be available..."); } } }
40.007194
173
0.62255
22050335775a5407018e35635bc46466ff097a00
2,027
/** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ package com.raytheon.uf.viz.monitor.ffmp.ui.rsc; import java.util.List; /** * Holds the results of calculating forcings from the FFFGForceUtil. * * <pre> * * SOFTWARE HISTORY * * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Jun 17, 2013 2085 njensen Initial creation * * </pre> * * @author njensen * @version 1.0 */ public class ForceUtilResult { protected boolean forced; protected List<Long> pfafList; protected List<Long> forcedPfafList; /** * Constructor * * @param forced * @param pfafList * @param forcedPfafList */ protected ForceUtilResult(boolean forced, List<Long> pfafList, List<Long> forcedPfafList) { this.forced = forced; this.pfafList = pfafList; this.forcedPfafList = forcedPfafList; } /** * @return the forced */ public boolean isForced() { return forced; } /** * @return the forcedPfafList */ public List<Long> getForcedPfafList() { return forcedPfafList; } /** * @return the pfafList */ public List<Long> getPfafList() { return pfafList; } }
23.847059
70
0.596941
af733e7bbeac17b90c28b82720a05a8391fc1ff2
3,327
/* * Zeebe Workflow Engine * Copyright © 2017 camunda services GmbH ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.zeebe.engine.processor.workflow.deployment.model.transformer; import io.zeebe.engine.processor.workflow.deployment.model.BpmnStep; import io.zeebe.engine.processor.workflow.deployment.model.element.ExecutableCatchEvent; import io.zeebe.engine.processor.workflow.deployment.model.element.ExecutableEventBasedGateway; import io.zeebe.engine.processor.workflow.deployment.model.element.ExecutableWorkflow; import io.zeebe.engine.processor.workflow.deployment.model.transformation.ModelElementTransformer; import io.zeebe.engine.processor.workflow.deployment.model.transformation.TransformContext; import io.zeebe.model.bpmn.instance.EventBasedGateway; import io.zeebe.protocol.intent.WorkflowInstanceIntent; import java.util.List; import java.util.stream.Collectors; public class EventBasedGatewayTransformer implements ModelElementTransformer<EventBasedGateway> { @Override public Class<EventBasedGateway> getType() { return EventBasedGateway.class; } @Override public void transform(EventBasedGateway element, TransformContext context) { final ExecutableWorkflow workflow = context.getCurrentWorkflow(); final ExecutableEventBasedGateway gateway = workflow.getElementById(element.getId(), ExecutableEventBasedGateway.class); final List<ExecutableCatchEvent> connectedEvents = getConnectedCatchEvents(gateway); gateway.setEvents(connectedEvents); bindLifecycle(gateway); } private List<ExecutableCatchEvent> getConnectedCatchEvents( final ExecutableEventBasedGateway gateway) { return gateway.getOutgoing().stream() .map(e -> (ExecutableCatchEvent) e.getTarget()) .collect(Collectors.toList()); } private void bindLifecycle(final ExecutableEventBasedGateway gateway) { gateway.bindLifecycleState( WorkflowInstanceIntent.ELEMENT_ACTIVATING, BpmnStep.EVENT_BASED_GATEWAY_ELEMENT_ACTIVATING); gateway.bindLifecycleState( WorkflowInstanceIntent.ELEMENT_ACTIVATED, BpmnStep.EVENT_BASED_GATEWAY_ELEMENT_ACTIVATED); gateway.bindLifecycleState( WorkflowInstanceIntent.EVENT_OCCURRED, BpmnStep.EVENT_BASED_GATEWAY_EVENT_OCCURRED); gateway.bindLifecycleState( WorkflowInstanceIntent.ELEMENT_COMPLETING, BpmnStep.EVENT_BASED_GATEWAY_ELEMENT_COMPLETING); gateway.bindLifecycleState( WorkflowInstanceIntent.ELEMENT_COMPLETED, BpmnStep.EVENT_BASED_GATEWAY_ELEMENT_COMPLETED); gateway.bindLifecycleState( WorkflowInstanceIntent.ELEMENT_TERMINATING, BpmnStep.EVENT_BASED_GATEWAY_ELEMENT_TERMINATING); } }
45.575342
100
0.80012
8152eac73b5a4562aaa56dedc0e4c9dae04d25bb
251
package com.google.firebase.example.appindexing.model; public class Recipe { public String getTitle() { return ""; } public Note getNote() { return null; } public String getNoteUrl() { return ""; } }
15.6875
54
0.577689
78843a6f291c9e9a410952f33fca02d45a04f7df
353
package org.proteored.miapeapi.interfaces.ms; import org.proteored.miapeapi.cv.ms.ContactPositionMS; import org.proteored.miapeapi.interfaces.Contact; public interface MSContact extends Contact { /** * Gets the position of the contact. It should be one of the possible values * from {@link ContactPositionMS} */ public String getPosition(); }
27.153846
77
0.776204
9f92837007c523d6d3a067c251fbae09b9230a1d
19,168
package com.hedera.services.state.merkle; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 Hedera Hashgraph, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import com.hedera.services.fees.FeeMultiplierSource; import com.hedera.services.state.DualStateAccessor; import com.hedera.services.state.serdes.DomainSerdes; import com.hedera.services.state.submerkle.ExchangeRates; import com.hedera.services.state.submerkle.SequenceNumber; import com.hedera.services.throttles.DeterministicThrottle; import com.hedera.services.throttling.FunctionalityThrottling; import com.hederahashgraph.api.proto.java.FreezeTransactionBody; import com.swirlds.common.CommonUtils; import com.swirlds.common.io.SerializableDataInputStream; import com.swirlds.common.io.SerializableDataOutputStream; import com.swirlds.common.merkle.utility.AbstractMerkleLeaf; import com.swirlds.platform.state.DualStateImpl; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.annotation.Nullable; import java.io.IOException; import java.time.Instant; import java.util.List; import java.util.function.Supplier; import static com.hedera.services.context.properties.StaticPropertiesHolder.STATIC_PROPERTIES; import static com.hedera.services.state.submerkle.RichInstant.fromJava; import static java.util.stream.Collectors.toList; public class MerkleNetworkContext extends AbstractMerkleLeaf { private static final Logger log = LogManager.getLogger(MerkleNetworkContext.class); private static final String LINE_WRAP = "\n "; private static final String NOT_EXTANT = "<NONE>"; private static final String NOT_AVAILABLE = "<N/A>"; private static final String NOT_AVAILABLE_SUFFIX = " <N/A>"; public static final int UPDATE_FILE_HASH_LEN = 48; public static final int UNRECORDED_STATE_VERSION = -1; public static final long NO_PREPARED_UPDATE_FILE_NUM = -1; public static final byte[] NO_PREPARED_UPDATE_FILE_HASH = new byte[0]; static final int RELEASE_0130_VERSION = 2; static final int RELEASE_0140_VERSION = 3; static final int RELEASE_0150_VERSION = 4; static final int RELEASE_0190_VERSION = 5; static final int CURRENT_VERSION = RELEASE_0190_VERSION; static final long RUNTIME_CONSTRUCTABLE_ID = 0x8d4aa0f0a968a9f3L; static final Instant[] NO_CONGESTION_STARTS = new Instant[0]; static final DeterministicThrottle.UsageSnapshot[] NO_SNAPSHOTS = new DeterministicThrottle.UsageSnapshot[0]; public static final Instant UNKNOWN_CONSENSUS_TIME = null; static DomainSerdes serdes = new DomainSerdes(); static Supplier<ExchangeRates> ratesSupplier = ExchangeRates::new; static Supplier<SequenceNumber> seqNoSupplier = SequenceNumber::new; private int stateVersion = UNRECORDED_STATE_VERSION; private Instant[] congestionLevelStarts = NO_CONGESTION_STARTS; private ExchangeRates midnightRates; private Instant lastMidnightBoundaryCheck = null; private Instant consensusTimeOfLastHandledTxn = UNKNOWN_CONSENSUS_TIME; private SequenceNumber seqNo; private long lastScannedEntity; private long entitiesScannedThisSecond = 0L; private long entitiesTouchedThisSecond = 0L; private long preparedUpdateFileNum = NO_PREPARED_UPDATE_FILE_NUM; private byte[] preparedUpdateFileHash = NO_PREPARED_UPDATE_FILE_HASH; private FeeMultiplierSource multiplierSource = null; private FunctionalityThrottling throttling = null; private DeterministicThrottle.UsageSnapshot[] usageSnapshots = NO_SNAPSHOTS; public MerkleNetworkContext() { /* No-op for RuntimeConstructable facility; will be followed by a call to deserialize. */ } /* Used at network genesis only */ public MerkleNetworkContext( Instant consensusTimeOfLastHandledTxn, SequenceNumber seqNo, long lastScannedEntity, ExchangeRates midnightRates ) { this.consensusTimeOfLastHandledTxn = consensusTimeOfLastHandledTxn; this.seqNo = seqNo; this.lastScannedEntity = lastScannedEntity; this.midnightRates = midnightRates; } public MerkleNetworkContext(MerkleNetworkContext that) { this.consensusTimeOfLastHandledTxn = that.consensusTimeOfLastHandledTxn; this.seqNo = that.seqNo.copy(); this.lastScannedEntity = that.lastScannedEntity; this.midnightRates = that.midnightRates.copy(); this.usageSnapshots = that.usageSnapshots; this.congestionLevelStarts = that.congestionLevelStarts; this.stateVersion = that.stateVersion; this.entitiesScannedThisSecond = that.entitiesScannedThisSecond; this.entitiesTouchedThisSecond = that.entitiesTouchedThisSecond; this.lastMidnightBoundaryCheck = that.lastMidnightBoundaryCheck; this.preparedUpdateFileNum = that.preparedUpdateFileNum; this.preparedUpdateFileHash = that.preparedUpdateFileHash; } /* --- Helpers that reset the received argument based on the network context */ public void resetMultiplierSourceFromSavedCongestionStarts(FeeMultiplierSource feeMultiplierSource) { if (congestionLevelStarts.length > 0) { feeMultiplierSource.resetCongestionLevelStarts(congestionLevelStarts); } } public void resetThrottlingFromSavedSnapshots(FunctionalityThrottling throttling) { var activeThrottles = throttling.allActiveThrottles(); if (activeThrottles.size() != usageSnapshots.length) { log.warn("There are " + activeThrottles.size() + " active throttles, but " + usageSnapshots.length + " usage snapshots from saved state. " + "Not performing a reset!"); return; } reset(activeThrottles); } /* --- Mutators that change this network context --- */ public void clearAutoRenewSummaryCounts() { throwIfImmutable("Cannot reset auto-renew summary counts on an immutable context"); entitiesScannedThisSecond = 0L; entitiesTouchedThisSecond = 0L; } public void updateAutoRenewSummaryCounts(int numScanned, int numTouched) { throwIfImmutable("Cannot update auto-renew summary counts on an immutable context"); entitiesScannedThisSecond += numScanned; entitiesTouchedThisSecond += numTouched; } public void updateLastScannedEntity(long lastScannedEntity) { throwIfImmutable("Cannot update last scanned entity on an immutable context"); this.lastScannedEntity = lastScannedEntity; } public void syncThrottling(FunctionalityThrottling throttling) { this.throttling = throttling; } public void syncMultiplierSource(FeeMultiplierSource multiplierSource) { this.multiplierSource = multiplierSource; } public void setConsensusTimeOfLastHandledTxn(Instant consensusTimeOfLastHandledTxn) { throwIfImmutable("Cannot set consensus time of last transaction on an immutable context"); this.consensusTimeOfLastHandledTxn = consensusTimeOfLastHandledTxn; } public void setLastMidnightBoundaryCheck(Instant lastMidnightBoundaryCheck) { throwIfImmutable("Cannot update last midnight boundary check on an immutable context"); this.lastMidnightBoundaryCheck = lastMidnightBoundaryCheck; } public void setStateVersion(int stateVersion) { throwIfImmutable("Cannot set state version on an immutable context"); this.stateVersion = stateVersion; } public boolean hasPreparedUpgrade() { return preparedUpdateFileNum != NO_PREPARED_UPDATE_FILE_NUM; } public void recordPreparedUpgrade(FreezeTransactionBody op) { throwIfImmutable("Cannot record a prepared upgrade on an immutable context"); preparedUpdateFileNum = op.getUpdateFile().getFileNum(); preparedUpdateFileHash = op.getFileHash().toByteArray(); } public boolean isPreparedFileHashValidGiven(MerkleSpecialFiles specialFiles) { if (preparedUpdateFileNum == NO_PREPARED_UPDATE_FILE_NUM) { return true; } final var fid = STATIC_PROPERTIES.scopedFileWith(preparedUpdateFileNum); return specialFiles.hashMatches(fid, preparedUpdateFileHash); } public void discardPreparedUpgradeMeta() { throwIfImmutable("Cannot rollback a prepared upgrade on an immutable context"); preparedUpdateFileNum = NO_PREPARED_UPDATE_FILE_NUM; preparedUpdateFileHash = NO_PREPARED_UPDATE_FILE_HASH; } /* --- MerkleLeaf --- */ @Override public MerkleNetworkContext copy() { if (throttling != null) { updateSnapshotsFrom(throttling); throttling = null; } if (multiplierSource != null) { updateCongestionStartsFrom(multiplierSource); multiplierSource = null; } setImmutable(true); return new MerkleNetworkContext(this); } @Override public void deserialize(SerializableDataInputStream in, int version) throws IOException { final var lastHandleTime = serdes.readNullableInstant(in); consensusTimeOfLastHandledTxn = (lastHandleTime == null) ? null : lastHandleTime.toJava(); seqNo = seqNoSupplier.get(); seqNo.deserialize(in); midnightRates = in.readSerializable(true, ratesSupplier); if (version >= RELEASE_0130_VERSION) { readCongestionControlData(in); } if (version >= RELEASE_0140_VERSION) { whenVersionHigherOrEqualTo0140(in); } if (version >= RELEASE_0150_VERSION) { whenVersionHigherOrEqualTo0150(in); } if (version >= RELEASE_0190_VERSION) { preparedUpdateFileNum = in.readLong(); preparedUpdateFileHash = in.readByteArray(UPDATE_FILE_HASH_LEN); } } private void readCongestionControlData(final SerializableDataInputStream in) throws IOException { int numUsageSnapshots = in.readInt(); if (numUsageSnapshots > 0) { usageSnapshots = new DeterministicThrottle.UsageSnapshot[numUsageSnapshots]; for (int i = 0; i < numUsageSnapshots; i++) { var used = in.readLong(); var lastUsed = serdes.readNullableInstant(in); usageSnapshots[i] = new DeterministicThrottle.UsageSnapshot( used, (lastUsed == null) ? null : lastUsed.toJava()); } } int numCongestionStarts = in.readInt(); if (numCongestionStarts > 0) { congestionLevelStarts = new Instant[numCongestionStarts]; for (int i = 0; i < numCongestionStarts; i++) { final var levelStart = serdes.readNullableInstant(in); congestionLevelStarts[i] = (levelStart == null) ? null : levelStart.toJava(); } } } private void whenVersionHigherOrEqualTo0140(final SerializableDataInputStream in) throws IOException { lastScannedEntity = in.readLong(); entitiesScannedThisSecond = in.readLong(); entitiesTouchedThisSecond = in.readLong(); stateVersion = in.readInt(); } private void whenVersionHigherOrEqualTo0150(final SerializableDataInputStream in) throws IOException { final var lastBoundaryCheck = serdes.readNullableInstant(in); lastMidnightBoundaryCheck = (lastBoundaryCheck == null) ? null : lastBoundaryCheck.toJava(); } @Override public void serialize(SerializableDataOutputStream out) throws IOException { serdes.writeNullableInstant(fromJava(consensusTimeOfLastHandledTxn), out); seqNo.serialize(out); out.writeSerializable(midnightRates, true); int n = usageSnapshots.length; out.writeInt(n); for (var usageSnapshot : usageSnapshots) { out.writeLong(usageSnapshot.used()); serdes.writeNullableInstant(fromJava(usageSnapshot.lastDecisionTime()), out); } n = congestionLevelStarts.length; out.writeInt(n); for (var congestionStart : congestionLevelStarts) { serdes.writeNullableInstant(fromJava(congestionStart), out); } out.writeLong(lastScannedEntity); out.writeLong(entitiesScannedThisSecond); out.writeLong(entitiesTouchedThisSecond); out.writeInt(stateVersion); serdes.writeNullableInstant(fromJava(lastMidnightBoundaryCheck), out); out.writeLong(preparedUpdateFileNum); out.writeByteArray(preparedUpdateFileHash); } @Override public long getClassId() { return RUNTIME_CONSTRUCTABLE_ID; } @Override public int getVersion() { return CURRENT_VERSION; } public String summarized() { return summarizedWith(null); } public String summarizedWith(DualStateAccessor dualStateAccessor) { final var isDualStateAvailable = dualStateAccessor != null && dualStateAccessor.getDualState() != null; final var freezeTime = isDualStateAvailable ? ((DualStateImpl) dualStateAccessor.getDualState()).getFreezeTime() : null; final var pendingUpdateDesc = currentPendingUpdateDesc(); final var pendingMaintenanceDesc = freezeTimeDesc(freezeTime, isDualStateAvailable) + pendingUpdateDesc; return "The network context (state version " + (stateVersion == UNRECORDED_STATE_VERSION ? NOT_AVAILABLE : stateVersion) + ") is," + "\n Consensus time of last handled transaction :: " + reprOf(consensusTimeOfLastHandledTxn) + "\n Pending maintenance :: " + pendingMaintenanceDesc + "\n Midnight rate set :: " + midnightRates.readableRepr() + "\n Last midnight boundary check :: " + reprOf(lastMidnightBoundaryCheck) + "\n Next entity number :: " + seqNo.current() + "\n Last scanned entity :: " + lastScannedEntity + "\n Entities scanned last consensus second :: " + entitiesScannedThisSecond + "\n Entities touched last consensus second :: " + entitiesTouchedThisSecond + "\n Throttle usage snapshots are ::" + usageSnapshotsDesc() + "\n Congestion level start times are ::" + congestionStartsDesc(); } private String usageSnapshotsDesc() { if (usageSnapshots.length == 0) { return NOT_AVAILABLE_SUFFIX; } else { final var sb = new StringBuilder(); for (var snapshot : usageSnapshots) { sb.append(LINE_WRAP).append(snapshot.used()) .append(" used (last decision time ") .append(reprOf(snapshot.lastDecisionTime())).append(")"); } return sb.toString(); } } private String congestionStartsDesc() { if (congestionLevelStarts.length == 0) { return NOT_AVAILABLE_SUFFIX; } else { final var sb = new StringBuilder(); for (var start : congestionLevelStarts) { sb.append(LINE_WRAP).append(reprOf(start)); } return sb.toString(); } } private String currentPendingUpdateDesc() { final var nmtDescStart = "w/ NMT upgrade prepped :: "; if (preparedUpdateFileNum == NO_PREPARED_UPDATE_FILE_NUM) { return nmtDescStart + NOT_EXTANT; } return nmtDescStart + "from " + STATIC_PROPERTIES.scopedIdLiteralWith(preparedUpdateFileNum) + " # " + CommonUtils.hex(preparedUpdateFileHash).substring(0, 8); } private String freezeTimeDesc(@Nullable Instant freezeTime, boolean isDualStateAvailable) { final var nmtDescSkip = LINE_WRAP; if (freezeTime == null) { return (isDualStateAvailable ? NOT_EXTANT : NOT_AVAILABLE) + nmtDescSkip; } return freezeTime + nmtDescSkip; } /* --- Getters --- */ public long getEntitiesScannedThisSecond() { return entitiesScannedThisSecond; } public long getEntitiesTouchedThisSecond() { return entitiesTouchedThisSecond; } public Instant consensusTimeOfLastHandledTxn() { return consensusTimeOfLastHandledTxn; } public SequenceNumber seqNo() { return seqNo; } public ExchangeRates midnightRates() { return midnightRates; } public Instant lastMidnightBoundaryCheck() { return lastMidnightBoundaryCheck; } public long lastScannedEntity() { return lastScannedEntity; } public ExchangeRates getMidnightRates() { return midnightRates; } public int getStateVersion() { return stateVersion; } /* --- Internal helpers --- */ void updateSnapshotsFrom(FunctionalityThrottling throttling) { throwIfImmutable("Cannot update usage snapshots on an immutable context"); var activeThrottles = throttling.allActiveThrottles(); int n = activeThrottles.size(); if (n == 0) { usageSnapshots = NO_SNAPSHOTS; } else { usageSnapshots = new DeterministicThrottle.UsageSnapshot[n]; for (int i = 0; i < n; i++) { usageSnapshots[i] = activeThrottles.get(i).usageSnapshot(); } } } void updateCongestionStartsFrom(FeeMultiplierSource feeMultiplierSource) { throwIfImmutable("Cannot update congestion starts on an immutable context"); final var congestionStarts = feeMultiplierSource.congestionLevelStarts(); if (null == congestionStarts) { congestionLevelStarts = NO_CONGESTION_STARTS; } else { congestionLevelStarts = congestionStarts; } } private void reset(List<DeterministicThrottle> throttles) { var currUsageSnapshots = throttles.stream() .map(DeterministicThrottle::usageSnapshot) .collect(toList()); for (int i = 0, n = usageSnapshots.length; i < n; i++) { var savedUsageSnapshot = usageSnapshots[i]; var throttle = throttles.get(i); try { throttle.resetUsageTo(savedUsageSnapshot); log.info("Reset {} with saved usage snapshot", throttle); } catch (Exception e) { log.warn("Saved usage snapshot #" + (i + 1) + " was not compatible with the corresponding active throttle (" + e.getMessage() + "); not performing a reset!"); resetUnconditionally(throttles, currUsageSnapshots); break; } } } private void resetUnconditionally( List<DeterministicThrottle> throttles, List<DeterministicThrottle.UsageSnapshot> knownCompatible ) { for (int i = 0, n = knownCompatible.size(); i < n; i++) { throttles.get(i).resetUsageTo(knownCompatible.get(i)); } } private String reprOf(Instant consensusTime) { return consensusTime == null ? NOT_AVAILABLE : consensusTime.toString(); } public long getPreparedUpdateFileNum() { return preparedUpdateFileNum; } public void setPreparedUpdateFileNum(long preparedUpdateFileNum) { throwIfImmutable("Cannot update prepared update file num on an immutable context"); this.preparedUpdateFileNum = preparedUpdateFileNum; } public byte[] getPreparedUpdateFileHash() { return preparedUpdateFileHash; } public void setPreparedUpdateFileHash(byte[] preparedUpdateFileHash) { throwIfImmutable("Cannot update prepared update file hash on an immutable context"); this.preparedUpdateFileHash = preparedUpdateFileHash; } /* Only used for unit tests */ void setCongestionLevelStarts(Instant[] congestionLevelStarts) { this.congestionLevelStarts = congestionLevelStarts; } Instant[] getCongestionLevelStarts() { return congestionLevelStarts; } Instant getConsensusTimeOfLastHandledTxn() { return consensusTimeOfLastHandledTxn; } void setUsageSnapshots(DeterministicThrottle.UsageSnapshot[] usageSnapshots) { this.usageSnapshots = usageSnapshots; } DeterministicThrottle.UsageSnapshot[] usageSnapshots() { return usageSnapshots; } public void setMidnightRates(ExchangeRates midnightRates) { this.midnightRates = midnightRates; } public void setSeqNo(SequenceNumber seqNo) { this.seqNo = seqNo; } FeeMultiplierSource getMultiplierSource() { return multiplierSource; } FunctionalityThrottling getThrottling() { return throttling; } }
34.724638
110
0.760904
d397fa98cfeb84bec047368d69a1bd1125c1737f
5,072
package com.snail.job.admin.service.trigger; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.snail.job.admin.biz.JobExecutorBiz; import com.snail.job.admin.model.App; import com.snail.job.admin.model.JobInfo; import com.snail.job.admin.model.JobLog; import com.snail.job.admin.route.AbstractRoute; import com.snail.job.admin.route.RouteEnum; import com.snail.job.admin.service.AppService; import com.snail.job.admin.service.JobInfoService; import com.snail.job.admin.service.JobLogService; import com.snail.job.common.enums.AlarmStatus; import com.snail.job.common.enums.TriggerType; import com.snail.job.common.model.ResultT; import com.snail.job.common.model.TriggerParam; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.time.LocalDateTime; /** * 进行任务的调度 * @author 吴庆龙 * @date 2020/6/17 1:56 下午 */ @Slf4j @Component public class JobTriggerService { @Resource private JobExecutorBiz jobExecutorBiz; @Resource private JobInfoService jobInfoService; @Resource private AppService appService; @Resource private JobLogService jobLogService; /** * 触发 Job * @param jobId 任务的id * @param triggerType 触发类型 * @param overrideFailRetryCount 如果指定则使用该值,-1表示不指定 * @param overrideExecParam 如果指定则使用改制,null表示不指定 */ public void trigger(Long jobId, Integer overrideFailRetryCount, String overrideExecParam, TriggerType triggerType) { // 查询任务信息 JobInfo jobInfo = jobInfoService.getById(jobId); if (jobInfo == null) { log.error("任务不存在,jobId={}", jobId); return; } System.out.println("执行任务:" + jobId); // 优先使用传入的调度参数 if (overrideExecParam != null) { jobInfo.setExecParam(overrideExecParam); } // 优先使用参数的值 if (overrideFailRetryCount != null && overrideFailRetryCount >= 0) { jobInfo.setExecFailRetryCount(overrideFailRetryCount); } // 获取执行器地址列表 QueryWrapper<App> appQueryWrapper = new QueryWrapper<>(); appQueryWrapper.eq("name", jobInfo.getAppName()); App app = appService.getOne(appQueryWrapper); String addresses = app.getAddresses(); String[] addressArray = addresses.split(","); // 执行调度 if (RouteEnum.BROADCAST.getName().equals(jobInfo.getExecRouteStrategy())) { // 广播执行 int shardTotal = addressArray.length; for (int i = 0; i < addressArray.length; i++) { String executorAddress = addressArray[i]; // 进行调度 doTrigger(jobInfo, executorAddress, triggerType, i, shardTotal); } } else { // 非广播执行,选择一个执行器执行 AbstractRoute route = RouteEnum.match(jobInfo.getExecRouteStrategy()); String executorAddress = route.getExecutorAddress(app.getId(), jobId, addressArray); // 进行调度 doTrigger(jobInfo, executorAddress, triggerType, 1, 1); } } /** * 进行调度 */ private void doTrigger(JobInfo jobInfo, String executorAddress, TriggerType triggerType, Integer shareIndex, Integer shareTotal) { // 预先插入日志,获取日志id JobLog jobLog = new JobLog() .setJobId(jobInfo.getId()) .setAppName(jobInfo.getAppName()) .setTriggerType(triggerType.name()); jobLogService.save(jobLog); // 初始化触发参数 TriggerParam tp = new TriggerParam(); tp.setLogId(jobLog.getId()); tp.setJobId(jobInfo.getId()); tp.setExecHandler(jobInfo.getExecHandler()); tp.setExecParam(jobInfo.getExecParam()); tp.setExecTimeout(jobInfo.getExecTimeout()); tp.setShardIndex(shareIndex); tp.setShardIndex(shareTotal); log.info("调度任务:{} {}", jobInfo.getId(), jobInfo.getExecHandler()); // 触发远程执行器 ResultT<String> triggerResult; if (StrUtil.isEmpty(executorAddress)) { triggerResult = new ResultT<>(ResultT.FAIL_CODE, "未找到可用的执行器!"); } else { // 执行器那边的调度是异步的 triggerResult = jobExecutorBiz.run(executorAddress, tp); } // 更新日志的调度信息 JobLog updateLog = new JobLog() .setId(jobLog.getId()) // 执行参数 .setExecAddress(executorAddress) .setExecHandler(jobInfo.getExecHandler()) .setExecParam(jobInfo.getExecParam()) .setFailRetryCount(jobInfo.getExecFailRetryCount()) // 调度信息 .setTriggerTime(LocalDateTime.now()) .setTriggerCode(triggerResult.getCode()) .setTriggerMsg(triggerResult.getMsg()) // 告警状态 .setAlarmStatus(AlarmStatus.WAIT_ALARM.getValue()); // execTime、execCode和execMsg 在回调中填充 jobLogService.updateById(updateLog); } }
34.503401
120
0.630521
3d0e5bf6656dfe4d7c3748dc635847b7e6e74560
9,614
/* * Copyright 2019 Insurance Australia Group Limited * * 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.mark59.metrics.data.eventMapping.dao; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import com.mark59.metrics.data.beans.EventMapping; /** * @author Philip Webb * Written: Australian Winter 2019 */ public class EventMappingDAOjdbcTemplateImpl implements EventMappingDAO { @Autowired private DataSource dataSource; @Override public void insertData(EventMapping eventMapping) { String sql = "INSERT INTO EVENTMAPPING " + "(TXN_TYPE, PERFORMANCE_TOOL, METRIC_SOURCE, MATCH_WHEN_LIKE, TARGET_NAME_LB, TARGET_NAME_RB, IS_PERCENTAGE, IS_INVERTED_PERCENTAGE, COMMENT )" + " VALUES (?,?,?,?,?,?,?,?,?)"; System.out.println("EventMappingDAOjdbcTemplateImpl insert EVENTMAPPING : " + eventMapping.toString() ); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new Object[] { eventMapping.getTxnType(),eventMapping.getPerformanceTool(), eventMapping.getMetricSource(), eventMapping.getMatchWhenLike(), eventMapping.getTargetNameLB(), eventMapping.getTargetNameRB(), eventMapping.getIsPercentage(), eventMapping.getIsInvertedPercentage(), eventMapping.getComment()}); } @Override public void deleteData(String txnType, String metricSource, String matchhWenLike) { String sql = " DELETE FROM EVENTMAPPING where TXN_TYPE = '" + txnType + "' and METRIC_SOURCE = '" + metricSource + "' and MATCH_WHEN_LIKE = '" + matchhWenLike + "'"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql); } @Override public void updateData(EventMapping eventMapping) { String sql = "UPDATE EVENTMAPPING SET TARGET_NAME_LB = '" + eventMapping.getTargetNameLB() + "', " + "TARGET_NAME_RB = '" + eventMapping.getTargetNameRB() + "', " + "IS_PERCENTAGE = '" + eventMapping.getIsPercentage() + "', " + "IS_INVERTED_PERCENTAGE = '" + eventMapping.getIsInvertedPercentage() + "', " + "PERFORMANCE_TOOL = '" + eventMapping.getPerformanceTool() + "', " + "COMMENT = '" + eventMapping.getComment() + "' " + " where TXN_TYPE ='" + eventMapping.getTxnType() + "' " + " and METRIC_SOURCE='" + eventMapping.getMetricSource() + "'" + " and MATCH_WHEN_LIKE='" + eventMapping.getMatchWhenLike() + "'"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql); } @Override public EventMapping getEventMapping(String metricSource, String matchhWenLike) { String sql = " SELECT * FROM EVENTMAPPING where METRIC_SOURCE = '" + metricSource + "' and MATCH_WHEN_LIKE = '" + matchhWenLike + "'"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); if (rows.isEmpty()){ return null; } else { Map<String, Object> row = rows.get(0); EventMapping eventMapping = populateFromResultSet(row); return eventMapping; } } @Override public List<EventMapping> findEventMappingsForPerformanceTool(String performanceTool) { return findEventMappings("PERFORMANCE_TOOL", performanceTool); } @Override public List<EventMapping> findEventMappings(){ return findEventMappings("",""); } @Override public List<EventMapping> findEventMappings(String selectionCol, String selectionValue){ List<EventMapping> eventMappingList = new ArrayList<EventMapping>(); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List<Map<String, Object>> rows = jdbcTemplate.queryForList(getEventsMappingListSelectionSQL(selectionCol, selectionValue)); for (Map<String, Object> row : rows) { EventMapping eventMapping = populateFromResultSet(row); eventMappingList.add(eventMapping); //System.out.println("values from EventMappingDAOjdbcTemplateImpl.findEventMappings : " + eventMapping.toString() ) ; } return eventMappingList; } private String getEventsMappingListSelectionSQL(String selectionCol, String selectionValue){ String eventsMappingListSelectionSQL = "select TXN_TYPE, METRIC_SOURCE, MATCH_WHEN_LIKE, TARGET_NAME_LB, TARGET_NAME_RB, IS_PERCENTAGE, IS_INVERTED_PERCENTAGE, PERFORMANCE_TOOL, COMMENT from EVENTMAPPING "; if (!selectionValue.isEmpty() ) { eventsMappingListSelectionSQL += " where " + selectionCol + " like '" + selectionValue + "' "; } eventsMappingListSelectionSQL += " order by METRIC_SOURCE, " + orderingByMatchingProcess(); //System.out.println("EventMappingDAOjdbcTemplateImpl.getEventsMappingListSelectionSQL: " + eventsMappingListSelectionSQL); return eventsMappingListSelectionSQL; } @Override public boolean doesLrEventMapEntryMatchThisEventMapping(String eventType, String eventName, EventMapping eventMapping) { Integer matchCount = 0; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String[] matchWhenLikeSplit = eventMapping.getMetricSource().split("_", 2); if (matchWhenLikeSplit.length != 2) { throw new RuntimeException("Unexpected Metric_Source Format on EventMapping Table for a Loadrunner event. \n " + "Expected underscord separated value (Loadrunncer_EventType) but got : " + eventMapping.getMetricSource() + "\n ,EventMapping : " + eventMapping.toString() + "\n ,for eventType = " + eventType + ", eventName = " + eventName ); } String sql = "SELECT count(*) col FROM dual where '" + eventType + "'" + " = '" + matchWhenLikeSplit[1] + "' and '" + eventName + "' like '" + eventMapping.getMatchWhenLike() + "'"; matchCount = Integer.valueOf(jdbcTemplate.queryForObject(sql, String.class)); if ( matchCount > 0 ){ // System.out.println(" Event matched using sql: " + sql + " RESULT = " + matchCount ); return true; } return false; } /** * See if the passed transaction id / metric source type (eg 'Jmeter_DATAPONT') matches to an event on the event mapping table * (if it does, it will be the mapped data type that will used for SLA checking with this transaction). * * <p>Selection is based on a "best-guess" algorithm as to what a user was attempting to match against when multiple rows * match the passed transaction id / metric source: * <ul> * <li>any rows with no percent symbol (no free wild-cards) take precedence * <li>next is the length of the match (minus the number of free wild-cards - high to low) * <li>then next is the total length boundary characters (longest to shortest) * </ul> **/ @Override public EventMapping findAnEventForTxnIdAndSource(String txnId, String metricSource) { String sql = "SELECT * FROM EVENTMAPPING" + " where '" + txnId + "'" + " like MATCH_WHEN_LIKE " + " and METRIC_SOURCE = '" + metricSource + "' " + " order by " + orderingByMatchingProcess(); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); if (rows.isEmpty()){ // System.out.println("findAnEventForTxnIdByType sql : " + sql + " : NULL RESULT " ); return null; } else { Map<String, Object> row = rows.get(0); EventMapping eventMapping = populateFromResultSet(row); // System.out.println("findAnEventForTxnIdByType sql : " + sql + ", event mapping : " + eventMapping ); return eventMapping; } } private String orderingByMatchingProcess() { return " case when position( '%' in MATCH_WHEN_LIKE) = 0 then 0 else 1 end," + // do any free wildcard_exists?" + ; " length(replace( MATCH_WHEN_LIKE, '%', '' )) desc, " + // num_of_chars_exclude_wildcards " length(TARGET_NAME_LB) + length(TARGET_NAME_RB) desc "; } private EventMapping populateFromResultSet(Map<String, Object> row) { EventMapping eventMapping = new EventMapping(); eventMapping.setTxnType((String)row.get("TXN_TYPE")); eventMapping.setMetricSource((String)row.get("METRIC_SOURCE")); eventMapping.setMatchWhenLike((String)row.get("MATCH_WHEN_LIKE")); try { eventMapping.setMatchWhenLikeURLencoded(URLEncoder.encode((String)row.get("MATCH_WHEN_LIKE"), "UTF-8") ) ; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } eventMapping.setTargetNameLB((String)row.get("TARGET_NAME_LB")); eventMapping.setTargetNameRB((String)row.get("TARGET_NAME_RB")); eventMapping.setIsPercentage((String)row.get("IS_PERCENTAGE")); eventMapping.setIsInvertedPercentage((String)row.get("IS_INVERTED_PERCENTAGE")); eventMapping.setPerformanceTool((String)row.get("PERFORMANCE_TOOL")); eventMapping.setComment((String)row.get("COMMENT")); return eventMapping; } }
41.261803
222
0.706678
5a461e43e54ba7f22491d0451f0611de75c9deae
1,499
/** * -------------------------------------------------------------------------- * SBML4j * -------------------------------------------------------------------------- * University of Tuebingen, 2020. * * This code is part of the SBML4j software package and subject to the terms * and conditions defined by its license (MIT License). For license details * please refer to the LICENSE file included as part of this source code * package. * * For a full list of authors, please refer to the file AUTHORS. */ package org.tts.api; import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-07-28T10:58:57.976Z[GMT]") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); res.addHeader("Access-Control-Allow-Headers", "Content-Type"); chain.doFilter(request, response); } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
36.560976
130
0.627085
f84eb0193e56dc545c20aca646a793f32fe1ee68
23,714
/* * SoapUI, Copyright (C) 2004-2016 SmartBear Software * * Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequen * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * http://ec.europa.eu/idabc/eupl * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the Licence for the specific language governing permissions and limitations * under the Licence. */ package com.eviware.soapui.impl.wsdl; import com.eviware.soapui.SoapUI; import com.eviware.soapui.config.CredentialsConfig; import com.eviware.soapui.config.WsaVersionTypeConfig; import com.eviware.soapui.config.WsdlRequestConfig; import com.eviware.soapui.config.WsrmVersionTypeConfig; import com.eviware.soapui.impl.rest.RestRequestInterface; import com.eviware.soapui.impl.support.AbstractHttpRequest; import com.eviware.soapui.impl.wsdl.submit.RequestTransportRegistry; import com.eviware.soapui.impl.wsdl.submit.transports.http.WsdlResponse; import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils; import com.eviware.soapui.impl.wsdl.submit.transports.jms.JMSHeader; import com.eviware.soapui.impl.wsdl.support.jms.header.JMSHeaderConfig; import com.eviware.soapui.impl.wsdl.support.jms.property.JMSPropertiesConfig; import com.eviware.soapui.impl.wsdl.support.wsa.WsaConfig; import com.eviware.soapui.impl.wsdl.support.wsa.WsaContainer; import com.eviware.soapui.impl.wsdl.support.wsrm.WsrmConfig; import com.eviware.soapui.impl.wsdl.support.wsrm.WsrmContainer; import com.eviware.soapui.impl.wsdl.teststeps.HttpTestRequestStep; import com.eviware.soapui.model.ModelItem; import com.eviware.soapui.model.iface.Attachment.AttachmentEncoding; import com.eviware.soapui.model.iface.Interface; import com.eviware.soapui.model.iface.MessagePart; import com.eviware.soapui.model.iface.SubmitContext; import com.eviware.soapui.model.propertyexpansion.PropertyExpander; import com.eviware.soapui.model.propertyexpansion.PropertyExpansion; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContainer; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionsResult; import com.eviware.soapui.model.support.InterfaceListenerAdapter; import com.eviware.soapui.settings.WsdlSettings; import com.eviware.soapui.support.StringUtils; import com.eviware.soapui.support.UISupport; import com.eviware.soapui.support.types.StringToStringsMap; import org.apache.log4j.Logger; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Request implementation holding a SOAP reques * * @author Ole.Matzura */ public class WsdlRequest extends AbstractHttpRequest<WsdlRequestConfig> implements WsdlAttachmentContainer, PropertyExpansionContainer, WsaContainer, WsrmContainer, PropertyChangeListener { public final static Logger log = Logger.getLogger(WsdlRequest.class); public static final String RESPONSE_CONTENT_PROPERTY = WsdlRequest.class.getName() + "@response-content"; public static final String INLINE_RESPONSE_ATTACHMENTS = WsdlRequest.class.getName() + "@inline-response-attachments"; public static final String EXPAND_MTOM_RESPONSE_ATTACHMENTS = WsdlRequest.class.getName() + "@expand-mtom-attachments"; public static final String FORCE_MTOM = WsdlRequest.class.getName() + "@force_mtom"; public static final String ENABLE_INLINE_FILES = WsdlRequest.class.getName() + "@enable_inline_files"; public static final String SKIP_SOAP_ACTION = WsdlRequest.class.getName() + "@skip_soap_action"; public static final String ENCODE_ATTACHMENTS = WsdlRequest.class.getName() + "@encode_attachments"; public static final String WSS_TIMETOLIVE = WsdlRequest.class.getName() + "@wss-time-to-live"; public static final String OPERATION_PROPERTY = WsdlRequest.class.getName() + "@operation"; public static final String INCOMING_WSS = WsdlRequest.class.getName() + "@incoming-wss"; public static final String OUGOING_WSS = WsdlRequest.class.getName() + "@outgoing-wss"; public final static String PW_TYPE_NONE = "None"; public final static String PW_TYPE_DIGEST = "PasswordDigest"; public final static String PW_TYPE_TEXT = "PasswordText"; private WsdlOperation operation; private List<HttpAttachmentPart> definedAttachmentParts; private InternalInterfaceListener interfaceListener = new InternalInterfaceListener(); private WsaConfig wsaConfig; private WsrmConfig wsrmConfig; public WsdlRequest(WsdlOperation operation, WsdlRequestConfig callConfig) { this(operation, callConfig, false); } public WsdlRequest(WsdlOperation operation, WsdlRequestConfig callConfig, boolean forLoadTest) { super(callConfig, operation, null, forLoadTest); this.operation = operation; initEndpoints(); // ensure encoding if (callConfig.getEncoding() == null || callConfig.getEncoding().length() == 0) { callConfig.setEncoding("UTF-8"); } if (!forLoadTest) { operation.getInterface().addPropertyChangeListener(interfaceListener); operation.getInterface().addInterfaceListener(interfaceListener); } } public void updateConfig(WsdlRequestConfig request) { setConfig(request); if (wsaConfig != null) { wsaConfig.setConfig(request.getWsaConfig()); } if (wsrmConfig != null) { wsrmConfig.setWsrmConfig(request.getWsrmConfig()); } if (jmsHeaderConfig != null) { jmsHeaderConfig.setJMSHeaderConfConfig(request.getJmsConfig()); } if (jmsPropertyConfig != null) { jmsPropertyConfig.setJmsPropertyConfConfig(request.getJmsPropertyConfig()); } } protected void initEndpoints() { if (getEndpoint() == null) { String[] endpoints = operation.getInterface().getEndpoints(); if (endpoints.length > 0) { setEndpoint(endpoints[0]); } } } public boolean isInlineResponseAttachments() { return getSettings().getBoolean(INLINE_RESPONSE_ATTACHMENTS); } public void setInlineResponseAttachments(boolean inlineResponseAttachments) { boolean old = getSettings().getBoolean(INLINE_RESPONSE_ATTACHMENTS); getSettings().setBoolean(INLINE_RESPONSE_ATTACHMENTS, inlineResponseAttachments); notifyPropertyChanged(INLINE_RESPONSE_ATTACHMENTS, old, inlineResponseAttachments); } public boolean isExpandMtomResponseAttachments() { return getSettings().getBoolean(EXPAND_MTOM_RESPONSE_ATTACHMENTS); } public void setExpandMtomResponseAttachments(boolean expandMtomResponseAttachments) { boolean old = getSettings().getBoolean(EXPAND_MTOM_RESPONSE_ATTACHMENTS); getSettings().setBoolean(EXPAND_MTOM_RESPONSE_ATTACHMENTS, expandMtomResponseAttachments); notifyPropertyChanged(EXPAND_MTOM_RESPONSE_ATTACHMENTS, old, expandMtomResponseAttachments); } /** * Use getResponse().getContentAsString(); * * @deprecated */ @Deprecated public String getResponseContent() { return getResponse() == null ? null : getResponse().getContentAsString(); } public WsdlResponse getResponse() { return (WsdlResponse) super.getResponse(); } public WsdlOperation getOperation() { return operation; } public void setOperation(WsdlOperation wsdlOperation) { WsdlOperation oldOperation = operation; this.operation = wsdlOperation; definedAttachmentParts = null; notifyPropertyChanged(OPERATION_PROPERTY, oldOperation, operation); } public void setRequestContent(String request) { definedAttachmentParts = null; super.setRequestContent(request); } // public void setResponse( WsdlResponse response, SubmitContext context ) // { // WsdlResponse oldResponse = getResponse(); // this.response = response; // // notifyPropertyChanged( RESPONSE_PROPERTY, oldResponse, response ); // } public WsdlSubmit<WsdlRequest> submit(SubmitContext submitContext, boolean async) throws SubmitException { String endpoint = PropertyExpander.expandProperties(submitContext, getEndpoint()); if (endpoint == null || endpoint.trim().length() == 0) { UISupport.showErrorMessage("Missing endpoint for request [" + getName() + "]"); return null; } try { WsdlSubmit<WsdlRequest> submitter = new WsdlSubmit<WsdlRequest>(this, getSubmitListeners(), RequestTransportRegistry.getTransport(endpoint, submitContext)); submitter.submitRequest(submitContext, async); return submitter; } catch (Exception e) { throw new SubmitException(e.toString()); } } private class InternalInterfaceListener extends InterfaceListenerAdapter implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(Interface.ENDPOINT_PROPERTY)) { String endpoint = getEndpoint(); if (evt.getOldValue() != null && evt.getOldValue().equals(endpoint)) { setEndpoint((String) evt.getNewValue()); } } } } public String getWssPasswordType() { String wssPasswordType = getConfig().getWssPasswordType(); return StringUtils.isNullOrEmpty(wssPasswordType) || PW_TYPE_NONE.equals(wssPasswordType) ? null : wssPasswordType; } public void setWssPasswordType(String wssPasswordType) { if (wssPasswordType == null || wssPasswordType.equals(PW_TYPE_NONE)) { if (getConfig().isSetWssPasswordType()) { getConfig().unsetWssPasswordType(); } } else { getConfig().setWssPasswordType(wssPasswordType); } } /* * (non-Javadoc) * * @see * com.eviware.soapui.impl.wsdl.AttachmentContainer#getDefinedAttachmentParts * () */ public synchronized HttpAttachmentPart[] getDefinedAttachmentParts() { if (definedAttachmentParts == null) { try { UISupport.setHourglassCursor(); definedAttachmentParts = AttachmentUtils.extractAttachmentParts(operation, getRequestContent(), true, false, isMtomEnabled()); } catch (Exception e) { log.warn(e.toString()); definedAttachmentParts = new ArrayList<HttpAttachmentPart>(); } finally { UISupport.resetCursor(); } } return definedAttachmentParts.toArray(new HttpAttachmentPart[definedAttachmentParts.size()]); } public RestRequestInterface.HttpMethod getMethod() { return RestRequestInterface.HttpMethod.POST; } /* * (non-Javadoc) * * @see * com.eviware.soapui.impl.wsdl.AttachmentContainer#getAttachmentPart(java * .lang.String) */ public HttpAttachmentPart getAttachmentPart(String partName) { HttpAttachmentPart[] parts = getDefinedAttachmentParts(); for (HttpAttachmentPart part : parts) { if (part.getName().equals(partName)) { return part; } } return null; } public void copyTo(WsdlRequest newRequest, boolean copyAttachments, boolean copyHeaders) { newRequest.setEncoding(getEncoding()); newRequest.setEndpoint(getEndpoint()); newRequest.setRequestContent(getRequestContent()); newRequest.setWssPasswordType(getWssPasswordType()); CredentialsConfig credentials = getConfig().getCredentials(); if (credentials != null) { newRequest.getConfig().setCredentials((CredentialsConfig) credentials.copy()); } if (copyAttachments) { copyAttachmentsTo(newRequest); } if (copyHeaders) { newRequest.setRequestHeaders(getRequestHeaders()); } // ((DefaultWssContainer)newRequest.getWssContainer()).updateConfig( ( // WSSConfigConfig ) getConfig().getWssConfig().copy() ); } /* * (non-Javadoc) * * @see com.eviware.soapui.impl.wsdl.AttachmentContainer#isMtomEnabled() */ public boolean isMtomEnabled() { return getSettings().getBoolean(WsdlSettings.ENABLE_MTOM); } public void setMtomEnabled(boolean mtomEnabled) { getSettings().setBoolean(WsdlSettings.ENABLE_MTOM, mtomEnabled); definedAttachmentParts = null; } public boolean isInlineFilesEnabled() { return getSettings().getBoolean(WsdlRequest.ENABLE_INLINE_FILES); } public void setInlineFilesEnabled(boolean inlineFilesEnabled) { getSettings().setBoolean(WsdlRequest.ENABLE_INLINE_FILES, inlineFilesEnabled); } public boolean isSkipSoapAction() { return getSettings().getBoolean(WsdlRequest.SKIP_SOAP_ACTION); } public void setSkipSoapAction(boolean skipSoapAction) { getSettings().setBoolean(WsdlRequest.SKIP_SOAP_ACTION, skipSoapAction); } @Override public void release() { super.release(); getOperation().getInterface().removeInterfaceListener(interfaceListener); getOperation().getInterface().removePropertyChangeListener(interfaceListener); } public MessagePart[] getRequestParts() { try { List<MessagePart> result = new ArrayList<MessagePart>(); result.addAll(Arrays.asList(getOperation().getDefaultRequestParts())); result.addAll(Arrays.asList(getDefinedAttachmentParts())); return result.toArray(new MessagePart[result.size()]); } catch (Exception e) { SoapUI.logError(e); return new MessagePart[0]; } } public MessagePart[] getResponseParts() { try { List<MessagePart> result = new ArrayList<MessagePart>(); result.addAll(Arrays.asList(getOperation().getDefaultResponseParts())); if (getResponse() != null) { result.addAll(AttachmentUtils.extractAttachmentParts(getOperation(), getResponse().getContentAsString(), true, true, isMtomEnabled())); } return result.toArray(new MessagePart[result.size()]); } catch (Exception e) { SoapUI.logError(e); return new MessagePart[0]; } } public String getWssTimeToLive() { return getSettings().getString(WSS_TIMETOLIVE, null); } public void setWssTimeToLive(String ttl) { getSettings().setString(WSS_TIMETOLIVE, ttl); } public long getContentLength() { return getRequestContent().length(); } public boolean isForceMtom() { return getSettings().getBoolean(FORCE_MTOM); } public void setForceMtom(boolean forceMtom) { boolean old = getSettings().getBoolean(FORCE_MTOM); getSettings().setBoolean(FORCE_MTOM, forceMtom); notifyPropertyChanged(FORCE_MTOM, old, forceMtom); } public boolean isEncodeAttachments() { return getSettings().getBoolean(ENCODE_ATTACHMENTS); } public void setEncodeAttachments(boolean encodeAttachments) { boolean old = getSettings().getBoolean(ENCODE_ATTACHMENTS); getSettings().setBoolean(ENCODE_ATTACHMENTS, encodeAttachments); notifyPropertyChanged(ENCODE_ATTACHMENTS, old, encodeAttachments); } public String getIncomingWss() { return getConfig().getIncomingWss(); } public void setIncomingWss(String incomingWss) { String old = getIncomingWss(); getConfig().setIncomingWss(incomingWss); notifyPropertyChanged(INCOMING_WSS, old, incomingWss); } public String getOutgoingWss() { return getConfig().getOutgoingWss(); } public void setOutgoingWss(String outgoingWss) { String old = getOutgoingWss(); getConfig().setOutgoingWss(outgoingWss); notifyPropertyChanged(OUGOING_WSS, old, outgoingWss); } public boolean isWsAddressing() { return getConfig().getUseWsAddressing(); } public void setWsAddressing(boolean wsAddressing) { boolean old = getConfig().getUseWsAddressing(); getConfig().setUseWsAddressing(wsAddressing); notifyPropertyChanged("wsAddressing", old, wsAddressing); } public PropertyExpansion[] getPropertyExpansions() { PropertyExpansionsResult result = new PropertyExpansionsResult(this, this); result.addAll(super.getPropertyExpansions()); StringToStringsMap requestHeaders = getRequestHeaders(); for (Map.Entry<String, List<String>> headerEntry : requestHeaders.entrySet()) { for (String value : headerEntry.getValue()) { result.addAll(PropertyExpansionUtils.extractPropertyExpansions(this, new HttpTestRequestStep.RequestHeaderHolder(headerEntry.getKey(), value, this), "value")); } } addWsaPropertyExpansions(result, getWsaConfig(), this); addJMSHeaderExpansions(result, getJMSHeaderConfig(), this); return result.toArray(); } public void addWsaPropertyExpansions(PropertyExpansionsResult result, WsaConfig wsaConfig, ModelItem modelItem) { result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "action")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "from")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "to")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "replyTo")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "replyToRefParams")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "faultTo")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "faultToRefParams")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "relatesTo")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "relationshipType")); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, wsaConfig, "messageID")); } public void addJMSHeaderExpansions(PropertyExpansionsResult result, JMSHeaderConfig jmsHeaderConfig, ModelItem modelItem) { result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, jmsHeaderConfig, JMSHeader.JMSCORRELATIONID)); result.addAll(PropertyExpansionUtils .extractPropertyExpansions(modelItem, jmsHeaderConfig, JMSHeader.JMSREPLYTO)); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, jmsHeaderConfig, JMSHeader.JMSTYPE)); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, jmsHeaderConfig, JMSHeader.JMSPRIORITY)); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, jmsHeaderConfig, JMSHeader.DURABLE_SUBSCRIPTION_NAME)); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, jmsHeaderConfig, JMSHeader.CLIENT_ID)); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, jmsHeaderConfig, JMSHeader.SEND_AS_BYTESMESSAGE)); result.addAll(PropertyExpansionUtils.extractPropertyExpansions(modelItem, jmsHeaderConfig, JMSHeader.SOAP_ACTION_ADD)); } public AttachmentEncoding getAttachmentEncoding(String partName) { HttpAttachmentPart attachmentPart = getAttachmentPart(partName); if (attachmentPart == null) { return AttachmentUtils.getAttachmentEncoding(getOperation(), partName, false); } else { return AttachmentUtils.getAttachmentEncoding(getOperation(), attachmentPart, false); } } public WsaConfig getWsaConfig() { if (wsaConfig == null) { if (!getConfig().isSetWsaConfig()) { getConfig().addNewWsaConfig(); } wsaConfig = new WsaConfig(getConfig().getWsaConfig(), this); } return wsaConfig; } public ModelItem getModelItem() { return this; } public boolean isWsaEnabled() { return isWsAddressing(); } public void setWsaEnabled(boolean arg0) { setWsAddressing(arg0); } public boolean isWsReliableMessaging() { return getConfig().getUseWsReliableMessaging(); } public void setWsReliableMessaging(boolean wsReliableMessaging) { boolean old = getConfig().getUseWsReliableMessaging(); getConfig().setUseWsReliableMessaging(wsReliableMessaging); notifyPropertyChanged("wsReliableMessaging", old, wsReliableMessaging); } public WsrmConfig getWsrmConfig() { if (wsrmConfig == null) { if (!getConfig().isSetWsrmConfig()) { getConfig().addNewWsrmConfig(); } wsrmConfig = new WsrmConfig(getConfig().getWsrmConfig(), this); wsrmConfig.addPropertyChangeListener("version", this); } return wsrmConfig; } public boolean isWsrmEnabled() { return isWsReliableMessaging(); } public void setWsrmEnabled(boolean arg0) { setWsReliableMessaging(arg0); } public String getResponseContentAsXml() { return getResponse() == null ? null : getResponse().getContentAsString(); } private JMSHeaderConfig jmsHeaderConfig; private JMSPropertiesConfig jmsPropertyConfig; public JMSHeaderConfig getJMSHeaderConfig() { if (jmsHeaderConfig == null) { if (!getConfig().isSetJmsConfig()) { getConfig().addNewJmsConfig(); } jmsHeaderConfig = new JMSHeaderConfig(getConfig().getJmsConfig(), this); } return jmsHeaderConfig; } public JMSPropertiesConfig getJMSPropertiesConfig() { if (jmsPropertyConfig == null) { if (!getConfig().isSetJmsPropertyConfig()) { getConfig().addNewJmsPropertyConfig(); } jmsPropertyConfig = new JMSPropertiesConfig(getConfig().getJmsPropertyConfig(), this); } return jmsPropertyConfig; } public String getAction() { if (isWsaEnabled() && StringUtils.hasContent(getWsaConfig().getAction())) { return getWsaConfig().getAction(); } return getOperation().getAction(); } @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getSource() == wsrmConfig && evt.getPropertyName().equals("version")) { if (evt.getNewValue().equals(WsrmVersionTypeConfig.X_1_0.toString())) { getWsaConfig().setVersion(WsaVersionTypeConfig.X_200408.toString()); } } } }
39.392027
121
0.692671
6c62eaf32bd1340dc6647e2773e304937f7b4e23
1,759
package ch.eth.jcd.badgers.vfs.core.journaling; import java.util.List; import ch.eth.jcd.badgers.vfs.core.interfaces.VFSEntry; import ch.eth.jcd.badgers.vfs.core.interfaces.VFSPath; import ch.eth.jcd.badgers.vfs.core.journaling.items.JournalItem; import ch.eth.jcd.badgers.vfs.exception.VFSException; public interface VFSJournaling { void addJournalItem(JournalItem journalEntry) throws VFSException; /** * Persist the current journal */ void closeJournal() throws VFSException; /** * gets a list of journals which have not yet been published to the synchronization server * * @return * @throws VFSException */ List<Journal> getPendingJournals() throws VFSException; /** * scans the whole disk and creates a journals which when replayed creates exactly the same content * * @param root * @return * @throws VFSException */ Journal journalizeDisk(VFSEntry root) throws VFSException; void pauseJournaling(boolean pause); VFSPath copyFileToJournal(String absolutePath) throws VFSException; void persistServerJournal(Journal journal) throws VFSException; void overrideJournal(Journal journal) throws VFSException; void openNewJournal(boolean doEnableJournaling) throws VFSException; void openNewJournal(List<JournalItem> journalItemsToAdd, boolean doEnableJournaling) throws VFSException; /** * get all persisted journals from lastSeenServerVersion (excluded) up to the most recent one * * @param lastSeenServerVersion * @return any journal which is newer than lastSeenServerVersion * @throws VFSException */ List<Journal> getJournalsSince(long lastSeenServerVersion) throws VFSException; void deleteJournals() throws VFSException; }
29.813559
107
0.757248
e8460ddd069a5a5855c13811f826ad86a4bf1643
612
package com.shopify.model; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.LinkedList; import java.util.List; @XmlRootElement public class ShopifyCustomCollectionsRoot { @XmlElement(name = "custom_collections") private List<ShopifyCustomCollection> customCollections = new LinkedList<ShopifyCustomCollection>(); public List<ShopifyCustomCollection> getCustomCollections() { return customCollections; } public void setCustomCollections(List<ShopifyCustomCollection> customCollections) { this.customCollections = customCollections; } }
27.818182
101
0.823529
89ebf090f1218511f23204ed902ca567734326d6
1,452
package com.example.sagar.qrcodereader; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; /** * Created by sagar on 10/7/2017. */ public class codeScanner implements scanner { IntentIntegrator _intentIntegrator; IntentResult _result; Context _context; public codeScanner(Activity activity,Context c){ _context=c; _intentIntegrator=new IntentIntegrator(activity); } @Override public void startScan() { _intentIntegrator.initiateScan(); _intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES); _intentIntegrator.setPrompt("Scan"); _intentIntegrator.setCameraId(0); _intentIntegrator.setBeepEnabled(true); } @Override public IntentResult getScanedResult(int requestCode, int resultCode, Intent data) { _result=_intentIntegrator.parseActivityResult( requestCode, resultCode, data); if(_result!=null){ if(_result.getContents()==null){ Toast.makeText(_context,"cancelled",Toast.LENGTH_LONG); return null; } else{ return _result; } } Toast.makeText(_context,"null",Toast.LENGTH_LONG); return null; } }
29.632653
88
0.681818
83ccd790827d6f205a429af0a293955175a337b1
313
package es.msanchez.frameworks.java.spring.boot.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = { "es.msanchez.frameworks.java.spring.boot.**" }) public class SpringConfig { }
26.083333
60
0.798722
1b7c16089f866713df6047037758393239610202
3,660
package com.bin.david.form.data.format.draw; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import com.bin.david.form.data.CellInfo; import com.bin.david.form.data.Column; import com.bin.david.form.core.TableConfig; import com.bin.david.form.data.format.bg.IBackgroundFormat; import java.util.Map; /** * Created by huang on 2017/10/30. */ public abstract class BitmapDrawFormat<T> implements IDrawFormat<T> { private int imageWidth; private int imageHeight; private Rect imgRect; private Rect drawRect; private boolean isDrawBg =true; CellInfo<T> cellInfo = new CellInfo<>(); public BitmapDrawFormat(int imageWidth, int imageHeight) { this.imageWidth = imageWidth; this.imageHeight = imageHeight; imgRect = new Rect(); drawRect = new Rect(); } @Override public int measureWidth(Column<T>column, TableConfig config) { return imageWidth; } @Override public int measureHeight(Column<T> column,int position, TableConfig config) { return imageHeight; } /** * 获取bitmap * @param t 数据 * @param value 值 * @param position 位置 * @return Bitmap 占位图 */ protected abstract Bitmap getBitmap(T t,String value, int position); @Override public void draw(Canvas c,Column<T> column, T t, String value, Rect rect, int position, TableConfig config) { Paint paint = config.getPaint(); cellInfo.set(column,t,value,position); drawBackground(c,cellInfo,rect,config); Bitmap bitmap = getBitmap(t,value,position); if(bitmap != null) { paint.setStyle(Paint.Style.FILL); int width = bitmap.getWidth(); int height = bitmap.getHeight(); imgRect.set(0,0,width,height); float scaleX = (float)width/imageWidth; float scaleY = (float)height/imageHeight; if(scaleX >1 || scaleY >1){ if(scaleX > scaleY){ width = (int) (width/scaleX); height = imageHeight; }else{ height = (int) (height/scaleY); width = imageWidth; } } width= (int) (width*config.getZoom()); height = (int) (height*config.getZoom()); int disX= (rect.right-rect.left-width)/2; int disY= (rect.bottom-rect.top-height)/2; drawRect.left = rect.left+disX; drawRect.top = rect.top+ disY; drawRect.right = rect.right - disX; drawRect.bottom = rect.bottom - disY; c.drawBitmap(bitmap, imgRect, drawRect, paint); } } public boolean drawBackground(Canvas c, CellInfo<T> cellInfo, Rect rect,TableConfig config) { IBackgroundFormat<CellInfo> backgroundFormat = config.getContentBackgroundFormat(); if(isDrawBg &&backgroundFormat != null && backgroundFormat.isDraw(cellInfo)){ backgroundFormat.drawBackground(c,rect,cellInfo,config.getPaint()); return true; } return false; } public boolean isDrawBg() { return isDrawBg; } public void setDrawBg(boolean drawBg) { isDrawBg = drawBg; } public int getImageWidth() { return imageWidth; } public void setImageWidth(int imageWidth) { this.imageWidth = imageWidth; } public int getImageHeight() { return imageHeight; } public void setImageHeight(int imageHeight) { this.imageHeight = imageHeight; } }
28.59375
113
0.612022
8651aa24764fd516d0d99e9a0b3453b649e7e877
10,158
package com.company.GUI.Database; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtils; import org.jfree.chart.JFreeChart; import java.io.*; import java.util.*; public class DBHandler { public static String materialPath = "data/materialDB/"; public static List<Material> materials; public static String graphPath = "data/graphDB/"; // заполнение списка материалов public static void getAllMaterials() { materials = new ArrayList<Material>(); File folder = new File(materialPath); File[] materialFiles = folder.listFiles(); if(materialFiles != null) { // чтение всех материалов for (File file : materialFiles) { if (file.isFile()) { Material material = getMaterial(file); if(material!=null) materials.add(material); } } } } // чтение материала из файла public static Material getMaterial(File file){ try (BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()))) { String line = ""; //name=... line = br.readLine(); if (!line.startsWith("name=")) return null; String name = line.substring(5); if (name.equals("")) return null; //lambda=... line = br.readLine(); if (!line.startsWith("lambda=")) return null; String lambda_string = line.substring(7); if (lambda_string.equals("")) return null; double lambda = 0; try { lambda = Double.parseDouble(lambda_string); } catch (Exception e) {return null;} //nu=... line = br.readLine(); if (!line.startsWith("nu=")) return null; String nu_string = line.substring(3); if (nu_string.equals("")) return null; double nu = 0; try { nu = Double.parseDouble(nu_string); } catch (Exception e) {return null;} //mu=... line = br.readLine(); if (!line.startsWith("mu=")) return null; String mu_string = line.substring(3); if (mu_string.equals("")) return null; double mu = 0; try { mu = Double.parseDouble(mu_string); } catch (Exception e) {return null;} //density=... line = br.readLine(); if (!line.startsWith("density=")) return null; String density_string = line.substring(8); if (density_string.equals("")) return null; double density = 0; try { density = Double.parseDouble(density_string); } catch (Exception e) {return null;} return new Material(name, mu, lambda, density, nu); } catch(IOException ex){} return null; } // получение массива названий материалов public static String[] getMaterialNames(){ String[] names = new String[materials.size()]; int i=0; for(Material material:materials) names[i++] = material.name; return names; } // добавление материала в массив public static boolean addMaterial(Material material){ for(Material mat: materials){ if(material.name.equals(mat.name)) return false; } addMaterialFile(material); materials.add(material); return true; } // создание файла материала. public static void addMaterialFile(Material material){ // создание файла String file_path = materialPath + material.name + ".txt"; File file = new File(file_path); try { file.createNewFile(); } catch (IOException ex){} //запись в файл try { FileWriter fileWriter = new FileWriter(file_path, false); fileWriter.write("name=" + material.name); fileWriter.write("\nlambda=" + material.lameLambda); fileWriter.write("\nnu=" + material.coefficientNu); fileWriter.write("\nmu=" + material.lameMu); fileWriter.write("\ndensity=" + material.materialDensity); fileWriter.close(); } catch (IOException ex) {} } // обновление записи о материале public static boolean updateMaterial(int index, double p1, double p2, double p3, double p4){ boolean updated = false; if(materials.get(index).lameMu != p1){ updated = true; materials.get(index).lameMu = p1; } if(materials.get(index).lameLambda != p2){ updated = true; materials.get(index).lameLambda = p2; } if(materials.get(index).materialDensity != p3){ updated = true; materials.get(index).materialDensity = p3; } if(materials.get(index).coefficientNu != p4){ updated = true; materials.get(index).coefficientNu = p4; } if(updated) addMaterialFile(materials.get(index)); return updated; } // удаление материала public static void deleteMaterial(int index){ Material material = materials.get(index); materials.remove(index); File file = new File(materialPath + material.name + ".txt"); file.delete(); } // чтение всех имен файлов графиков public static List<String> getGraphNames(){ List<String> names = new ArrayList<>(); File folder = new File(graphPath); File[] graphFiles = folder.listFiles(); if(graphFiles != null) { // чтение всех материалов for (File file : graphFiles) { if (file.isFile()) { names.add(file.getName()); } } } return names; } // чтение содержимого файла графика public static double[][] getGraphArray(String filename){ File folder = new File(graphPath); File[] graphFiles = folder.listFiles(); File target_file = null; // поиск файла по имени if(graphFiles != null) { for (File file : graphFiles) { if (file.isFile() && filename.equals(file.getName())) { target_file = file; } } } if (target_file == null) return null; // создание массива размера файла int size = getGraphFileSize(target_file); if(size < 1) return null; double[][] array = new double[2][size]; // чтение координат из файла try (BufferedReader br = new BufferedReader(new FileReader(target_file.getAbsolutePath()))) { int i=0; for(String line = br.readLine(); line!=null; line = br.readLine()) { String[] parts = line.split(";"); try{ array[0][i] = Double.parseDouble(parts[0]); array[1][i] = Double.parseDouble(parts[1]); } catch (Exception ex){return null;} i++; } } catch (Exception ex){return null;} return array; } // Проверка на корректность + подсчет строк в файле графика public static int getGraphFileSize(File file){ int rows = 0; try (BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()))) { for(String line = br.readLine(); line!=null; line = br.readLine()){ // подсчет строк rows++; // проверка строки файла на 2 части, разделенные символом ";" String[] parts = line.split(";"); if(parts.length!=2) return -1; // проверка на числа try{ Double.parseDouble(parts[0]); Double.parseDouble(parts[1]); } catch (Exception ex){return -1;} } } catch (Exception ex){return -1;} return rows; } // запись координат в файл public static void addGraphFile(String fileName, double[][] array){ File file = new File(graphPath + fileName + ".txt"); try{ file.createNewFile(); } catch (Exception ex){} //запись в файл try { FileWriter fileWriter = new FileWriter(file, false); for(int i=1; i<array[0].length; i++) fileWriter.write(array[0][i] + ";" + array[1][i] + "\n"); fileWriter.close(); } catch (IOException ex) {} } // удаление файла с координатами графика public static void deleteGraphFile(String fileName){ File folder = new File(graphPath); File[] graphFiles = folder.listFiles(); File target_file = null; // поиск файла по имени if(graphFiles != null) { for (File file : graphFiles) { if (file.isFile() && fileName.equals(file.getName())) { target_file = file; } } } if(target_file != null) target_file.delete(); } // Сохранение графика в файл public static void SaveChart(JFreeChart chart, ChartPanel panel, String file){ // Удаление названия графика в изображении String title = chart.getTitle().getText(); chart.getTitle().setText(""); // сохранение графика try { ChartUtils.saveChartAsPNG( new File(file), chart, panel.getWidth(), panel.getHeight() ); } catch (IOException ex) {} // Откат названия графика chart.getTitle().setText(title); } }
29.61516
101
0.51959
74c775be28cae179a6524d1343273e5d9a9e730c
3,434
/* * GIPO COPYRIGHT NOTICE, LICENSE AND DISCLAIMER. * * Copyright 2001 - 2003 by R.M.Simpson W.Zhao T.L.McCLuskey D Liu D. Kitchin * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies and that * both the copyright notice and this permission notice and warranty * disclaimer appear in supporting documentation, and that the names of * the authors or their employers not be used in advertising or publicity * pertaining to distribution of the software without specific, written * prior permission. * * The authors and their employers disclaim all warranties with regard to * this software, including all implied warranties of merchantability and * fitness. In no event shall the authors or their employers be liable * for any special, indirect or consequential damages or any damages * whatsoever resulting from loss of use, data or profits, whether in an * action of contract, negligence or other tortious action, arising out of * or in connection with the use or performance of this software. */ // InconsistentConst - Store inconsistent predicate list package jplan.ocl; import java.util.List; import java.util.ArrayList; import java.util.ListIterator; import java.io.*; /** * oclInconsistentConst * store the list of predicates forming a nigative invariant * @author Ron Simpson * @version 0 */ public class oclInconsistentConst implements oclPrint,Serializable,Cloneable { private List preds = new ArrayList(); /** * add a predicate to to be built the list * @param fname - the predicate name * @return reference to the new predicate added */ public oclPredicate addClause(String fname) { oclPredicate cur = new oclPredicate(fname); preds.add(cur); return cur; } /** * getPredicateList * return the predicate of this invariant * @return List - the predicate list */ public List getPredicateList() { return preds; } /** * setPredicateList * update the predicate list with new list of oclPredicates * @param pList - the predicate list */ public void setPredicateList(List pList) { preds = pList; } /** * toString() * standard single line string representation * @return String */ public String toString() { String res = ""; ListIterator li = preds.listIterator(); while(li.hasNext()) { res = res.concat(((oclPredicate)li.next()).toString()); if (li.hasNext()) res = res.concat(new String(" ")); } return res; } /** * clone() * */ public Object clone() throws CloneNotSupportedException { try { oclInconsistentConst oIC = new oclInconsistentConst(); ListIterator li = preds.listIterator(); while (li.hasNext()) { oIC.preds.add(((oclPredicate)li.next()).clone()); } return oIC; } catch (CloneNotSupportedException e) { throw e; } } /** * standard ocl print routine to output canonical ocl */ public void oclPrintComponent(PrintWriter ps,int indent,boolean nline) { ps.print("inconsistent_constraint(["); ListIterator li = preds.listIterator(); while (li.hasNext()) { ((oclPredicate)li.next()).oclPrintComponent(ps,0,false); if (li.hasNext()) ps.print(","); } ps.println("])."); } }
29.350427
78
0.688119
0fcbd4da408bd6e3f3097ea8cd9c43ba95e27594
114
package org.folio.marccat.exception; public class InvalidShelfListTypeException extends ValidationException { }
19
72
0.850877
01e26cdc09396a7b8560b18f4ee3e3fb74461e5c
19,694
package em.demonorium.timetable.Menu; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.ButtonGroup; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.utils.Align; import java.util.Calendar; import em.demonorium.timetable.BasicScreen; import em.demonorium.timetable.Core; import em.demonorium.timetable.Factory.LabelFactory; import em.demonorium.timetable.Factory.ScrollPaneFactory; import em.demonorium.timetable.Factory.TextButtonFactory; import em.demonorium.timetable.TimeData.DataAPI; import em.demonorium.timetable.TimeData.DataBase.Entry; import em.demonorium.timetable.TimeData.Models.DayModel; import em.demonorium.timetable.TimeData.Models.LessonModel; import em.demonorium.timetable.TimeData.Prototypes; import em.demonorium.timetable.TimeData.SimpleDate; import em.demonorium.timetable.Utils.AbstractLocalFactory; import em.demonorium.timetable.Utils.AlignedButton; import em.demonorium.timetable.Utils.AlignedGroup.AlignedGroup; import em.demonorium.timetable.Utils.AlignedGroup.AlignedGroupConstructor; import em.demonorium.timetable.Utils.AlignedGroup.GroupRow; import em.demonorium.timetable.Utils.ButtonList; import em.demonorium.timetable.Utils.SharedCollection.Default.SharedList; import em.demonorium.timetable.Utils.SharedCollection.Editable; import em.demonorium.timetable.Utils.VariableSystem.Action; import em.demonorium.timetable.Utils.VariableSystem.VariableSystem; public class DayEditScreen extends BasicScreen { public static boolean mode; private boolean localMode; private TextButton resetTimetable; private TextButton resetBT; private TextButton backBT; private Editor ed; private TextButton acceptBT; private static class Editor implements Editable<Integer, LessonModel> { private final DayEditScreen screen; private Editor(DayEditScreen screen) { this.screen = screen; } @Override public void added(Integer integer, LessonModel data) { screen.dayChanged(); } @Override public void removed(Integer integer) { screen.dayChanged(); } @Override public void cleared() { screen.dayChanged(); } @Override public void updated(Integer integer) { screen.dayChanged(); } } public DayEditScreen(Core core) { super(core, core.colors.getBasicColor("base")); } private ButtonList<LessonModel> lessonList; private DayModel day; private Label date; private static String getDate(Calendar calendar) { return calendar.get(Calendar.DAY_OF_MONTH) + "." + (calendar.get(Calendar.MONTH) + 1) + "." + calendar.get(Calendar.YEAR); } private void dateChanged() { if (localMode) { day.fromEntry((Entry) vars.getValue("day")); } else { day.fromEntry(DataAPI.getDay(DataAPI.getSelectedDate())); date.setText(getDate(DataAPI.getSelectedDate())); } resetTimetable.setDisabled(day.standard); dayChanged_v = false; acceptBT.setDisabled(true); resetBT.setDisabled(true); factory.update(); } private boolean dayChanged_v = false; private void dayChanged() { dayChanged_v = true; newLesson.setDisabled(!day.mayInsertLesson()); resetBT.setDisabled(false); acceptBT.setDisabled(false); factory.update(); } public static class LessonFactory extends AbstractLocalFactory<LessonModel, DayEditScreen> { LessonFactory(DayEditScreen dayEditScreen) { super(dayEditScreen); } @Override protected void onSelected() { Source.upperLesson.setDisabled(this.group.getSelectedIndex() <= 0); Source.downLesson.setDisabled( (group.getSelectedIndex() >= (group.size() - 1)) && !Source.day.mayInsertLesson()); } @Override public Button get(LessonModel data) { if (data.isSpace()) { Button button = TextButtonFactory.make("SPACE", null, null, Core.fontSettings.main.regular.getCapHeight()*2.3f); button.addListener(new TextButtonFactory.UpListener(){ @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { boolean hasSelected = group.hasSelected(); update(); if (hasSelected) onSelected(); else onUnselected(); } }); return button; } return super.get(data); } @Override public Button newButton(LessonModel data) { AlignedButton button = TextButtonFactory.make("BIG", Core.fontSettings.main.regular.getCapHeight()*2.3f, new AlignedGroup( new GroupRow(1f, 1f), new GroupRow(10f, 0.1f, 0.6f, 0.05f, 0.25f, 0.05f), new GroupRow(1f, 0.1f), new GroupRow(4f, 0.1f, 0.6f, 0.05f, 0.25f, 0.05f), new GroupRow(1f, 1f) )); int id = Source.day.lessons.keyOf(data); { Label label = LabelFactory.make("INFO_NO_B", Source.day.timetable.get(Prototypes.Day.getStart(id)).toString() + " - " + Source.day.timetable.get(Prototypes.Day.getEnd(id)).toString()); label.setAlignment(Align.left); button.setActor(label, 1, 1); } { Label label = LabelFactory.make("MEDIUM_NO_B", (String)DataAPI.object.get(data.subject).get("name")); label.setAlignment(Align.left); button.setActor(label, 3, 1); } { button.setActor(LabelFactory.make("INFO_NO_B", data.auditory), 3,3); button.setActor(LabelFactory.make("INFO_NO_B", data.building), 1,3); } return button; } } private LessonFactory factory; private TextButton upperLesson, downLesson, removeLesson, newLesson, editLesson; @Override public void create() { localMode = mode; removeLesson = TextButtonFactory.make("BIG", "-"); upperLesson = TextButtonFactory.make("BIG", "U"); downLesson = TextButtonFactory.make("BIG", "D"); day = new DayModel(); factory = new LessonFactory(this); lessonList = new ButtonList<>(day.lessons, factory); { removeLesson.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (lessonList.hasSelected()) { VariableSystem localVars = core.varsOf("listYN"); localVars.set("what", "Удалить?"); localVars.set("yes", new Action() { @Override public void action() { lessonList.remove(); dayChanged(); } }); localVars.set("no", Action.NONE_ACTION); core.setScreen("listYN"); } } }); newLesson = TextButtonFactory.make("BIG", "+"); newLesson.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (newLesson.isDisabled()) return; VariableSystem localVars; localVars = core.varsOf("lessonEdit"); localVars.set("lessonList", lessonList); localVars.setFlag("isLessonEdit", false); localVars = core.varsOf("subSelect"); localVars.setFlag("isSelect"); localVars.setFlag("hasNext"); localVars.set("next", "lessonEdit"); core.setScreen("subSelect"); } }); editLesson = TextButtonFactory.make("BIG", "E"); editLesson.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (editLesson.isDisabled()) return; VariableSystem localVars; localVars = core.varsOf("lessonEdit"); localVars.set("lessonList", lessonList); localVars.setFlag("isLessonEdit", true); localVars.set("editLesson", lessonList.getSelectedIndex()); core.setScreen("lessonEdit"); } }); } TextButton editTimetable = TextButtonFactory.make("MEDIUM", "Изм. звонки"); editTimetable.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { VariableSystem localVars = core.varsOf("timetableEdit"); localVars.set("timetable", day.timetable); localVars.set("date", DataAPI.getSelectedDate()); localVars.setFlag("loadTimetable"); core.setScreen("timetableEdit"); } }); resetTimetable = TextButtonFactory.make("MEDIUM", "Сбросить звонки"); resetTimetable.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (resetTimetable.isDisabled()) return; SharedList<SimpleDate> timetable = DataAPI.getStandardTimetable(); day.applyTimetable(timetable); day.standard = true; resetTimetable.setDisabled(true); lessonList.update(); } }); ScrollPane basePane = ScrollPaneFactory.make("main", lessonList.getVL()); upperLesson.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (lessonList.hasSelected()) { int index = lessonList.getSelectedIndex(); if (index > 0) { lessonList.swap(index - 1, index); dayChanged(); } } } }); downLesson.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (lessonList.hasSelected()) { int index = lessonList.getSelectedIndex(); if (index < (lessonList.size() - 1)) { lessonList.swap(index, index + 1); } else { if (!newLesson.isDisabled()) lessonList.add(lessonList.size() - 1, new LessonModel()); } dayChanged(); } } }); acceptBT = TextButtonFactory.make("MEDIUM", "Принять"); acceptBT.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (acceptBT.isDisabled()) return; if (dayChanged_v) { if (localMode) { core.returnValues().set("newDay", day); core.returnValues().setFlag("returnDay"); } else { DataAPI.addChanges(DataAPI.getSelectedDate(), day); } } if (!localMode) core.back(); core.back(); } }); backBT = TextButtonFactory.make("MEDIUM", "Назад"); backBT.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (dayChanged_v) { VariableSystem localVars = core.varsOf("listYN"); localVars.set("what", "Вернуться?"); localVars.set("yes", new Action() { @Override public void action() { core.back(); core.back(); } }); localVars.set("no", Action.NONE_ACTION); core.setScreen("listYN"); } else { core.back(); if (!localMode) core.back(); } } }); resetBT = TextButtonFactory.make("MEDIUM", "Сбросить"); resetBT.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (dayChanged_v) { VariableSystem localVars = core.varsOf("listYN"); localVars.set("what", "Сбросить?"); localVars.set("yes", new Action() { @Override public void action() { dayChanged_v = false; dateChanged(); } }); localVars.set("no", Action.NONE_ACTION); core.setScreen("listYN"); } resetBT.setDisabled(true); } }); factory.addActors(removeLesson, upperLesson, downLesson, editLesson); AlignedGroupConstructor.RowConstructor lastRow = beginUI() .r(1f) .r(8f).c(0.1f).c(0.7f/3f, backBT).c(0.05f).c(0.7f/3f, resetBT).c(0.05f).c(0.7f/3f, acceptBT).c(0.1f) .r(1f) .r(5f) .r(8f).c(0.1f).c(0.35f, resetTimetable).c(0.1f).c(0.35f, editTimetable).c(0.1f) .r(1f) .r(2f) .r(8f).c(0.1f).c(0.2f - 0.15f/2f).c(0.2f, editLesson).c(0.2f- 0.15f/2f).c(0.05f).c(0.3f, downLesson).c(0.1f) .r(2f) .r(8f).c(0.1f).c(0.2f, newLesson).c(0.05f).c(0.2f, removeLesson).c(0.05f).c(0.3f, upperLesson).c(0.1f) .r(2f) .r(54f).c(0.1f).c(0.8f, basePane).c(0.1f) .r(1f) .r(8f) ; if (mode) { date = LabelFactory.make("BIG_NO_B", "Понедельник 1Н"); lastRow.c(1f, date).r(1f); endUI(); } else { TextButton upper = TextButtonFactory.make("BIG", "<"); upper.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (dayChanged_v) { VariableSystem localVars = core.varsOf("listYN"); localVars.set("what", "Сбросить?"); localVars.set("yes", new Action() { @Override public void action() { dayChanged_v = false; DataAPI.leftDate(); dateChanged(); } }); localVars.set("no", Action.NONE_ACTION); core.setScreen("listYN"); } else { DataAPI.leftDate(); dateChanged(); } } }); date = LabelFactory.make("BIG", getDate(DataAPI.getSelectedDate())); TextButton down = TextButtonFactory.make("BIG", ">"); down.addListener(new TextButtonFactory.UpListener() { @Override public void touchUp(InputEvent event, float x, float y, int pointer, int button) { if (dayChanged_v) { VariableSystem localVars = core.varsOf("listYN"); localVars.set("what", "Сбросить?"); localVars.set("yes", new Action() { @Override public void action() { DataAPI.rightDate(); dateChanged(); dayChanged_v = false; } }); localVars.set("no", Action.NONE_ACTION); core.setScreen("listYN"); } else { DataAPI.rightDate(); dateChanged(); } } }); lastRow.c(0.1f).c(0.1f, upper).c(0.05f).c(0.5f, date).c(0.05f).c(0.1f, down).c(0.1f) .r(1f); endUI(); } ed = new Editor(this); this.lessonList.register(ed); } @Override public void show() { super.show(); if (vars.testAndSet("loadDay", false)) { if (localMode) { date.setText((String) vars.getValue("currentDay")); day.fromEntry((Entry) vars.getValue("day")); } else { date.setText(getDate(DataAPI.getSelectedDate())); day.fromEntry(DataAPI.getSelectedDay()); } dateChanged(); } upperLesson.setDisabled(!lessonList.hasSelected()); downLesson.setDisabled(!lessonList.hasSelected()); removeLesson.setDisabled(!lessonList.hasSelected()); editLesson.setDisabled(lessonList.hasSelected()); if (vars.testAndSet("returnTimetable", false)) { SharedList<SimpleDate> dates = vars.getValue("timetable"); day.applyTimetable(dates); day.standard = false; lessonList.update(); dayChanged(); } newLesson.setDisabled(!day.mayInsertLesson()); resetTimetable.setDisabled(day.standard); factory.update(); } }
35.677536
135
0.505027
a2996ab9f083976de6d01563f7a7d642ea78874d
348
package org.jmagic.actions.rules.game; import org.jmagic.core.states.State; import org.jmagic.infrastructure.validation.rules.ValidationRule; public class GameIsFinished extends ValidationRule { @Override public void onValidate(State state) { if (!state.done) { errors.add("game is not finished"); } } }
21.75
65
0.692529
651ecbf0c0de13a9f7bbf1f5798a0ad24afee2d6
24,468
// Copyright 2000-2020 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 org.jetbrains.plugins.gradle.model; import com.intellij.openapi.externalSystem.model.ExternalSystemException; import com.intellij.util.Consumer; import com.intellij.util.ReflectionUtilRt; import org.gradle.api.Action; import org.gradle.tooling.BuildAction; import org.gradle.tooling.BuildController; import org.gradle.tooling.UnknownModelException; import org.gradle.tooling.UnsupportedVersionException; import org.gradle.tooling.internal.adapter.ProtocolToModelAdapter; import org.gradle.tooling.internal.adapter.TargetTypeProvider; import org.gradle.tooling.internal.gradle.DefaultBuildIdentifier; import org.gradle.tooling.internal.gradle.DefaultProjectIdentifier; import org.gradle.tooling.model.*; import org.gradle.tooling.model.build.BuildEnvironment; import org.gradle.tooling.model.build.JavaEnvironment; import org.gradle.tooling.model.gradle.BasicGradleProject; import org.gradle.tooling.model.gradle.GradleBuild; import org.gradle.tooling.model.idea.IdeaProject; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider.BuildModelConsumer; import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider.ProjectModelConsumer; import org.jetbrains.plugins.gradle.model.internal.TurnOffDefaultTasks; import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.InternalBuildIdentifier; import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.InternalJavaEnvironment; import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.Supplier; import org.jetbrains.plugins.gradle.tooling.serialization.internal.adapter.build.InternalBuildEnvironment; import java.io.File; import java.io.Serializable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @author Vladislav.Soroka */ public class ProjectImportAction implements BuildAction<ProjectImportAction.AllModels>, Serializable { private static final ModelConverter NOOP_CONVERTER = new NoopConverter(); private final Set<ProjectImportModelProvider> myProjectsLoadedModelProviders = new HashSet<ProjectImportModelProvider>(); private final Set<ProjectImportModelProvider> myBuildFinishedModelProviders = new HashSet<ProjectImportModelProvider>(); private final Set<Class<?>> myTargetTypes = new HashSet<Class<?>>(); private final boolean myIsPreviewMode; private final boolean myIsCompositeBuildsSupported; private boolean myUseProjectsLoadedPhase; private boolean myParallelModelsFetch; private AllModels myAllModels = null; @Nullable private transient GradleBuild myGradleBuild; private ModelConverter myModelConverter; public ProjectImportAction(boolean isPreviewMode, boolean isCompositeBuildsSupported) { myIsPreviewMode = isPreviewMode; myIsCompositeBuildsSupported = isCompositeBuildsSupported; } public void addProjectImportModelProvider(@NotNull ProjectImportModelProvider provider) { addProjectImportModelProvider(provider, false); } public void addProjectImportModelProvider(@NotNull ProjectImportModelProvider provider, boolean isProjectLoadedProvider) { if (isProjectLoadedProvider) { myProjectsLoadedModelProviders.add(provider); } else { myBuildFinishedModelProviders.add(provider); } } @ApiStatus.Internal public Set<Class<?>> getModelProvidersClasses() { Set<Class<?>> result = new LinkedHashSet<Class<?>>(); for (ProjectImportModelProvider provider : myProjectsLoadedModelProviders) { result.add(provider.getClass()); } for (ProjectImportModelProvider provider : myBuildFinishedModelProviders) { result.add(provider.getClass()); } return result; } public void addTargetTypes(@NotNull Set<Class<?>> targetTypes) { myTargetTypes.addAll(targetTypes); } public void prepareForPhasedExecuter() { myUseProjectsLoadedPhase = true; } public void prepareForNonPhasedExecuter() { myUseProjectsLoadedPhase = false; } @NotNull protected ModelConverter getToolingModelConverter(@NotNull BuildController controller) { return NOOP_CONVERTER; } @Nullable @Override public AllModels execute(final BuildController controller) { configureAdditionalTypes(controller); final boolean isProjectsLoadedAction = myAllModels == null && myUseProjectsLoadedPhase; if (isProjectsLoadedAction || !myUseProjectsLoadedPhase) { long startTime = System.currentTimeMillis(); myGradleBuild = controller.getBuildModel(); Build mainBuild = convert(myGradleBuild); AllModels allModels = new AllModels(mainBuild); allModels.logPerformance("Get model GradleBuild", System.currentTimeMillis() - startTime); long startTimeBuildEnv = System.currentTimeMillis(); BuildEnvironment buildEnvironment = controller.findModel(BuildEnvironment.class); allModels.setBuildEnvironment(convert(buildEnvironment)); allModels.logPerformance("Get model BuildEnvironment", System.currentTimeMillis() - startTimeBuildEnv); myAllModels = allModels; myModelConverter = getToolingModelConverter(controller); } assert myGradleBuild != null; assert myModelConverter != null; final MyBuildController wrappedController = new MyBuildController(controller, myGradleBuild); fetchProjectBuildModels(wrappedController, isProjectsLoadedAction, myGradleBuild); addBuildModels(wrappedController, myAllModels, myGradleBuild, isProjectsLoadedAction); if (myIsCompositeBuildsSupported) { forEachNestedBuild(myGradleBuild, new GradleBuildConsumer() { @Override public void accept(@NotNull GradleBuild includedBuild) { if (!isProjectsLoadedAction) { myAllModels.getIncludedBuilds().add(convert(includedBuild)); } fetchProjectBuildModels(wrappedController, isProjectsLoadedAction, includedBuild); addBuildModels(wrappedController, myAllModels, includedBuild, isProjectsLoadedAction); } }); } if (isProjectsLoadedAction) { wrappedController.getModel(TurnOffDefaultTasks.class); } return isProjectsLoadedAction && !myAllModels.hasModels() ? null : myAllModels; } @ApiStatus.Internal public void setParallelModelsFetch(boolean parallelModelsFetch) { myParallelModelsFetch = parallelModelsFetch; } @Contract("null -> null") private static BuildEnvironment convert(final @Nullable BuildEnvironment buildEnvironment) { if (buildEnvironment == null) return null; return buildEnvironment instanceof InternalBuildEnvironment ? buildEnvironment : new InternalBuildEnvironment( new Supplier<InternalBuildIdentifier>() { @Override public InternalBuildIdentifier get() { return new InternalBuildIdentifier(buildEnvironment.getBuildIdentifier().getRootDir()); } }, new Supplier<InternalJavaEnvironment>() { @Override public InternalJavaEnvironment get() { JavaEnvironment java = buildEnvironment.getJava(); return new InternalJavaEnvironment(java.getJavaHome(), java.getJvmArguments()); } }, new Supplier<File>() { @Override public File get() { return buildEnvironment.getGradle().getGradleUserHome(); } }, buildEnvironment.getGradle().getGradleVersion()); } private interface GradleBuildConsumer { void accept(@NotNull GradleBuild build); } private static void forEachNestedBuild(@NotNull GradleBuild rootBuild, @NotNull GradleBuildConsumer buildConsumer) { Set<String> processedBuildsPaths = new HashSet<String>(); String rootBuildPath = rootBuild.getBuildIdentifier().getRootDir().getPath(); processedBuildsPaths.add(rootBuildPath); Queue<GradleBuild> queue = new LinkedList<GradleBuild>(rootBuild.getIncludedBuilds()); while (!queue.isEmpty()) { GradleBuild includedBuild = queue.remove(); String includedBuildPath = includedBuild.getBuildIdentifier().getRootDir().getPath(); if (processedBuildsPaths.add(includedBuildPath)) { buildConsumer.accept(includedBuild); queue.addAll(includedBuild.getIncludedBuilds()); } } } private void fetchProjectBuildModels(BuildController controller, final boolean isProjectsLoadedAction, GradleBuild build) { // Prepare nested build actions. List<BuildAction<List<Runnable>>> buildActions = new ArrayList<BuildAction<List<Runnable>>>(); for (final BasicGradleProject gradleProject : build.getProjects()) { buildActions.add( new BuildAction<List<Runnable>>() { @Override public List<Runnable> execute(BuildController controller) { return getProjectModels(controller, myAllModels, gradleProject, isProjectsLoadedAction); } } ); } // Execute nested build actions. List<List<Runnable>> addFetchedModelActions = new ArrayList<List<Runnable>>(buildActions.size()); if (myParallelModelsFetch) { addFetchedModelActions.addAll(controller.run(buildActions)); } else { for (BuildAction<List<Runnable>> buildAction : buildActions) { addFetchedModelActions.add(buildAction.execute(controller)); } } // Execute returned actions sequentially in one thread to populate myAllModels. for (List<Runnable> actions : addFetchedModelActions) { for (Runnable action : actions) { action.run(); } } } @NotNull private static Build convert(@NotNull GradleBuild build) { DefaultBuild rootProject = new DefaultBuild(build.getRootProject().getName(), build.getBuildIdentifier().getRootDir()); for (BasicGradleProject project : build.getProjects()) { rootProject.addProject(project.getName(), project.getProjectIdentifier()); } return rootProject; } private void configureAdditionalTypes(BuildController controller) { if (myTargetTypes.isEmpty()) return; try { ProtocolToModelAdapter modelAdapter = ReflectionUtilRt.getField(controller.getClass(), controller, ProtocolToModelAdapter.class, "adapter"); if (modelAdapter == null) return; TargetTypeProvider typeProvider = ReflectionUtilRt.getField(ProtocolToModelAdapter.class, modelAdapter, TargetTypeProvider.class, "targetTypeProvider"); if (typeProvider == null) return; //noinspection unchecked Map<String, Class<?>> targetTypes = ReflectionUtilRt.getField(typeProvider.getClass(), typeProvider, Map.class, "configuredTargetTypes"); if (targetTypes == null) return; for (Class<?> targetType : myTargetTypes) { targetTypes.put(targetType.getCanonicalName(), targetType); } } catch (Exception ignore) { } } /** * Gets project level models for a given {@code project} and returns a collection of actions, * which when executed add these models to {@code allModels}. * * <p>The actions returned by this method are supposed to be executed on a single thread. */ private List<Runnable> getProjectModels(@NotNull BuildController controller, @NotNull final AllModels allModels, @NotNull final BasicGradleProject project, boolean isProjectsLoadedAction) { try { final List<Runnable> result = new ArrayList<Runnable>(); Set<ProjectImportModelProvider> modelProviders = getModelProviders(isProjectsLoadedAction); for (ProjectImportModelProvider extension : modelProviders) { final Set<String> obtainedModels = new HashSet<String>(); long startTime = System.currentTimeMillis(); ProjectModelConsumer modelConsumer = new ProjectModelConsumer() { @Override public void consume(final @NotNull Object object, final @NotNull Class clazz) { result.add(new Runnable() { @Override public void run() { Object o = myModelConverter.convert(object); allModels.addModel(o, clazz, project); } }); obtainedModels.add(clazz.getName()); } }; extension.populateProjectModels(controller, project, modelConsumer); allModels.logPerformance( "Ran extension " + extension.getClass().getName() + " for project " + project.getProjectIdentifier().getProjectPath() + " obtained " + obtainedModels.size() + " model(s): " + joinClassNamesToString(obtainedModels), System.currentTimeMillis() - startTime); } return result; } catch (Exception e) { // do not fail project import in a preview mode if (!myIsPreviewMode) { throw new ExternalSystemException(e); } } return Collections.emptyList(); } private void addBuildModels(@NotNull BuildController controller, @NotNull final AllModels allModels, @NotNull final GradleBuild buildModel, boolean isProjectsLoadedAction) { try { Set<ProjectImportModelProvider> modelProviders = getModelProviders(isProjectsLoadedAction); for (ProjectImportModelProvider extension : modelProviders) { final Set<String> obtainedModels = new HashSet<String>(); long startTime = System.currentTimeMillis(); BuildModelConsumer modelConsumer = new BuildModelConsumer() { @Override public void consumeProjectModel(@NotNull ProjectModel projectModel, @NotNull Object object, @NotNull Class clazz) { object = myModelConverter.convert(object); allModels.addModel(object, clazz, projectModel); obtainedModels.add(clazz.getName()); } @Override public void consume(@NotNull BuildModel buildModel, @NotNull Object object, @NotNull Class clazz) { if (myModelConverter != null) { object = myModelConverter.convert(object); } allModels.addModel(object, clazz, buildModel); obtainedModels.add(clazz.getName()); } }; extension.populateBuildModels(controller, buildModel, modelConsumer); allModels.logPerformance( "Ran extension " + extension.getClass().getName() + " for build " + buildModel.getBuildIdentifier().getRootDir().getPath() + " obtained " + obtainedModels.size() + " model(s): " + joinClassNamesToString(obtainedModels), System.currentTimeMillis() - startTime); } } catch (Exception e) { // do not fail project import in a preview mode if (!myIsPreviewMode) { throw new ExternalSystemException(e); } } } private Set<ProjectImportModelProvider> getModelProviders(boolean isProjectsLoadedAction) { Set<ProjectImportModelProvider> modelProviders = new LinkedHashSet<ProjectImportModelProvider>(); if (!myUseProjectsLoadedPhase) { modelProviders.addAll(myProjectsLoadedModelProviders); modelProviders.addAll(myBuildFinishedModelProviders); } else { modelProviders = isProjectsLoadedAction ? myProjectsLoadedModelProviders : myBuildFinishedModelProviders; } return modelProviders; } @NotNull private static String joinClassNamesToString(@NotNull Set<String> names) { StringBuilder sb = new StringBuilder(); for (Iterator<String> it = names.iterator(); it.hasNext(); ) { sb.append(it.next()); if (it.hasNext()) { sb.append(", "); } } return sb.toString(); } @ApiStatus.Experimental public interface ModelConverter extends Serializable { Object convert(Object object); } // Note: This class is NOT thread safe and it is supposed to be used from a single thread. // Performance logging related methods are thread safe. public static final class AllModels extends ModelsHolder<BuildModel, ProjectModel> { @NotNull private final List<Build> includedBuilds = new ArrayList<Build>(); private final Map<String, Long> performanceTrace = new ConcurrentHashMap<String, Long>(); private transient Map<String, String> myBuildsKeyPrefixesMapping; public AllModels(@NotNull Build mainBuild) { super(mainBuild); } public AllModels(@NotNull IdeaProject ideaProject) { super(new LegacyIdeaProjectModelAdapter(ideaProject)); addModel(ideaProject, IdeaProject.class); } /** * @deprecated use {@link #getModel(Class<IdeaProject>)} */ @NotNull @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") public IdeaProject getIdeaProject() { IdeaProject ideaProject = getModel(IdeaProject.class); assert ideaProject != null; return ideaProject; } @NotNull public Build getMainBuild() { return (Build)getRootModel(); } @NotNull public List<Build> getIncludedBuilds() { return includedBuilds; } @Nullable public BuildEnvironment getBuildEnvironment() { return getModel(BuildEnvironment.class); } public void setBuildEnvironment(@Nullable BuildEnvironment buildEnvironment) { if (buildEnvironment != null) { addModel(buildEnvironment, BuildEnvironment.class); } } public void logPerformance(@NotNull final String description, long millis) { performanceTrace.put(description, millis); } public Map<String, Long> getPerformanceTrace() { return performanceTrace; } @Override public void applyPathsConverter(@NotNull Consumer<Object> pathsConverter) { super.applyPathsConverter(pathsConverter); BuildEnvironment buildEnvironment = getBuildEnvironment(); if (buildEnvironment != null) { pathsConverter.consume(buildEnvironment); } myBuildsKeyPrefixesMapping = new HashMap<String, String>(); convertPaths(pathsConverter, getMainBuild()); for (Build includedBuild : includedBuilds) { convertPaths(pathsConverter, includedBuild); } } private void convertPaths(@NotNull Consumer<Object> fileMapper, @NotNull Build build) { String originalKey = getBuildKeyPrefix(build.getBuildIdentifier()); fileMapper.consume(build); String currentKey = getBuildKeyPrefix(build.getBuildIdentifier()); if (!originalKey.equals(currentKey)) { myBuildsKeyPrefixesMapping.put(currentKey, originalKey); } } @NotNull @Override protected String getBuildKeyPrefix(@NotNull BuildIdentifier buildIdentifier) { String currentKey = super.getBuildKeyPrefix(buildIdentifier); String originalKey = myBuildsKeyPrefixesMapping == null ? null : myBuildsKeyPrefixesMapping.get(currentKey); return originalKey == null ? currentKey : originalKey; } } private final static class DefaultBuild implements Build, Serializable { private final String myName; private final DefaultBuildIdentifier myBuildIdentifier; private final Collection<Project> myProjects = new ArrayList<Project>(0); private DefaultBuild(String name, File rootDir) { myName = name; myBuildIdentifier = new DefaultBuildIdentifier(rootDir); } @Override public String getName() { return myName; } @Override public BuildIdentifier getBuildIdentifier() { return myBuildIdentifier; } @Override public Collection<Project> getProjects() { return myProjects; } private void addProject(String name, final ProjectIdentifier projectIdentifier) { final String projectPath = projectIdentifier.getProjectPath(); File rootDir = myBuildIdentifier.getRootDir(); assert rootDir.getPath().equals(projectIdentifier.getBuildIdentifier().getRootDir().getPath()); myProjects.add(new DefaultProjectModel(name, rootDir, projectPath)); } private final static class DefaultProjectModel implements Project, Serializable { private final String myName; private final DefaultProjectIdentifier myProjectIdentifier; private DefaultProjectModel(@NotNull String name, @NotNull File rootDir, @NotNull String projectPath) { myName = name; myProjectIdentifier = new DefaultProjectIdentifier(rootDir, projectPath); } @Override public String getName() { return myName; } @Override public ProjectIdentifier getProjectIdentifier() { return myProjectIdentifier; } @Override public String toString() { return "ProjectModel{" + "name='" + myName + '\'' + ", id=" + myProjectIdentifier + '}'; } } } private final static class MyBuildController implements BuildController { private final BuildController myDelegate; private final GradleBuild myMainGradleBuild; private final Model myMyMainGradleBuildRootProject; private MyBuildController(@NotNull BuildController buildController, @NotNull GradleBuild mainGradleBuild) { myDelegate = buildController; myMainGradleBuild = mainGradleBuild; myMyMainGradleBuildRootProject = myMainGradleBuild.getRootProject(); } @Override public <T> T getModel(Class<T> aClass) throws UnknownModelException { if (aClass == GradleBuild.class) { //noinspection unchecked return (T)myMainGradleBuild; } return myDelegate.getModel(myMyMainGradleBuildRootProject, aClass); } @Override public <T> T findModel(Class<T> aClass) { if (aClass == GradleBuild.class) { //noinspection unchecked return (T)myMainGradleBuild; } return myDelegate.findModel(myMyMainGradleBuildRootProject, aClass); } @Override public GradleBuild getBuildModel() { return myMainGradleBuild; } @Override public <T> T getModel(Model model, Class<T> aClass) throws UnknownModelException { if (isMainBuild(model)) { return getModel(aClass); } else { return myDelegate.getModel(model, aClass); } } @Override public <T> T findModel(Model model, Class<T> aClass) { if (isMainBuild(model)) { return findModel(aClass); } else { return myDelegate.findModel(model, aClass); } } @Override public <T, P> T getModel(Class<T> aClass, Class<P> aClass1, Action<? super P> action) throws UnsupportedVersionException { return myDelegate.getModel(myMyMainGradleBuildRootProject, aClass, aClass1, action); } @Override public <T, P> T findModel(Class<T> aClass, Class<P> aClass1, Action<? super P> action) { return myDelegate.findModel(myMyMainGradleBuildRootProject, aClass, aClass1, action); } @Override public <T, P> T getModel(Model model, Class<T> aClass, Class<P> aClass1, Action<? super P> action) throws UnsupportedVersionException { if (isMainBuild(model)) { return getModel(aClass, aClass1, action); } else { return myDelegate.getModel(model, aClass, aClass1, action); } } @Override public <T, P> T findModel(Model model, Class<T> aClass, Class<P> aClass1, Action<? super P> action) { if (isMainBuild(model)) { return findModel(aClass, aClass1, action); } else { return myDelegate.findModel(model, aClass, aClass1, action); } } @Override public <T> List<T> run(Collection<? extends BuildAction<? extends T>> collection) { return myDelegate.run(collection); } @Override public boolean getCanQueryProjectModelInParallel(Class<?> aClass) { return myDelegate.getCanQueryProjectModelInParallel(aClass); } private boolean isMainBuild(Model model) { return model == null || model == myMainGradleBuild; } } private static class NoopConverter implements ModelConverter { @Override public Object convert(Object object) { return object; } } }
38.29108
140
0.702182
f70156dac74433f540386701521d3cee73589d19
2,845
package com.alibaba.chaosblade.exec.plugin.jvm.cpu; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.alibaba.chaosblade.exec.common.aop.EnhancerModel; import com.alibaba.chaosblade.exec.common.model.action.ActionExecutor; import com.alibaba.chaosblade.exec.common.util.StringUtil; import com.alibaba.chaosblade.exec.plugin.jvm.JvmConstant; import com.alibaba.chaosblade.exec.plugin.jvm.StoppableActionExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Changjun Xiao */ public class JvmCpuFullLoadExecutor implements ActionExecutor, StoppableActionExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(JvmCpuFullLoadExecutor.class); private volatile ExecutorService executorService; private Object lock = new Object(); private volatile boolean flag; /** * Through the infinite loop to achieve full CPU load. * * @param enhancerModel * @throws Exception */ @Override public void run(EnhancerModel enhancerModel) throws Exception { if (executorService != null && (!executorService.isShutdown())) { throw new IllegalStateException("The jvm cpu full load experiment is running"); } // 绑定 CPU 核心数, 即指定几个核心满载 String cpuCount = enhancerModel.getActionFlag(JvmConstant.FLAG_NAME_CPU_COUNT); // 获取所有核心 int maxProcessors = Runtime.getRuntime().availableProcessors(); int threadCount = maxProcessors; if (!StringUtil.isBlank(cpuCount)) { Integer count = Integer.valueOf(cpuCount.trim()); if (count > 0 && count < maxProcessors) { threadCount = count; } } synchronized (lock) { if (executorService != null && (!executorService.isShutdown())) { throw new IllegalStateException("The jvm cpu full load experiment is running..."); } // 需要N核心满载,就生成N个的线程, executorService = Executors.newFixedThreadPool(threadCount); } flag = true; for (int i = 0; i < threadCount; i++) { executorService.submit(new Runnable() { @Override public void run() { // 死循环, 循环内什么都不要做 while (flag) { } } }); LOGGER.info("start jvm cpu full load thread, {}", i); } } @Override public void stop(EnhancerModel enhancerModel) throws Exception { flag = false; if (executorService != null && !executorService.isShutdown()) { // 关闭 executorService.shutdownNow(); // 设置为 null , 加快 GC executorService = null; LOGGER.info("jvm cpu full load stopped"); } } }
35.123457
98
0.625308
0841c0a4cb885d3035053c7a1e6880bca352584b
4,898
package datawave.iterators; import java.util.*; import datawave.edge.protobuf.EdgeData; import datawave.edge.protobuf.EdgeData.MetadataValue; import datawave.edge.protobuf.EdgeData.MetadataValue.Metadata; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.Combiner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.InvalidProtocolBufferException; /** * Combines edge metadata from different values. * * This will always write protocol buffers as the value * */ public class EdgeMetadataCombiner extends Combiner { private static final Logger log = LoggerFactory.getLogger(EdgeMetadataCombiner.class); /** * Reduces a list of Values into a single Value. * * @param key * The most recent version of the Key being reduced. * @param iter * An iterator over the Values for different versions of the key. * @return The combined Value. */ @Override public Value reduce(Key key, Iterator<Value> iter) { // Since similar metadata values can have different date strings we only want to keep one // version of each piece of metadata along with its earliest start date. Map<Metadata,String> metadataFields = new TreeMap<>(new MetadataComparator()); // possibly check that the key has "edge" as the cf? String earliestDate = null; while (iter.hasNext()) { Value value = iter.next(); MetadataValue metadataVal; try { metadataVal = datawave.edge.protobuf.EdgeData.MetadataValue.parseFrom(value.get()); } catch (InvalidProtocolBufferException e) { log.error("Found invalid Edge Metadata Value bytes."); continue; } List<Metadata> metadata = metadataVal.getMetadataList(); // Go through and store the metadata with its earliest start date for (Metadata meta : metadata) { String tempDate = meta.getDate(); if (!metadataFields.containsKey(meta)) { metadataFields.put(meta, meta.getDate()); } else if (metadataFields.get(meta).compareTo(meta.getDate()) > 0) { metadataFields.put(meta, meta.getDate()); } } } // Afterwards insert the earliest start date into its respective metadata object and add it to // the MetadataValueBuilder. EdgeData.MetadataValue.Metadata.Builder metaDatabuilder = MetadataValue.Metadata.newBuilder(); MetadataValue.Builder builder = MetadataValue.newBuilder(); for (Map.Entry<Metadata,String> metaEntry : metadataFields.entrySet()) { metaDatabuilder.clear(); Metadata metadata = metaEntry.getKey(); String date = metaEntry.getValue(); metaDatabuilder.mergeFrom(metadata); metaDatabuilder.setDate(date); builder.addMetadata(metaDatabuilder); } return new Value(builder.build().toByteArray()); } /* * Only compare the first 5 fields in the metedata Want to use this to match other metadata objects with the same fields but different dates 0 = they are * the same, this is good else = they are different, this is bad */ private class MetadataComparator implements Comparator<Metadata> { @Override public int compare(Metadata m1, Metadata m2) { int comparison = metadataComparatorHelper(m1.getJexlPrecondition(), m2.getJexlPrecondition()); if (comparison != 0) { return comparison; } comparison = metadataComparatorHelper(m1.getSource(), m2.getSource()); if (comparison != 0) { return comparison; } comparison = metadataComparatorHelper(m1.getSink(), m2.getSink()); if (comparison != 0) { return comparison; } comparison = metadataComparatorHelper(m1.getEnrichment(), m2.getEnrichment()); return comparison; } /* * 0 = they are the same, this is good 1 = they are different, this is bad */ private int metadataComparatorHelper(String s1, String s2) { if (s1 != null && s2 != null) { return s1.compareTo(s2); } else if (s1 == null && s2 == null) { return 0; } else { return 1; } } } }
36.281481
157
0.581258
b36083b1b840208d57350ea1b01a380471de7d53
1,067
package io.husaind.controller; import io.husaind.dto.MonteCarloRequest; import io.husaind.dto.MonteCarloResponse; import io.husaind.service.MonteCarloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; @RestController @RequestMapping(value = "/monte-carlo") public class MonteCarloController { private MonteCarloService monteCarloService; @Autowired public MonteCarloController(MonteCarloService monteCarloService) { this.monteCarloService = monteCarloService; } @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE) public MonteCarloResponse simulate(@Valid @RequestBody MonteCarloRequest monteCarloRequest) { return monteCarloService.simulate(monteCarloRequest); } }
30.485714
97
0.81537
bad6ba98c19f17935c4dafd20d532be5182ccc16
4,456
package com.code_embryo.android.ble.beacon.record; import android.bluetooth.le.ScanRecord; import android.bluetooth.le.ScanResult; import com.code_embryo.android.ble.beacon.Beacon; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; public class BeaconRecordTest { ScanRecord mockRecord; ScanResult mockResult; @Before public void setUp() { mockRecord = Mockito.mock(ScanRecord.class); mockResult = Mockito.mock(ScanResult.class); Mockito.when(mockResult.getScanRecord()).thenReturn(mockRecord); byte[] rawRecord = new byte[]{ (byte) 0x02, (byte) 0x01, (byte) 0x1A, (byte) 0x1A, (byte) 0xFF, (byte) 0x4C, (byte) 0x00, // AdType, CompanyId (byte) 0x02, (byte) 0x15, // FormatInfo (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, // Uuid (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B, (byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F, (byte) 0x10, (byte) 0x55, (byte) 0xAA, (byte) 0xAA, (byte) 0x55, // Major, Minor (byte) 0x80 // TxPower }; Mockito.when(mockRecord.getBytes()).thenReturn(rawRecord); } @Test public void testGenerate() throws Exception { BeaconRecord record = BeaconRecord.generate(mockResult); assertThat(record, is(notNullValue())); } @Test public void testInputNullValue() { BeaconRecord record = BeaconRecord.generate(null); assertThat(record, is(nullValue())); } @Test public void testIncorrectValidate() { byte[] rawRecord = new byte[]{ (byte) 0x02, (byte) 0x01, (byte) 0x1A, (byte) 0x1A, (byte) 0xFF, (byte) 0x4C, (byte) 0x01, // AdType, CompanyId (incorrect) (byte) 0x02, (byte) 0x15, // FormatInfo (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, // Uuid (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B, (byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F, (byte) 0x10, (byte) 0x55, (byte) 0xAA, (byte) 0xAA, (byte) 0x55, // Major, Minor (byte) 0x80 // TxPower }; Mockito.when(mockRecord.getBytes()).thenReturn(rawRecord); BeaconRecord record = BeaconRecord.generate(mockResult); assertThat(record, is(nullValue())); } @Test public void testAdType() throws Exception { BeaconRecord record = BeaconRecord.generate(mockResult); byte actual = record.adType(); byte expected = (byte) 0xFF; assertThat(actual, is(expected)); } @Test public void testCompanyId() throws Exception { BeaconRecord record = BeaconRecord.generate(mockResult); byte[] actual = record.companyId(); byte[] expected = new byte[]{(byte) 0x4C, (byte) 0x00}; assertThat(actual, is(expected)); } @Test public void testBeaconFormatInfo() throws Exception { BeaconRecord record = BeaconRecord.generate(mockResult); byte[] actual = record.beaconFormatInfo(); byte[] expected = new byte[]{(byte) 0x02, (byte) 0x15}; assertThat(actual, is(expected)); } @Test public void testUuid() throws Exception { BeaconRecord record = BeaconRecord.generate(mockResult); byte[] actual = record.uuid(); byte[] expected = new byte[] { (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, // Uuid (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08, (byte) 0x09, (byte) 0x0A, (byte) 0x0B, (byte) 0x0C, (byte) 0x0D, (byte) 0x0E, (byte) 0x0F, (byte) 0x10 }; assertThat(actual, is(expected)); } @Test public void testMajor() throws Exception { BeaconRecord record = BeaconRecord.generate(mockResult); byte[] actual = record.major(); byte[] expected = new byte[] {(byte) 0x55, (byte) 0xAA}; assertThat(actual, is(expected)); } @Test public void testMinor() throws Exception { BeaconRecord record = BeaconRecord.generate(mockResult); byte[] actual = record.minor(); byte[] expected = new byte[]{(byte) 0xAA, (byte) 0x55}; assertThat(actual, is(expected)); } @Test public void testTxPower() throws Exception { BeaconRecord record = BeaconRecord.generate(mockResult); byte actual = record.txPower(); byte expected = -128; assertThat(actual, is(expected)); } }
30.312925
96
0.634425
5af236325702baf96d4788ba08be78507b642efe
1,909
package part_1.medium.math; public class Divide29 { public int divide(int dividend, int divisor) { // // 辗转相减法 // /** // * 因为将 -2147483648 转成正数会越界,但是将 2147483647 转成负数,则不会 // * 所以,我们将 dividend 和 divisor 都转成负数时间复杂度:O(n), // * n 是最大值 2147483647 --> 10^10 --> 超时 // * 32 位最大值:2^31 - 1 = 2147483647 // * 32 位最小值:-2^31 = -2147483648 // * -2147483648 / (-1) = 2147483648 > 2147483647 越界了 // */ // // 边界处理 // if(dividend == Integer.MIN_VALUE && divisor == -1) { // return Integer.MAX_VALUE; // } // // 记录符号,然后统一转化成负数处理,防止溢出 // int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1; // if(dividend > 0) dividend = -dividend; // if(divisor > 0) divisor = -divisor; // int res = 0; // while(dividend <= divisor) { // dividend -= divisor; // res++; // } // // 结果把符号位加上 // return sign == -1 ? -res : res; // 辗转相减法 优化后 if(dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } int sign = (dividend > 0) ^ (divisor > 0) ? -1 : 1; if(dividend > 0) dividend = -dividend; if(divisor > 0) divisor = -divisor; int res = 0; while(dividend <= divisor) { int value = divisor; int k = 1; // 0xc0000000 是十进制 -2^30 的十六进制的表示 // 判断 value >= 0xc0000000 的原因:保证 value + value 不会溢出 // 可以这样判断的原因是:0xc0000000 是最小值 -2^31 的一半, // 而 a 的值不可能比 -2^31 还要小,所以 value 不可能比 0xc0000000 小 // -2^31 / 2 = -2^30 while(value >= 0xc0000000 && dividend <= value + value) { value += value; k += k; } dividend -= value; res += k; } return sign == -1 ? -res : res; } }
32.355932
69
0.462022
690e03ba62446f305e6d56dfab160113b54bc40d
2,590
// Copyright (c) 2018 Joy Diamond. All rights reserved. package link.crystal.Gem.Format; import link.crystal.Gem.Core.Gem_StringBuilder; import link.crystal.Gem.Core.Zone; import link.crystal.Gem.Format.ArgumentSegmentFormatter; import link.crystal.Gem.Inspection.Inspection; import link.crystal.Gem.Inspection.World_Inspection; import link.crystal.Gem.Interface.Inspectable; // // NOTE: // This is not an extension of `Comparable_Inspection` because, at present, SegmentFormatters are not comparable // (They might become comparable in the future). // public /*:*/ class SegmentFormatter_Inspection extends Inspection // extends Gem_Object <World_Inspection> // extends Object implements Inspectable<World_Inspection>//, { private static final World_Inspection inspection = World_Inspection.create("SegmentFormatter_Inspection"); // // Members // public final boolean is_adornment_segment_formatter; public final boolean is_portray_segment_formatter; // // Constructor & Factory // protected SegmentFormatter_Inspection(final String simple_class_name) { super(simple_class_name, /*is_cache=*/ false); this.is_adornment_segment_formatter = simple_class_name.equals("AdornmentSegmentFormatter"); this.is_portray_segment_formatter = simple_class_name.equals("PortraySegmentFormatter"); } public static /*overrideable*/ SegmentFormatter_Inspection create(final String simple_class_name) { final Zone z = Zone.current_zone(); final String interned__simple_class_name = z.intern_permenant_string(simple_class_name); return new SegmentFormatter_Inspection(interned__simple_class_name); } // // Interface Inspectable // @Override public /*overrideable*/ World_Inspection inspect() { return /*static*/ this.inspection; } @Override public final void portray(final Gem_StringBuilder builder) { final World_Inspection meta_inspection = this.inspect(); builder.append("<", meta_inspection.simple_class_name, " ", this.simple_class_name); if (this.is_adornment_segment_formatter) { builder.append("; is_adornment_segment_formatter"); } if (this.is_portray_segment_formatter) { builder.append("; is_portray_segment_formatter"); } builder.append(">"); } }
30.116279
117
0.672201
b2d00c2d5083be9abbf8b5940f6dea448555cad1
248
package com.workshopspringmongo.workshopspringmongo; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class WorkshopspringmongoApplicationTests { @Test void contextLoads() { } }
17.714286
60
0.818548
9ebc65252e8f4ee7a44e8e81e24852fa9ab9c033
54
package jnet.packet; public class PacketEncoder { }
7.714286
26
0.759259
894f10b87735fbd16e12a84505960121c1e5215f
4,829
package com.hdeva.space.ui.viewer; import android.content.Intent; import android.support.v4.view.ViewCompat; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.View; import com.hdeva.space.base.ActivityPresenter; import com.hdeva.space.core.helper.GlideHelper; import com.hdeva.space.core.model.images.MediaType; import com.hdeva.space.core.service.extractor.VideoLinkHelper; import com.hdeva.space.service.ContentShareHelper; import com.hdeva.space.service.FullScreenHelper; import com.hdeva.space.ui.home.HomeActivity; import com.hdeva.space.ui.navigator.MediaViewerNavigator; import javax.inject.Inject; class MediaViewerActivityPresenter extends ActivityPresenter<MediaViewerActivity> { private FullScreenHelper fullScreenHelper; private GlideHelper glideHelper; private ContentShareHelper contentShareHelper; private VideoLinkHelper videoLinkHelper; private MediaViewerNavigator mediaViewerNavigator; private AlertDialog dialog; private boolean overlayHidden; private boolean isDialogShowing; @Inject public MediaViewerActivityPresenter(FullScreenHelper fullScreenHelper, GlideHelper glideHelper, ContentShareHelper contentShareHelper, VideoLinkHelper videoLinkHelper, MediaViewerNavigator mediaViewerNavigator) { this.fullScreenHelper = fullScreenHelper; this.glideHelper = glideHelper; this.contentShareHelper = contentShareHelper; this.videoLinkHelper = videoLinkHelper; this.mediaViewerNavigator = mediaViewerNavigator; } @Override public void attach(MediaViewerActivity activity) { super.attach(activity); setupItem(); enablePlayButtonIfNeeded(); activity.close.setOnClickListener(v -> handleCloseAction()); activity.share.setOnClickListener(v -> contentShareHelper.shareContent(activity.descriptor)); activity.photoView.setOnClickListener(v -> toggleOverlay()); activity.playButton.setOnClickListener(v -> mediaViewerNavigator.openMedia(activity, activity.descriptor)); activity.bottomOverlay.setOnClickListener(v -> dialog.show()); activity.root.post(() -> refreshUi(false)); } @Override public void detach() { if (dialog != null) { isDialogShowing = dialog.isShowing(); dialog.dismiss(); dialog = null; } super.detach(); } public void setImmersiveFullScreen() { fullScreenHelper.setImmersiveFullScreen(activity); } private void handleCloseAction() { if (activity.fromNotification) { activity.finish(); activity.startActivity(new Intent(activity, HomeActivity.class)); } else { activity.onBackPressed(); } } private void toggleOverlay() { overlayHidden = !overlayHidden; refreshUi(true); } private void setupItem() { activity.title.setText(activity.descriptor.title); activity.subTitle.setText(activity.descriptor.subTitle); activity.description.setText(activity.descriptor.description); glideHelper.setImage(activity.photoView, activity.descriptor.thumbnail); dialog = new AlertDialog.Builder(activity) .setTitle(activity.descriptor.title) .setMessage(activity.descriptor.description) .create(); if (isDialogShowing) dialog.show(); } private void refreshUi(boolean shouldAnimate) { float offset = overlayHidden ? 1.0f : 0.0f; float topOffset = -offset * activity.topOverlay.getMeasuredHeight(); float bottomOffset = offset * activity.bottomOverlay.getMeasuredHeight(); float alphaOffset = 1 - offset; if (shouldAnimate) { ViewCompat.animate(activity.topOverlay).translationY(topOffset).alpha(alphaOffset).start(); ViewCompat.animate(activity.bottomOverlay).translationY(bottomOffset).alpha(alphaOffset).start(); } else { activity.topOverlay.setTranslationY(topOffset); activity.topOverlay.setAlpha(alphaOffset); activity.bottomOverlay.setTranslationY(bottomOffset); activity.bottomOverlay.setAlpha(alphaOffset); } } private void enablePlayButtonIfNeeded() { boolean shouldShow; if (videoLinkHelper.isYouTubeVideo(activity.descriptor.media)) { shouldShow = true; } else if (videoLinkHelper.isVideo(activity.descriptor.media)) { shouldShow = true; } else if (TextUtils.equals(MediaType.AUDIO, activity.descriptor.mediaType)) { shouldShow = true; } else { shouldShow = false; } activity.playButton.setVisibility(shouldShow ? View.VISIBLE : View.GONE); } }
37.434109
216
0.700352
a23318f901e10b2e096aca44c9a061410f05fd79
138
package in.balamt.practice.designpattern.abstractfactory; public interface ComputerAbstractFactory { public Computer buildComputer(); }
23
57
0.84058
226f8f075b62f6d998200b7fd8a642b899977f42
1,607
//////////////////////////////////////////////////////////////////////////////// // // Created by DAlbrecht on 06.02.2019. // // Copyright (c) 2006 - 2019 FORCAM GmbH. All rights reserved. //////////////////////////////////////////////////////////////////////////////// package com.forcam.na.ffwebservices.model.operation.quantity; import io.swagger.annotations.ApiModel; /** * Model for qualified quantities. */ @ApiModel("qualifiedQuantities") public class QualifiedQuantitiesWSModel { // ------------------------------------------------------------------------ // members // ------------------------------------------------------------------------ private QualifiedQuantityWSModel mYield = new QualifiedQuantityWSModel(); private QualifiedQuantityWSModel mScrap = new QualifiedQuantityWSModel(); private QualifiedQuantityWSModel mRework = new QualifiedQuantityWSModel(); // ------------------------------------------------------------------------ // getters/setters // ------------------------------------------------------------------------ public QualifiedQuantityWSModel getYield() { return mYield; } public void setYield(QualifiedQuantityWSModel yield) { mYield = yield; } public QualifiedQuantityWSModel getScrap() { return mScrap; } public void setScrap(QualifiedQuantityWSModel scrap) { mScrap = scrap; } public QualifiedQuantityWSModel getRework() { return mRework; } public void setRework(QualifiedQuantityWSModel rework) { mRework = rework; } }
28.192982
80
0.494711
e6f589a844887b827d5070530170ee753aa3d8ce
1,156
package org.codepay.model.merchant; import java.io.Serializable; import org.codepay.common.orm.domain.BaseDomain; import org.codepay.model.merchant.enums.PublicEnum; /** * 支付产品实体类 */ public class PayProduct extends BaseDomain implements Serializable { private String productCode; private String productName; private String auditStatus; private static final long serialVersionUID = 1L; public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode == null ? null : productCode.trim(); } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName == null ? null : productName.trim(); } public String getAuditStatus() { return auditStatus; } public void setAuditStatus(String auditStatus) { this.auditStatus = auditStatus == null ? null : auditStatus.trim(); } public String getAuditStatusDesc() { return PublicEnum.getEnum(this.getAuditStatus()).getDesc(); } }
24.083333
75
0.687716
05b0173eacc5814c7b72ec8df9673f420d8875fd
866
package com.alley.flipperview.adapter; import android.content.Context; import android.view.View; import android.widget.TextView; import com.alley.flipper.BaseFlipperAdapter; import com.alley.flipperview.R; import java.util.List; /** * 首页垂直轮播图适配器 * * @author Phoenix * @date 2017/4/7 17:14 */ public class FlipperAdapter extends BaseFlipperAdapter<String> { public FlipperAdapter(Context context, List<String> list) { super(context, list); } @Override public View getInflaterView(int position) { return layoutInflater.inflate(R.layout.view_vertical_flipper, null); } @Override public View getView(int position, View convertView, String body) { TextView textView = (TextView) convertView.findViewById(R.id.tv_vertical_flipper_content); textView.setText(body); return convertView; } }
24.055556
98
0.721709
f9ca67cbebbc13e97b94e4cdf53ba7c725a32dd0
143
package org.javacs.example; public class ErrorInDependency { public String test() { return (new UndefinedSymbol()).test(); } }
20.428571
46
0.664336
ca0f0c9d6420d548e2019ea162c43931bba3113a
110
package com.zup.orange.proposta.entity.card.enums; public enum WalletStatusEnum { ASSOCIADA, FALHA }
15.714286
50
0.745455
bfee2fc1dc416efe3ee3e9e8b966ce805fe04396
9,049
/* * Copyright (c) 2016-2020, MiLaboratory LLC * All Rights Reserved * * Permission to use, copy, modify and distribute any part of this program for * educational, research and non-profit purposes, by non-profit institutions * only, without fee, and without a written agreement is hereby granted, * provided that the above copyright notice, this paragraph and the following * three paragraphs appear in all copies. * * Those desiring to incorporate this work into commercial products or use for * commercial purposes should contact MiLaboratory LLC, which owns exclusive * rights for distribution of this program for commercial purposes, using the * following email address: [email protected]. * * IN NO EVENT SHALL THE INVENTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, * SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, * ARISING OUT OF THE USE OF THIS SOFTWARE, EVEN IF THE INVENTORS HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * THE SOFTWARE PROVIDED HEREIN IS ON AN "AS IS" BASIS, AND THE INVENTORS HAS * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR * MODIFICATIONS. THE INVENTORS MAKES NO REPRESENTATIONS AND EXTENDS NO * WARRANTIES OF ANY KIND, EITHER IMPLIED OR EXPRESS, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A * PARTICULAR PURPOSE, OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY * PATENT, TRADEMARK OR OTHER RIGHTS. */ package com.milaboratory.minnn.pattern; import com.milaboratory.core.Range; import com.milaboratory.core.sequence.NSequenceWithQuality; import com.milaboratory.minnn.io.IO; import com.milaboratory.minnn.outputconverter.MatchedGroup; import com.milaboratory.primitivio.PrimitivI; import com.milaboratory.primitivio.PrimitivO; import com.milaboratory.primitivio.annotations.Serializable; import java.util.*; import java.util.stream.Collectors; @Serializable(by = IO.MatchSerializer.class) public class Match implements java.io.Serializable { protected final int numberOfTargets; protected final long score; protected final ArrayList<MatchedGroupEdge> matchedGroupEdges; private ArrayList<MatchedGroup> groups = null; private Map<String, NSequenceWithQuality> groupValues = null; private HashMap<MatchedGroupEdgeIndex, MatchedGroupEdge> matchedGroupEdgesCache = null; /** * Serializable final match for single- or multi-pattern. * * @param numberOfTargets number of targets (R1, R2 etc) * @param score match score * @param matchedGroupEdges list of matched group edges */ public Match(int numberOfTargets, long score, ArrayList<MatchedGroupEdge> matchedGroupEdges) { this.numberOfTargets = numberOfTargets; this.score = score; this.matchedGroupEdges = matchedGroupEdges; } /** * Return MatchedGroupEdge by name and isStart flag. * * @param groupName group name * @param isStart flag, true if it must be group start, false if must be group end * @return MatchedRange for specified pattern */ public MatchedGroupEdge getMatchedGroupEdge(String groupName, boolean isStart) { if (matchedGroupEdgesCache == null) matchedGroupEdgesCache = new HashMap<>(); MatchedGroupEdgeIndex index = new MatchedGroupEdgeIndex(groupName, isStart); MatchedGroupEdge cachedMatchedGroupEdge = matchedGroupEdgesCache.get(index); if (cachedMatchedGroupEdge != null) return cachedMatchedGroupEdge; else { for (MatchedGroupEdge matchedGroupEdge : matchedGroupEdges) if (matchedGroupEdge.getGroupName().equals(groupName) && (matchedGroupEdge.isStart() == isStart)) { matchedGroupEdgesCache.put(index, matchedGroupEdge); return matchedGroupEdge; } throw new IllegalStateException("Trying to get group " + (isStart ? "start" : "end") + " with name " + groupName + " and it doesn't exist"); } } /** * Get all matched group edges. * * @return ArrayList with all matched group edges. */ public ArrayList<MatchedGroupEdge> getMatchedGroupEdges() { return matchedGroupEdges; } public int getNumberOfTargets() { return numberOfTargets; } public long getScore() { return score; } public void assembleGroups() { if (groups == null) { groups = new ArrayList<>(); ArrayList<MatchedGroupEdge> matchedGroupEdges = getMatchedGroupEdges(); /* in matches made with ParsedRead.retarget() we can have duplicate groups; in this case use first instance of each group */ LinkedHashSet<String> groupNames = matchedGroupEdges.stream() .map(MatchedGroupEdge::getGroupName).collect(Collectors.toCollection(LinkedHashSet::new)); MatchedGroupEdge start; MatchedGroupEdge end; Range range; for (String groupName : groupNames) { start = getMatchedGroupEdge(groupName, true); end = getMatchedGroupEdge(groupName, false); if ((start.getPosition() == -1) ^ (end.getPosition() == -1)) throw new IllegalStateException("Group start and group end can be -1 only simultaneously. Start: " + start.getPosition() + ", end: " + end.getPosition()); else if ((start.getPosition() != -1) && (start.getPosition() > end.getPosition())) throw new IllegalStateException("Group start must not be bigger than the end. Start: " + start.getPosition() + ", end: " + end.getPosition()); if ((start.getValueOverride() != null) ^ (start.getPosition() == -1)) throw new IllegalStateException("Value override must be set if position is -1 and not set if " + "position is not -1. Value override: " + start.getValueOverride() + ", position: " + start.getPosition()); if (start.getTargetId() != end.getTargetId()) throw new IllegalStateException("Group start has targetId " + start.getTargetId() + ", end has targetId " + end.getTargetId()); if (start.getValueOverride() != null) groups.add(new MatchedGroup(groupName, start.getTarget(), start.getTargetId(), start.getValueOverride())); else { range = new Range(start.getPosition(), end.getPosition()); groups.add(new MatchedGroup(groupName, start.getTarget(), start.getTargetId(), range)); } } } } public ArrayList<MatchedGroup> getGroups() { assembleGroups(); return new ArrayList<>(groups); } public NSequenceWithQuality getGroupValue(String groupName) { if (groupValues == null) groupValues = getGroups().stream() .collect(Collectors.toMap(MatchedGroup::getGroupName, MatchedGroup::getValue)); return groupValues.get(groupName); } public static Match read(PrimitivI input) { int numberOfPatterns = input.readVarIntZigZag(); long score = input.readVarLongZigZag(); ArrayList<MatchedGroupEdge> matchedGroupEdges = new ArrayList<>(); int matchedGroupEdgesNum = input.readVarIntZigZag(); for (int i = 0; i < matchedGroupEdgesNum; i++) matchedGroupEdges.add(input.readObject(MatchedGroupEdge.class)); return new Match(numberOfPatterns, score, matchedGroupEdges); } public static void write(PrimitivO output, Match object) { output.writeVarIntZigZag(object.getNumberOfTargets()); output.writeVarLongZigZag(object.getScore()); output.writeVarIntZigZag(object.getMatchedGroupEdges().size()); for (MatchedGroupEdge matchedGroupEdge : object.getMatchedGroupEdges()) output.writeObject(matchedGroupEdge); } private static class MatchedGroupEdgeIndex implements java.io.Serializable { private final String groupName; private final boolean isStart; MatchedGroupEdgeIndex(String groupName, boolean isStart) { this.groupName = groupName; this.isStart = isStart; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MatchedGroupEdgeIndex that = (MatchedGroupEdgeIndex)o; return isStart == that.isStart && groupName.equals(that.groupName); } @Override public int hashCode() { int result = groupName.hashCode(); result = 31 * result + (isStart ? 1 : 0); return result; } } }
45.0199
119
0.651564
217768274a8d6b91559f107834e5c1c608defbda
754
package org.tourgune.apptrack.bean; import java.util.Collection; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * AppTrack * * Created by CICtourGUNE on 10/04/13. * Copyright (c) 2013 CICtourGUNE. All rights reserved. * */ @XmlRootElement(name = "visores") public class VisorList { private Collection<Visor> visores; private int rowCount; @XmlElementRef public Collection<Visor> getVisores() { return visores; } public void setqrs(Collection<Visor> visores) { this.visores = visores; } @XmlTransient public int getRowCount() { return rowCount; } public void setRowCount(int rowCount) { this.rowCount = rowCount; } }
17.952381
55
0.740053
e8552316246ed1b63e55da2105bf71fbe6c3017e
9,292
package org.javamoney.moneta.format; import java.text.DecimalFormatSymbols; import java.util.Currency; import java.util.Locale; import java.util.Objects; import javax.money.CurrencyUnit; import javax.money.Monetary; import javax.money.format.MonetaryAmountFormat; /** * This class represents symbols to be used on {@link MonetaryAmountFormatSymbols}, this class decorate the * {@link DecimalFormatSymbols} * @see {@link DecimalFormatSymbols} * @see {@link MonetaryAmountFormat} * @see {@link MonetaryAmountFormatSymbols} * @author Otavio Santana * @since 1.0.1 */ public final class MonetaryAmountSymbols { private final DecimalFormatSymbols formatSymbols; /** * Create a MonetaryAmountFormatSymbols object for the given locale * @see {@link DecimalFormatSymbols#DecimalFormatSymbols(Locale)} * @param locale */ public MonetaryAmountSymbols(Locale locale) { this.formatSymbols = new DecimalFormatSymbols(locale); } /** * Create a MonetaryAmountFormatSymbols object for the default FORMAT locale. * @see {@link Locale.getDefault(Locale.Category.FORMAT)} * {@link DecimalFormatSymbols#DecimalFormatSymbols()} */ public MonetaryAmountSymbols() { this.formatSymbols = new DecimalFormatSymbols(); } /** * * @return */ public CurrencyUnit getCurrency() { return Monetary.getCurrency(formatSymbols.getCurrency().getCurrencyCode()); } /** * Sets the currency of these MonetaryAmountFormatSymbols. This also sets the currency symbol attribute to the * currency's symbol in the MonetaryAmountFormatSymbols' locale, and the international currency symbol attribute * to the currency's ISO 4217 currency code. * @param currency * @throws NullPointerException if currency is null */ public void setCurrency(CurrencyUnit currency) { Objects.requireNonNull(currency); formatSymbols.setCurrency(Currency.getInstance(currency.getCurrencyCode())); } /** * @return Returns the currency symbol for the currency of these MonetaryAmountFormatSymbols in their locale. */ public String getCurrencySymbol() { return formatSymbols.getCurrencySymbol(); } /** * Sets the currency symbol for the currency of these MonetaryAmountFormatSymbols in their locale. * @param currencySymbol */ public void setCurrencySymbol(String currencySymbol) { formatSymbols.setCurrencySymbol(currencySymbol); } /** * Gets the character used for decimal sign. * @return */ public char getDecimalSeparator() { return formatSymbols.getDecimalSeparator(); } /** * Sets the character used for decimal sign. * @param decimalSeparator */ public void setDecimalSeparator(char decimalSeparator) { formatSymbols.setDecimalSeparator(decimalSeparator); } /** * @return Gets the character used for a digit in a pattern. */ public char getDigit() { return formatSymbols.getDigit(); } /** * Sets the character used for a digit in a pattern. * @param digit */ public void setDigit(char digit) { formatSymbols.setDigit(digit); } /** * @return Returns the string used to separate the mantissa from the exponent. Examples: "x10^" for 1.23x10^4, * "E" for 1.23E4. */ public String getExponentSeparator() { return formatSymbols.getExponentSeparator(); } /** * Sets the string used to separate the mantissa from the exponent. Examples: "x10^" for 1.23x10^4, "E" for 1.23E4. * @param exponentSeparator */ public void setExponentSeparator(String exponentSeparator) { formatSymbols.setExponentSeparator(exponentSeparator); } /** * @return Gets the character used for thousands separator. */ public char getGroupingSeparator() { return formatSymbols.getGroupingSeparator(); } /** * Sets the character used for thousands separator. * @param groupingSeparator */ public void setGroupingSeparator(char groupingSeparator) { formatSymbols.setGroupingSeparator(groupingSeparator); } /** * @return Gets the string used to represent infinity. Almost always left unchanged. */ public String getInfinity() { return formatSymbols.getInfinity(); } /** * Sets the string used to represent infinity. Almost always left unchanged. * @param infinity */ public void setInfinity(String infinity) { formatSymbols.setInfinity(infinity); } /** * @return the ISO 4217 currency code of the currency of these MonetaryAmountFormatSymbols. */ public String getInternationalCurrencySymbol() { return formatSymbols.getInternationalCurrencySymbol(); } /** * Sets the ISO 4217 currency code of the currency of these MonetaryAmountFormatSymbols. * @param internationalCurrencySymbol */ public void setInternationalCurrencySymbol(String internationalCurrencySymbol) { Objects.requireNonNull(internationalCurrencySymbol); Currency.getInstance(internationalCurrencySymbol); formatSymbols.setInternationalCurrencySymbol(internationalCurrencySymbol); } /** * Gets the character used to represent minus sign. If no explicit negative format is specified, one is * formed by prefixing minusSign to the positive format. * @return */ public char getMinusSign() { return formatSymbols.getMinusSign(); } /** * Sets the character used to represent minus sign. If no explicit negative format is specified, one is * formed by prefixing minusSign to the positive format. * @param minusSign */ public void setMinusSign(char minusSign) { formatSymbols.setMinusSign(minusSign); } /** * @return the monetary decimal separator. */ public char getMonetaryDecimalSeparator() { return formatSymbols.getMonetaryDecimalSeparator(); } /** * Sets the monetary decimal separator. * @param monetaryDecimalSeparator */ public void setMonetaryDecimalSeparator(char monetaryDecimalSeparator) { formatSymbols.setMonetaryDecimalSeparator(monetaryDecimalSeparator); } /** * @return the string used to represent "not a number". Almost always left unchanged. */ public String getNaN() { return formatSymbols.getNaN(); } /** * Sets the string used to represent "not a number". Almost always left unchanged. * @param naN */ public void setNaN(String naN) { formatSymbols.setNaN(naN); } /** * @return the character used to separate positive and negative subpatterns in a pattern. */ public char getPatternSeparator() { return formatSymbols.getPatternSeparator(); } /** * Sets the character used to separate positive and negative subpatterns in a pattern. * @param patternSeparator */ public void setPatternSeparator(char patternSeparator) { formatSymbols.setPatternSeparator(patternSeparator); } /** * @return the character used for percent sign. */ public char getPercent() { return formatSymbols.getPercent(); } /** * Sets the character used for percent sign. * @param percent */ public void setPercent(char percent) { formatSymbols.setPercent(percent); } /** * @return the character used for per mille sign. */ public char getPerMill() { return formatSymbols.getPerMill(); } /** * Sets the character used for per mille sign. * @param perMill */ public void setPerMill(char perMill) { formatSymbols.setPerMill(perMill); } /** * @return Gets the character used for zero. */ public char getZeroDigit() { return formatSymbols.getZeroDigit(); } /** * Sets the character used for zero. * @param zeroDigit */ public void setZeroDigit(char zeroDigit) { formatSymbols.setZeroDigit(zeroDigit); } @Override public boolean equals(Object obj) { if(obj == this) { return true; } if(MonetaryAmountSymbols.class.isInstance(obj)) { MonetaryAmountSymbols other = MonetaryAmountSymbols.class.cast(obj); return Objects.equals(other.formatSymbols, formatSymbols); } return false; } @Override public int hashCode() { return Objects.hash(formatSymbols); } DecimalFormatSymbols getFormatSymbol() { return formatSymbols; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getName()).append('{'); sb.append(" Currency: ").append(formatSymbols.getCurrency()).append(','); sb.append(" currencySymbol: ").append(formatSymbols.getCurrencySymbol()).append(','); sb.append(" decimalSeparator: ").append(formatSymbols.getDecimalSeparator()).append(','); sb.append(" digit: ").append(formatSymbols.getDigit()).append(','); sb.append(" exponentSeparator: ").append(formatSymbols.getExponentSeparator()).append(','); sb.append(" groupingSeparator: ").append(formatSymbols.getGroupingSeparator()).append(','); sb.append(" infinity: ").append(formatSymbols.getInfinity()).append(','); sb.append(" internationalCurrencySymbol: ").append(formatSymbols.getInternationalCurrencySymbol()).append(','); sb.append(" minusSign: ").append(formatSymbols.getMinusSign()).append(','); sb.append(" monetaryDecimalSeparator: ").append(formatSymbols.getMonetaryDecimalSeparator()).append(','); sb.append(" naN: ").append(formatSymbols.getNaN()).append(','); sb.append(" patternSeparator: ").append(formatSymbols.getPatternSeparator()).append(','); sb.append(" percent: ").append(formatSymbols.getPercent()).append(','); sb.append(" perMill: ").append(formatSymbols.getPerMill()).append(','); sb.append(" zeroDigit: ").append(formatSymbols.getZeroDigit()).append('}'); return sb.toString(); } }
31.931271
116
0.739023
ec10068a3369a4cb13794160671843fa350fa230
5,708
/* * Copyright (c) 2010-2017 Evolveum * * 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.evolveum.midpoint.repo.sql; import com.evolveum.midpoint.audit.api.AuditEventRecord; import com.evolveum.midpoint.audit.api.AuditReferenceValue; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.repo.sql.data.audit.RAuditEventRecord; import com.evolveum.midpoint.repo.sql.util.DtoTranslationException; import com.evolveum.midpoint.repo.sql.util.SimpleTaskAdapter; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; import java.util.*; import static org.testng.AssertJUnit.assertEquals; /** * @author mederly */ @ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class AuditTest extends BaseSQLRepoTest { private static final Trace LOGGER = TraceManager.getTrace(AuditTest.class); @Test public void test100AuditSimple() throws Exception { LOGGER.info("===[ test100AuditSimple ]==="); // WHEN AuditEventRecord record = new AuditEventRecord(); record.addPropertyValue("prop1", "val1.1"); record.addPropertyValue("prop1", "val1.2"); record.addPropertyValue("prop2", "val2"); record.addPropertyValue("prop3", null); AuditReferenceValue refVal1_1 = new AuditReferenceValue("oid1.1", UserType.COMPLEX_TYPE, new PolyString("user1.1")); AuditReferenceValue refVal1_2 = new AuditReferenceValue("oid1.2", RoleType.COMPLEX_TYPE, new PolyString("role1.2")); AuditReferenceValue refVal2 = new AuditReferenceValue("oid2", null, new PolyString("object2")); AuditReferenceValue refVal3 = new AuditReferenceValue(); record.addReferenceValue("ref1", refVal1_1); record.addReferenceValue("ref1", refVal1_2); record.addReferenceValue("ref2", refVal2); record.addReferenceValue("ref3", refVal3); LOGGER.info("Adding audit record {}", record); auditService.audit(record, new SimpleTaskAdapter()); // THEN System.out.println("Record written:\n" + record.debugDump()); System.out.println("Repo ID: " + record.getRepoId()); AuditEventRecord loaded = getAuditEventRecord(1, 0); System.out.println("Record loaded:\n" + loaded.debugDump()); System.out.println("Repo ID: " + loaded.getRepoId()); assertEquals("Wrong # of properties", 3, loaded.getProperties().size()); assertEquals("Wrong prop1 values", new HashSet<>(Arrays.asList("val1.1", "val1.2")), loaded.getPropertyValues("prop1")); assertEquals("Wrong prop2 values", new HashSet<>(Collections.singletonList("val2")), loaded.getPropertyValues("prop2")); assertEquals("Wrong prop3 values", new HashSet<>(Collections.singletonList(null)), loaded.getPropertyValues("prop3")); assertEquals("Wrong # of references", 3, loaded.getReferences().size()); assertEquals("Wrong ref1 values", new HashSet<>(Arrays.asList(refVal1_1, refVal1_2)), loaded.getReferenceValues("ref1")); assertEquals("Wrong ref2 values", new HashSet<>(Collections.singletonList(refVal2)), loaded.getReferenceValues("ref2")); assertEquals("Wrong ref3 values", new HashSet<>(Collections.singletonList(refVal3)), loaded.getReferenceValues("ref3")); } @Test public void test110AuditSecond() throws Exception { LOGGER.info("===[ test110AuditSecond ]==="); // WHEN AuditEventRecord record = new AuditEventRecord(); record.addPropertyValue("prop", "val"); LOGGER.info("Adding audit record {}", record); auditService.audit(record, new SimpleTaskAdapter()); // THEN System.out.println("Record written:\n" + record.debugDump()); System.out.println("Repo ID: " + record.getRepoId()); AuditEventRecord loaded = getAuditEventRecord(2, 1); System.out.println("Record loaded:\n" + loaded.debugDump()); System.out.println("Repo ID: " + loaded.getRepoId()); assertEquals("Wrong # of properties", 1, loaded.getProperties().size()); assertEquals("Wrong prop values", new HashSet<>(Collections.singletonList("val")), loaded.getPropertyValues("prop")); assertEquals("Wrong # of references", 0, loaded.getReferences().size()); } private AuditEventRecord getAuditEventRecord(int expectedCount, int index) { Session session = getFactory().openSession(); try { session.beginTransaction(); Query query = session.createQuery("from " + RAuditEventRecord.class.getSimpleName() + " order by id"); List<RAuditEventRecord> records = query.list(); assertEquals(expectedCount, records.size()); AuditEventRecord eventRecord = RAuditEventRecord.fromRepo(records.get(index), prismContext); session.getTransaction().commit(); return eventRecord; } catch (DtoTranslationException e) { throw new SystemException(e); } finally { session.close(); } } }
44.248062
123
0.747898
5f549185790816feec72ba976840febf65090752
5,199
/*L * Copyright Moxie Informatics. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/calims/LICENSE.txt for details. */ package gov.nih.nci.calims2.domain.common.environmentalcondition; import gov.nih.nci.calims2.domain.administration.Quantity; import gov.nih.nci.calims2.domain.interfaces.DisplayableEntity; import gov.nih.nci.calims2.domain.common.Type; import java.util.Collection; import gov.nih.nci.calims2.domain.inventory.event.Event; import org.joda.time.DateTime; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Id; import javax.persistence.Column; import javax.persistence.CascadeType; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.DiscriminatorColumn; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.OneToMany; import javax.persistence.ManyToMany; import javax.persistence.JoinTable; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.FetchType; import javax.persistence.GenerationType; import javax.persistence.GeneratedValue; import javax.persistence.Embeddable; import javax.persistence.Embedded; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.AttributeOverrides; import javax.persistence.AssociationOverrides; import javax.persistence.AttributeOverride; import javax.persistence.AssociationOverride; import org.hibernate.annotations.CollectionOfElements; import org.hibernate.annotations.ForeignKey; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.Index; import org.hibernate.annotations.IndexColumn; import javax.validation.constraints.Pattern; import javax.validation.constraints.NotNull; import gov.nih.nci.calims2.domain.interfaces.EntityWithExternalId; import java.util.ArrayList; import java.io.Serializable; import gov.nih.nci.calims2.domain.common.visitor.EnvironmentalConditionVisitor; import java.util.Set; import java.util.List; import java.util.HashSet; import gov.nih.nci.calims2.domain.interfaces.EntityWithId; /** * **/ @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="entitytype", discriminatorType=DiscriminatorType.STRING, length=30) @DiscriminatorValue("EnvironmentalCondition") public class EnvironmentalCondition extends DisplayableEntity { /** * An attribute to allow serialization of the domain objects. */ private static final long serialVersionUID = 1234567890L; /** * An associated gov.nih.nci.calims2.domain.inventory.event.Event object. **/ private gov.nih.nci.calims2.domain.inventory.event.Event event; /** * Retrieves the value of the event attribute. * @return event **/ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "EVENT_FK") @org.hibernate.annotations.ForeignKey(name = "ENVIROEVENT_FK") public gov.nih.nci.calims2.domain.inventory.event.Event getEvent() { return event; } /** * Sets the value of event attribute. * @param event . **/ public void setEvent(gov.nih.nci.calims2.domain.inventory.event.Event event) { this.event = event; } /** * An associated gov.nih.nci.calims2.domain.common.Type object. **/ private gov.nih.nci.calims2.domain.common.Type type; /** * Retrieves the value of the type attribute. * @return type **/ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "TYPE_FK") @org.hibernate.annotations.ForeignKey(name = "ENVIROTYPE_FK") public gov.nih.nci.calims2.domain.common.Type getType() { return type; } /** * Sets the value of type attribute. * @param type . **/ public void setType(gov.nih.nci.calims2.domain.common.Type type) { this.type = type; } private Set<gov.nih.nci.calims2.domain.administration.Quantity> quantityCollection = new HashSet<gov.nih.nci.calims2.domain.administration.Quantity>(); @SuppressWarnings("deprecation") @IndexColumn(name="LIST_INDEX") @CollectionOfElements(fetch=FetchType.LAZY) @JoinTable(name="QUANTITY_ENVIRONMENTALCON",joinColumns=@JoinColumn(name="ID_QUANTITY_ENVIRONMENTAL")) @ForeignKey(name="FK_QUANTITY_ENVIRONMENTAL") @Fetch(FetchMode.SUBSELECT) public Set<gov.nih.nci.calims2.domain.administration.Quantity> getQuantityCollection() { return quantityCollection; } public void setQuantityCollection(Set<gov.nih.nci.calims2.domain.administration.Quantity> quantityCollection) { this.quantityCollection = quantityCollection; } /** Accepts the EnvironmentalConditionVisitor. * @param environmentalConditionVisitor The EnvironmentalConditionVisitor to accept. **/ public void accept(EnvironmentalConditionVisitor environmentalConditionVisitor) { environmentalConditionVisitor.visitEnvironmentalCondition(this); } }
33.11465
159
0.762454
49c1479608a9a65495ad10203f8fed6e35773a5c
2,995
/** * Mobius Software LTD * Copyright 2015-2016, Mobius Software LTD * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.mobius.software.mqtt.performance.controller.task; import com.mobius.software.mqtt.parser.avps.MessageType; import com.mobius.software.mqtt.parser.header.api.MQMessage; import com.mobius.software.mqtt.parser.header.impl.Publish; import com.mobius.software.mqtt.performance.commons.data.ErrorType; import com.mobius.software.mqtt.performance.controller.PeriodicQueuedTasks; import com.mobius.software.mqtt.performance.controller.client.ConnectionContext; import com.mobius.software.mqtt.performance.controller.client.IdentityReport; import com.mobius.software.mqtt.performance.controller.net.NetworkHandler; public class MessageResendTimer implements TimedTask { private ConnectionContext ctx; private PeriodicQueuedTasks<TimedTask> scheduler; private NetworkHandler listener; private MQMessage message; private Long timestamp; private Long resendInterval; private IdentityReport report; public MessageResendTimer(ConnectionContext ctx, PeriodicQueuedTasks<TimedTask> scheduler, NetworkHandler listener, MQMessage message, Long resendInterval, IdentityReport report) { this.ctx = ctx; this.scheduler = scheduler; this.message = message; this.listener = listener; this.resendInterval = resendInterval; this.timestamp = System.currentTimeMillis() + resendInterval; this.report = report; } @Override public Boolean execute() { if (message.getType() == MessageType.PUBLISH) { Publish publish = (Publish) message; publish.setDup(true); } listener.send(ctx.localAddress(), message); report.countOut(message.getType()); if (message.getType() != MessageType.PINGREQ) { report.countDuplicateOut(); report.reportError(ErrorType.DUPLICATE, message.getType() + " sent"); } timestamp = System.currentTimeMillis() + resendInterval; scheduler.store(timestamp, this); return true; } @Override public Long getRealTimestamp() { return timestamp; } @Override public void stop() { this.timestamp = Long.MAX_VALUE; } public MQMessage retrieveMessage() { return message; } public void restart() { this.timestamp = System.currentTimeMillis() + resendInterval; } }
31.526316
179
0.767947
816f764f9ba2b5bd2059402cd3ea01325c2e38fd
3,947
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have * questions. */ /* * @test * @bug 8012900 * @library ../UTIL * @build TestUtil * @run main TestCICOWithGCMAndAAD * @summary Test CipherInputStream/OutputStream with AES GCM mode with AAD. * @author Valerie Peng */ import java.io.*; import java.security.*; import java.util.*; import javax.crypto.*; public class TestCICOWithGCMAndAAD { public static void main(String[] args) throws Exception { //init Secret Key KeyGenerator kg = KeyGenerator.getInstance("AES", "SunJCE"); kg.init(128); SecretKey key = kg.generateKey(); //Do initialization of the plainText byte[] plainText = new byte[700]; Random rdm = new Random(); rdm.nextBytes(plainText); byte[] aad = new byte[128]; rdm.nextBytes(aad); byte[] aad2 = aad.clone(); aad2[50]++; Cipher encCipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); encCipher.init(Cipher.ENCRYPT_MODE, key); encCipher.updateAAD(aad); Cipher decCipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); decCipher.init(Cipher.DECRYPT_MODE, key, encCipher.getParameters()); decCipher.updateAAD(aad); byte[] recovered = test(encCipher, decCipher, plainText); if (!Arrays.equals(plainText, recovered)) { throw new Exception("sameAAD: diff check failed!"); } else System.out.println("sameAAD: passed"); encCipher.init(Cipher.ENCRYPT_MODE, key); encCipher.updateAAD(aad2); recovered = test(encCipher, decCipher, plainText); if (recovered != null && recovered.length != 0) { throw new Exception("diffAAD: no data should be returned!"); } else System.out.println("diffAAD: passed"); } private static byte[] test(Cipher encCipher, Cipher decCipher, byte[] plainText) throws Exception { //init cipher streams ByteArrayInputStream baInput = new ByteArrayInputStream(plainText); CipherInputStream ciInput = new CipherInputStream(baInput, encCipher); ByteArrayOutputStream baOutput = new ByteArrayOutputStream(); CipherOutputStream ciOutput = new CipherOutputStream(baOutput, decCipher); //do test byte[] buffer = new byte[200]; int len = ciInput.read(buffer); System.out.println("read " + len + " bytes from input buffer"); while (len != -1) { ciOutput.write(buffer, 0, len); System.out.println("wite " + len + " bytes to output buffer"); len = ciInput.read(buffer); if (len != -1) { System.out.println("read " + len + " bytes from input buffer"); } else { System.out.println("finished reading"); } } ciOutput.flush(); ciInput.close(); ciOutput.close(); return baOutput.toByteArray(); } }
37.235849
83
0.649101
30fc6608b2fdee968a20838e13cbc55faff0a943
19,751
/* * Copyright (c) 2014, Harald Kuhr * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name "TwelveMonkeys" nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.twelvemonkeys.imageio.plugins.tiff; import com.twelvemonkeys.io.FastByteArrayOutputStream; import com.twelvemonkeys.io.LittleEndianDataInputStream; import com.twelvemonkeys.io.LittleEndianDataOutputStream; import org.junit.Test; import java.io.*; import java.nio.ByteOrder; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * HorizontalDifferencingStreamTest * * @author <a href="mailto:[email protected]">Harald Kuhr</a> * @author last modified by $Author: haraldk$ * @version $Id: HorizontalDifferencingStreamTest.java,v 1.0 02.12.13 09:50 haraldk Exp$ */ public class HorizontalDifferencingStreamTest { @Test public void testWrite1SPP1BPS() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream stream = new HorizontalDifferencingStream(bytes, 24, 1, 1, ByteOrder.BIG_ENDIAN); // Row 1 stream.write(0xff); stream.write(0xff); stream.write(0xff); // Row 2 stream.write(0x5e); stream.write(0x1e); stream.write(0x78); // 1 sample per pixel, 1 bits per sample (mono/indexed) byte[] data = { (byte) 0x80, 0x00, 0x00, 0x71, 0x11, 0x44, }; assertArrayEquals(data, bytes.toByteArray()); } @Test public void testWrite1SPP2BPS() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream stream = new HorizontalDifferencingStream(bytes, 16, 1, 2, ByteOrder.BIG_ENDIAN); // Row 1 stream.write(0xff); stream.write(0xff); stream.write(0xff); stream.write(0xff); // Row 2 stream.write(0x41); stream.write(0x6b); stream.write(0x05); stream.write(0x0f); // 1 sample per pixel, 2 bits per sample (gray/indexed) byte[] data = { (byte) 0xc0, 0x00, 0x00, 0x00, 0x71, 0x11, 0x44, (byte) 0xcc, }; assertArrayEquals(data, bytes.toByteArray()); } @Test public void testWrite1SPP4BPS() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream stream = new HorizontalDifferencingStream(bytes, 8, 1, 4, ByteOrder.BIG_ENDIAN); // Row 1 stream.write(0xff); stream.write(0xff); stream.write(0xff); stream.write(0xff); // Row 2 stream.write(0x77); stream.write(0x89); stream.write(0xd1); stream.write(0xd9); // Row 3 stream.write(0x00); stream.write(0x01); stream.write(0x22); stream.write(0x00); // 1 sample per pixel, 4 bits per sample (gray/indexed) byte[] data = { (byte) 0xf0, 0x00, 0x00, 0x00, 0x70, 0x11, 0x44, (byte) 0xcc, 0x00, 0x01, 0x10, (byte) 0xe0 }; assertArrayEquals(data, bytes.toByteArray()); } @Test public void testWrite1SPP8BPS() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream stream = new HorizontalDifferencingStream(bytes, 4, 1, 8, ByteOrder.BIG_ENDIAN); // Row 1 stream.write(0xff); stream.write(0xff); stream.write(0xff); stream.write(0xff); // Row 2 stream.write(0x7f); stream.write(0x80); stream.write(0x84); stream.write(0x80); // Row 3 stream.write(0x00); stream.write(0x7f); stream.write(0xfe); stream.write(0x7f); // 1 sample per pixel, 8 bits per sample (gray/indexed) byte[] data = { (byte) 0xff, 0, 0, 0, 0x7f, 1, 4, -4, 0x00, 127, 127, -127 }; assertArrayEquals(data, bytes.toByteArray()); } @Test public void testWriteArray1SPP8BPS() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream stream = new HorizontalDifferencingStream(bytes, 4, 1, 8, ByteOrder.BIG_ENDIAN); stream.write(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x7f, (byte) 0x80, (byte) 0x84, (byte) 0x80, 0x00, 0x7f, (byte) 0xfe, 0x7f, }); // 1 sample per pixel, 8 bits per sample (gray/indexed) byte[] data = { (byte) 0xff, 0, 0, 0, 0x7f, 1, 4, -4, 0x00, 127, 127, -127 }; assertArrayEquals(data, bytes.toByteArray()); } @Test public void testWrite1SPP32BPS() throws IOException { // 1 sample per pixel, 32 bits per sample (gray) FastByteArrayOutputStream bytes = new FastByteArrayOutputStream(16); OutputStream out = new HorizontalDifferencingStream(bytes, 4, 1, 32, ByteOrder.BIG_ENDIAN); DataOutput dataOut = new DataOutputStream(out); dataOut.writeInt(0x00000000); dataOut.writeInt(305419896); dataOut.writeInt(305419896); dataOut.writeInt(-610839792); InputStream in = bytes.createInputStream(); DataInput dataIn = new DataInputStream(in); // Row 1 assertEquals(0, dataIn.readInt()); assertEquals(305419896, dataIn.readInt()); assertEquals(0, dataIn.readInt()); assertEquals(-916259688, dataIn.readInt()); // EOF assertEquals(-1, in.read()); } @Test public void testWrite1SPP32BPSLittleEndian() throws IOException { // 1 sample per pixel, 32 bits per sample (gray) FastByteArrayOutputStream bytes = new FastByteArrayOutputStream(16); OutputStream out = new HorizontalDifferencingStream(bytes, 4, 1, 32, ByteOrder.LITTLE_ENDIAN); DataOutput dataOut = new LittleEndianDataOutputStream(out); dataOut.writeInt(0x00000000); dataOut.writeInt(305419896); dataOut.writeInt(305419896); dataOut.writeInt(-610839792); InputStream in = bytes.createInputStream(); DataInput dataIn = new LittleEndianDataInputStream(in); // Row 1 assertEquals(0, dataIn.readInt()); assertEquals(305419896, dataIn.readInt()); assertEquals(0, dataIn.readInt()); assertEquals(-916259688, dataIn.readInt()); // EOF assertEquals(-1, in.read()); } @Test public void testWrite1SPP64BPS() throws IOException { // 1 sample per pixel, 64 bits per sample (gray) FastByteArrayOutputStream bytes = new FastByteArrayOutputStream(32); OutputStream out = new HorizontalDifferencingStream(bytes, 4, 1, 64, ByteOrder.BIG_ENDIAN); DataOutput dataOut = new DataOutputStream(out); dataOut.writeLong(0x00000000); dataOut.writeLong(81985529216486895L); dataOut.writeLong(81985529216486895L); dataOut.writeLong(-163971058432973790L); InputStream in = bytes.createInputStream(); DataInput dataIn = new DataInputStream(in); // Row 1 assertEquals(0, dataIn.readLong()); assertEquals(81985529216486895L, dataIn.readLong()); assertEquals(0, dataIn.readLong()); assertEquals(-245956587649460685L, dataIn.readLong()); // EOF assertEquals(-1, in.read()); } @Test public void testWrite1SPP64BPSLittleEndian() throws IOException { // 1 sample per pixel, 64 bits per sample (gray) FastByteArrayOutputStream bytes = new FastByteArrayOutputStream(32); OutputStream out = new HorizontalDifferencingStream(bytes, 4, 1, 64, ByteOrder.LITTLE_ENDIAN); DataOutput dataOut = new LittleEndianDataOutputStream(out); dataOut.writeLong(0x00000000); dataOut.writeLong(81985529216486895L); dataOut.writeLong(81985529216486895L); dataOut.writeLong(-163971058432973790L); InputStream in = bytes.createInputStream(); DataInput dataIn = new LittleEndianDataInputStream(in); // Row 1 assertEquals(0, dataIn.readLong()); assertEquals(81985529216486895L, dataIn.readLong()); assertEquals(0, dataIn.readLong()); assertEquals(-245956587649460685L, dataIn.readLong()); // EOF assertEquals(-1, in.read()); } @Test public void testWrite3SPP8BPS() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream stream = new HorizontalDifferencingStream(bytes, 4, 3, 8, ByteOrder.BIG_ENDIAN); // Row 1 stream.write(0xff); stream.write(0x00); stream.write(0x7f); stream.write(0xfe); stream.write(0xff); stream.write(0x7e); stream.write(0xfa); stream.write(0xfb); stream.write(0x7a); stream.write(0xfe); stream.write(0xff); stream.write(0x7e); // Row 2 stream.write(0x7f); stream.write(0x7f); stream.write(0x7f); stream.write(0x80); stream.write(0x80); stream.write(0x80); stream.write(0x84); stream.write(0x84); stream.write(0x84); stream.write(0x80); stream.write(0x80); stream.write(0x80); // Row 3 stream.write(0x00); stream.write(0x00); stream.write(0x00); stream.write(0x7f); stream.write(0x81); stream.write(0x00); stream.write(0x00); stream.write(0x00); stream.write(0x00); stream.write(0x00); stream.write(0x00); stream.write(0x7f); // 3 samples per pixel, 8 bits per sample (RGB) byte[] data = { (byte) 0xff, (byte) 0x00, (byte) 0x7f, -1, -1, -1, -4, -4, -4, 4, 4, 4, 0x7f, 0x7f, 0x7f, 1, 1, 1, 4, 4, 4, -4, -4, -4, 0x00, 0x00, 0x00, 127, -127, 0, -127, 127, 0, 0, 0, 127, }; assertArrayEquals(data, bytes.toByteArray()); } @Test public void testWrite3SPP16BPS() throws IOException { FastByteArrayOutputStream bytes = new FastByteArrayOutputStream(24); OutputStream out = new HorizontalDifferencingStream(bytes, 4, 3, 16, ByteOrder.BIG_ENDIAN); DataOutput dataOut = new DataOutputStream(out); dataOut.writeShort(0x0000); dataOut.writeShort(0x0000); dataOut.writeShort(0x0000); dataOut.writeShort(4660); dataOut.writeShort(30292); dataOut.writeShort(4660); dataOut.writeShort(4660); dataOut.writeShort(30292); dataOut.writeShort(4660); dataOut.writeShort(-9320); dataOut.writeShort(-60584); dataOut.writeShort(-9320); dataOut.writeShort(0x0000); dataOut.writeShort(0x0000); dataOut.writeShort(0x0000); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(-60584); dataOut.writeShort(-60584); dataOut.writeShort(-60584); InputStream in = bytes.createInputStream(); DataInput dataIn = new DataInputStream(in); // Row 1 assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(4660, dataIn.readUnsignedShort()); assertEquals(30292, dataIn.readUnsignedShort()); assertEquals(4660, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(51556, dataIn.readUnsignedShort()); assertEquals(40196, dataIn.readUnsignedShort()); assertEquals(51556, dataIn.readUnsignedShort()); // Row 2 assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(30292, dataIn.readUnsignedShort()); assertEquals(30292, dataIn.readUnsignedShort()); assertEquals(30292, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(40196, dataIn.readUnsignedShort()); assertEquals(40196, dataIn.readUnsignedShort()); assertEquals(40196, dataIn.readUnsignedShort()); // EOF assertEquals(-1, in.read()); } @Test public void testWrite3SPP16BPSLittleEndian() throws IOException { FastByteArrayOutputStream bytes = new FastByteArrayOutputStream(24); OutputStream out = new HorizontalDifferencingStream(bytes, 4, 3, 16, ByteOrder.LITTLE_ENDIAN); DataOutput dataOut = new LittleEndianDataOutputStream(out); dataOut.writeShort(0x0000); dataOut.writeShort(0x0000); dataOut.writeShort(0x0000); dataOut.writeShort(4660); dataOut.writeShort(30292); dataOut.writeShort(4660); dataOut.writeShort(4660); dataOut.writeShort(30292); dataOut.writeShort(4660); dataOut.writeShort(-9320); dataOut.writeShort(-60584); dataOut.writeShort(-9320); dataOut.writeShort(0x0000); dataOut.writeShort(0x0000); dataOut.writeShort(0x0000); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(30292); dataOut.writeShort(-60584); dataOut.writeShort(-60584); dataOut.writeShort(-60584); InputStream in = bytes.createInputStream(); DataInput dataIn = new LittleEndianDataInputStream(in); // Row 1 assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(4660, dataIn.readUnsignedShort()); assertEquals(30292, dataIn.readUnsignedShort()); assertEquals(4660, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(51556, dataIn.readUnsignedShort()); assertEquals(40196, dataIn.readUnsignedShort()); assertEquals(51556, dataIn.readUnsignedShort()); // Row 2 assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(30292, dataIn.readUnsignedShort()); assertEquals(30292, dataIn.readUnsignedShort()); assertEquals(30292, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(0, dataIn.readUnsignedShort()); assertEquals(40196, dataIn.readUnsignedShort()); assertEquals(40196, dataIn.readUnsignedShort()); assertEquals(40196, dataIn.readUnsignedShort()); // EOF assertEquals(-1, in.read()); } @Test public void testWrite4SPP8BPS() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream stream = new HorizontalDifferencingStream(bytes, 4, 4, 8, ByteOrder.BIG_ENDIAN); // Row 1 stream.write(0xff); stream.write(0x00); stream.write(0x7f); stream.write(0x00); stream.write(0xfe); stream.write(0xff); stream.write(0x7e); stream.write(0xff); stream.write(0xfa); stream.write(0xfb); stream.write(0x7a); stream.write(0xfb); stream.write(0xfe); stream.write(0xff); stream.write(0x7e); stream.write(0xff); // Row 2 stream.write(0x7f); stream.write(0x7f); stream.write(0x7f); stream.write(0x7f); stream.write(0x80); stream.write(0x80); stream.write(0x80); stream.write(0x80); stream.write(0x84); stream.write(0x84); stream.write(0x84); stream.write(0x84); stream.write(0x80); stream.write(0x80); stream.write(0x80); stream.write(0x80); // 4 samples per pixel, 8 bits per sample (RGBA) byte[] data = { (byte) 0xff, (byte) 0x00, (byte) 0x7f, 0x00, -1, -1, -1, -1, -4, -4, -4, -4, 4, 4, 4, 4, 0x7f, 0x7f, 0x7f, 0x7f, 1, 1, 1, 1, 4, 4, 4, 4, -4, -4, -4, -4, }; assertArrayEquals(data, bytes.toByteArray()); } @Test public void testWriteArray4SPP8BPS() throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); OutputStream stream = new HorizontalDifferencingStream(bytes, 4, 4, 8, ByteOrder.BIG_ENDIAN); stream.write( new byte[] { (byte) 0xff, 0x00, 0x7f, 0x00, (byte) 0xfe, (byte) 0xff, 0x7e, (byte) 0xff, (byte) 0xfa, (byte) 0xfb, 0x7a, (byte) 0xfb, (byte) 0xfe, (byte) 0xff, 0x7e, (byte) 0xff, 0x7f, 0x7f, 0x7f, 0x7f, (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x84, (byte) 0x84, (byte) 0x84, (byte) 0x84, (byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x80, } ); // 4 samples per pixel, 8 bits per sample (RGBA) byte[] data = { (byte) 0xff, (byte) 0x00, (byte) 0x7f, 0x00, -1, -1, -1, -1, -4, -4, -4, -4, 4, 4, 4, 4, 0x7f, 0x7f, 0x7f, 0x7f, 1, 1, 1, 1, 4, 4, 4, 4, -4, -4, -4, -4, }; assertArrayEquals(data, bytes.toByteArray()); } }
34.349565
104
0.619159
d280fbfefc8b8f70adde05b2934d527ffa193e2b
1,201
package com.qintess.veterinaria.entidades; import java.time.LocalDate; import java.time.LocalDateTime; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import lombok.Getter; import lombok.Setter; @Entity //@NoArgsConstructor @Getter @Setter public class Atendimento { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int idAtendimento; @OneToOne public Veterinario veterinario; @ManyToOne public Animal animal; @OneToOne public Cliente nomeDono; public String cpfDono; public String outrasInformacoes; private LocalDate dataAtendimento; public Atendimento() {} public Atendimento(int idAtendimento, Veterinario veterinario, Animal animal, Cliente nomeDono, String cpfDono, String outrasInformacoes, LocalDate dataAtendimento) { this.idAtendimento = idAtendimento; this.veterinario = veterinario; this.animal = animal; this.nomeDono = nomeDono; this.cpfDono = cpfDono; this.outrasInformacoes = outrasInformacoes; this.dataAtendimento = dataAtendimento; } }
19.370968
112
0.787677
ea7fc0954d9f406d779703a07e00a6e395df5064
8,427
/** * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mr4c.nativec.jna; import com.google.mr4c.dataset.DataFile; import com.google.mr4c.dataset.Dataset; import com.google.mr4c.keys.DataKey; import com.google.mr4c.nativec.ExternalDataFile; import com.google.mr4c.nativec.ExternalDataset; import com.google.mr4c.nativec.ExternalDatasetSerializer; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalDatasetPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalDataFilePtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalAddFunctionPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalFileNameFunctionPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalFindFunctionPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalQueryOnlyFunctionPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalRandomAccessFileSinkPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalRandomAccessFileSourcePtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalRandomAccessSinkFunctionPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalRandomAccessSourceFunctionPtr; import com.google.mr4c.nativec.jna.lib.CExternalDatasetCallbacksStruct; import com.google.mr4c.serialize.DatasetSerializer; import com.google.mr4c.util.MR4CLogging; import com.sun.jna.Pointer; import java.io.FileNotFoundException; import org.slf4j.Logger; public class JnaExternalDataset implements ExternalDataset { protected static final Logger s_log = MR4CLogging.getLogger(JnaExternalDataset.class); static Mr4cLibrary s_lib = Mr4cLibrary.INSTANCE; private Dataset m_dataset; private CExternalDatasetPtr m_nativeDataset; private CExternalDatasetCallbacksStruct m_callbacks; private DatasetSerializer m_serializer; private ExternalDatasetSerializer m_extSerializer; /*package*/ JnaExternalDataset(CExternalDatasetPtr nativeDataset) { m_nativeDataset = nativeDataset; } public JnaExternalDataset(String name, Dataset dataset, DatasetSerializer serializer, ExternalDatasetSerializer extSerializer) { m_dataset = dataset; m_serializer = serializer; m_extSerializer = extSerializer; m_callbacks = new CExternalDatasetCallbacksStruct(); buildAddFileCallback(); buildFileNameCallback(); buildFindFileCallback(); buildQueryOnlyCallback(); buildRandomAccessSourceCallback(); buildRandomAccessSinkCallback(); m_nativeDataset = s_lib.CExternalDataset_newDataset(name, new CExternalDatasetCallbacksStruct[] {m_callbacks}); JnaUtils.protectDataset(m_dataset.getToken(), this); } public String getName() { return s_lib.CExternalDataset_getName(m_nativeDataset); } public String getSerializedDataset() { return s_lib.CExternalDataset_getSerializedDataset(m_nativeDataset); } public void setSerializedDataset(String serializedDataset) { s_lib.CExternalDataset_setSerializedDataset(m_nativeDataset, serializedDataset); } public void addDataFile(ExternalDataFile file) { s_lib.CExternalDataset_addDataFile(m_nativeDataset, JnaExternalDataFile.toNative(file)); } public ExternalDataFile getDataFile(int index) { return JnaExternalDataFile.fromNative(s_lib.CExternalDataset_getDataFile(m_nativeDataset, index)); } public int getFileCount() { return s_lib.CExternalDataset_getFileCount(m_nativeDataset).intValue(); } /*package*/ CExternalDatasetPtr getNativeDataset() { return m_nativeDataset; } /*package*/ static CExternalDatasetPtr toNative(ExternalDataset dataset) { JnaExternalDataset jnaDataset = (JnaExternalDataset) dataset; return jnaDataset==null ? null : jnaDataset.getNativeDataset(); } /*package*/ static JnaExternalDataset fromNative(CExternalDatasetPtr nativeDataset) { return nativeDataset==null ? null : new JnaExternalDataset(nativeDataset); } private void buildAddFileCallback() { m_callbacks.addFileCallback = new CExternalAddFunctionPtr() { public byte apply(CExternalDataFilePtr filePtr) { return doAddFile(filePtr); } }; } private synchronized byte doAddFile(CExternalDataFilePtr filePtr) { try { JnaExternalDataFile extFile = new JnaExternalDataFile(filePtr); String serKey = extFile.getSerializedKey(); DataKey key = m_serializer.deserializeDataKey(serKey); DataFile file = m_extSerializer.deserializeDataFile(extFile); m_dataset.addFile(key, file); if ( file.getFileSink()!=null ) { JnaDataFileSink jnaSink = new JnaDataFileSink(file.getFileSink()); s_lib.CExternalDataFile_setFileSink(filePtr, jnaSink.getNativeSink()); } return (byte)1; } catch ( Exception e ) { s_log.error("Error adding file", e); return (byte)0; } } private void buildFileNameCallback() { m_callbacks.getFileNameCallback = new CExternalFileNameFunctionPtr() { public String apply(Pointer serKey) { return doGetFileName(serKey); } }; } private String doGetFileName(Pointer serKey) { try { DataKey key = m_serializer.deserializeDataKey(serKey.getString(0)); return m_dataset.getFileName(key); } catch ( Exception e ) { s_log.error("Error getting file name", e); return null; } } private void buildFindFileCallback() { m_callbacks.findFileCallback = new CExternalFindFunctionPtr() { public CExternalDataFilePtr apply(Pointer serializedKey) { return doFind(serializedKey); } }; } private synchronized CExternalDataFilePtr doFind(Pointer serializedKey) { try { DataKey key = m_serializer.deserializeDataKey(serializedKey.getString(0)); DataFile file = m_dataset.getFile(key); if ( file==null ) { return null; } ExternalDataFile extFile = m_extSerializer.serializeDataFile(key, file); addDataFile(extFile); return JnaExternalDataFile.toNative(extFile); } catch ( Exception e ) { s_log.error("Error finding file", e); return null; } } private void buildQueryOnlyCallback() { m_callbacks.isQueryOnlyCallback = new CExternalQueryOnlyFunctionPtr() { public byte apply() { return doIsQueryOnly(); } }; } private byte doIsQueryOnly() { return (byte) (m_dataset.isQueryOnly() ? 1 : 0); } private void buildRandomAccessSourceCallback() { m_callbacks.randomAccessSourceCallback = new CExternalRandomAccessSourceFunctionPtr() { public CExternalRandomAccessFileSourcePtr apply(Pointer serializedKey) { return doRandomAccessSource(serializedKey); } }; } private CExternalRandomAccessFileSourcePtr doRandomAccessSource(Pointer serializedKey) { try { DataKey key = m_serializer.deserializeDataKey(serializedKey.getString(0)); DataFile file = m_dataset.getFile(key); if ( file==null ) { throw new FileNotFoundException(String.format("No file with key = [%s]", key)); } JnaRandomAccessFileSource rafSrc = new JnaRandomAccessFileSource(file.getFileSource()); return rafSrc.getNativeSource(); } catch ( Exception e ) { s_log.error("Error preparing random access source", e); return null; } } private void buildRandomAccessSinkCallback() { m_callbacks.randomAccessSinkCallback = new CExternalRandomAccessSinkFunctionPtr() { public CExternalRandomAccessFileSinkPtr apply(Pointer serializedKey) { return doRandomAccessSink(serializedKey); } }; } private CExternalRandomAccessFileSinkPtr doRandomAccessSink(Pointer serializedKey) { try { DataKey key = m_serializer.deserializeDataKey(serializedKey.getString(0)); DataFile file = m_dataset.getFile(key); if ( file==null ) { throw new FileNotFoundException(String.format("No file with key = [%s]", key)); } JnaRandomAccessFileSink rafSink = new JnaRandomAccessFileSink(file.getFileSink()); return rafSink.getNativeSink(); } catch ( Exception e ) { s_log.error("Error preparing random access sink", e); return null; } } }
34.256098
129
0.77667
4583485f2afbd92490947ab1c469aba5e9293a7c
257
package checkers.util.report.quals; import java.lang.annotation.*; /** * Report all read or write access to a field with this annotation. */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ReportReadWrite {}
21.416667
67
0.774319
bf70b3a8fe302b5409c5cda2d03b26fe1fc8b93a
8,539
package fi.vincit.jmobster.processor.defaults; /* * Copyright 2012-2013 Juha Siponen * * 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. */ import fi.vincit.jmobster.annotation.FieldGroupFilter; import fi.vincit.jmobster.annotation.IgnoreField; import fi.vincit.jmobster.processor.*; import fi.vincit.jmobster.processor.model.ModelField; import fi.vincit.jmobster.util.groups.GenericGroupManager; import fi.vincit.jmobster.util.groups.GroupMode; import fi.vincit.jmobster.util.groups.HasGroups; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.*; import java.security.AccessControlException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Scans the given bean for fields that should be included in the client side model. Field group filtering settings * use GroupMode.ANY_OF_REQUIRED with no groups as default which allows all fields and properties. */ public class DefaultModelFieldFactory implements ModelFieldFactory { private static final Logger LOG = LoggerFactory.getLogger( DefaultModelFieldFactory.class ); private boolean allowStaticFields; private boolean allowFinalFields; private final FieldScanMode scanMode; private final ValidatorScanner validatorScanner; private final GenericGroupManager fieldGroupManager; public DefaultModelFieldFactory( FieldScanMode scanMode, ValidatorScanner validatorScanner, GenericGroupManager fieldGroupManager ) { this.allowStaticFields = false; this.allowFinalFields = true; this.scanMode = scanMode; this.validatorScanner = validatorScanner; this.fieldGroupManager = fieldGroupManager; } @Override public List<ModelField> getFields( Class clazz ) { switch( scanMode ) { case BEAN_PROPERTY: return getFieldsByGetters( clazz ); case DIRECT_FIELD_ACCESS: return getFieldsByDirectFieldAccess( clazz ); default: throw new IllegalArgumentException("Invalid field scan mode: " + scanMode); } } @Override public void setFieldFilterGroups( GroupMode groupMode, Collection<Class> groups ) { fieldGroupManager.setGroups(groupMode, groups); } /** * Scans the given class for model fields. Accesses bean properties (getter methods). * @param clazz Class to scan * @return List of model fields. Empty list if nothing found. */ private List<ModelField> getFieldsByGetters(Class clazz) { List<ModelField> fields = new ArrayList<ModelField>(); try { // Introspector will find also properties from super classes final BeanInfo beanInfo = Introspector.getBeanInfo( clazz, Introspector.USE_ALL_BEANINFO ); for( PropertyDescriptor property : beanInfo.getPropertyDescriptors() ) { if( shouldAddField(property) ) { final String name = property.getName(); // Java's standard class getter is omitted if( name.equals("class") ) { continue; } final ModelField field = new ModelField(property, validatorScanner.getValidators( property )); fields.add(field); } } } catch( IntrospectionException e ) { LOG.error("Introspection failed", e); throw new IllegalArgumentException("Cannot init property: Introspection failed", e); } return fields; } /** * Scans the given class for model fields. Accesses field directly via member variables. * @param clazz Class to scan * @return List of model fields. Empty list if nothing found. */ private List<ModelField> getFieldsByDirectFieldAccess( Class clazz ) { List<ModelField> fields = new ArrayList<ModelField>(); getFieldsByDirectFieldAccess(clazz, fields); return fields; } /** * Sames as {@link DefaultModelFieldFactory#getFieldsByDirectFieldAccess(Class)} but * takes a list as a parameter for performance reasons. Since some calls may be recursive * it is more efficient to use the same list than to allocate new list for every recursion * level. * @param clazz Class to scan * @param fields List of model fields */ private void getFieldsByDirectFieldAccess( Class clazz, List<ModelField> fields) { for( Field field : clazz.getDeclaredFields() ) { try { field.setAccessible(true); if( shouldAddField(field) ) { ModelField modelField = new ModelField(field, validatorScanner.getValidators( field )); fields.add( modelField ); } else { LOG.warn( "Field {} not added to model fields", field.getName() ); } } catch (AccessControlException ace) { LOG.warn( "Field {} not added to model fields due to SecurityManager", field.getName() ); } } // Also find all fields from every super classes if( clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class) ) { getFieldsByDirectFieldAccess(clazz.getSuperclass(), fields); } } /** * Checks if the field should be added to model fields. * @param field Field to checks * @return True if the field should be included in model fields. Otherwise false. */ private boolean shouldAddField(Field field) { return allowedByAnnotation(field) && allowedByModifiers(field.getModifiers()); } /** * Checks if the property should be added to model fields. Uses * the getter method properties to determine this. * @param property Bean property to check * @return True if the property should be included in the model fields. Otherwise false. */ private boolean shouldAddField(PropertyDescriptor property) { Method method = property.getReadMethod(); return allowedByAnnotation(method) && allowedByModifiers(method.getModifiers()); } /** * Checks if the given modifiers allow a field or property to * be added to model fields * @param modifiers Modifiers * @return True if the field or property should be included, otherwise false. */ private boolean allowedByModifiers(int modifiers) { return (allowStaticFields || !Modifier.isStatic(modifiers)) && (allowFinalFields || !Modifier.isFinal(modifiers)); } /** * Checks if the given field or property should be added to model * fields. For this method the bean property getter method should * be given. * @param element Bean property getter or field * @return True if the field or property should be included, otherwise false. */ private boolean allowedByAnnotation(AnnotatedElement element) { if( element.isAnnotationPresent(IgnoreField.class) ) { return false; } if( element.isAnnotationPresent( FieldGroupFilter.class ) ) { FieldGroupFilter fieldGroupFilter = element.getAnnotation(FieldGroupFilter.class); final Class[] groups = fieldGroupFilter.groups(); HasGroups<Class> groupsObject = new HasGroups<Class>() { @Override public Class[] getGroups() { return groups; } @Override public boolean hasGroups() { return groups.length > 0; } }; return fieldGroupManager.match(groupsObject); } return true; } @Override public void setAllowStaticFields( boolean allowStaticFields ) { this.allowStaticFields = allowStaticFields; } @Override public void setAllowFinalFields( boolean allowFinalFields ) { this.allowFinalFields = allowFinalFields; } }
40.661905
137
0.674084
1c2f47a105f0f0a124b6100b70c022de9d913c29
1,271
package org.ros.internal.node.client; import org.ros.exception.RosRuntimeException; import org.ros.internal.node.rpc.RpcClientConfigImpl; import org.ros.internal.node.rpc.RpcEndpoint; import org.ros.internal.node.server.RpcServer; import java.net.InetSocketAddress; import java.net.URI; /** * Base class for RPC clients (e.g. MasterClient and SlaveClient). * @param <T> * the RPC interface this {@link Client} connects to * @author Jonathan Groff Copyright (C) NeoCoreTechs 2015,2021 */ abstract class Client<T extends RpcEndpoint> { private final InetSocketAddress uri; protected T rpcEndpoint = null; /** * @param subscriberSlaveUri * the {@link URI} to connect to * @param interfaceClass * the class literal for the XML-RPC interface */ public Client(InetSocketAddress subscriberSlaveUri, int connTimeout, int replyTimeout) { this.uri = subscriberSlaveUri; RpcClientConfigImpl config = new RpcClientConfigImpl(); config.setServerURL(subscriberSlaveUri); config.setConnectionTimeout(connTimeout); config.setReplyTimeout(replyTimeout); } /** * @return the {@link URI} of the remote {@link RpcServer} */ public InetSocketAddress getRemoteUri() { return uri; } }
27.630435
90
0.720692
5d0c9acae16bf30416df557729cbf1186964198e
841
package com.blazemeter.api.explorer; import kg.apc.jmeter.http.HttpUtils; import kg.apc.jmeter.reporters.notifier.StatusNotifierCallbackTest; import static org.junit.Assert.*; public class BZAObjectTest { @org.junit.Test public void test() throws Exception { HttpUtils httpUtils = new HttpUtils(new StatusNotifierCallbackTest.StatusNotifierCallbackImpl(), "", ""); BZAObject entity = new BZAObject(httpUtils, "id", "name"); assertEquals(httpUtils, entity.getHttpUtils()); assertEquals("id", entity.getId()); assertEquals("name", entity.getName()); entity.setHttpUtils(null); entity.setId("id1"); entity.setName("name1"); assertNull(entity.getHttpUtils()); assertEquals("id1", entity.getId()); assertEquals("name1", entity.getName()); } }
35.041667
113
0.677765
8316d2176d6f11cb9bfbe75d6a73d69393cde930
4,646
package imj.apps.modules; import static imj.apps.modules.SeamGridSegmentationSieve.countSegments4; import static imj.apps.modules.SeamGridSegmentationSieve.getCost; import static imj.apps.modules.ViewFilter.getCurrentImage; import static imj.apps.modules.ViewFilter.parseChannel; import static java.lang.Math.min; import static multij.tools.Tools.debugPrint; import imj.Image; import imj.ImageOfInts; import imj.apps.modules.ViewFilter.Channel; import java.util.Date; import java.util.Locale; import multij.context.Context; import multij.tools.TicToc; /** * @author codistmonk (creation 2013-05-02) */ public final class SeamGridSegmentation2Sieve extends Sieve { private RegionOfInterest segmentation; public SeamGridSegmentation2Sieve(final Context context) { super(context); this.getParameters().put("channel", "rgb"); this.getParameters().put("cellSize", "32"); } @Override public final boolean accept(final int index, final int value) { return this.segmentation.get(index); } @Override public final void initialize() { final Channel channel = parseChannel(this.getParameters().get("channel").toUpperCase(Locale.ENGLISH)); final int cellSize = this.getIntParameter("cellSize"); final Image image = getCurrentImage(this.getContext()); final RegionOfInterest roi = this.getROI(); this.segmentation = RegionOfInterest.newInstance(roi.getRowCount(), roi.getColumnCount()); this.segmentation.reset(true); final TicToc timer = new TicToc(); debugPrint("Setting horizontal band seams...", new Date(timer.tic())); setHorizontalBandSeams(image, channel, cellSize, this.segmentation); debugPrint("Setting horizontal band seams done", "time:", timer.toc()); debugPrint("Setting vertical band seams...", new Date(timer.tic())); setHorizontalBandSeams(new Transpose(image), channel, cellSize, new Transpose(this.segmentation)); debugPrint("Setting vertical band seams done", "time:", timer.toc()); debugPrint("segmentCount:", countSegments4(this.segmentation)); } public static final void setHorizontalBandSeams(final Image image, final Channel channel, final int cellSize, final Image segmentation) { final int rowCount = image.getRowCount(); final int columnCount = image.getColumnCount(); final Image band = new ImageOfInts(cellSize, columnCount, 1); for (int rowIndex0 = cellSize; rowIndex0 + cellSize < rowCount; rowIndex0 += cellSize) { System.out.print(rowIndex0 + "/" + rowCount + "\r"); for (int rowIndex = rowIndex0; rowIndex < rowIndex0 + cellSize; ++rowIndex) { band.setValue(rowIndex - rowIndex0, 0, getCost(image, channel, rowIndex, 0)); } for (int columnIndex = 1; columnIndex < columnCount; ++columnIndex) { for (int rowIndex = rowIndex0; rowIndex < rowIndex0 + cellSize; ++rowIndex) { final int northWest = rowIndex0 < rowIndex ? getCost(image, channel, rowIndex - 1, columnIndex - 1) : Integer.MAX_VALUE; final int west = getCost(image, channel, rowIndex, columnIndex - 1); final int southWest = rowIndex + 1 < rowIndex0 + cellSize ? getCost(image, channel, rowIndex + 1, columnIndex - 1) : Integer.MAX_VALUE; final int min = min(northWest, min(west, southWest)); band.setValue(rowIndex - rowIndex0, columnIndex, clampedSum(min, getCost(image, channel, rowIndex, columnIndex))); } } final int lastColumnIndex = columnCount - 1; int rowIndexOfMin = rowIndex0; int min = band.getValue(rowIndexOfMin - rowIndex0, lastColumnIndex); for (int rowIndex = rowIndex0; rowIndex < rowIndex0 + cellSize; ++rowIndex) { final int value = band.getValue(rowIndex - rowIndex0, lastColumnIndex); if (value < min) { min = value; rowIndexOfMin = rowIndex; } } for (int columnIndex = lastColumnIndex, rowIndex = rowIndexOfMin; 0 <= columnIndex; --columnIndex) { segmentation.setValue(rowIndex, columnIndex, 0); if (columnIndex == 0) { break; } final int northWest = rowIndex0 < rowIndex ? band.getValue(rowIndex - rowIndex0 - 1, columnIndex - 1) : Integer.MAX_VALUE; final int west = band.getValue(rowIndex - rowIndex0, columnIndex - 1); final int southWest = rowIndex + 1 < rowIndex0 + cellSize ? band.getValue(rowIndex - rowIndex0 + 1, columnIndex - 1) : Integer.MAX_VALUE; if (west <= northWest && west <= southWest) { // NOP } else if (northWest <= southWest) { --rowIndex; } else { ++rowIndex; } } } } public static final int clampedSum(final int a, final int b) { return (int) min(Integer.MAX_VALUE, (long) a + b); } }
36.296875
104
0.705553
90a710eda3ac3350a576c5898121d325bf5e47eb
6,690
package de.tum.in.www1.artemis.service.plagiarism; import static java.util.stream.Collectors.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; import de.tum.in.www1.artemis.domain.TextExercise; import de.tum.in.www1.artemis.domain.TextSubmission; import de.tum.in.www1.artemis.domain.User; import de.tum.in.www1.artemis.domain.participation.Participation; import de.tum.in.www1.artemis.domain.participation.StudentParticipation; import de.tum.in.www1.artemis.domain.plagiarism.text.TextPlagiarismResult; import de.tum.in.www1.artemis.service.TextSubmissionExportService; import de.tum.in.www1.artemis.service.util.TimeLogUtil; import jplag.*; import jplag.options.LanguageOption; @Service public class TextPlagiarismDetectionService { private final Logger log = LoggerFactory.getLogger(TextPlagiarismDetectionService.class); private final TextSubmissionExportService textSubmissionExportService; public TextPlagiarismDetectionService(TextSubmissionExportService textSubmissionExportService) { this.textSubmissionExportService = textSubmissionExportService; } /** * Reduce a TextExercise Object to a list of latest text submissions. Filters the empty ones because they do not need to be compared * * @param exerciseWithParticipationsAndSubmissions TextExercise with fetched participations and submissions * @param minimumScore consider only submissions whose score is greater or equal to this value * @param minimumSize consider only submissions whose number of words is greater or equal to this value * @return List containing the latest text submission for every participation */ public List<TextSubmission> textSubmissionsForComparison(TextExercise exerciseWithParticipationsAndSubmissions, int minimumScore, int minimumSize) { var textSubmissions = exerciseWithParticipationsAndSubmissions.getStudentParticipations().parallelStream().map(Participation::findLatestSubmission) .filter(Optional::isPresent).map(Optional::get).filter(submission -> submission instanceof TextSubmission).map(submission -> (TextSubmission) submission) .filter(submission -> minimumSize == 0 || submission.getText() != null && submission.countWords() >= minimumSize) .filter(submission -> minimumScore == 0 || submission.getLatestResult() != null && submission.getLatestResult().getScore() != null && submission.getLatestResult().getScore() >= minimumScore) .collect(toList()); log.info("Found {} text submissions in exercise {}", textSubmissions.size(), exerciseWithParticipationsAndSubmissions.getId()); return textSubmissions.parallelStream().filter(textSubmission -> !textSubmission.isEmpty()).toList(); } /** * Download all submissions of the exercise, run JPlag, and return the result * * @param textExercise to detect plagiarism for * @param similarityThreshold ignore comparisons whose similarity is below this threshold (%) * @param minimumScore consider only submissions whose score is greater or equal to this value * @param minimumSize consider only submissions whose size is greater or equal to this value * @return a zip file that can be returned to the client * @throws ExitException is thrown if JPlag exits unexpectedly */ public TextPlagiarismResult checkPlagiarism(TextExercise textExercise, float similarityThreshold, int minimumScore, int minimumSize) throws ExitException { long start = System.nanoTime(); // TODO: why do we have such a strange folder name? final var submissionsFolderName = "./tmp/submissions"; final var submissionFolderFile = new File(submissionsFolderName); submissionFolderFile.mkdirs(); final List<TextSubmission> textSubmissions = textSubmissionsForComparison(textExercise, minimumScore, minimumSize); final var submissionsSize = textSubmissions.size(); log.info("Save text submissions for JPlag text comparison with {} submissions", submissionsSize); if (textSubmissions.size() < 2) { log.info("Insufficient amount of submissions for plagiarism detection. Return empty result."); TextPlagiarismResult textPlagiarismResult = new TextPlagiarismResult(); textPlagiarismResult.setExercise(textExercise); textPlagiarismResult.setSimilarityDistribution(new int[0]); return textPlagiarismResult; } textSubmissions.forEach(submission -> { submission.setResults(new ArrayList<>()); StudentParticipation participation = (StudentParticipation) submission.getParticipation(); participation.setExercise(null); participation.setSubmissions(null); String studentLogin = participation.getStudent().map(User::getLogin).orElse("unknown"); try { textSubmissionExportService.saveSubmissionToFile(submission, studentLogin, submissionsFolderName); } catch (IOException e) { log.error(e.getMessage()); } }); log.info("Saving text submissions done"); JPlagOptions options = new JPlagOptions(submissionsFolderName, LanguageOption.TEXT); options.setMinTokenMatch(minimumSize); // Important: for large courses with more than 1000 students, we might get more than one million results and 10 million files in the file system due to many 0% results, // therefore we limit the results to at least 50% or 0.5 similarity, the passed threshold is between 0 and 100% options.setSimilarityThreshold(similarityThreshold); log.info("Start JPlag Text comparison"); JPlag jplag = new JPlag(options); JPlagResult jPlagResult = jplag.run(); log.info("JPlag Text comparison finished with {} comparisons", jPlagResult.getComparisons().size()); log.info("Delete submission folder"); if (submissionFolderFile.exists()) { FileSystemUtils.deleteRecursively(submissionFolderFile); } TextPlagiarismResult textPlagiarismResult = new TextPlagiarismResult(jPlagResult); textPlagiarismResult.setExercise(textExercise); log.info("JPlag text comparison for {} submissions done in {}", submissionsSize, TimeLogUtil.formatDurationFrom(start)); return textPlagiarismResult; } }
49.925373
176
0.73154
cd71b8e9f1768500e7cac8dccdff5c053354dcd8
683
package com.ouc.dcrms.collect.util; //保存需采集数据的设备信息 public class InstrumentArray { private int instrumentID = 0; private String sensorsList; // 传感器序列 private Instrument instrument; public int getInstrumentID() { return instrumentID; } public void setInstrumentID(int instrumentID) { this.instrumentID = instrumentID; } public String getSensorsList() { return sensorsList; } public void setSensorsList(String sensorsList) { this.sensorsList = sensorsList; } public Instrument getInstrument() { return instrument; } public void setInstrument(Instrument instrument) { this.instrument = instrument; } }
18.972222
54
0.699854
8a0782ea7ee77c80a79ae2ab49376de52ac3d4dd
2,463
package com.github.mmonkey.destinations.commands; import com.flowpowered.math.vector.Vector3d; import com.github.mmonkey.destinations.entities.SpawnEntity; import com.github.mmonkey.destinations.events.PlayerTeleportPreEvent; import com.github.mmonkey.destinations.events.PlayerTeleportSpawnEvent; import com.github.mmonkey.destinations.persistence.cache.SpawnCache; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; public class SpawnCommand implements CommandExecutor { public static final String[] ALIASES = {"spawn", "s"}; /** * Get the Command Specifications for this command * * @return CommandSpec */ public static CommandSpec getCommandSpec() { return CommandSpec.builder() .permission("destinations.spawn.use") .description(Text.of("/spawn")) .extendedDescription(Text.of("Teleports the player to their current world's spawn location.")) .executor(new SpawnCommand()) .build(); } @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (!(src instanceof Player)) { return CommandResult.empty(); } Player player = (Player) src; Location<World> location = new Location<>(player.getWorld(), player.getWorld().getProperties().getSpawnPosition()); Vector3d rotation = null; for (SpawnEntity spawnEntity : SpawnCache.instance.get()) { if (spawnEntity.getWorld().getIdentifier().equals(player.getWorld().getUniqueId().toString())) { rotation = spawnEntity.getRotation(); } } Sponge.getGame().getEventManager().post(new PlayerTeleportPreEvent(player, player.getLocation(), player.getRotation())); Sponge.getGame().getEventManager().post(new PlayerTeleportSpawnEvent(player, location, rotation)); return CommandResult.empty(); } }
41.05
128
0.717418
0c7bd4207c92b187a124bb98101fe7cff1e34d74
583
package chico3434.billjobs.objects; public class Software extends Product { public Software(String name, String version, String description, double cost, double price) { super(name, version, description, cost, price); } public Software(String name, String version) { super(name, version); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Software) || o == null) return false; Software software = (Software) o; return getId().equals(software.getId()); } }
27.761905
97
0.636364
bb0cb1412cecc8d0be7c880d531e72f97a2d1932
3,922
package de.tum.in.www1.artemis.web.rest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import de.tum.in.www1.artemis.config.Constants; import de.tum.in.www1.artemis.domain.Exercise; import de.tum.in.www1.artemis.domain.ProgrammingExercise; import de.tum.in.www1.artemis.security.SecurityUtils; import de.tum.in.www1.artemis.service.ExerciseService; import de.tum.in.www1.artemis.service.ProgrammingExerciseService; import de.tum.in.www1.artemis.service.ProgrammingSubmissionService; /** * REST controller for managing ProgrammingSubmission. */ @RestController @RequestMapping("/api") public class ProgrammingSubmissionResource { private final Logger log = LoggerFactory.getLogger(ProgrammingSubmissionResource.class); private static final String ENTITY_NAME = "programmingSubmission"; private final ProgrammingSubmissionService programmingSubmissionService; private final ExerciseService exerciseService; private final ProgrammingExerciseService programmingExerciseService; public ProgrammingSubmissionResource(ProgrammingSubmissionService programmingSubmissionService, ExerciseService exerciseService, ProgrammingExerciseService programmingExerciseService) { this.programmingSubmissionService = programmingSubmissionService; this.exerciseService = exerciseService; this.programmingExerciseService = programmingExerciseService; } /** * POST /programming-submissions/:participationId : Notify the application about a new push to the VCS for the participation with Id participationId This API is invoked by the * VCS Server at the push of a new commit * * @param participationId the participationId of the participation the repository is linked to * @return the ResponseEntity with status 200 (OK), or with status 400 (Bad Request) if the latest commit was already notified about */ @PostMapping(value = Constants.PROGRAMMING_SUBMISSION_RESOURCE_PATH + "{participationId}") public ResponseEntity<?> notifyPush(@PathVariable("participationId") Long participationId, @RequestBody Object requestBody) { log.info("REST request to inform about new commit+push for participation: {}", participationId); programmingSubmissionService.notifyPush(participationId, requestBody); return ResponseEntity.status(HttpStatus.OK).build(); } /** * POST /programming-exercises/test-cases-changed/:exerciseId : informs ArTEMiS about changed test cases for the "id" programmingExercise. e * * @param exerciseId the id of the programmingExercise where the test cases got changed * @return the ResponseEntity with status 200 (OK) */ @PostMapping(Constants.TEST_CASE_CHANGED_PATH + "{exerciseId}") public ResponseEntity<Void> testCaseChanged(@PathVariable Long exerciseId, @RequestBody Object requestBody) { log.info("REST request to inform about changed test cases of ProgrammingExercise : {}", exerciseId); // This is needed as a request using a custom query is made using the ExerciseRepository, but the user is not authenticated // as the VCS-server performs the request SecurityUtils.setAuthorizationObject(); Exercise exercise = exerciseService.findOneLoadParticipations(exerciseId); if (!(exercise instanceof ProgrammingExercise)) { log.warn("REST request to inform about changed test cases of non existing ProgrammingExercise : {}", exerciseId); return ResponseEntity.notFound().build(); } ProgrammingExercise programmingExercise = (ProgrammingExercise) exercise; programmingExerciseService.notifyChangedTestCases(programmingExercise, requestBody); return ResponseEntity.ok().build(); } }
47.253012
179
0.766191
31da03d6e9e7a14cbe40793d4f43290e7bcac524
2,065
/* * 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.giraph.types.ops; import org.apache.giraph.types.ops.collections.array.WBooleanArrayList; import org.apache.hadoop.io.BooleanWritable; import java.io.DataInput; import java.io.IOException; // AUTO-GENERATED class via class: // org.apache.giraph.generate.GeneratePrimitiveClasses /** TypeOps implementation for working with BooleanWritable type */ public enum BooleanTypeOps implements PrimitiveTypeOps<BooleanWritable> { /** Singleton instance */ INSTANCE; @Override public Class<BooleanWritable> getTypeClass() { return BooleanWritable.class; } @Override public BooleanWritable create() { return new BooleanWritable(); } @Override public BooleanWritable createCopy(BooleanWritable from) { return new BooleanWritable(from.get()); } @Override public void set(BooleanWritable to, BooleanWritable from) { to.set(from.get()); } @Override public WBooleanArrayList createArrayList() { return new WBooleanArrayList(); } @Override public WBooleanArrayList createArrayList(int capacity) { return new WBooleanArrayList(capacity); } @Override public WBooleanArrayList readNewArrayList(DataInput in) throws IOException { return WBooleanArrayList.readNew(in); } }
29.5
78
0.753995
eacd2cdb8525b1c66ca504dce757e21bcb052dfe
4,080
package bio.terra.workspace.service.workspace.flight; import static bio.terra.workspace.service.workspace.flight.WorkspaceFlightMapKeys.GCP_PROJECT_ID; import bio.terra.cloudres.google.iam.IamCow; import bio.terra.stairway.FlightContext; import bio.terra.stairway.Step; import bio.terra.stairway.StepResult; import bio.terra.stairway.exception.RetryException; import bio.terra.workspace.service.resource.controlled.mappings.CustomGcpIamRole; import bio.terra.workspace.service.resource.controlled.mappings.CustomGcpIamRoleMapping; import bio.terra.workspace.service.workspace.CloudSyncRoleMapping; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.iam.v1.model.CreateRoleRequest; import com.google.api.services.iam.v1.model.Role; import com.google.common.collect.ImmutableSet; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; /** * This step creates custom role definitions in our GCP context. It does not grant these roles to * any users, though other steps do. */ public class CreateCustomGcpRolesStep implements Step { private final IamCow iamCow; private final Logger logger = LoggerFactory.getLogger(CreateCustomGcpRolesStep.class); public CreateCustomGcpRolesStep(IamCow iamCow) { this.iamCow = iamCow; } @Override public StepResult doStep(FlightContext flightContext) throws InterruptedException, RetryException { String projectId = flightContext.getWorkingMap().get(GCP_PROJECT_ID, String.class); // First, create the project-level custom roles. // Multiple WSM roles may share the same GCP role. De-duping here prevents duplicate requests, // which would lead to unnecessary CONFLICT responses from GCP. ImmutableSet<CustomGcpIamRole> customProjectRoles = CloudSyncRoleMapping.CUSTOM_GCP_PROJECT_IAM_ROLES.values().stream() .collect(ImmutableSet.toImmutableSet()); for (CustomGcpIamRole customProjectRole : customProjectRoles) { createCustomRole(customProjectRole, projectId); } // Second, create the resource-level custom roles. for (CustomGcpIamRole customResourceRole : CustomGcpIamRoleMapping.CUSTOM_GCP_RESOURCE_IAM_ROLES.values()) { createCustomRole(customResourceRole, projectId); } return StepResult.getStepResultSuccess(); } /** * Utility for creating custom roles in GCP from WSM's CustomGcpIamRole objects. These roles will * be defined at the project level in the specified by projectId. */ private void createCustomRole(CustomGcpIamRole customRole, String projectId) throws RetryException { try { Role gcpRole = new Role() .setIncludedPermissions(customRole.getIncludedPermissions()) .setTitle(customRole.getRoleName()); CreateRoleRequest request = new CreateRoleRequest().setRole(gcpRole).setRoleId(customRole.getRoleName()); logger.debug( "Creating role {} with permissions {} in project {}", customRole.getRoleName(), customRole.getIncludedPermissions(), projectId); iamCow.projects().roles().create("projects/" + projectId, request).execute(); } catch (GoogleJsonResponseException googleEx) { // Because this step may run multiple times, we need to handle duplicate role creation. // The project was retrieved from RBS earlier in this flight, so we assume that any conflict // of role names must be due to duplicate step execution. if (googleEx.getStatusCode() != HttpStatus.CONFLICT.value()) { throw new RetryException(googleEx); } } catch (IOException e) { // Retry on IO exceptions thrown by CRL. throw new RetryException(e); } } @Override public StepResult undoStep(FlightContext flightContext) throws InterruptedException { // No need to delete roles if the project is being deleted by other steps in // CreateGoogleContextFlight. return StepResult.getStepResultSuccess(); } }
42.5
99
0.75
acd1b1b15b964b3c86fe28aaa2c39f57657b2979
810
package no.nav.familie.ks.sak; import org.springframework.boot.test.util.TestPropertyValues; import org.testcontainers.containers.PostgreSQLContainer; import java.util.ArrayList; import java.util.List; public class ApplicationTestPropertyValues { public static TestPropertyValues using(PostgreSQLContainer<?> postgreSQLContainer) { List<String> pairs = new ArrayList<>(); // postgres pairs.add("spring.datasource.url=" + postgreSQLContainer.getJdbcUrl()); pairs.add("spring.datasource.username=" + postgreSQLContainer.getUsername()); pairs.add("spring.datasource.password=" + postgreSQLContainer.getPassword()); pairs.add("spring.cloud.vault.database.role=" + postgreSQLContainer.getUsername()); return TestPropertyValues.of(pairs); } }
31.153846
91
0.735802
7456d4fc0471ecbbaff64d90a56dc36b8727d315
256
package com.padcmyanmar.charles.and.keith.assignment.tra.delegates; import com.padcmyanmar.charles.and.keith.assignment.tra.data.vos.NewProductsVO; public interface CharlesAndKeithShowItemsDelegate { void onTapShowItems(NewProductsVO newProducts); }
32
79
0.839844
01eeaf4862f2bc50a8424277b9f70d10a2f86a5f
9,874
/* * Copyright 2018 Key Bridge. * * 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.ietf.oauth.message; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import javax.json.bind.annotation.JsonbProperty; import javax.json.bind.annotation.JsonbTypeAdapter; import javax.ws.rs.core.MultivaluedMap; import org.ietf.oauth.AbstractUrlEncodedMessage; import org.ietf.oauth.OauthUtility; import org.ietf.oauth.adapter.JsonStringCollectionAdapter; /** * RFC 6749 OAuth 2.0 1.5. Refresh Token * <p> * Refresh tokens are credentials used to obtain access tokens. Refresh tokens * are issued to the client by the authorization server and are used to obtain a * new access token when the current access token becomes invalid or expires, or * to obtain additional access tokens with identical or narrower scope (access * tokens may have a shorter lifetime and fewer permissions than authorized by * the resource owner). Issuing a refresh token is optional at the discretion of * the authorization server. If the authorization server issues a refresh token, * it is included when issuing an access token (i.e., step (D) in Figure 1). * <p> * A refresh token is a string representing the authorization granted to the * client by the resource owner. The string is usually opaque to the client. The * token denotes an identifier used to retrieve the authorization information. * Unlike access tokens, refresh tokens are intended for use only with * authorization servers and are never sent to resource servers. * <p> * Unlike access tokens, refresh tokens are intended for use only with * authorization servers and are never sent to resource servers. * <pre> * +--------+ +---------------+ * | |--(A)------- Authorization Grant ---------=| | * | |=-(B)---Access Token + Refresh Token ------| | * | | +----------+ | | * | |--(C)---- Access Token ----=| | | | * | |=-(D)- Protected Resource --| Resource | | Authorization | * | Client | | Server | | Server | * | |--(E)---- Access Token ----=| | | | * | |=-(F)- Invalid Token Error -| | | | * | | +----------+ | | * | |--(G)----------- Refresh Token -----------=| | * | |=-(H)--Access + Optional Refresh Token-----| | * +--------+ +---------------+ * Figure 2: Refreshing an Expired Access Token</pre> * <p> * 6. Refreshing an Access Token * <p> * If the authorization server issued a refresh token to the client, the client * makes a refresh request to the token endpoint by adding the following * parameters using the "application/x-www-form-urlencoded" format per Appendix * B with a character encoding of UTF-8 in the HTTP request entity-body: * grant_type, refresh_token, scope. * <p> * Because refresh tokens are typically long-lasting credentials used to request * additional access tokens, the refresh token is bound to the client to which * it was issued. If the client type is confidential or the client was issued * client credentials (or assigned other authentication requirements), the * client MUST authenticate with the authorization server as described in * Section 3.2.1. * <p> * For example, the client makes the following HTTP request using * transport-layer security (with extra line breaks for display purposes only): * <pre> * POST /token HTTP/1.1 * Host: server.example.com * Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW * Content-Type: application/x-www-form-urlencoded * * grant_type=refresh_token&amp;refresh_token=tGzv3JOkF0XG5Qx2TlKWIA * </pre> * <p> * If valid and authorized, the authorization server issues an access token as * described in Section 5.1. If the request failed verification or is invalid, * the authorization server returns an error response as described in Section * 5.2. * <p> * The authorization server MAY issue a new refresh token, in which case the * client MUST discard the old refresh token and replace it with the new refresh * token. The authorization server MAY revoke the old refresh token after * issuing a new refresh token to the client. If a new refresh token is issued, * the refresh token scope MUST be identical to that of the refresh token * included by the client in the request. * * @author Key Bridge 10/08/17 * @since 0.2.0 */ public class RefreshTokenRequest extends AbstractUrlEncodedMessage implements Serializable { /** * 12.1. Refresh Request */ private static final String REFRESH_TOKEN = "refresh_token"; /** * REQUIRED. Value MUST be set to "refresh_token". */ @JsonbProperty("grant_type") private String grantType; /** * REQUIRED, if the client is not authenticating with the authorization server * as described in OpenID Section 3.2.1. */ @JsonbProperty("client_id") private String clientId; /** * REQUIRED. The refresh token issued to the client. */ @JsonbProperty("refresh_token") private String refreshToken; /** * OPTIONAL. The scope of the access request as described by Section 3.3. The * requested scope MUST NOT include any scope not originally granted by the * resource owner, and if omitted is treated as equal to the scope originally * granted by the resource owner. */ @JsonbTypeAdapter(JsonStringCollectionAdapter.class) private Collection<String> scope; public RefreshTokenRequest() { this.grantType = refreshToken; } /** * Construct a new TokenRequest REFRESH instance. * <p> * The refresh token is included for regular OAuth 2.0 reasons, so that the * client can get a new access token when the old one expires without * involving explicit user authentication again. * <p> * The using application must set the SCOPE. * * @param client_id the client id * @param refresh_token the previously issued token (if any) * @return a RefreshTokenRequest instance with no scope. */ public static RefreshTokenRequest getInstance(String client_id, String refresh_token) { RefreshTokenRequest tr = new RefreshTokenRequest(); tr.setGrantType(REFRESH_TOKEN); tr.setClientId(client_id); tr.setRefreshToken(refresh_token); return tr; } /** * Create a new instance of this type and set field values from the provided * input configuration. * * @param multivaluedMap a MultivaluedMap instance * @return a new class instance * @throws java.lang.Exception on mv-map parse error */ public static RefreshTokenRequest fromMultivaluedMap(MultivaluedMap<String, String> multivaluedMap) throws Exception { return OauthUtility.fromMultivaluedMap(multivaluedMap, RefreshTokenRequest.class); } /** * Create a new instance of this type and set field values from the provided * input configuration. * * @param urlEncodedString a URL encoded string * @return the class instance * @throws Exception on error */ public static RefreshTokenRequest fromUrlEncodedString(String urlEncodedString) throws Exception { return OauthUtility.fromUrlEncodedString(urlEncodedString, RefreshTokenRequest.class); } //<editor-fold defaultstate="collapsed" desc="Getter and Setter"> public String getGrantType() { return grantType; } public void setGrantType(String grantType) { this.grantType = grantType; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getRefreshToken() { return refreshToken; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public Collection<String> getScope() { if (scope == null) { scope = new HashSet<>(); } return scope; } public void setScope(Collection<String> scope) { this.scope = scope; } public void addScope(String scope) { getScope().add(scope); }//</editor-fold> //<editor-fold defaultstate="collapsed" desc="Equals and Hashcode"> @Override public int hashCode() { int hash = 3; hash = 31 * hash + Objects.hashCode(this.grantType); hash = 31 * hash + Objects.hashCode(this.clientId); hash = 31 * hash + Objects.hashCode(this.refreshToken); hash = 31 * hash + Objects.hashCode(this.scope); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RefreshTokenRequest other = (RefreshTokenRequest) obj; if (!Objects.equals(this.grantType, other.grantType)) { return false; } if (!Objects.equals(this.clientId, other.clientId)) { return false; } if (!Objects.equals(this.refreshToken, other.refreshToken)) { return false; } if (!this.getScope().containsAll(other.getScope())) { return false; } return other.getScope().containsAll(this.getScope()); }//</editor-fold> }
37.120301
120
0.674499
da49e6698e24d6153d64429d26c93395b6abedca
23,700
package com.kovaciny.linemonitorbot; import static com.kovaciny.linemonitorbot.MainActivity.DEBUG; import java.beans.PropertyChangeEvent; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Locale; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.LightingColorFilter; import android.os.Bundle; import android.os.Vibrator; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.kovaciny.helperfunctions.HelperFunction; import com.kovaciny.primexmodel.PrimexModel; import com.kovaciny.primexmodel.Product; import com.kovaciny.primexmodel.Skid; import com.kovaciny.primexmodel.WorkOrder; public class SkidTimesFragment extends Fragment implements OnClickListener, ViewEventResponder { private Button mBtn_enterProduct; private ImageButton mImgBtn_cancelAlarm; private Button mBtn_calculateTimes; private Button mBtn_goByHeight; private Button mBtn_rollMath; private ImageButton mBtn_skidNumberUp; private ImageButton mBtn_totalSkidsUp; private ImageButton mImgBtn_launchSkidsList; private EditText mEdit_currentSkidNumber; private EditText mEdit_currentCount; private EditText mEdit_totalCountPerSkid; private EditText mEdit_numSkidsInJob; private TextView mLbl_productType; private TextView mLbl_skidFinishTime; private TextView mTxt_skidFinishTime; private TextView mLbl_jobFinishTime; private TextView mTxt_jobFinishTime; private TextView mLbl_skidStartTime; private TextView mTxt_skidStartTime; private TextView mLbl_timePerSkid; private TextView mTxt_timePerSkid; private TextView mLbl_productsPerMinute; private TextView mTxt_productsPerMinute; private TextView mLbl_totalProducts; private TextView mLbl_products; private TextView mLbl_timeToMaxson; private TextView mTxt_timeToMaxson; private SkidFinishedBroadcastReceiver mAlarmReceiver; private List<Skid<Product>> mSkidList; private List<EditText> mEditableGroup; private List<TextView> mTimesDisplayList; private List<TextView> mTimesDisplayLabelsList; private long mMillisPerSkid; private String mProductUnits = DEFAULT_PRODUCT_UNITS; private String mProductGrouping = DEFAULT_PRODUCT_GROUPING; public static final int MAXIMUM_NUMBER_OF_SKIDS = 200; public static final String DEFAULT_PRODUCT_UNITS = "Sheets"; public static final String DEFAULT_PRODUCT_GROUPING = "Skid"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAlarmReceiver = new SkidFinishedBroadcastReceiver(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.skid_times_fragment, container, false); //set up editTexts mEdit_numSkidsInJob = (EditText) rootView.findViewById(R.id.edit_num_skids_in_job); mEdit_currentSkidNumber = (EditText) rootView.findViewById(R.id.edit_skid_number); mEdit_currentCount = (EditText) rootView.findViewById(R.id.edit_current_count); mEdit_totalCountPerSkid = (EditText) rootView.findViewById(R.id.edit_total_sheets_per_skid); mEditableGroup = new ArrayList<EditText>(); ViewGroup dataEntryGroup = (RelativeLayout) rootView.findViewById(R.id.rl_data_entry_group); for (int i = 0, n = dataEntryGroup.getChildCount(); i < n; i++) { View nextChild = dataEntryGroup.getChildAt(i); if (nextChild instanceof EditText) { mEditableGroup.add((EditText)nextChild); } } //set up buttons mBtn_skidNumberUp = (ImageButton) rootView.findViewById(R.id.btn_skid_number_up); mBtn_skidNumberUp.setOnClickListener(this); mBtn_skidNumberUp.setColorFilter(new LightingColorFilter(0xFF99DDFF, 0xFF0000FF)); mBtn_totalSkidsUp = (ImageButton) rootView.findViewById(R.id.btn_total_skids_up); mBtn_totalSkidsUp.setOnClickListener(this); mBtn_totalSkidsUp.setColorFilter(new LightingColorFilter(0xFF99DDFF, 0xFF0000FF)); mBtn_enterProduct = (Button) rootView .findViewById(R.id.btn_enter_product); mBtn_enterProduct.setOnClickListener(this); mBtn_enterProduct.getBackground().setColorFilter(new LightingColorFilter(0xFF99DDFF, 0xFF0000FF)); mImgBtn_cancelAlarm = (ImageButton) rootView.findViewById(R.id.imgbtn_cancel_alarm); mImgBtn_cancelAlarm.setOnClickListener(this); mImgBtn_launchSkidsList = (ImageButton) rootView.findViewById(R.id.imgbtn_launch_skids_list); mImgBtn_launchSkidsList.setOnClickListener((MainActivity)getActivity()); mImgBtn_launchSkidsList.setVisibility(ImageButton.VISIBLE); mBtn_calculateTimes = (Button) rootView.findViewById(R.id.btn_get_times); mBtn_calculateTimes.setOnClickListener(this); mBtn_calculateTimes.getBackground().setColorFilter(new LightingColorFilter(0xFF99DDFF,0xFF0000FF)); mBtn_goByHeight = (Button) rootView.findViewById(R.id.btn_go_by_height); mBtn_goByHeight.setOnClickListener(this); mBtn_rollMath = (Button) rootView.findViewById(R.id.btn_roll_math); mBtn_rollMath.setOnClickListener((MainActivity) getActivity()); //set up textViews mTxt_timePerSkid = (TextView) rootView.findViewById(R.id.txt_time_per_skid); mTxt_jobFinishTime = (TextView) rootView.findViewById(R.id.txt_job_finish_time); mTxt_timeToMaxson = (TextView) rootView.findViewById(R.id.txt_time_to_maxson); mTxt_productsPerMinute = (TextView) rootView.findViewById(R.id.txt_products_per_minute); mTxt_skidStartTime = (TextView) rootView.findViewById(R.id.txt_skid_start_time); mTxt_skidFinishTime = (TextView) rootView.findViewById(R.id.txt_skid_finish_time); mTimesDisplayList = Arrays.asList(new TextView[]{mTxt_timePerSkid, mTxt_jobFinishTime, mTxt_timeToMaxson, mTxt_productsPerMinute, mTxt_skidStartTime, mTxt_skidFinishTime}); mLbl_skidFinishTime = (TextView) rootView.findViewById(R.id.lbl_skid_finish_time); mLbl_jobFinishTime = (TextView) rootView.findViewById(R.id.lbl_job_finish_time); mLbl_skidStartTime = (TextView) rootView.findViewById(R.id.lbl_skid_start_time); mLbl_timePerSkid = (TextView) rootView.findViewById(R.id.lbl_time_per_skid); mLbl_productsPerMinute = (TextView) rootView.findViewById(R.id.lbl_products_per_minute); mLbl_timeToMaxson = (TextView) rootView.findViewById(R.id.lbl_time_to_maxson); mTimesDisplayLabelsList = Arrays.asList(new TextView[] {mLbl_skidFinishTime, mLbl_jobFinishTime, mLbl_skidStartTime, mLbl_timePerSkid, mLbl_productsPerMinute, mLbl_timeToMaxson}); mLbl_products = (TextView) rootView.findViewById(R.id.lbl_products); mLbl_productType = (TextView) rootView.findViewById(R.id.lbl_product_type); //restore saved state SharedPreferences settings = this.getActivity().getPreferences(Context.MODE_PRIVATE); boolean visible = settings.getBoolean("cancelAlarmVisible", false); String tps = settings.getString("timePerSkid", ""); String ppm = settings.getString("productsPerMinute", ""); String jft = settings.getString("jobFinishTime", ""); String ttm = settings.getString("timeToMaxson", ""); String sst = settings.getString("skidStartTime", ""); String sft = settings.getString("skidFinishTime", ""); if (visible) { mImgBtn_cancelAlarm.setVisibility(Button.VISIBLE); } else mImgBtn_cancelAlarm.setVisibility(Button.INVISIBLE); mTxt_timePerSkid.setText(tps); mTxt_productsPerMinute.setText(ppm); mTxt_jobFinishTime.setText(jft); mTxt_timeToMaxson.setText(ttm); mTxt_skidStartTime.setText(sst); mTxt_skidFinishTime.setText(sft); return rootView; } public List<Skid<Product>> getSkidList() { return mSkidList; } public void setSkidList(List<Skid<Product>> skidList) { this.mSkidList = skidList; } @Override public void onClick(View v) { DialogController dialogController = new DialogController((MainActivity)getActivity()); switch (v.getId()) { case (R.id.btn_skid_number_up): HelperFunction.hideKeyboard(getActivity()); HelperFunction.incrementEditText(mEdit_currentSkidNumber); if (Double.valueOf(mEdit_currentSkidNumber.getText().toString()) > Math.ceil(Double.valueOf(mEdit_numSkidsInJob.getText().toString()))) { //it's OK for this to be higher than a fractional number of skids HelperFunction.incrementEditText(mEdit_numSkidsInJob); } for (EditText ett : mEditableGroup) { ett.clearFocus(); } break; case (R.id.btn_total_skids_up): HelperFunction.hideKeyboard(getActivity()); HelperFunction.incrementEditText(mEdit_numSkidsInJob); mEdit_numSkidsInJob.clearFocus(); for (EditText ett : mEditableGroup) { ett.clearFocus(); } break; case (R.id.btn_enter_product): mBtn_enterProduct.setError(null); for (EditText et : mEditableGroup) { et.clearFocus(); } dialogController.showEnterProductDialog(); break; case (R.id.btn_go_by_height): int updatedTotalSheets = Skid.DEFAULT_SHEET_COUNT; if (mEdit_totalCountPerSkid.getText().length() > 0) { updatedTotalSheets = Integer.valueOf(mEdit_totalCountPerSkid.getText().toString()); } dialogController.showGoByHeightDialog(updatedTotalSheets); break; case (R.id.imgbtn_cancel_alarm): cancelAlarm(); Toast.makeText(getActivity(), getResources().getString(R.string.toast_alarm_canceled), Toast.LENGTH_SHORT).show(); break; case (R.id.btn_get_times): //supply default values if (mEdit_currentCount.getText().length() == 0) { mEdit_currentCount.setText("0"); } if (mEdit_currentSkidNumber.getText().length() == 0) { mEdit_currentSkidNumber.setText("1"); } String currentSkidNumText = mEdit_currentSkidNumber.getText().toString(); if (mEdit_numSkidsInJob.getText().length() == 0 ) { mEdit_numSkidsInJob.setText(currentSkidNumText); } if (mEdit_numSkidsInJob.getText().toString() == "0") { mEdit_numSkidsInJob.setText("1"); } if (mEdit_totalCountPerSkid.getText().length() == 0) { mEdit_totalCountPerSkid.setText("0"); } Integer currentSkidNum = Integer.valueOf(currentSkidNumText); Double totalSkids = Double.valueOf(mEdit_numSkidsInJob.getText().toString()); if (currentSkidNum > Math.ceil(totalSkids)) { mEdit_numSkidsInJob.setText(currentSkidNumText); } BigDecimal fractionalSkid = new BigDecimal(totalSkids).remainder(BigDecimal.ONE); if (fractionalSkid.compareTo(BigDecimal.ZERO) != 0) { int wholeSkids = (int) Math.ceil(totalSkids); if (currentSkidNum == wholeSkids) { BigDecimal fractionalSheetCount = fractionalSkid.multiply(new BigDecimal(mEdit_totalCountPerSkid.getText().toString())); String roundedString = String.valueOf(fractionalSheetCount.toBigInteger()); mEdit_totalCountPerSkid.setText(roundedString); mEdit_numSkidsInJob.setText(String.valueOf(wholeSkids)); } } //Process the entries only if all the necessary ones are filled. Iterator<EditText> itr = mEditableGroup.iterator(); boolean validInputs = true; int currentCount = Integer.valueOf(mEdit_currentCount.getText().toString()); int totalCount = Integer.valueOf(mEdit_totalCountPerSkid.getText().toString()); if (currentCount > totalCount) { mEdit_currentCount.setError(getString(R.string.error_current_greater_than_total)); validInputs = false; } if (totalCount == 0) { mEdit_totalCountPerSkid.setError(getString(R.string.error_need_nonzero)); validInputs = false; } if (Double.valueOf(mEdit_numSkidsInJob.getText().toString()) > MAXIMUM_NUMBER_OF_SKIDS) { mEdit_numSkidsInJob.setError(getString(R.string.error_over_maximum_skids).replace("%1", String.valueOf(MAXIMUM_NUMBER_OF_SKIDS))); validInputs = false; } while (itr.hasNext()) { EditText et = itr.next(); if ( et.getText().toString().trim().equals("") ) { et.setError(getString(R.string.error_empty_field)); validInputs = false; } } if (validInputs) { HelperFunction.hideKeyboard(getActivity()); mBtn_enterProduct.setError(null); try { dialogController.updateSkidData( Integer.valueOf(mEdit_currentSkidNumber.getText().toString()), Integer.valueOf(mEdit_currentCount.getText().toString()), Integer.valueOf(mEdit_totalCountPerSkid.getText().toString()), Double.valueOf(mEdit_numSkidsInJob.getText().toString()) ); } catch (IllegalStateException e) { if (e.getCause().getMessage().equals(PrimexModel.ERROR_NO_PRODUCT_SELECTED)) { mBtn_enterProduct.setError(getString(R.string.prompt_need_product)); } else { throw e; } } for (EditText ett : mEditableGroup) { ett.setError(null); ett.clearFocus(); } } break; } } public void onetimeTimer(View v, long interval) { Context context = getActivity(); if (mAlarmReceiver != null) { mAlarmReceiver.setOnetimeTimer(context, interval); } else { Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show(); } mImgBtn_cancelAlarm.setVisibility(Button.VISIBLE); } public void repeatingTimer(View v, long trigger, long interval) { Context context = getActivity(); if (mAlarmReceiver != null) { mAlarmReceiver.setRepeatingTimer(context, trigger, interval); } else { Toast.makeText(context, "Alarm is null", Toast.LENGTH_SHORT).show(); } mImgBtn_cancelAlarm.setVisibility(Button.VISIBLE); } public void cancelAlarm() { Context context = getActivity(); Vibrator vib = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vib.vibrate(new long[]{0,10},-1); vib.cancel(); Intent intent = new Intent(context, SkidFinishedBroadcastReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); pi.cancel(); mImgBtn_cancelAlarm.setVisibility(Button.INVISIBLE); } public void modelPropertyChange (PropertyChangeEvent event) { String propertyName = event.getPropertyName(); Object newProperty = event.getNewValue(); if (propertyName == PrimexModel.PRODUCT_CHANGE_EVENT) { if (newProperty == null) { mProductUnits = DEFAULT_PRODUCT_UNITS; mProductGrouping = DEFAULT_PRODUCT_GROUPING; mBtn_goByHeight.setVisibility(Button.GONE); mBtn_rollMath.setVisibility(Button.GONE); mBtn_calculateTimes.setEnabled(false); mBtn_enterProduct.getBackground().setColorFilter(new LightingColorFilter(0xFF99DDFF, 0xFF0000FF)); mBtn_enterProduct.setTextAppearance(getActivity(), R.style.Button); mBtn_enterProduct.setText(getString(R.string.btn_enter_product_text)); } else { Product p = (Product)newProperty; mProductUnits = HelperFunction.capitalizeFirstChar(p.getUnits()); mProductGrouping = HelperFunction.capitalizeFirstChar(p.getGrouping()); if (p.hasStacks()) { mBtn_goByHeight.setVisibility(Button.VISIBLE); mBtn_rollMath.setVisibility(Button.GONE); } else { mBtn_goByHeight.setVisibility(Button.GONE); mBtn_rollMath.setVisibility(Button.VISIBLE); } mBtn_calculateTimes.setEnabled(true); mBtn_enterProduct.setText(p.getFormattedDimensions()); mBtn_enterProduct.getBackground().clearColorFilter(); mBtn_enterProduct.setTextAppearance(getActivity(), R.style.Button_Minor); } updateLabels(); } else if (propertyName == PrimexModel.PRODUCTS_PER_MINUTE_CHANGE_EVENT) { if ( (newProperty == null) || ((Double)newProperty <= 0) ) { mTxt_productsPerMinute.setText(""); mLbl_productsPerMinute.setVisibility(TextView.INVISIBLE); } else { mTxt_productsPerMinute.setText(String.valueOf(newProperty)); mLbl_productsPerMinute.setVisibility(TextView.VISIBLE); } } else if (propertyName == PrimexModel.CURRENT_SKID_FINISH_TIME_CHANGE_EVENT) { if (newProperty == null) { mTxt_skidFinishTime.setText(""); mLbl_skidFinishTime.setVisibility(TextView.INVISIBLE); mImgBtn_cancelAlarm.setVisibility(ImageButton.GONE); } else { Date roundedTimeForDisplay = HelperFunction.toNearestWholeMinute((Date)newProperty); SimpleDateFormat formatter; formatter = new SimpleDateFormat("h:mm a", Locale.US); //drops seconds String formattedTime = formatter.format(roundedTimeForDisplay); mTxt_skidFinishTime.setText(formattedTime); mLbl_skidFinishTime.setVisibility(TextView.VISIBLE); mImgBtn_cancelAlarm.setVisibility(ImageButton.VISIBLE); //set alarm long alarmLeadTime = (long) (1.5 * HelperFunction.ONE_MINUTE_IN_MILLIS); //TODO Date curDate = new Date(); long timeNow = curDate.getTime(); long timeThen = ((Date)newProperty).getTime(); Long triggerAtMillis = timeThen - timeNow - alarmLeadTime; if (triggerAtMillis > 0) { SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity()); Boolean repeatPref = sharedPref.getBoolean("repeating_timer", false); if (repeatPref) { repeatingTimer( mTxt_skidFinishTime, triggerAtMillis, mMillisPerSkid ); } else { onetimeTimer(mTxt_skidFinishTime, triggerAtMillis); } } } } else if (propertyName == PrimexModel.JOB_FINISH_TIME_CHANGE_EVENT) { if (newProperty == null) { mTxt_jobFinishTime.setText(""); mLbl_jobFinishTime.setVisibility(TextView.INVISIBLE); mImgBtn_launchSkidsList.setVisibility(ImageButton.INVISIBLE); } else { Date roundedTimeForDisplay = HelperFunction.toNearestWholeMinute((Date)newProperty); SimpleDateFormat formatter3 = new SimpleDateFormat("h:mm a E", Locale.US); //"Pace time": Don't show the day of the week if it's before 6 am the next day. Calendar finishDate = new GregorianCalendar(Locale.US); finishDate.setTime(roundedTimeForDisplay); Calendar today = Calendar.getInstance(Locale.US); today.add(Calendar.DAY_OF_MONTH, 1); today.set(Calendar.HOUR_OF_DAY, 6); today.set(Calendar.MINUTE, 0); if (finishDate.before(today)) { formatter3 = new SimpleDateFormat("h:mm a", Locale.US); } mTxt_jobFinishTime.setText(formatter3.format(roundedTimeForDisplay)); mLbl_jobFinishTime.setVisibility(TextView.VISIBLE); mImgBtn_launchSkidsList.setVisibility(ImageButton.VISIBLE); } } else if (propertyName == PrimexModel.CURRENT_SKID_START_TIME_CHANGE_EVENT) { if (newProperty == null) { mTxt_skidStartTime.setText(""); mLbl_skidStartTime.setVisibility(TextView.INVISIBLE); } else { SimpleDateFormat formatter2 = new SimpleDateFormat("h:mm a", Locale.US); String formattedTime2 = formatter2.format((Date)newProperty); mTxt_skidStartTime.setText(formattedTime2); mLbl_skidStartTime.setVisibility(TextView.VISIBLE); } } else if (propertyName == PrimexModel.MINUTES_PER_SKID_CHANGE_EVENT) { if ((newProperty == null) || ((Double)newProperty <= 0) ) { mTxt_timePerSkid.setText(""); mLbl_timePerSkid.setVisibility(TextView.INVISIBLE); } else { long minutes = Math.round((Double)newProperty); mMillisPerSkid = minutes * HelperFunction.ONE_MINUTE_IN_MILLIS; mTxt_timePerSkid.setText( HelperFunction.formatMinutesAsHours(minutes) ); mLbl_timePerSkid.setVisibility(TextView.VISIBLE); } } else if (propertyName == PrimexModel.NUMBER_OF_SKIDS_CHANGE_EVENT) { String number = new DecimalFormat("#.###").format(newProperty); mEdit_numSkidsInJob.setText(number); } else if (propertyName == PrimexModel.NUMBER_OF_TABLE_SKIDS_CHANGE_EVENT) { } else if (propertyName == PrimexModel.SKID_CHANGE_EVENT) { Skid<?> skid = (Skid<?>)newProperty; //TODO check if null, clear the fields mEdit_currentSkidNumber.setText(String.valueOf(skid.getSkidNumber())); mEdit_currentCount.setText(String.valueOf(skid.getCurrentItems())); mEdit_totalCountPerSkid.setText(String.valueOf(skid.getTotalItems())); } else if (propertyName == PrimexModel.SECONDS_TO_MAXSON_CHANGE_EVENT) { Long timeToMaxson = (Long)newProperty; if (!(timeToMaxson > 0l)) { mTxt_timeToMaxson.setText(""); mLbl_timeToMaxson.setVisibility(TextView.INVISIBLE); mTxt_timeToMaxson.setVisibility(TextView.GONE); } else { mTxt_timeToMaxson.setText( HelperFunction.formatSecondsAsMinutes(timeToMaxson) ); mLbl_timeToMaxson.setVisibility(TextView.VISIBLE); mTxt_timeToMaxson.setVisibility(TextView.VISIBLE); } } else if (propertyName == PrimexModel.NEW_WORK_ORDER_EVENT) { for (TextView tv : mTimesDisplayList) { tv.setText(""); } for (TextView lbl : mTimesDisplayLabelsList) { lbl.setVisibility(TextView.INVISIBLE); } } else if (propertyName == PrimexModel.SELECTED_WO_CHANGE_EVENT) { WorkOrder wo = (WorkOrder)newProperty; Skid<Product> skid = wo.getSelectedSkid(); mEdit_currentSkidNumber.setText(String.valueOf(skid.getSkidNumber())); mBtn_goByHeight.setText(getString(R.string.btn_go_by_height_text)); } } private void updateLabels() { mLbl_productType.setText(mProductGrouping + ":"); mLbl_productsPerMinute.setText(mProductUnits + " per minute"); mLbl_products.setText(mProductUnits + ":"); mLbl_skidFinishTime.setText(mProductGrouping + " finish"); mLbl_skidStartTime.setText(mProductGrouping + " start"); mLbl_timePerSkid.setText("Time per " + mProductGrouping.toLowerCase(Locale.getDefault())); } @Override public void onSaveInstanceState(Bundle outState) { //save the user's current state super.onSaveInstanceState(outState); } /* (non-Javadoc) * @see android.support.v4.app.Fragment#onPause() */ @Override public void onPause() { SharedPreferences settings = this.getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); boolean visible = false; if (mImgBtn_cancelAlarm.getVisibility() == Button.VISIBLE) { visible = true; } editor.putBoolean("cancelAlarmVisible", visible); editor.putString("timePerSkid", mTxt_timePerSkid.getText().toString()); editor.putString("productsPerMinute", mTxt_productsPerMinute.getText().toString()); editor.putString("jobFinishTime", mTxt_jobFinishTime.getText().toString()); editor.putString("timeToMaxson", mTxt_timeToMaxson.getText().toString()); editor.putString("skidStartTime", mTxt_skidStartTime.getText().toString()); editor.putString("skidFinishTime", mTxt_skidFinishTime.getText().toString()); // Commit the edits! editor.commit(); super.onPause(); } }
41.217391
135
0.733586
682b2b5e09afdea24866b7b5ac91250b2fc3996b
3,847
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.auth0.client; import org.osgi.service.component.annotations.Component; import org.wso2.carbon.apimgt.api.model.ConfigurationDto; import org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @Component( name = "auth0.configuration.component", immediate = true, service = KeyManagerConnectorConfiguration.class ) public class Auth0ConnectorConfiguration implements KeyManagerConnectorConfiguration { @Override public String getImplementation() { return Auth0OAuthClient.class.getName(); } @Override public String getJWTValidator() { return null; } @Override public List<ConfigurationDto> getConnectionConfigurations() { List<ConfigurationDto> configurationDtoList = new ArrayList<>(); configurationDtoList .add(new ConfigurationDto(Auth0Constants.CLIENT_ID, "Client ID", "input", "Client ID of Service Application", "", true, false, Collections.emptyList(), false)); configurationDtoList .add(new ConfigurationDto(Auth0Constants.CLIENT_SECRET, "Client Secret", "input", "Client Secret of Service Application", "", true, true, Collections.emptyList(), false)); configurationDtoList.add(new ConfigurationDto(Auth0Constants.AUDIENCE, "Audience", "input", "Audience of the Admin API", "https://[tenant].[region].auth0.com/api/v2/", true, false, Collections.emptyList(), false)); return configurationDtoList; } @Override public List<ConfigurationDto> getApplicationConfigurations() { List<ConfigurationDto> configurationDtoList = new ArrayList<>(); configurationDtoList.add(new ConfigurationDto("app_type", "Application Type", "select", "Type of the application to create", "regular_web", false, false, Arrays.asList("regular_web", "native", "spa", "non_interactive"), false)); configurationDtoList.add(new ConfigurationDto("token_endpoint_auth_method", "Token Endpoint Authentication Method", "select", "How to Authenticate Token Endpoint", "client_secret_basic", true, true, Arrays.asList("client_secret_basic", "client_secret_post"), false)); configurationDtoList.add(new ConfigurationDto("audience_of_api", "Audience of the API", "text", "The audience of the API which intended to use this application", "", true, false, Collections.emptyList(), false)); return configurationDtoList; } @Override public String getType() { return Auth0Constants.AUTH0_TYPE; } @Override public String getDisplayName() { return Auth0Constants.AUTH0_DISPLAY_NAME; } @Override public String getDefaultScopesClaim() { return Auth0Constants.SCOPE; } @Override public String getDefaultConsumerKeyClaim() { return Auth0Constants.AZP; } }
38.858586
99
0.676891
0b9ae7340794bac337c41fe059d5177395263ccf
1,267
package com.fmi.bytecode.annotations.gui.businesslogic.model.export; import java.io.File; import java.util.List; public class ExportModel { private String fileName; private String fileDir; private String xslLocation; private List<SaveUnit> units; private File exportFile; private File xslFile; public ExportModel(String fileName, String fileDir, String xslLocation, List<SaveUnit> units) throws ExportException { this.fileName = fileName; this.fileDir = fileDir; this.xslLocation = xslLocation; this.units = units; init(); } public File getExportFile() { return exportFile; } //TODO: private void init() throws ExportException { String fileFullPath = fileDir + File.separator + fileName; exportFile = new File(fileFullPath); if (xslLocation != null) { xslFile = new File(xslLocation); if (!xslFile.exists()) { throw new ExportException("Invalid xsl file location\r\n" + xslLocation); } } } public List<SaveUnit> getUnits() { return units; } public String getXslLocation() { return xslLocation; } }
24.365385
89
0.610103
d4ba340d94d697ce672a2a4b105a0e5d3f7df847
4,582
package androidx.constraintlayout.motion.widget; import android.content.Context; import android.util.Log; import android.util.Xml; import androidx.constraintlayout.widget.ConstraintAttribute; import androidx.constraintlayout.widget.ConstraintLayout; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; public class KeyFrames { private static final String TAG = "KeyFrames"; public static final int UNSET = -1; static HashMap<String, Constructor<? extends Key>> sKeyMakers; private HashMap<Integer, ArrayList<Key>> mFramesMap = new HashMap<>(); static { HashMap<String, Constructor<? extends Key>> hashMap = new HashMap<>(); sKeyMakers = hashMap; try { hashMap.put("KeyAttribute", KeyAttributes.class.getConstructor(new Class[0])); sKeyMakers.put("KeyPosition", KeyPosition.class.getConstructor(new Class[0])); sKeyMakers.put("KeyCycle", KeyCycle.class.getConstructor(new Class[0])); sKeyMakers.put("KeyTimeCycle", KeyTimeCycle.class.getConstructor(new Class[0])); sKeyMakers.put("KeyTrigger", KeyTrigger.class.getConstructor(new Class[0])); } catch (NoSuchMethodException e) { Log.e(TAG, "unable to load", e); } } private void addKey(Key key) { if (!this.mFramesMap.containsKey(Integer.valueOf(key.mTargetId))) { this.mFramesMap.put(Integer.valueOf(key.mTargetId), new ArrayList<>()); } this.mFramesMap.get(Integer.valueOf(key.mTargetId)).add(key); } public KeyFrames(Context context, XmlPullParser xmlPullParser) { Key key; Exception e; Key key2 = null; try { int eventType = xmlPullParser.getEventType(); while (eventType != 1) { if (eventType == 2) { String name = xmlPullParser.getName(); if (sKeyMakers.containsKey(name)) { try { key = (Key) sKeyMakers.get(name).newInstance(new Object[0]); try { key.load(context, Xml.asAttributeSet(xmlPullParser)); addKey(key); } catch (Exception e2) { e = e2; } } catch (Exception e3) { key = key2; e = e3; Log.e(TAG, "unable to create ", e); key2 = key; eventType = xmlPullParser.next(); } key2 = key; } else if (!(!name.equalsIgnoreCase("CustomAttribute") || key2 == null || key2.mCustomConstraints == null)) { ConstraintAttribute.parse(context, xmlPullParser, key2.mCustomConstraints); } } else if (eventType == 3) { if ("KeyFrameSet".equals(xmlPullParser.getName())) { return; } } eventType = xmlPullParser.next(); } } catch (XmlPullParserException e4) { e4.printStackTrace(); } catch (IOException e5) { e5.printStackTrace(); } } public void addFrames(MotionController motionController) { ArrayList<Key> arrayList = this.mFramesMap.get(Integer.valueOf(motionController.mId)); if (arrayList != null) { motionController.addKeys(arrayList); } ArrayList<Key> arrayList2 = this.mFramesMap.get(-1); if (arrayList2 != null) { Iterator<Key> it = arrayList2.iterator(); while (it.hasNext()) { Key next = it.next(); if (next.matches(((ConstraintLayout.LayoutParams) motionController.mView.getLayoutParams()).constraintTag)) { motionController.addKey(next); } } } } static String name(int i, Context context) { return context.getResources().getResourceEntryName(i); } public Set<Integer> getKeys() { return this.mFramesMap.keySet(); } public ArrayList<Key> getKeyFramesForView(int i) { return this.mFramesMap.get(Integer.valueOf(i)); } }
39.5
129
0.557835
6addf7255ab41f9d1564c51339b27fc7ac8bcb00
471
/* * Copyright (c) 2012-2015 iWave Software LLC * All Rights Reserved */ package com.emc.sa.service.windows.tasks; public class AddDiskToCluster extends WindowsExecutionTask<String> { private final String diskId; public AddDiskToCluster(String diskId) { this.diskId = diskId; provideDetailArgs(diskId); } @Override public String executeTask() throws Exception { return getTargetSystem().addDiskToCluster(diskId); } }
23.55
68
0.70276
62c8351f7ee7a8b4e0b2eed97f6b407e08dd61ea
3,636
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.classloader; import com.google.common.base.Charsets; import com.google.common.hash.HashCode; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.gradle.internal.classpath.ClassPath; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; public class DefaultHashingClassLoaderFactory extends DefaultClassLoaderFactory implements HashingClassLoaderFactory { private final ClassPathSnapshotter snapshotter; private final Map<ClassLoader, HashCode> hashCodes = new WeakHashMap<ClassLoader, HashCode>(); public DefaultHashingClassLoaderFactory(ClassPathSnapshotter snapshotter) { this.snapshotter = snapshotter; } @Override protected ClassLoader doCreateClassLoader(ClassLoader parent, ClassPath classPath) { ClassLoader classLoader = super.doCreateClassLoader(parent, classPath); hashCodes.put(classLoader, calculateClassLoaderHash(classPath)); return classLoader; } @Override protected ClassLoader doCreateFilteringClassLoader(ClassLoader parent, FilteringClassLoader.Spec spec) { ClassLoader classLoader = super.doCreateFilteringClassLoader(parent, spec); hashCodes.put(classLoader, calculateFilterSpecHash(spec)); return classLoader; } @Override public ClassLoader createChildClassLoader(ClassLoader parent, ClassPath classPath, HashCode overrideHashCode) { HashCode hashCode = overrideHashCode != null ? overrideHashCode : calculateClassLoaderHash(classPath); ClassLoader classLoader = super.doCreateClassLoader(parent, classPath); hashCodes.put(classLoader, hashCode); return classLoader; } @Override public HashCode getHash(ClassLoader classLoader) { return hashCodes.get(classLoader); } private HashCode calculateClassLoaderHash(ClassPath classPath) { return snapshotter.snapshot(classPath).getStrongHash(); } private static HashCode calculateFilterSpecHash(FilteringClassLoader.Spec spec) { Hasher hasher = Hashing.md5().newHasher(); addToHash(hasher, spec.getClassNames()); addToHash(hasher, spec.getPackageNames()); addToHash(hasher, spec.getPackagePrefixes()); addToHash(hasher, spec.getResourcePrefixes()); addToHash(hasher, spec.getResourceNames()); addToHash(hasher, spec.getDisallowedClassNames()); addToHash(hasher, spec.getDisallowedPackagePrefixes()); return hasher.hash(); } private static void addToHash(Hasher hasher, Set<String> items) { int count = items.size(); hasher.putInt(count); if (count == 0) { return; } String[] sortedItems = items.toArray(new String[count]); Arrays.sort(sortedItems); for (String item : sortedItems) { hasher.putInt(0); hasher.putString(item, Charsets.UTF_8); } } }
37.875
118
0.718647
c79e9233cbd3f6ba5770b5a03dd4e9d9f4452394
6,026
package net.simplifiedlearning.simplifiedcoding.Activities; import android.content.Intent; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import net.simplifiedlearning.simplifiedcoding.R; import net.simplifiedlearning.simplifiedcoding.Webservices.ApiInterface; import net.simplifiedlearning.simplifiedcoding.Webservices.ServiceGenerator; import okhttp3.MultipartBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import static android.content.ContentValues.TAG; public class ReportEdit extends AppCompatActivity { private int reportId; private String name; private String description; private String patient_name; private int patient_age; private int patient_height; private int patient_weight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_report_edit); Toolbar toolbar = findViewById(R.id.edit_report_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Bundle extras = getIntent().getExtras(); if (extras != null) { int id = extras.getInt("report_id"); reportId = id; name = extras.getString("name"); ((TextView) findViewById(R.id.edit_report_name)).setText(name); description = extras.getString("description"); ((TextView) findViewById(R.id.edit_report_description)).setText(description); patient_name = extras.getString("patient_name"); ((TextView) findViewById(R.id.edit_report_patient_name)).setText(patient_name); patient_age = extras.getInt("patient_age"); ((TextView) findViewById(R.id.edit_report_patient_age)).setText(String.valueOf(patient_age)); patient_height = extras.getInt("patient_height"); ((TextView) findViewById(R.id.edit_report_patient_height)).setText(String.valueOf(patient_height)); patient_weight = extras.getInt("patient_weight"); ((TextView) findViewById(R.id.edit_report_patient_weight)).setText(String.valueOf(patient_weight)); } String arr[]={ "Type of report", "Report type 1", "Report type 2", "Report type 3"}; Spinner spin = findViewById(R.id.spinner3); ArrayAdapter<String> adapter = new ArrayAdapter<>( this, android.R.layout.simple_spinner_item, arr ); adapter.setDropDownViewResource( android.R.layout.simple_list_item_single_choice ); spin.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_report_edit, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // app icon in action bar clicked; go home finish(); return true; case R.id.edit_report_save: // app icon in action bar clicked; go home updateReport(); Intent resultIntent = new Intent(); resultIntent.putExtra("result", 1); setResult(ReportEdit.RESULT_OK, resultIntent); finish(); return true; default: return super.onOptionsItemSelected(item); } } private void updateReport() { ApiInterface apiInterface = ServiceGenerator.createService(ApiInterface.class); MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); builder.addFormDataPart("report_id", String.valueOf(this.reportId)); builder.addFormDataPart("name", ((TextView) findViewById(R.id.edit_report_name)).getText().toString()); builder.addFormDataPart("description", ((TextView) findViewById(R.id.edit_report_description)).getText().toString()); builder.addFormDataPart("patient_name", ((TextView) findViewById(R.id.edit_report_patient_name)).getText().toString()); builder.addFormDataPart("patient_age", ((TextView) findViewById(R.id.edit_report_patient_age)).getText().toString()); builder.addFormDataPart("patient_height", ((TextView) findViewById(R.id.edit_report_patient_height)).getText().toString()); builder.addFormDataPart("patient_weight", ((TextView) findViewById(R.id.edit_report_patient_weight)).getText().toString()); builder.addFormDataPart("apicall", "patch"); MultipartBody requestBody = builder.build(); Call<ResponseBody> call = apiInterface.updateReport(requestBody); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { if(response.isSuccessful()){ Toast.makeText(ReportEdit.this, "Report updated successfully", Toast.LENGTH_SHORT).show(); Log.e(TAG, response.body().toString()); } else { Log.e(TAG, response.message()); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Toast.makeText(ReportEdit.this, t.getMessage(), Toast.LENGTH_SHORT).show(); Log.e(TAG, t.getMessage()); } }); } }
41.273973
131
0.664122
2fad049dfe7dceb1773ffacbccedc4a7aed3dd8c
1,763
package io.swagger; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.io.IOException; import org.testng.annotations.Test; import io.swagger.models.ModelImpl; import io.swagger.models.properties.ObjectProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.StringProperty; import io.swagger.util.Json; public class ObjectPropertyTest { @Test (description = "convert a model with object properties") public void readModelWithObjectProperty() throws IOException { String json = "{" + " \"properties\":{" + " \"id\":{" + " \"type\":\"string\"" + " }," + " \"someObject\":{" + " \"type\":\"object\"," + " \"x-foo\": \"vendor x\"," + " \"properties\":{" + " \"innerId\":{" + " \"type\":\"string\"" + " }" + " }" + " }" + " }" + "}"; ModelImpl model = Json.mapper().readValue(json, ModelImpl.class); Property p = model.getProperties().get("someObject"); assertTrue(p instanceof ObjectProperty); ObjectProperty op = (ObjectProperty) p; Property sp = op.getProperties().get("innerId"); assertTrue(sp instanceof StringProperty); assertTrue(op.getVendorExtensions() != null); assertNotNull(op.getVendorExtensions().get("x-foo")); assertEquals(op.getVendorExtensions().get("x-foo"), "vendor x"); } }
34.568627
73
0.532615
d355b20b68253e420ac8cbb918eb4815cc60b72b
2,374
package uk.offtopica.monerocore.blockchain; import java.util.Arrays; import java.util.Objects; public class BlockHeader { private final byte majorVersion; private final byte minorVersion; private final long timestamp; private final byte[] prevHash; private final byte[] nonce; public BlockHeader(byte majorVersion, byte minorVersion, long timestamp, byte[] prevHash, byte[] nonce) { this.majorVersion = majorVersion; this.minorVersion = minorVersion; this.timestamp = timestamp; this.prevHash = Objects.requireNonNull(prevHash); this.nonce = Objects.requireNonNull(nonce); if (prevHash.length != 32) { throw new IllegalArgumentException("prevHash be 32 bytes"); } if (nonce.length != 4) { throw new IllegalArgumentException("nonce must be 4 bytes"); } } public byte getMajorVersion() { return majorVersion; } public byte getMinorVersion() { return minorVersion; } public long getTimestamp() { return timestamp; } public byte[] getPrevHash() { return prevHash; } public byte[] getNonce() { return nonce; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BlockHeader blockHeader = (BlockHeader) o; return majorVersion == blockHeader.majorVersion && minorVersion == blockHeader.minorVersion && timestamp == blockHeader.timestamp && Arrays.equals(prevHash, blockHeader.prevHash) && Arrays.equals(nonce, blockHeader.nonce); } @Override public int hashCode() { int result = Objects.hash(majorVersion, minorVersion, timestamp); result = 31 * result + Arrays.hashCode(prevHash); result = 31 * result + Arrays.hashCode(nonce); return result; } @Override public String toString() { return "BlockHeader{" + "majorVersion=" + majorVersion + ", minorVersion=" + minorVersion + ", timestamp=" + timestamp + ", prevHash=" + Arrays.toString(prevHash) + ", nonce=" + Arrays.toString(nonce) + '}'; } }
29.675
76
0.590564
813aca833b0825e5e0c6e5405cfae2325385115e
885
package assignment; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; /** * A {@link Button} that accepts and draws text content which is essentially a {@link Label}. * @author I.A */ public final class TextButton extends Button { /** * The {@link Label} to place inside of this button. */ public final Label label; /** * The color of this button. */ public Color color; /** * Creates a new {@link TextButton}. */ public TextButton(String textContent, int size, Rectangle rectangle, Runnable action) { super(rectangle, action); this.label = new Label(textContent, size, new Vector2(rectangle.x, rectangle.y)); } @Override public void draw(DrawVisitor visitor) { // TODO missing code here } @Override public void update(UpdateVisitor visitor) { // TODO missing code here } }
21.585366
93
0.706215
fe28c11cd7b66ed12eb2f36810684ad650d05734
11,831
/** Generated Model - DO NOT CHANGE */ package de.metas.marketing.base.model; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for MKTG_Campaign_ContactPerson * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_MKTG_Campaign_ContactPerson extends org.compiere.model.PO implements I_MKTG_Campaign_ContactPerson, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 870930022L; /** Standard Constructor */ public X_MKTG_Campaign_ContactPerson (Properties ctx, int MKTG_Campaign_ContactPerson_ID, String trxName) { super (ctx, MKTG_Campaign_ContactPerson_ID, trxName); /** if (MKTG_Campaign_ContactPerson_ID == 0) { setMKTG_Campaign_ContactPerson_ID (0); setMKTG_Campaign_ID (0); setMKTG_ContactPerson_ID (0); } */ } /** Load Constructor */ public X_MKTG_Campaign_ContactPerson (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public org.compiere.model.I_AD_User getAD_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setAD_User(org.compiere.model.I_AD_User AD_User) { set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User); } /** Set Ansprechpartner. @param AD_User_ID User within the system - Internal or Business Partner Contact */ @Override public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class); } @Override public void setC_BPartner(org.compiere.model.I_C_BPartner C_BPartner) { set_ValueFromPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class, C_BPartner); } /** Set Geschäftspartner. @param C_BPartner_ID Bezeichnet einen Geschäftspartner */ @Override public void setC_BPartner_ID (int C_BPartner_ID) { throw new IllegalArgumentException ("C_BPartner_ID is virtual column"); } /** Get Geschäftspartner. @return Bezeichnet einen Geschäftspartner */ @Override public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Location getC_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Location_ID, org.compiere.model.I_C_Location.class); } @Override public void setC_Location(org.compiere.model.I_C_Location C_Location) { set_ValueFromPO(COLUMNNAME_C_Location_ID, org.compiere.model.I_C_Location.class, C_Location); } /** Set Anschrift. @param C_Location_ID Adresse oder Anschrift */ @Override public void setC_Location_ID (int C_Location_ID) { throw new IllegalArgumentException ("C_Location_ID is virtual column"); } /** Get Anschrift. @return Adresse oder Anschrift */ @Override public int getC_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** * DeactivatedOnRemotePlatform AD_Reference_ID=540861 * Reference name: Yes_No_Unknown */ public static final int DEACTIVATEDONREMOTEPLATFORM_AD_Reference_ID=540861; /** YES = Y */ public static final String DEACTIVATEDONREMOTEPLATFORM_YES = "Y"; /** NO = N */ public static final String DEACTIVATEDONREMOTEPLATFORM_NO = "N"; /** UNKNOWN = Unknown */ public static final String DEACTIVATEDONREMOTEPLATFORM_UNKNOWN = "Unknown"; /** Set Platformseitig deaktiviert. @param DeactivatedOnRemotePlatform Platformseitig deaktiviert */ @Override public void setDeactivatedOnRemotePlatform (java.lang.String DeactivatedOnRemotePlatform) { throw new IllegalArgumentException ("DeactivatedOnRemotePlatform is virtual column"); } /** Get Platformseitig deaktiviert. @return Platformseitig deaktiviert */ @Override public java.lang.String getDeactivatedOnRemotePlatform () { return (java.lang.String)get_Value(COLUMNNAME_DeactivatedOnRemotePlatform); } /** Set eMail. @param EMail EMail-Adresse */ @Override public void setEMail (java.lang.String EMail) { throw new IllegalArgumentException ("EMail is virtual column"); } /** Get eMail. @return EMail-Adresse */ @Override public java.lang.String getEMail () { return (java.lang.String)get_Value(COLUMNNAME_EMail); } /** Set Synchronisierungstatus-Detail. @param LastSyncDetailMessage Synchronisierungstatus-Detail */ @Override public void setLastSyncDetailMessage (java.lang.String LastSyncDetailMessage) { throw new IllegalArgumentException ("LastSyncDetailMessage is virtual column"); } /** Get Synchronisierungstatus-Detail. @return Synchronisierungstatus-Detail */ @Override public java.lang.String getLastSyncDetailMessage () { return (java.lang.String)get_Value(COLUMNNAME_LastSyncDetailMessage); } /** Set Zuletzt auf Platform hochgeladen. @param LastSyncOfLocalToRemote Zuletzt auf Platform hochgeladen */ @Override public void setLastSyncOfLocalToRemote (java.sql.Timestamp LastSyncOfLocalToRemote) { throw new IllegalArgumentException ("LastSyncOfLocalToRemote is virtual column"); } /** Get Zuletzt auf Platform hochgeladen. @return Zuletzt auf Platform hochgeladen */ @Override public java.sql.Timestamp getLastSyncOfLocalToRemote () { return (java.sql.Timestamp)get_Value(COLUMNNAME_LastSyncOfLocalToRemote); } /** Set Zuletzt von Platform runtergeladen. @param LastSyncOfRemoteToLocal Zuletzt von Platform runtergeladen */ @Override public void setLastSyncOfRemoteToLocal (java.sql.Timestamp LastSyncOfRemoteToLocal) { throw new IllegalArgumentException ("LastSyncOfRemoteToLocal is virtual column"); } /** Get Zuletzt von Platform runtergeladen. @return Zuletzt von Platform runtergeladen */ @Override public java.sql.Timestamp getLastSyncOfRemoteToLocal () { return (java.sql.Timestamp)get_Value(COLUMNNAME_LastSyncOfRemoteToLocal); } /** Set Letzter Synchronisierungsstatus. @param LastSyncStatus Letzter Synchronisierungsstatus */ @Override public void setLastSyncStatus (java.lang.String LastSyncStatus) { throw new IllegalArgumentException ("LastSyncStatus is virtual column"); } /** Get Letzter Synchronisierungsstatus. @return Letzter Synchronisierungsstatus */ @Override public java.lang.String getLastSyncStatus () { return (java.lang.String)get_Value(COLUMNNAME_LastSyncStatus); } /** Set MKTG_Campaign_ContactPerson. @param MKTG_Campaign_ContactPerson_ID MKTG_Campaign_ContactPerson */ @Override public void setMKTG_Campaign_ContactPerson_ID (int MKTG_Campaign_ContactPerson_ID) { if (MKTG_Campaign_ContactPerson_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Campaign_ContactPerson_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Campaign_ContactPerson_ID, Integer.valueOf(MKTG_Campaign_ContactPerson_ID)); } /** Get MKTG_Campaign_ContactPerson. @return MKTG_Campaign_ContactPerson */ @Override public int getMKTG_Campaign_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Campaign_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_Campaign getMKTG_Campaign() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_Campaign_ID, de.metas.marketing.base.model.I_MKTG_Campaign.class); } @Override public void setMKTG_Campaign(de.metas.marketing.base.model.I_MKTG_Campaign MKTG_Campaign) { set_ValueFromPO(COLUMNNAME_MKTG_Campaign_ID, de.metas.marketing.base.model.I_MKTG_Campaign.class, MKTG_Campaign); } /** Set MKTG_Campaign. @param MKTG_Campaign_ID MKTG_Campaign */ @Override public void setMKTG_Campaign_ID (int MKTG_Campaign_ID) { if (MKTG_Campaign_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Campaign_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Campaign_ID, Integer.valueOf(MKTG_Campaign_ID)); } /** Get MKTG_Campaign. @return MKTG_Campaign */ @Override public int getMKTG_Campaign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Campaign_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class); } @Override public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson) { set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson); } /** Set MKTG_ContactPerson. @param MKTG_ContactPerson_ID MKTG_ContactPerson */ @Override public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_Platform getMKTG_Platform() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class); } @Override public void setMKTG_Platform(de.metas.marketing.base.model.I_MKTG_Platform MKTG_Platform) { set_ValueFromPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class, MKTG_Platform); } /** Set MKTG_Platform. @param MKTG_Platform_ID MKTG_Platform */ @Override public void setMKTG_Platform_ID (int MKTG_Platform_ID) { throw new IllegalArgumentException ("MKTG_Platform_ID is virtual column"); } /** Get MKTG_Platform. @return MKTG_Platform */ @Override public int getMKTG_Platform_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { throw new IllegalArgumentException ("Name is virtual column"); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Externe Datensatz-ID. @param RemoteRecordId Externe Datensatz-ID */ @Override public void setRemoteRecordId (java.lang.String RemoteRecordId) { throw new IllegalArgumentException ("RemoteRecordId is virtual column"); } /** Get Externe Datensatz-ID. @return Externe Datensatz-ID */ @Override public java.lang.String getRemoteRecordId () { return (java.lang.String)get_Value(COLUMNNAME_RemoteRecordId); } }
29.140394
147
0.76494
e55b567a2aeea95acccd53b4c2aad576c2336bc8
1,199
package consumingrest; public class Drink { private String idDrink; private String strDrink; private String strAlcoholic; private String strInstructions; public Drink() { } public String getIdDrink() { return idDrink; } public void setIdDrink(String idDrink) { this.idDrink = idDrink; } public String getStrDrink() { return strDrink; } public void setStrDrink(String strDrink) { this.strDrink = strDrink; } public String getStrAlcoholic() { return strAlcoholic; } public void setStrAlcoholic(String strAlcoholic) { this.strAlcoholic = strAlcoholic; } public String getStrInstructions() { return strInstructions; } public void setStrInstructions(String strInstructions) { this.strInstructions = strInstructions; } @Override public String toString() { return "Drink{" + "idDrink='" + idDrink + '\'' + ", strDrink='" + strDrink + '\'' + ", strAlcoholic='" + strAlcoholic + '\'' + ", strInstructions='" + strInstructions + '\'' + '}'; } }
21.8
64
0.577148
4aade7964f68978d56367a65efc3f74f4a7091f0
572
package com.springboot; import brave.sampler.Sampler; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; @SpringBootApplication @EnableEurekaClient public class DynamoDbApplication { @Bean public Sampler defaultSampler() { return Sampler.ALWAYS_SAMPLE; } public static void main(String[] args) { SpringApplication.run(DynamoDbApplication.class, args); } }
27.238095
68
0.805944
7226357523b292ecdb05c1ef090789fbf33447a8
1,518
package me.ianhe.security.config; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Component; import java.util.Collection; /** * @author iHelin * @date 2018-12-17 17:16 */ @Component public class UrlAccessDecisionManager implements AccessDecisionManager { @Override public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, AuthenticationException { for (ConfigAttribute configAttribute : collection) { //当前请求需要的权限 String needRole = configAttribute.getAttribute(); //当前用户所具有的权限 Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (GrantedAuthority authority : authorities) { if (authority.getAuthority().equals(needRole)) { return; } } } throw new AccessDeniedException("权限不足!"); } @Override public boolean supports(ConfigAttribute configAttribute) { return true; } @Override public boolean supports(Class<?> aClass) { return true; } }
33
159
0.713439
c0643f3e1e6f64919a56cae3324e60a6e2eecb33
283
package com.dic.common.tool; import lombok.AllArgsConstructor; import lombok.Data; import lombok.experimental.Accessors; import java.util.List; @Data @AllArgsConstructor @Accessors(chain = true) public class SimplePageInfo<T> { private List<T> list; private Long total; }
17.6875
37
0.770318
1d0bd33c60429aba7dc205a50aa7f4b3535bd0d7
442
package uk.gov.pay.webhooks.message.resource; import io.swagger.v3.oas.annotations.media.Schema; import java.util.List; public record WebhookMessageSearchResponse(@Schema(example = "120") int total, @Schema(example = "100") int count, @Schema(example = "1") int page, List<WebhookMessageResponse> results) { }
36.833333
82
0.542986