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
8cee6709b5d66cd4d389babac9c6b7c662002ddb
93
package com.xcode.onboarding; public interface OnFinishLastPage { void onNext(); }
15.5
36
0.709677
22a497f22f419742e86a586075fddb69447987e9
2,655
/* * Copyright 2017 University of Ulm * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.uniulm.omi.cloudiator.domain; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Iterator; import java.util.Optional; import org.hamcrest.Matchers; import org.junit.Test; /** * Created by daniel on 17.01.17. */ public class LocationScopeTest { @Test public void testParents() { assertThat(LocationScope.PROVIDER.parents(), empty()); assertThat(LocationScope.HOST.parents(), Matchers.hasItem(LocationScope.ZONE)); assertThat(LocationScope.HOST.parents(), Matchers.hasItem(LocationScope.REGION)); assertThat(LocationScope.HOST.parents(), Matchers.hasItem(LocationScope.PROVIDER)); } @Test public void testParent() { assertThat(LocationScope.PROVIDER.parent(), is(equalTo(Optional.empty()))); assertThat(LocationScope.HOST.parent().get(), is(equalTo(LocationScope.ZONE))); } @Test public void testHasParent() { assertFalse(LocationScope.PROVIDER.hasParent(LocationScope.ZONE)); assertTrue(LocationScope.HOST.hasParent(LocationScope.REGION)); assertTrue(LocationScope.REGION.hasParent(LocationScope.PROVIDER)); assertTrue(LocationScope.ZONE.hasParent(LocationScope.PROVIDER)); assertFalse(LocationScope.ZONE.hasParent(LocationScope.HOST)); } @Test public void testIteration() { final Iterator hostIterator = LocationScope.HOST.iterator(); assertTrue(hostIterator.hasNext()); assertThat(hostIterator.next(), is(equalTo(LocationScope.HOST))); assertTrue(hostIterator.hasNext()); assertThat(hostIterator.next(), is(equalTo(LocationScope.ZONE))); assertTrue(hostIterator.hasNext()); assertThat(hostIterator.next(), is(equalTo(LocationScope.REGION))); assertTrue(hostIterator.hasNext()); assertThat(hostIterator.next(), is(equalTo(LocationScope.PROVIDER))); assertFalse(hostIterator.hasNext()); } }
35.878378
87
0.755556
bd97e13398ffb03b0f4de641100816740be7488b
1,001
import java.util.Arrays; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.UnaryOperator; class MySample { <T> MySample bar(Function<String, T> f) {return null;} <T> MySample bar(BiFunction<String, String, T> f) {return null;} private void example() { update(x -> x.bar(y -> { var e1 = Optional.of(y); var e2 = Optional.of(e1.orElse(y + 1)); var e3 = Optional.of(e2.orElse(y + 1)); var e4 = Optional.of(e3.orElse(y + 1)); var e5 = Optional.of(e4.orElse(y + 1)); var e6 = Optional.of(e5.orElse(y + 1)); var e7 = Optional.of(e6.orElse(y + 1)); var e8 = Optional.of(e7.orElse(y + 1)); var e9 = Optional.of(e8.orElse(y + 1)); var e10 = Optional.of(e9.orElse(y + 1)); return Arrays.as<caret>List(e1, e2); })); } void update(UnaryOperator<MySample> u) { } }
37.074074
68
0.566434
4f7f7e85bc50fecae636f441f335051ea0b6f674
1,212
package engine.nutritionists; import engine.cake.AbstractCake; import engine.Entity; import log.IGLog; import java.awt.*; import java.util.List; public class CakeChaserNutritionist extends AbstractNutritionist { public CakeChaserNutritionist(int nbLifes) { super(nbLifes); } public CakeChaserNutritionist(float speed, float direction, int nbLifes) { super(speed, direction, nbLifes); } public CakeChaserNutritionist(Point startPosition, Dimension size, float speed, float direction, int nbLifes) { super(startPosition, size, speed, direction, nbLifes); } @Override public void nextStep() { List<Entity> cakes = getManager().getCakes(); if (cakes.isEmpty()) { /* no cake, do nothing ?? */ } else { Entity closestCakes = getClosestEntity(cakes); moveToEntity(closestCakes); } } @Override public boolean effect(Entity e) { if (e instanceof AbstractCake) { IGLog.info("CakeChaser, effect: cake."); return getLife() <= 0; } return getLife() <= 0; } @Override public int scoreValue() { return 5; } }
24.24
115
0.623762
44acdad3094d0dbb7dca6594399d6844d2abf5e3
598
package no.priv.garshol.duke.genetic; /** * Represents a pair of records. */ public class Pair { public String id1; public String id2; public int counter; public boolean[] believers; // which configurations think this pair is correct public Pair(String id1, String id2) { this.id1 = id1; this.id2 = id2; } public boolean equals(Object other) { if (!(other instanceof Pair)) return false; Pair opair = (Pair) other; return opair.id1.equals(id1) && opair.id2.equals(id2); } public int hashCode() { return id1.hashCode() + id2.hashCode(); } }
19.933333
80
0.655518
3e2ae012f4357324b92f447f4bc73db3d11c30e4
375
package org.javamaster.b2c.mail; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author yudong * @date 2020/8/14 */ @SpringBootApplication public class B2cMailApplication { public static void main(String[] args) { SpringApplication.run(B2cMailApplication.class, args); } }
20.833333
68
0.757333
934c3db5e3e609e462e156263f3042b9dccc57c5
1,837
/******************************************************************************* * Copyright 2021 Konexios, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.konexios.acn.client.model; import com.konexios.acs.client.model.StatusModelAbstract; public abstract class UserResponseModelAbstract<T extends UserResponseModelAbstract<T>> extends StatusModelAbstract<T> { private static final long serialVersionUID = 8024113461039476969L; private UserModel user; public T withUser(UserModel user) { setUser(user); return self(); } public UserModel getUser() { return user; } public void setUser(UserModel user) { this.user = user; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((user == null) ? 0 : user.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; UserResponseModelAbstract<?> other = (UserResponseModelAbstract<?>) obj; if (user == null) { if (other.user != null) return false; } else if (!user.equals(other.user)) return false; return true; } }
29.15873
120
0.649973
d38c01bd1fb649653eeaa4e9fef69e275222dbcc
5,270
package net.minecraft.world.storage; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.AnvilConverterException; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IProgressUpdate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; public class SaveFormatOld implements ISaveFormat { private static final Logger logger = LogManager.getLogger(); public final File savesDirectory; public SaveFormatOld(File p_i2147_1_) { if (!p_i2147_1_.exists()) { p_i2147_1_.mkdirs(); } savesDirectory = p_i2147_1_; } @Override @SideOnly(Side.CLIENT) public String func_154333_a() { return "Old Format"; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override @SideOnly(Side.CLIENT) public List getSaveList() throws AnvilConverterException { ArrayList arraylist = new ArrayList(); for (int i = 0; i < 5; ++i) { String s = "World" + (i + 1); WorldInfo worldinfo = getWorldInfo(s); if (worldinfo != null) { arraylist.add(new SaveFormatComparator(s, "", worldinfo.getLastTimePlayed(), worldinfo.getSizeOnDisk(), worldinfo.getGameType(), false, worldinfo.isHardcoreModeEnabled(), worldinfo.areCommandsAllowed())); } } return arraylist; } @Override public void flushCache() { } @Override public WorldInfo getWorldInfo(String p_75803_1_) { File file1 = new File(savesDirectory, p_75803_1_); if (!file1.exists()) return null; else { File file2 = new File(file1, "level.dat"); NBTTagCompound nbttagcompound; NBTTagCompound nbttagcompound1; if (file2.exists()) { try { nbttagcompound = CompressedStreamTools.readCompressed(new FileInputStream(file2)); nbttagcompound1 = nbttagcompound.getCompoundTag("Data"); return new WorldInfo(nbttagcompound1); } catch (Exception exception1) { logger.error("Exception reading " + file2, exception1); } } file2 = new File(file1, "level.dat_old"); if (file2.exists()) { try { nbttagcompound = CompressedStreamTools.readCompressed(new FileInputStream(file2)); nbttagcompound1 = nbttagcompound.getCompoundTag("Data"); return new WorldInfo(nbttagcompound1); } catch (Exception exception) { logger.error("Exception reading " + file2, exception); } } return null; } } @Override @SideOnly(Side.CLIENT) public void renameWorld(String p_75806_1_, String p_75806_2_) { File file1 = new File(savesDirectory, p_75806_1_); if (file1.exists()) { File file2 = new File(file1, "level.dat"); if (file2.exists()) { try { NBTTagCompound nbttagcompound = CompressedStreamTools.readCompressed(new FileInputStream(file2)); NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Data"); nbttagcompound1.setString("LevelName", p_75806_2_); CompressedStreamTools.writeCompressed(nbttagcompound, new FileOutputStream(file2)); } catch (Exception exception) { exception.printStackTrace(); } } } } @Override @SideOnly(Side.CLIENT) public boolean func_154335_d(String p_154335_1_) { File file1 = new File(savesDirectory, p_154335_1_); if (file1.exists()) return false; else { try { file1.mkdir(); file1.delete(); return true; } catch (Throwable throwable) { logger.warn("Couldn't make new level", throwable); return false; } } } @Override public boolean deleteWorldDirectory(String p_75802_1_) { File file1 = new File(savesDirectory, p_75802_1_); if (!file1.exists()) return true; else { logger.info("Deleting level " + p_75802_1_); for (int i = 1; i <= 5; ++i) { logger.info("Attempt " + i + "..."); if (deleteFiles(file1.listFiles())) { break; } logger.warn("Unsuccessful in deleting contents."); if (i < 5) { try { Thread.sleep(500L); } catch (InterruptedException interruptedexception) { } } } return file1.delete(); } } protected static boolean deleteFiles(File[] p_75807_0_) { for (int i = 0; i < p_75807_0_.length; ++i) { File file1 = p_75807_0_[i]; logger.debug("Deleting " + file1); if (file1.isDirectory() && !deleteFiles(file1.listFiles())) { logger.warn("Couldn't delete directory " + file1); return false; } if (!file1.delete()) { logger.warn("Couldn't delete file " + file1); return false; } } return true; } @Override public ISaveHandler getSaveLoader(String p_75804_1_, boolean p_75804_2_) { return new SaveHandler(savesDirectory, p_75804_1_, p_75804_2_); } @Override @SideOnly(Side.CLIENT) public boolean func_154334_a(String p_154334_1_) { return false; } @Override public boolean isOldMapFormat(String p_75801_1_) { return false; } @Override public boolean convertMapFormat(String p_75805_1_, IProgressUpdate p_75805_2_) { return false; } @Override @SideOnly(Side.CLIENT) public boolean canLoadWorld(String p_90033_1_) { File file1 = new File(savesDirectory, p_90033_1_); return file1.isDirectory(); } }
24.858491
107
0.698292
ace2379abfa44ba4ddcfebf04558179bdce8b616
13,506
package com.iographica.core; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.SystemTray; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import com.iographica.events.IEventDispatcher; import com.iographica.events.IEventHandler; import com.iographica.events.IOEvent; import com.iographica.gui.ControlPanel; import com.iographica.gui.FrontPanel; import com.iographica.gui.IOGraphMenu; import com.iographica.gui.IOGraphTrayIcon; import com.iographica.gui.MainFrame; import com.iographica.gui.SecondaryControls; import com.iographica.gui.TimerPanel; import com.iographica.gui.WelcomePanel; import com.iographica.tracker.TrackManager; import com.iographica.utils.debug.gui.DebugConsole; import com.iographica.utils.debug.gui.GraphicProfiler; public class IOGraph implements IEventHandler, IEventDispatcher { private static IOGraph _instance = null; public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } new IOGraph(); } private MainFrame _mainFrame; private TrackManager _trackManager; private ControlPanel _controlPanel; private SnapshotManager _snapshotManager; private TimerPanel _timerPanel; private SecondaryControls _secondaryControls; private PanelSwaper _panelSwaper; private TrackingTimer _trackingTimer; private FrontPanel _frontPanel; private WelcomePanel _welcomePanel; private IOGraphMenu _menu; private IOGraphTrayIcon _trayIcon; private UpdateChecker _updateChecker; private ArrayList<IEventHandler> _eventHandlers; private boolean _snapShotTaken; private boolean _isSnapshotMultimonitored; public IOGraph() { ImageIO.setUseCache(false); // TODO: Show recording status on icon. _instance = this; Data.getPrefs(); Data.isOSX = System.getProperty("os.name").toLowerCase().indexOf("mac") != -1; Data.isTrayGUI = Data.isOSX && SystemTray.isSupported(); _mainFrame = new MainFrame(); Data.mainFrame = _mainFrame; _updateChecker = new UpdateChecker(); GraphicsDevice s = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); if (!Data.isTrayGUI) { _mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { exitCheck(); } }); } _trackingTimer = new TrackingTimer(); _trackManager = new TrackManager(); _mainFrame.get_outputPanel().add(_trackManager, 0); _snapshotManager = new SnapshotManager(_mainFrame); _snapshotManager.addEventHandler(_trackManager); _secondaryControls = new SecondaryControls(); _secondaryControls.setOpaque(false); _mainFrame.get_bottomPanel().add(_secondaryControls); _secondaryControls.setLocation(Data.MAIN_FRAME_WIDTH - _secondaryControls.getWidth(), 0); _controlPanel = new ControlPanel(); _controlPanel.addEventHandler(this); _controlPanel.setOpaque(false); _mainFrame.get_bottomPanel().add(_controlPanel); _controlPanel.setLocation(0, Data.PANEL_HEIGHT); _frontPanel = new FrontPanel(); _frontPanel.setOpaque(false); _mainFrame.get_bottomPanel().add(_frontPanel); _timerPanel = new TimerPanel(Data.TEXT_COLOR); _timerPanel.setOpaque(false); _frontPanel.add(_timerPanel); _welcomePanel = new WelcomePanel(Data.TEXT_COLOR); _welcomePanel.setOpaque(false); _frontPanel.add(_welcomePanel); _menu = new IOGraphMenu(); _trayIcon = new IOGraphTrayIcon(_mainFrame); _mainFrame.setLocation((int) ((s.getDisplayMode().getWidth() - _mainFrame.getWidth()) * .5), (int) ((s.getDisplayMode().getHeight() - _mainFrame.getHeight()) * .5)); _mainFrame.pack(); _trackManager.setup(); _mainFrame.pack(); _mainFrame.setMenuBar(_menu); _mainFrame.setVisible(true); _mainFrame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowDeactivated(java.awt.event.WindowEvent e) { _secondaryControls.focusLost(); } public void windowActivated(java.awt.event.WindowEvent e) { _secondaryControls.focusGained(); } }); _panelSwaper = new PanelSwaper(_frontPanel, _controlPanel); _updateChecker.addEventHandler(_menu); _updateChecker.addEventHandler(_trayIcon); _menu.addEventHandler(this); _menu.addEventHandler(_menu); _menu.addEventHandler(_secondaryControls); _menu.addEventHandler(_snapshotManager); _menu.addEventHandler(_updateChecker); _menu.addEventHandler(_trackManager); _menu.addEventHandler(_trackingTimer); _menu.addEventHandler(_timerPanel); _menu.addEventHandler(_welcomePanel); _menu.addEventHandler(_controlPanel); _trayIcon.addEventHandler(this); _trayIcon.addEventHandler(_panelSwaper); _trayIcon.addEventHandler(_secondaryControls); _trayIcon.addEventHandler(_trackManager); _trayIcon.addEventHandler(_trackingTimer); _trayIcon.addEventHandler(_timerPanel); _trayIcon.addEventHandler(_welcomePanel); _trayIcon.addEventHandler(_trayIcon); _snapshotManager.addEventHandler(_menu); _controlPanel.addEventHandler(this); _controlPanel.addEventHandler(_controlPanel); _controlPanel.addEventHandler(_menu); _controlPanel.addEventHandler(_trayIcon); _controlPanel.addEventHandler(_snapshotManager); _controlPanel.addEventHandler(_trackManager); _controlPanel.addEventHandler(_timerPanel); _controlPanel.addEventHandler(_trackingTimer); _secondaryControls.addEventHandler(this); _secondaryControls.addEventHandler(_panelSwaper); _secondaryControls.addEventHandler(_trackManager); _secondaryControls.addEventHandler(_trayIcon); _trackManager.addEventHandler(_trackManager); _trackManager.addEventHandler(_secondaryControls); _trackManager.addEventHandler(_trackingTimer); _trackManager.addEventHandler(_timerPanel); _trackManager.addEventHandler(_menu); _trackManager.addEventHandler(_trayIcon); _trackManager.addEventHandler(_welcomePanel); _timerPanel.addEventHandler(_trackingTimer); _timerPanel.addEventHandler(_timerPanel); _timerPanel.addEventHandler(_trackManager); _timerPanel.addEventHandler(_welcomePanel); _timerPanel.addEventHandler(_menu); _timerPanel.addEventHandler(_secondaryControls); _timerPanel.addEventHandler(_trayIcon); _trackingTimer.addEventHandler(_timerPanel); _trackingTimer.addEventHandler(_trackManager); _trackingTimer.addEventHandler(this); this.addEventHandler(_trackingTimer); this.addEventHandler(_timerPanel); this.addEventHandler(_welcomePanel); this.addEventHandler(_trackManager); this.addEventHandler(_snapshotManager); this.addEventHandler(_controlPanel); this.addEventHandler(_menu); this.addEventHandler(this); if (Data.DEBUG) { DebugConsole console; console = new DebugConsole(); console.setVisible(true); System.getProperties().list(System.out); GraphicProfiler profiler = new GraphicProfiler(); profiler.setVisible(true); _trackManager.addEventHandler(profiler); } _updateChecker.check(); } protected void exitCheck() { System.out.println("exitCheck"); if (Data.trackingTime < 60000) System.exit(0); String header = "Wait! Wait! Wait!"; int timeTreshold = 60000 * 30; String message = "Do you really wanna exit and lose all your data?"; if (Data.trackingTime > timeTreshold) message += "\nAre you sure? After " + Data.time + " of laborious tracking?"; int mt = Data.trackingTime > timeTreshold ? JOptionPane.WARNING_MESSAGE : JOptionPane.QUESTION_MESSAGE; int cd = JOptionPane.showConfirmDialog(null, message, header, JOptionPane.YES_NO_OPTION, mt, IOGraph.getIcon("DialogIcon.png")); if (cd == JOptionPane.YES_OPTION) { System.exit(0); } } public void debugExit() { _trackManager.debugExit(); _trackManager = null; _controlPanel = null; _snapshotManager = null; _timerPanel = null; _secondaryControls = null; _panelSwaper = null; _trackingTimer = null; _frontPanel = null; _welcomePanel = null; _menu = null; Data.mainFrame = null; Data.mouseTrackRecording = false; _mainFrame.dispose(); _mainFrame = null; _instance = null; System.gc(); } public void onEvent(IOEvent event) { switch (event.type) { case Data.GET_URL: WebSurfer.get(Data.WEBSITE_URL); break; case Data.MULTI_MONITOR_USAGE_CHANGED: _mainFrame.pack(); break; case Data.SYSTEM_QUIT_REQUESTED: exitCheck(); break; case Data.CHECK_FOR_UPDATES: _updateChecker.check(); break; case Data.IGNORE_MOUSE_STOPS_CHANGED: Data.prefs.putBoolean(Data.IGNORE_MOUSE_STOPS, !Data.prefs.getBoolean(Data.IGNORE_MOUSE_STOPS, false)); break; case Data.MULTI_MONITOR_USAGE_CHANGING_REQUEST: changeMultiMonitorUsage(); break; case Data.COLORFUL_SCHEME_USAGE_CHANGING_REQUEST: changeColorfulSchemeUsage(); break; case Data.BACKGROUND_USAGE_CHANGE_REQUEST: changeBackgroundUsage(); break; default: break; } } private void changeBackgroundUsage() { Data.useScreenshot = !Data.useScreenshot; if (!Data.useScreenshot) { _isSnapshotMultimonitored = Data.prefs.getBoolean(Data.USE_MULTIPLE_MONITORS, true); } else { if (_isSnapshotMultimonitored != Data.prefs.getBoolean(Data.USE_MULTIPLE_MONITORS, true)) _snapShotTaken = false; } if (!_snapShotTaken) { _snapShotTaken = true; dispatchEvent(Data.UPDATE_BACKGROUND); } dispatchEvent(Data.BACKGROUND_USAGE_CHANGED); } private void changeColorfulSchemeUsage() { if (Data.trackingTime > 0) { Data.preventControlsHiding = true; String header = "Color Scheme Switch Confirmation"; int timeTreshold = 60000 * 30; String message = "We need to reset the tracking by switching\nbetween color schemas.\nDo you really wanna start from scratch?"; if (Data.trackingTime > timeTreshold) message += "\nAre you sure? After " + Data.time + " of laborious tracking?"; int mt = Data.trackingTime > timeTreshold ? JOptionPane.WARNING_MESSAGE : JOptionPane.QUESTION_MESSAGE; int cd = JOptionPane.showConfirmDialog(null, message, header, JOptionPane.YES_NO_OPTION, mt, getIcon("DialogIcon.png")); Data.preventControlsHiding = false; if (cd != JOptionPane.YES_OPTION) return; } Data.prefs.putBoolean(Data.USE_COLOR_SCHEME, Data.requestedColorfulSchemeUsage); dispatchEvent(Data.COLOR_SCHEME_CHANGED); } private void changeMultiMonitorUsage() { if (Data.trackingTime > 0) { Data.preventControlsHiding = true; String header = "Switch Confirmation"; int timeTreshold = 60000 * 30; String message = "We need to reset the tracking by switching\nbetween single/multiple monitors.\nDo you really wanna start from scratch?"; if (Data.trackingTime > timeTreshold) message += "\nAre you sure? After " + Data.time + " of laborious tracking?"; int mt = Data.trackingTime > timeTreshold ? JOptionPane.WARNING_MESSAGE : JOptionPane.QUESTION_MESSAGE; int cd = JOptionPane.showConfirmDialog(null, message, header, JOptionPane.YES_NO_OPTION, mt, getIcon("DialogIcon.png")); Data.preventControlsHiding = false; if (cd != JOptionPane.YES_OPTION) return; } Data.prefs.putBoolean(Data.USE_MULTIPLE_MONITORS, Data.requestedMultiMonitorUsage); if (Data.useScreenshot) dispatchEvent(Data.UPDATE_BACKGROUND); dispatchEvent(Data.MULTI_MONITOR_USAGE_CHANGED); } static public ImageIcon getIcon(String filename) { URL url = _instance.getClass().getResource(Data.RESOURCE_DIRECTORY + filename); ImageIcon i; try { i = new ImageIcon(url); } catch (Exception e) { i = null; System.err.println("Can't load ImageIcon from " + filename + "."); } return i; } static public BufferedImage getBufferedImage(String filename) { BufferedImage img = null; try { URL url = _instance.getClass().getResource(Data.RESOURCE_DIRECTORY + filename); img = ImageIO.read(url); } catch (IOException e) { System.out.println("IOGraph.getBufferedImage(): " + e); } return img; } public static IOGraph getInstance() { return _instance; } public static boolean resetConfirmation() { String header = "Reset confirmation"; int timeTreshold = 60000 * 30; String message = "Do you really wanna start from scratch?"; if (Data.trackingTime > timeTreshold) message += "\nAre you sure? After " + Data.time + " of laborious tracking?"; int mt = Data.trackingTime > timeTreshold ? JOptionPane.WARNING_MESSAGE : JOptionPane.QUESTION_MESSAGE; ImageIcon icon = null; icon = getIcon("DialogIcon.png"); int cd; cd = JOptionPane.showConfirmDialog(null, message, header, JOptionPane.YES_NO_OPTION, mt, icon); if (cd == JOptionPane.YES_OPTION) { return true; } return false; } public void addEventHandler(IEventHandler handler) { if (_eventHandlers == null) { _eventHandlers = new ArrayList<IEventHandler>(); } for (IEventHandler handler2 : _eventHandlers) if (handler2.equals(handler)) return; _eventHandlers.add(handler); } private void dispatchEvent(int type) { if (_eventHandlers != null) { final IOEvent event = new IOEvent(type, this); for (IEventHandler handler : _eventHandlers) { handler.onEvent(event); } } } }
35.448819
167
0.767733
508bb9a70db26e0791ad5cdc7ed5ef17a88ec277
572
package wannabit.io.bitcv.network.res; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import wannabit.io.bitcv.model.type.Coin; public class ResKavaHarvestDeposit { @SerializedName("height") public String height; @SerializedName("result") public ArrayList<HarvestDeposit> result; public class HarvestDeposit { @SerializedName("depositor") public String depositor; @SerializedName("amount") public Coin amount; @SerializedName("type") public String type; } }
19.724138
50
0.694056
6ee3d3b240cf7986c02f713776d586bb9de3335d
5,591
/* * 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 app.metatron.discovery.domain.dataprep.teddy; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import app.metatron.discovery.domain.dataprep.teddy.exceptions.TeddyException; import static org.junit.Assert.assertEquals; /** * WrangleTest */ public class PivotTest extends TeddyTest { @BeforeClass public static void setUp() throws Exception { loadGridCsv("multi", "teddy/pivot_test_multiple_column.csv"); } private DataFrame newMultiDataFrame() throws IOException, TeddyException { DataFrame multi = new DataFrame(); multi.setByGrid(grids.get("multi"), null); multi = prepare_multi(multi); multi.show(); return multi; } @Test public void test_pivot1() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "pivot col: minute value: sum(measure) group: machine_code"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals(new Long(124), newDf.rows.get(0).get("sum_measure_00_00")); } @Test public void test_pivot2() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "pivot col: minute value: sum(measure) group: machine_code,module_code"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals(new Long(30), newDf.rows.get(0).get("sum_measure_00_00")); } @Test public void test_pivot3() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "pivot col: minute, column15 value: count(), sum(measure) group: machine_code,module_code"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals(new Long(30), newDf.rows.get(0).get("sum_measure_00_00_true")); } @Test public void test_pivot4() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "pivot col: minute, column15 value: sum(measure), count() group: machine_code,module_code"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals(new Long(30), newDf.rows.get(0).get("sum_measure_00_00_true")); } @Test public void test_pivot5() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "pivot col: minute, column15 value: sum(measure), min(measure), max(measure), count() group: machine_code"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals(new Long(32), newDf.rows.get(0).get("sum_measure_00_00_false")); } @Test public void test_pivot6() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "pivot col: minute, column15 value: sum(measure), count() group: machine_code,module_code"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals(new Long(0), newDf.rows.get(0).get("sum_measure_00_00_false")); } @Test public void test_pivot7() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "pivot col: minute, column15,column7 value: sum(measure), count() group: machine_code,module_code"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals(new Long(0), newDf.rows.get(0).get("sum_measure_00_00_false_3")); } @Test public void test_pivot8() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "pivot col: minute, column11 value: count()"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals(new Long(8), newDf.rows.get(0).get("row_count_00_00_0_0")); } @Test public void test_unpivot1() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "unpivot col: minute,column15,column7 groupEvery: 3"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals("00:00", newDf.rows.get(0).get("value1")); } @Test public void test_unpivot2() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "unpivot col: column7,column11,column16,column12 groupEvery: 1"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals("2", newDf.rows.get(0).get("value1")); } @Test public void test_unpivot3() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "unpivot col: column7 groupEvery: 1"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals("2", newDf.rows.get(0).get("value1")); } @Test public void test_unpivot4() throws IOException, TeddyException { DataFrame multi = newMultiDataFrame(); String ruleString = "unpivot col: column7"; DataFrame newDf = apply_rule(multi, ruleString); newDf.show(); assertEquals("2", newDf.rows.get(0).get("value1")); } }
34.091463
131
0.716866
6a015d624c6c3fc08b98c02ae935118a090cd2c5
20,015
package com.psddev.dari.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Debug servlet for inspecting application build information. */ @DebugFilter.Path("build") @SuppressWarnings("serial") public class BuildDebugServlet extends HttpServlet { public static final String PROPERTIES_FILE_NAME = "build.properties"; public static final String PROPERTIES_FILE = "/WEB-INF/classes/" + PROPERTIES_FILE_NAME; public static final String LIB_PATH = "/WEB-INF/lib"; /** Returns all the properties in the build file. */ public static Properties getProperties(ServletContext context) throws IOException { return getEmbeddedProperties(context, null); } /** Returns all the properties in the build file of an embedded war file. */ public static Properties getEmbeddedProperties(ServletContext context, String embeddedPath) throws IOException { Properties build = new Properties(); InputStream stream = context.getResourceAsStream((embeddedPath != null ? embeddedPath : "") + PROPERTIES_FILE); if (stream != null) { try { build.load(stream); } finally { stream.close(); } } return build; } /** Returns all the properties in the build file of an embedded jar file. */ public static Properties getEmbeddedPropertiesInJar(ServletContext context, String jarResource) throws IOException { Properties build = new Properties(); InputStream inputStream = context.getResourceAsStream(jarResource); if (inputStream != null) { try { JarInputStream jarStream = new JarInputStream(inputStream); if (jarStream != null) { try { JarEntry entry = null; while ((entry = jarStream.getNextJarEntry()) != null) { if (PROPERTIES_FILE_NAME.equals(entry.getName())) { byte[] buffer = new byte[4096]; ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(); int read = 0; while ((read = jarStream.read(buffer)) != -1) { outputBytes.write(buffer, 0, read); } InputStream propertiesFileInputStream = new ByteArrayInputStream(outputBytes.toByteArray()); if (propertiesFileInputStream != null) { try { build.load(propertiesFileInputStream); break; } finally { propertiesFileInputStream.close(); } } } } } finally { jarStream.close(); } } } finally { inputStream.close(); } } return build; } /** * Returns a descriptive label that represents the build within the * given {@code context}. */ public static String getLabel(ServletContext context) { Properties build = null; try { build = getProperties(context); } catch (IOException error) { // If the build properties can't be read, pretend it's empty so // that the default label can be returned. } if (build == null) { build = new Properties(); } return getLabel(build); } // Returns a descriptive label using the given properties. private static String getLabel(Properties properties) { String title = properties.getProperty("name"); if (ObjectUtils.isBlank(title)) { title = "Anonymous Application"; } String version = properties.getProperty("version"); if (!ObjectUtils.isBlank(version)) { title += ": " + version; } String buildNumber = properties.getProperty("buildNumber"); if (!ObjectUtils.isBlank(buildNumber)) { title += " build " + buildNumber; } return title; } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { final String buildContext = request.getParameter("context"); new DebugFilter.PageWriter(getServletContext(), request, response) { { startPage("Build Information"); writeStart("style", "type", "text/css"); write("tr.merge { color: rgba(0, 0, 0, 0.3); }"); write("td.num { text-align: right; }"); write("td:not(.wrap) { white-space: nowrap; }"); writeEnd(); writeStart("script"); write("$(document).ready(function(){"); write("$('#contextPicker').change(function() {"); write("this.form.submit();"); write("});"); write("});"); writeEnd(); Map<String, Properties> embeddedProperties = new CompactMap<String, Properties>(); @SuppressWarnings("unchecked") Set<String> paths = (Set<String>) getServletContext().getResourcePaths("/"); if (paths != null) { for (String path : paths) { if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); Properties properties = getEmbeddedProperties(getServletContext(), path); if (!properties.isEmpty()) { embeddedProperties.put(path.substring(1), properties); } } } } @SuppressWarnings("unchecked") Set<String> libJars = (Set<String>) getServletContext().getResourcePaths(LIB_PATH); for (Object jar : libJars) { Properties properties = getEmbeddedPropertiesInJar(getServletContext(), (String) jar); if (!properties.isEmpty()) { embeddedProperties.put((String) jar, properties); } } Properties build = null; if (embeddedProperties.containsKey(buildContext)) { build = embeddedProperties.get(buildContext); } else { build = getProperties(getServletContext()); } String issueSystem = build.getProperty("issueManagementSystem"); String issueUrl = build.getProperty("issueManagementUrl"); Pattern issuePattern = null; String issueUrlFormat = null; if ("JIRA".equals(issueSystem)) { String prefix = "/browse/"; int prefixAt = issueUrl.indexOf(prefix); if (prefixAt > -1) { prefixAt += prefix.length(); int slashAt = issueUrl.indexOf('/', prefixAt); String jiraId = slashAt > -1 ? issueUrl.substring(prefixAt, slashAt) : issueUrl.substring(prefixAt); issuePattern = Pattern.compile("\\Q" + jiraId + "\\E-\\d+"); issueUrlFormat = issueUrl.substring(0, prefixAt) + "%s"; } } String scmUrlFormat = null; String scmConnection = build.getProperty("scmConnection"); if (ObjectUtils.isBlank(scmConnection)) { scmConnection = build.getProperty("scmDeveloperConnection"); } if (!ObjectUtils.isBlank(scmConnection)) { if (scmConnection.startsWith("scm:git:")) { scmUrlFormat = build.getProperty("scmUrl") + "/commit/%s"; } } String commitsString = build.getProperty("gitCommits"); Map<String, List<GitCommit>> commitsMap = new CompactMap<String, List<GitCommit>>(); if (!ObjectUtils.isBlank(commitsString)) { String currRefNames = null; for (String e : StringUtils.split(commitsString, "(?m)\\s*~-~\\s*")) { GitCommit commit = new GitCommit(e, issuePattern); String refNames = commit.refNames; if (!ObjectUtils.isBlank(refNames)) { if (refNames.startsWith("(")) { refNames = refNames.substring(1); } if (refNames.endsWith(")")) { refNames = refNames.substring( 0, refNames.length() - 1); } currRefNames = refNames; } List<GitCommit> commits = commitsMap.get(currRefNames); if (commits == null) { commits = new ArrayList<GitCommit>(); commitsMap.put(currRefNames, commits); } commits.add(commit); } } writeStart("h2").writeHtml("Commits").writeEnd(); writeStart("form", "action", "", "method", "GET", "class", "form-inline"); writeHtml("For: "); writeStart("select", "style", "width:auto;", "id", "contextPicker", "name", "context", "class", "input-xlarge"); writeStart("option", "value", ""); writeHtml(getLabel(getServletContext())); writeEnd(); for (Map.Entry<String, Properties> entry : embeddedProperties.entrySet()) { writeStart("option", "value", entry.getKey(), "selected", entry.getKey().equals(buildContext) ? "selected" : null); writeHtml(getLabel(entry.getValue())); writeEnd(); } writeEnd(); writeEnd(); if (commitsMap.isEmpty()) { writeStart("p", "class", "alert"); writeHtml("Not available!"); writeEnd(); } else { int colspan = 3; writeStart("table", "class", "table table-condensed table-striped"); writeStart("thead"); writeStart("tr"); writeStart("th").writeHtml("Date").writeEnd(); if (issuePattern != null) { writeStart("th").writeHtml("Issues").writeEnd(); ++ colspan; } writeStart("th").writeHtml("Author").writeEnd(); writeStart("th").writeHtml("Subject").writeEnd(); if (scmUrlFormat != null) { writeStart("th").writeHtml("SCM").writeEnd(); ++ colspan; } writeEnd(); writeEnd(); writeStart("tbody"); for (Map.Entry<String, List<GitCommit>> entry : commitsMap.entrySet()) { writeStart("tr"); writeStart("td", "class", "wrap", "colspan", colspan); writeStart("strong").writeHtml(entry.getKey()).writeEnd(); writeEnd(); writeEnd(); for (GitCommit commit : entry.getValue()) { writeStart("tr", "class", commit.subject != null && commit.subject.startsWith("Merge branch ") ? "merge" : null); writeStart("td").writeHtml(commit.date).writeEnd(); if (issuePattern != null) { writeStart("td"); for (String issue : commit.issues) { if (issueUrlFormat != null) { writeStart("a", "href", String.format(issueUrlFormat, issue), "target", "_blank"); writeHtml(issue); writeEnd(); } else { writeHtml(issue); } writeElement("br"); } writeEnd(); } writeStart("td").writeHtml(commit.author).writeEnd(); writeStart("td", "class", "wrap").writeHtml(commit.subject).writeEnd(); if (scmUrlFormat != null) { writeStart("td"); writeStart("a", "href", String.format(scmUrlFormat, commit.hash), "target", "_blank"); writeHtml(commit.hash.substring(0, 6)); writeEnd(); writeEnd(); } writeEnd(); } } writeEnd(); writeEnd(); } writeStart("h2").writeHtml("Resources").writeEnd(); writeStart("table", "class", "table table-condensed"); writeStart("thead"); writeStart("tr"); writeStart("th").writeHtml("Path").writeEnd(); writeStart("th").writeHtml("Size (Bytes)").writeEnd(); writeStart("th").writeHtml("MD5").writeEnd(); writeEnd(); writeEnd(); writeStart("tbody"); writeResourcesOfPath("", 0, "/"); writeEnd(); writeEnd(); endPage(); } private void writeResourcesOfPath(String parentPath, int depth, String path) throws IOException { writeStart("tr"); writeStart("td", "style", "padding-left: " + (depth * 20) + "px").writeHtml(path).writeEnd(); if (path.endsWith("/")) { writeStart("td").writeEnd(); writeStart("td").writeEnd(); List<String> subPaths = new ArrayList<String>(); @SuppressWarnings("unchecked") Set<String> resourcePaths = (Set<String>) getServletContext().getResourcePaths(path); if (resourcePaths != null) { subPaths.addAll(resourcePaths); } Collections.sort(subPaths); int subDepth = depth + 1; for (String subPath : subPaths) { writeResourcesOfPath(path, subDepth, subPath); } writeEnd(); } else { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException error) { throw new IllegalStateException(error); } try { InputStream input = getServletContext().getResourceAsStream(path); if (input != null) { try { input = new DigestInputStream(input, md5); int totalBytesRead = 0; int bytesRead = 0; byte[] buffer = new byte[4096]; while ((bytesRead = input.read(buffer)) > 0) { totalBytesRead += bytesRead; } writeStart("td", "class", "num").writeObject(totalBytesRead).writeEnd(); writeStart("td"); write(StringUtils.hex(md5.digest())); writeEnd(); } finally { input.close(); } } } catch (IOException error) { writeObject(error); } writeEnd(); } } }; } private static class GitCommit { public String hash; public String author; public Date date; public String refNames; public String subject; public String body; public List<String> issues; public GitCommit(String line, Pattern issuePattern) { String[] items = StringUtils.split(line, "(?m)\\s*~\\|~\\s*"); hash = items[0]; author = items.length > 1 ? items[1] : null; if (items.length > 2) { Long timestamp = ObjectUtils.to(Long.class, items[2]); if (timestamp != null) { date = new Date(timestamp * 1000); } } refNames = items.length > 3 ? items[3] : null; subject = items.length > 4 ? items[4] : null; body = items.length > 5 ? items[5] : null; if (issuePattern != null) { issues = new ArrayList<String>(); for (String e : new String[] { subject, body }) { if (e != null) { Matcher matcher = issuePattern.matcher(e); while (matcher.find()) { issues.add(matcher.group(0)); } } } } } } }
43.796499
149
0.443018
05740faa383a6f5fa12efc9020e95f900e31c010
961
/* * Copyright(c) 2019 Nippon Telegraph and Telephone Corporation */ package msf.ecmm.emctrl.pojo.parts; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; /** * Tracking IF Information Class */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "interface") public class TrackInterface { /** IF Name */ private String name = null; /** * Generating new instance. */ public TrackInterface() { super(); } /** * Getting IF name. * * @return IF name */ public String getName() { return name; } /** * Setting IF name. * * @param name * IF name */ public void setName(String name) { this.name = name; } /* * (Non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "TrackInterface [name=" + name + "]"; } }
16.568966
63
0.627471
9ac400ce5ebaf6a044720f1fe3e618aa4b321958
8,381
package com.ikerleon.birdwmod.client.render.europe; import com.ikerleon.birdwmod.client.render.BirdBaseRenderer; import com.ikerleon.birdwmod.entity.europe.EurasianBullfinchEntity; import com.ikerleon.birdwmod.entity.europe.StellersEiderEntity; import net.minecraft.block.Material; import net.minecraft.client.render.entity.EntityRenderDispatcher; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.Entity; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.soggymustache.bookworm.client.animation.part.BookwormModelRenderer; import net.soggymustache.bookworm.client.model.CMFAnimator; import net.soggymustache.bookworm.client.model.ModelCMF; public class StellersEiderRenderer extends BirdBaseRenderer<StellersEiderEntity> { public static final ModelCMF STELLERS_EIDER = new ModelCMF(new Identifier("birdwmod", "models/entity/stellers_eider/stellers_eider.bkm")); public static final ModelCMF STELLERS_EIDER_SWIMMING = new ModelCMF(new Identifier("birdwmod", "models/entity/stellers_eider/stellers_eider_swimming.bkm")); public static final ModelCMF STELLERS_EIDER_FLYING = new ModelCMF(new Identifier("birdwmod", "models/entity/stellers_eider/stellers_eider_flying.bkm")); public static final ModelCMF STELLERS_EIDER_SLEEPING = new ModelCMF(new Identifier("birdwmod", "models/entity/stellers_eider/stellers_eider_sleeping.bkm")); public static final Identifier TEXTUREMALE = new Identifier("birdwmod" + ":textures/entity/europe/stellerseidermale.png"); public static final Identifier TEXTUREFEMALE = new Identifier("birdwmod" + ":textures/entity/europe/stellerseiderfemale.png"); public static final Identifier TEXTURECHICK = new Identifier("birdwmod" + ":textures/entity/europe/stellerseider_chick.png"); public static final Identifier TEXTUREBLINK = new Identifier("birdwmod" + ":textures/entity/europe/stellerseider_sleeping.png"); private final Identifier EIDER_RING = new Identifier("birdwmod" + ":textures/entity/rings/eider_ring.png"); public StellersEiderRenderer(EntityRenderDispatcher dispatcher) { super(dispatcher, STELLERS_EIDER, 0.15F); STELLERS_EIDER.setAnimator(StellersEiderAnimator::new); } @Override protected void scale(StellersEiderEntity entity, MatrixStack matrices, float tickDelta) { if(entity.isBaby()){ float scaleFactor= 0.3F; matrices.scale(scaleFactor, scaleFactor, scaleFactor); } else { float scaleFactor = 0.6F; matrices.scale(scaleFactor, scaleFactor, scaleFactor); } super.scale(entity, matrices, tickDelta); } @Override public Identifier getBlinkTexture(StellersEiderEntity entity) { return TEXTUREBLINK; } @Override public Identifier getRingTexture(StellersEiderEntity entity) { return EIDER_RING; } @Override public Identifier getTexture(StellersEiderEntity entity) { if(entity.isBaby()){ return TEXTURECHICK; } else { if (entity.getGender() == 0) { return TEXTUREMALE; } else { return TEXTUREFEMALE; } } } private class StellersEiderAnimator extends CMFAnimator { private final BookwormModelRenderer rightleg = this.getModel().getPartByName("rightleg"); private final BookwormModelRenderer leftleg = this.getModel().getPartByName("leftleg"); private final BookwormModelRenderer neck = this.getModel().getPartByName("neck"); private final BookwormModelRenderer body2 = this.getModel().getPartByName("body2"); private final BookwormModelRenderer head = this.getModel().getPartByName("head"); private final BookwormModelRenderer rightwing = this.getModel().getPartByName("rightwing"); private final BookwormModelRenderer leftwing = this.getModel().getPartByName("leftwing"); private final BookwormModelRenderer rightwing2 = this.getModel().getPartByName("rightwing2"); private final BookwormModelRenderer leftwing2 = this.getModel().getPartByName("leftwing2"); public StellersEiderAnimator(ModelCMF model) { super(model); } @Override public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) { super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); this.getModel().reset(); BlockPos pos = new BlockPos(entityIn.getX(), entityIn.getY() - 0.2, entityIn.getZ()); if ((entityIn instanceof StellersEiderEntity)) { StellersEiderEntity eider = (StellersEiderEntity)entityIn; float globalSpeed = 1.5f; float globalDegree = 1.25F; if(eider.isSleeping() && eider.isOnGround()){ this.getModel().interpolateToPose(StellersEiderRenderer.STELLERS_EIDER_SLEEPING, eider.timer); this.body2.pitch = MathHelper.cos(eider.age * 0.17f) * 0.05F * 1 * 0.5f + 0.25F * 0.5f; this.head.pitch = MathHelper.cos(eider.age * 0.2f) * 0.06F * 1 * 0.5f + 2.8F * 0.5f; this.rightwing.pitch = MathHelper.cos(eider.age * 0.17f) * 0.03F * -1 * 0.5f; this.leftwing.pitch = MathHelper.cos(eider.age * 0.17f) * 0.03F * -1 * 0.5f; } else { this.rightleg.pitch = MathHelper.cos(limbSwing * 0.5f * globalSpeed) * 0.5f * globalDegree * 1 * limbSwingAmount - 4f * 0.5f; this.leftleg.pitch = MathHelper.cos(limbSwing * 0.5f * globalSpeed) * 0.5f * globalDegree * -1 * limbSwingAmount - 4f * 0.5f; this.neck.pitch = MathHelper.cos(limbSwing * 0.8f * globalSpeed) * 0.05f * globalDegree * -1 * limbSwingAmount + 5.25F * 0.5f; this.body2.pitch = MathHelper.cos(limbSwing * 0.8f * globalSpeed) * 0.1f * globalDegree * -1 * limbSwingAmount + 0 * 0.5f; this.body2.pitch = MathHelper.cos(eider.age * 0.17f) * 0.05F * 1 * 0.5f + 0.25F * 0.5f; this.head.pitch = MathHelper.cos(eider.age * 0.2f) * 0.06F * 1 * 0.5f + 2.8F * 0.5f; this.rightwing.pitch = MathHelper.cos(eider.age * 0.17f) * 0.03F * -1 * 0.5f; this.leftwing.pitch = MathHelper.cos(eider.age * 0.17f) * 0.03F * -1 * 0.5f; if ((!eider.isOnGround() && !eider.isTouchingWater() && !eider.isBaby()) && entityIn.world.getBlockState(pos).getMaterial() != Material.WATER) { this.getModel().interpolateToPose(StellersEiderRenderer.STELLERS_EIDER_FLYING, eider.timer); this.rightwing.pitch = MathHelper.cos(eider.age * 0.6f * globalSpeed + 0) * 0.2f * globalDegree * -1 * 0.5f + 2.5F * 0.5f; this.leftwing.pitch = MathHelper.cos(eider.age * 0.6f * globalSpeed + 0) * 0.2f * globalDegree * -1 * 0.5f + 2.5F * 0.5f; this.rightwing.yaw = MathHelper.cos(eider.age * 0.3f * globalSpeed + 0) * 0.4f * globalDegree * -1 * 0.5f - 3F * 0.5f; this.leftwing.yaw = MathHelper.cos(eider.age * 0.3f * globalSpeed + 0) * 0.4f * globalDegree * 1 * 0.5f + 3F * 0.5f; this.rightwing2.roll = MathHelper.cos(eider.age * 0.3f * globalSpeed + 0) * 0.4f * globalDegree * 1 * 0.5f + 0 * 0.5f; this.leftwing2.roll = MathHelper.cos(eider.age * 0.3f * globalSpeed + 0) * 0.4f * globalDegree * -1 * 0.5f + 0 * 0.5f; } else if (eider.isTouchingWater() || entityIn.world.getBlockState(pos).getMaterial() == Material.WATER) { this.getModel().interpolateToPose(StellersEiderRenderer.STELLERS_EIDER_SWIMMING, eider.timer); this.rightleg.pitch = MathHelper.cos(eider.age * 0.2f * globalSpeed + 0) * 0.5f * globalDegree * -1 * 0.5f - 4 * 0.5f; this.leftleg.pitch = MathHelper.cos(eider.age * 0.2f * globalSpeed + 0) * 0.5f * globalDegree * 1 * 0.5f + -4 * 0.5f; } } } } } }
57.40411
168
0.653144
7e3e041d279305e8407932d94963f4ea4f3766ab
160
package com.tmsl.vmart.dao; import com.tmsl.vmart.model.Logistics; public interface LogisticsDAO { public Logistics getLogisticalInfo(Double distance); }
16
53
0.79375
605d1321e8dc4713c64d44d6ee55cb71f1609156
1,463
/* gnu.classpath.tools.gjdoc.SourcePositionImpl Copyright (C) 2001 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ package gnu.classpath.tools.gjdoc; import com.sun.javadoc.SourcePosition; import java.io.File; public class SourcePositionImpl implements SourcePosition { private File file; private int line; private int column; public SourcePositionImpl(File file, int line, int column) { this.file = file; this.line = line; this.column = column; } public File file() { return this.file; } public int line() { return this.line; } public int column() { return this.column; } public String toString() { return this.file + ":" + this.line; } }
23.983607
70
0.714286
766d1d52446ed5d2c97e314732a4fa27b7f479fb
972
package com.example.hackathon.myapplication.models; import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class WeatherDetails implements Serializable{ int id; @SerializedName("main") String shotDescription; @SerializedName("description") String longDescription; String icon; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getShotDescription() { return shotDescription; } public void setShotDescription(String shotDescription) { this.shotDescription = shotDescription; } public String getLongDescription() { return longDescription; } public void setLongDescription(String longDescription) { this.longDescription = longDescription; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
20.680851
60
0.664609
a01fd8550ef5faca2761e5dcf57631f83a1595f8
2,914
/* GanttProject is an opensource project management tool. Copyright (C) 2011 GanttProject team This program is free software; you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.sourceforge.ganttproject.action.task; import net.sourceforge.ganttproject.IGanttProject; import net.sourceforge.ganttproject.action.GPAction; import net.sourceforge.ganttproject.gui.UIFacade; import net.sourceforge.ganttproject.gui.UIUtil; import net.sourceforge.ganttproject.task.Task; import net.sourceforge.ganttproject.task.TaskManager; import java.awt.event.ActionEvent; import java.util.List; public class TaskNewAction extends GPAction { private final IGanttProject myProject; private final UIFacade myUiFacade; public TaskNewAction(IGanttProject project, UIFacade uiFacade) { this(project, uiFacade, IconSize.MENU); } private TaskNewAction(IGanttProject project, UIFacade uiFacade, IconSize size) { super("task.new", size.asString()); myProject = project; myUiFacade = uiFacade; } @Override public GPAction withIcon(IconSize size) { return new TaskNewAction(myProject, myUiFacade, size); } @Override public void actionPerformed(ActionEvent e) { if (calledFromAppleScreenMenu(e)) { return; } myUiFacade.getUndoManager().undoableEdit(getLocalizedDescription(), new Runnable() { @Override public void run() { List<Task> selection = getUIFacade().getTaskSelectionManager().getSelectedTasks(); if (selection.size() > 1) { return; } Task selectedTask = selection.isEmpty() ? null : selection.get(0); Task newTask = getTaskManager().newTaskBuilder() .withPrevSibling(selectedTask).withStartDate(getUIFacade().getGanttChart().getStartDate()).build(); myUiFacade.getTaskTree().startDefaultEditing(newTask); } }); } protected TaskManager getTaskManager() { return myProject.getTaskManager(); } protected UIFacade getUIFacade() { return myUiFacade; } @Override public void updateAction() { super.updateAction(); } @Override public TaskNewAction asToolbarAction() { TaskNewAction result = new TaskNewAction(myProject, myUiFacade); result.setFontAwesomeLabel(UIUtil.getFontawesomeLabel(result)); return result; } }
32.021978
111
0.743651
d522077f1e575ef2652fa60026d60ca425661d3d
317
package com.eziozhao.leafblog.common; /** * @author eziozhao * @date 2020/7/20 */ public class ExceptionCast { public static void cast(ResultCode resultCode){ throw new CustomException(resultCode); } public static void cast(String message){ throw new CustomException(message); } }
21.133333
51
0.684543
b0037bad51f2d844259c86c948bffd2a72b89065
4,852
package uk.ac.liv.mzidlib.converters; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import uk.ac.liv.unimod.CompositionT; import uk.ac.liv.unimod.ModT; import uk.ac.liv.unimod.ModificationsT; import uk.ac.liv.unimod.SpecificityT; import uk.ac.liv.unimod.UnimodT; /** * * @author jonesar */ public class ReadUnimod { private static String inputUnimod = "unimod.xml"; private List<ModT> modList; public ReadUnimod() { try { //Use the getResourceAsStream trick to read the unimod.xml file as //a classpath resource. This enables us to also distribute the unimod.xml file //inside the .jar file which simplifies usage of the solution as no extra //classpath or path configurations are needed to let the code below find //the unimod.xml file: InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(inputUnimod); UnimodT unimod = unmarshal(UnimodT.class, stream); ModificationsT mods = unimod.getModifications(); modList = mods.getMod(); /* for (ModT mod : modList) { Long id = mod.getRecordId(); String modName = mod.getTitle(); CompositionT comp = mod.getDelta(); double mass = comp.getMonoMass(); System.out.println(id + " " + modName + " " + mass); } */ } catch (JAXBException ex) { String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); String className = this.getClass().getName(); String message = "The task \"" + methodName + "\" in the class \"" + className + "\" was not completed because of " + ex.getMessage() + "." + "\nPlease see the reference guide at 04 for more information on this error. https://code.google.com/p/mzidentml-lib/wiki/CommonErrors "; System.out.println(message); } } public ModT getModByMass(double testMass, double massError, boolean isMono, char res) { List<String> residues = new ArrayList<String>(); residues.add("" + res); return getModByMass(testMass, massError, isMono, residues); } public ModT getModByMass(double testMass, double massError, boolean isMono, List<String> residues) { ModT foundMod = null; boolean isFound = false; double diffFound = 1000000.0; //Choose smallest mass difference for (ModT mod : modList) { CompositionT comp = mod.getDelta(); double mass; if (isMono) { mass = comp.getMonoMass(); } else { mass = comp.getAvgeMass(); } boolean siteMatch = false; //check if the modification is a modification that can //occur on the given site/residue for (SpecificityT spec : mod.getSpecificity()) { for (String residue : residues) { if (residue.equals("[")) { residue = "N-term"; } else if (residue.equals("]")) { residue = "C-term"; } String site = spec.getSite(); if (site.equals(residue)) { siteMatch = true; break; } } if (siteMatch) { break; } } if (mass < testMass + massError && mass > testMass - massError && siteMatch) { //Choose smallest mass difference if (Math.abs(mass - testMass) < diffFound) { //System.out.println("Error: Multiple mods found with same mass, choosi: " + testMass); foundMod = mod; diffFound = Math.abs(mass - testMass); } isFound = true; } } if (!isFound) { //System.out.println("No mod found in Unimod with mass:" + testMass + " error: " + massError + " residue: " + residues.toString()); } return foundMod; } public <T> T unmarshal(Class<T> docClass, InputStream inputStream) throws JAXBException { String packageName = docClass.getPackage().getName(); JAXBContext jc = JAXBContext.newInstance(packageName); Unmarshaller u = jc.createUnmarshaller(); @SuppressWarnings("unchecked") JAXBElement<T> doc = (JAXBElement<T>) u.unmarshal(inputStream); return doc.getValue(); } }
33.006803
158
0.559151
78c972dc2bc220c89c81bf89288b8a7592a97c59
524
package com.steven.seata.business.feign; import com.steven.seata.util.Result; import com.steven.seata.vo.MallStockVo; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; /** * @author steven * @desc * @date 2021/6/17 16:18 */ @FeignClient("stock-service") public interface StockServiceFeignClient { @PostMapping("stock/reduceStock") Result reduceStock(@RequestBody MallStockVo vo); }
24.952381
59
0.782443
0144531377041a5465244d0f899ababc238929fa
2,740
package io.github.bmhm.twitter.metricbot.web.twitter; import io.github.bmhm.twitter.metricbot.common.TwitterConfig; import io.github.bmhm.twitter.metricbot.web.events.MentionEvent; import java.io.Serializable; import java.time.Instant; import java.util.Map; import java.util.Set; import java.util.StringJoiner; import java.util.stream.Collectors; import javax.enterprise.context.Dependent; import javax.enterprise.event.Event; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import twitter4j.RateLimitStatus; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.TwitterAdapter; import twitter4j.TwitterException; import twitter4j.TwitterMethod; @Dependent public class MentionEventHandler extends TwitterAdapter implements Serializable { private static final long serialVersionUID = -7892279525267720394L; private static final Logger LOG = LoggerFactory.getLogger(MentionEventHandler.class); @Inject private Event<MentionEvent> mentionEvent; @Inject private TwitterConfig twitterConfig; public MentionEventHandler() { } public MentionEventHandler(final Event<MentionEvent> mentionEvent) { this.mentionEvent = mentionEvent; LOG.info("Initializing [{}].", this); } @Override public void gotMentions(final ResponseList<Status> statuses) { final Set<Status> newMentions = statuses.stream() .filter(status -> status.getCreatedAt().toInstant() .isAfter(Instant.now().minusSeconds(60 * 10L))) // don't consider replies to mentions, tweet must contain the account name EXPLICITELY. .filter(status -> status.getText().contains(this.twitterConfig.getAccountName())) // don't reply to own replies containing the original unit. .filter(status -> !this.twitterConfig.getAccountName().contains(status.getUser().getName())) .collect(Collectors.toSet()); if (LOG.isInfoEnabled() && newMentions.size() > 0) { LOG.info("Found mention: [{}], new: [{}].", statuses.size(), newMentions.size()); } newMentions.forEach(this::publishEvent); } @Override public void gotRateLimitStatus(final Map<String, RateLimitStatus> rateLimitStatus) { LOG.info("Rate limit status: [{}].", rateLimitStatus); } @Override public void onException(final TwitterException te, final TwitterMethod method) { LOG.error("Problem executing [{}].", method, new IllegalStateException(te)); } private void publishEvent(final Status status) { this.mentionEvent.fire(new MentionEvent(status)); } @Override public String toString() { return new StringJoiner(", ", "MentionEventHandler{", "}") .add("mentionEvent=" + this.mentionEvent) .toString(); } }
32.619048
100
0.737226
3ed1b6ccc76bbc8019a61cad3aff90ea2862ad32
3,536
package universalelectricity.core.electricity; public class ElectricityDisplay { public static String getDisplay(double value, ElectricityDisplay.ElectricUnit unit, int decimalPlaces, boolean isShort) { String unitName = unit.name; if (isShort) { unitName = unit.symbol; } else if (value > 1.0D) { unitName = unit.getPlural(); } if (value == 0.0D) { return value + " " + unitName; } else if (value <= ElectricityDisplay.MeasurementUnit.MILLI.value) { return roundDecimals(ElectricityDisplay.MeasurementUnit.MICRO.process(value), decimalPlaces) + " " + ElectricityDisplay.MeasurementUnit.MICRO.getName(isShort) + unitName; } else if (value < 1.0D) { return roundDecimals(ElectricityDisplay.MeasurementUnit.MILLI.process(value), decimalPlaces) + " " + ElectricityDisplay.MeasurementUnit.MILLI.getName(isShort) + unitName; } else if (value > ElectricityDisplay.MeasurementUnit.MEGA.value) { return roundDecimals(ElectricityDisplay.MeasurementUnit.MEGA.process(value), decimalPlaces) + " " + ElectricityDisplay.MeasurementUnit.MEGA.getName(isShort) + unitName; } else { return value > ElectricityDisplay.MeasurementUnit.KILO.value ? roundDecimals(ElectricityDisplay.MeasurementUnit.KILO.process(value), decimalPlaces) + " " + ElectricityDisplay.MeasurementUnit.KILO.getName(isShort) + unitName : roundDecimals(value, decimalPlaces) + " " + unitName; } } public static String getDisplay(double value, ElectricityDisplay.ElectricUnit unit) { return getDisplay(value, unit, 2, false); } public static String getDisplayShort(double value, ElectricityDisplay.ElectricUnit unit) { return getDisplay(value, unit, 2, true); } public static String getDisplayShort(double value, ElectricityDisplay.ElectricUnit unit, int decimalPlaces) { return getDisplay(value, unit, decimalPlaces, true); } public static String getDisplaySimple(double value, ElectricityDisplay.ElectricUnit unit, int decimalPlaces) { if (value > 1.0D) { return decimalPlaces < 1 ? (int) value + " " + unit.getPlural() : roundDecimals(value, decimalPlaces) + " " + unit.getPlural(); } else { return decimalPlaces < 1 ? (int) value + " " + unit.name : roundDecimals(value, decimalPlaces) + " " + unit.name; } } public static double roundDecimals(double d, int decimalPlaces) { int j = (int) (d * Math.pow(10.0D, (double) decimalPlaces)); return (double) j / Math.pow(10.0D, (double) decimalPlaces); } public static double roundDecimals(double d) { return roundDecimals(d, 2); } public static enum MeasurementUnit { MICRO("Micro", "mi", 1.0E-6D), MILLI("Milli", "m", 0.001D), KILO("Kilo", "k", 1000.0D), MEGA("Mega", "M", 1000000.0D); public String name; public String symbol; public double value; private MeasurementUnit(String name, String symbol, double value) { this.name = name; this.symbol = symbol; this.value = value; } public String getName(boolean isSymbol) { return isSymbol ? this.symbol : this.name; } public double process(double value) { return value / this.value; } } public static enum ElectricUnit { AMPERE("Amp", "I"), AMP_HOUR("Amp Hour", "Ah"), VOLTAGE("Volt", "V"), WATT("Watt", "W"), WATT_HOUR("Watt Hour", "Wh"), RESISTANCE("Ohm", "R"), CONDUCTANCE("Siemen", "S"), JOULES("Joule", "J"); public String name; public String symbol; private ElectricUnit(String name, String symbol) { this.name = name; this.symbol = symbol; } public String getPlural() { return this.name + "s"; } } }
34.330097
282
0.710407
42f85ece73c9c77ea9bb6cab050203cde510eb96
4,437
package study.daydayup.wolf.business.pay.biz.domain.service; import org.springframework.beans.BeanUtils; import org.springframework.dao.DuplicateKeyException; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; import study.daydayup.wolf.business.pay.api.domain.exception.TradeNoCreateFailException; import study.daydayup.wolf.business.pay.api.dto.base.pay.PaymentCreateRequest; import study.daydayup.wolf.business.pay.api.dto.base.pay.PaymentCreateResponse; import study.daydayup.wolf.business.pay.api.domain.entity.Payment; import study.daydayup.wolf.business.pay.api.domain.enums.PaymentStateEnum; import study.daydayup.wolf.common.lang.ds.ObjectMap; import study.daydayup.wolf.common.lang.enums.trade.TradePhaseEnum; import study.daydayup.wolf.common.model.type.string.id.TradeNo; import study.daydayup.wolf.common.util.lang.DecimalUtil; import java.math.BigDecimal; /** * study.daydayup.wolf.business.pay.biz.service * * @author Wingle * @since 2020/2/29 3:19 下午 **/ @Component public abstract class AbstractPaymentCreator extends AbstractPaymentDomainService implements PaymentCreator { protected static final int INSERT_RETRY_TIMES = 3; protected PaymentCreateRequest createRequest; protected ObjectMap attachment; protected String apiResponse; @Override public void initPayment(boolean duplicateCheck) { if (!duplicateCheck) { createPayment(createRequest); return; } if (!checkExistence(createRequest.getTradeNo())) { createPayment(createRequest); } } @Override public PaymentCreateResponse create(@Validated PaymentCreateRequest request) { this.createRequest = request; validateRequest(); initPayment(request.isDuplicateCheck()); callPayEpi(); logCreateResponse(apiResponse); parseCreateResponse(); savePayment(); return formatResponse(); } @Override public void validateRequest() { } @Override public PaymentCreateResponse formatResponse() { PaymentCreateResponse response = new PaymentCreateResponse(); response.setPaymentNo(payment.getPaymentNo()); response.setAmount(payment.getAmount()); response.setPaymentChannel(payment.getPaymentMethod()); response.setPayArgs(attachment.getMap()); return response; } protected boolean checkExistence(String tradeNo) { Payment p = findByTradeNo(tradeNo); if (p == null) { return false; } payment = p; return true; } protected void createPayment(PaymentCreateRequest request) { payment = new Payment(); BeanUtils.copyProperties(request, payment); String paymentNo = TradeNo.builder() .tradePhase(TradePhaseEnum.PAYMENT_PHASE) .accountId(request.getPayerId()) .build() .create(); payment.setId(null); payment.setPaymentNo(paymentNo); payment.setPaymentMethod(request.getPaymentChannel()); payment.setState(PaymentStateEnum.WAIT_TO_PAY.getCode()); attachment = new ObjectMap(); addPayment(); } protected void addPayment() { Long id = null; for (int i = 0; i < INSERT_RETRY_TIMES; i++) { id = doAdding(); if (id == null) { changePaymentNo(); continue; } } if (id == null) { throw new TradeNoCreateFailException(); } payment.setId(id); } protected void changePaymentNo() { String tradeNo = payment.getTradeNo(); if (tradeNo == null) { throw new TradeNoCreateFailException("payment.tradeNo is null"); } String newTradeNo = TradeNo.recreate(tradeNo); if (newTradeNo == null) { throw new TradeNoCreateFailException("recreate tradeNo fail"); } payment.setPaymentNo(newTradeNo); } protected Long doAdding() { try { return paymentRepository.add(payment); } catch (DuplicateKeyException e) { return null; } } protected BigDecimal getAmount() { BigDecimal amount = createRequest.getAmount(); amount = DecimalUtil.scale(amount, 2); return amount; } }
29.778523
109
0.657877
ba0f3c625e52182e9668c7acfaea176f6fa63f7a
1,566
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicecomb.foundation.test.scaffolding.time; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; public class MockClock extends Clock { private MockValues<Long> values; public MockClock() { this(0L); } public MockClock(Long... values) { this.setValues(values); } public MockClock setValues(Long... values) { this.values = new MockValues<Long>() .setDefaultValue(0L) .setValues(values); return this; } @Override public ZoneId getZone() { return null; } @Override public Clock withZone(ZoneId zone) { return null; } @Override public Instant instant() { return null; } @Override public long millis() { return values.read(); } }
25.258065
75
0.710089
c2b45c0777ec775272eab965afb14f59c8c91f7d
1,021
package no.nav.foreldrepenger.regler.uttak.fastsetteperiode.betingelser; import static no.nav.foreldrepenger.regler.uttak.fastsetteperiode.betingelser.SjekkOmErUtsettelseFørSøknadMottattdato.mottattFørSisteDag; import no.nav.foreldrepenger.regler.uttak.fastsetteperiode.FastsettePeriodeGrunnlag; import no.nav.fpsak.nare.doc.RuleDocumentation; import no.nav.fpsak.nare.evaluation.Evaluation; import no.nav.fpsak.nare.specification.LeafSpecification; @RuleDocumentation(SjekkOmErGradertFørSøknadMottattdato.ID) public class SjekkOmErGradertFørSøknadMottattdato extends LeafSpecification<FastsettePeriodeGrunnlag> { public static final String ID = "FP_VK 26.1.15"; public SjekkOmErGradertFørSøknadMottattdato() { super(ID); } @Override public Evaluation evaluate(FastsettePeriodeGrunnlag grunnlag) { var periode = grunnlag.getAktuellPeriode(); if (periode.erSøktGradering() && mottattFørSisteDag(periode)) { return ja(); } return nei(); } }
36.464286
137
0.778648
9b1c5be0da2d7e0879230aa5b1e46fde3658be1c
851
package ru.job4j.chess; import org.junit.Ignore; import org.junit.Test; import ru.job4j.chess.firuges.Cell; import ru.job4j.chess.firuges.black.BishopBlack; import ru.job4j.chess.firuges.black.PawnBlack; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; public class LogicTest { //@Ignore @Test public void moveNotImposible() { Logic logic = new Logic(); logic.add(new PawnBlack(Cell.D7)); logic.add(new BishopBlack(Cell.C8)); boolean rsl = logic.move(Cell.C8, Cell.F5); assertThat(rsl, is(false)); } @Test public void moveImposible() { Logic logic = new Logic(); logic.add(new PawnBlack(Cell.C7)); logic.add(new BishopBlack(Cell.C8)); boolean rsl = logic.move(Cell.C8, Cell.F5); assertThat(rsl, is(true)); } }
26.59375
51
0.654524
9f6e3651380ea1e905fab6e5806bca1b2f204610
4,254
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.core.test.rule; import com.facebook.buck.core.util.immutables.BuckStyleValue; import com.facebook.buck.rules.macros.StringWithMacros; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; /** * Freeform JSON to be used for the test protocol. The JSON is composed of {@link * com.facebook.buck.rules.macros.StringWithMacros}. * * <p>The JSON map keys must be {@link StringWithMacros}, and not other complicated collection * structures. */ public abstract class TestRunnerSpec { private TestRunnerSpec() {} /** Map. */ @BuckStyleValue abstract static class TestRunnerSpecMap extends TestRunnerSpec { public abstract ImmutableMap<StringWithMacros, TestRunnerSpec> getMap(); @Override public <R> R match(Matcher<R> matcher) { return matcher.map(getMap()); } } /** Iterable. */ @BuckStyleValue abstract static class TestRunnerSpecList extends TestRunnerSpec { public abstract ImmutableList<TestRunnerSpec> getList(); @Override public <R> R match(Matcher<R> matcher) { return matcher.list(getList()); } } /** String with macros. */ @BuckStyleValue abstract static class TestRunnerSpecStringWithMacros extends TestRunnerSpec { public abstract StringWithMacros getStringWithMacros(); @Override public <R> R match(Matcher<R> matcher) { return matcher.stringWithMacros(getStringWithMacros()); } } /** Number. */ @BuckStyleValue abstract static class TestRunnerSpecNumber extends TestRunnerSpec { public abstract Number getNumber(); @Override public <R> R match(Matcher<R> matcher) { return matcher.number(getNumber()); } } /** Boolean. */ @BuckStyleValue abstract static class TestRunnerSpecBoolean extends TestRunnerSpec { public abstract boolean getBoolean(); @Override public <R> R match(Matcher<R> matcher) { return matcher.bool(getBoolean()); } private static class Holder { private static final TestRunnerSpecBoolean TRUE = ImmutableTestRunnerSpecBoolean.ofImpl(true); private static final TestRunnerSpecBoolean FALSE = ImmutableTestRunnerSpecBoolean.ofImpl(false); } } /** Constructor. */ public static TestRunnerSpec ofMap(ImmutableMap<StringWithMacros, TestRunnerSpec> map) { return ImmutableTestRunnerSpecMap.ofImpl(map); } /** Constructor. */ public static TestRunnerSpec ofList(ImmutableList<TestRunnerSpec> iterable) { return ImmutableTestRunnerSpecList.ofImpl(iterable); } /** Constructor. */ public static TestRunnerSpec ofStringWithMacros(StringWithMacros stringWithMacros) { return ImmutableTestRunnerSpecStringWithMacros.ofImpl(stringWithMacros); } /** Constructor. */ public static TestRunnerSpec ofNumber(Number number) { return ImmutableTestRunnerSpecNumber.ofImpl(number); } /** Constructor. */ public static TestRunnerSpec ofBoolean(boolean b) { return b ? TestRunnerSpecBoolean.Holder.TRUE : TestRunnerSpecBoolean.Holder.FALSE; } /** Callback for {@link #match(Matcher)}. */ public interface Matcher<R> { /** This is map. */ R map(ImmutableMap<StringWithMacros, TestRunnerSpec> map); /** This is list. */ R list(ImmutableList<TestRunnerSpec> list); /** This is string with macros. */ R stringWithMacros(StringWithMacros stringWithMacros); /** This is number. */ R number(Number number); /** This is boolean. */ R bool(boolean b); } /** Invoke a different callback based on this subclass. */ public abstract <R> R match(Matcher<R> matcher); }
29.957746
100
0.719558
f58abcc4d5c09c5bf7a701dd05336a50c31cc1df
1,175
/** * Copyright (c) 2018 Jerome Mrozak All Rights Reserved. * * Copyright is per the open MIT license (https://opensource.org/licenses/MIT), whose text * is also provided in the file com.logicaltiger.exchangeboard.ExchangeBoardApplication.java. */ package com.logicaltiger.exchangeboard.dao; import java.util.List; import javax.persistence.EntityManager; public interface OfferFilterDao { public void setEntityManager(EntityManager entityManager); /** * Retrieves all filter IDs for an offer. * * @param offerId The offer for which the org/filter combos exist. * @return A list, possibly containing zero elements, of filter ID values. */ public List<Long> getFilterIds(Long offerId); /** * Replace all existing offer/filter combos built from these values. * * If the filterIds parameter is null, or is an empty list, then * the existing combos are deleted and no new ones are created. * * @param offerId The ID for the controlling offer. * @param filterIds The IDs of the filters to associate with the offer. */ public void updateOfferFilters(Long offerId, List<Long> filterIds); }
31.756757
93
0.715745
a488e4a56693b02a1e4a007b900609bf7acd731b
1,192
package com.tam.converter; import com.tam.model.ApplicableStateResource; import com.tam.model.AppliedThreatResource; import com.tam.model.ThreatPriorityResource; import com.tam.model.ThreatResource; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; public class ThreatResourceToAppliedThreatConverter { public static List<AppliedThreatResource> convertThreatResourcesToAppliedThreats(List<ThreatResource> threatResources) { return threatResources.stream().map(ThreatResourceToAppliedThreatConverter::convert).collect(Collectors.toList()); } private static AppliedThreatResource convert(ThreatResource threatResource) { return new AppliedThreatResource() .threatID(UUID.randomUUID().toString()) .title(threatResource.getTitle()) .threatCategory(threatResource.getThreatCategory()) .description(threatResource.getDescription()) .applicable(ApplicableStateResource.NOT_SELECTED) .priority(ThreatPriorityResource.UNSPECIFIED) .affectedElements(threatResource.getAffectedElements()); } }
39.733333
124
0.745805
4cf2b0e2170b893b3978b50743309592e29483ee
2,486
package com.neu.bloodbankmanagement.pojo; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="blood_request") public class BloodRequest { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="Id", unique = true, nullable = false) private long id; @Column(name="date_requested") private Date date; @Column(name="blood_type") private String bloodType; @Column(name="amount_requested") private int bloodAmount; @Column(name="confirmation") private String confirmation; @ManyToOne @JoinColumn(name="Blood_Bank_Id") private BloodBank bloodBank; @ManyToOne @JoinColumn(name="Hospital_Id") private Hospital hospital; public BloodRequest() { } public BloodRequest(long id, Date date, String bloodType, int bloodAmount, String confirmation, BloodBank bloodBank, Hospital hospital) { super(); this.id = id; this.date = date; this.bloodType = bloodType; this.bloodAmount = bloodAmount; this.confirmation = confirmation; this.bloodBank = bloodBank; this.hospital = hospital; } public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date){ this.date = date; } public String getBloodType() { return bloodType; } public void setBloodType(String bloodType) { this.bloodType = bloodType; } public int getBloodAmount() { return bloodAmount; } public void setBloodAmount(int bloodAmount) { this.bloodAmount = bloodAmount; } public String getConfirmation() { return confirmation; } public void setConfirmation(String confirmation) { this.confirmation = confirmation; } public BloodBank getBloodBank() { return bloodBank; } public void setBloodBank(BloodBank bloodBank) { this.bloodBank = bloodBank; } public Hospital getHospital() { return hospital; } public void setHospital(Hospital hospital) { this.hospital = hospital; } @Override public String toString() { return "BloodRequest [id=" + id + ", date=" + date + ", bloodType=" + bloodType + ", bloodAmount=" + bloodAmount + ", confirmation=" + confirmation + ", bloodBank=" + bloodBank + ", hospital=" + hospital + "]"; } }
19.730159
117
0.72325
9df881f369f93b9ba76a6cd6ec0505ea30b1df8b
28,740
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|lockmgr package|; end_package begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|ImmutableList import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|conf operator|. name|HiveConf import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|JavaUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|metrics operator|. name|common operator|. name|Metrics import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|metrics operator|. name|common operator|. name|MetricsConstant import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|common operator|. name|metrics operator|. name|common operator|. name|MetricsFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|metastore operator|. name|api operator|. name|* import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ErrorMsg import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|ddl operator|. name|table operator|. name|lock operator|. name|show operator|. name|ShowLocksOperation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|ql operator|. name|DriverState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|thrift operator|. name|TException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|ByteArrayOutputStream import|; end_import begin_import import|import name|java operator|. name|io operator|. name|DataOutputStream import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashSet import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Objects import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit import|; end_import begin_comment comment|/** * An implementation of HiveLockManager for use with {@link org.apache.hadoop.hive.ql.lockmgr.DbTxnManager}. * Note, this lock manager is not meant to be stand alone. It cannot be used without the DbTxnManager. * See {@link DbTxnManager#getMS()} for important concurrency/metastore access notes. */ end_comment begin_class specifier|public specifier|final class|class name|DbLockManager implements|implements name|HiveLockManager block|{ specifier|static specifier|final specifier|private name|String name|CLASS_NAME init|= name|DbLockManager operator|. name|class operator|. name|getName argument_list|() decl_stmt|; specifier|static specifier|final specifier|private name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|CLASS_NAME argument_list|) decl_stmt|; specifier|private name|long name|MAX_SLEEP decl_stmt|; comment|//longer term we should always have a txn id and then we won't need to track locks here at all specifier|private name|Set argument_list|< name|DbHiveLock argument_list|> name|locks decl_stmt|; specifier|private name|long name|nextSleep init|= literal|50 decl_stmt|; specifier|private specifier|final name|HiveConf name|conf decl_stmt|; specifier|private specifier|final name|DbTxnManager name|txnManager decl_stmt|; name|DbLockManager parameter_list|( name|HiveConf name|conf parameter_list|, name|DbTxnManager name|txnManager parameter_list|) block|{ name|locks operator|= operator|new name|HashSet argument_list|<> argument_list|() expr_stmt|; name|this operator|. name|conf operator|= name|conf expr_stmt|; name|this operator|. name|txnManager operator|= name|txnManager expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|setContext parameter_list|( name|HiveLockManagerCtx name|ctx parameter_list|) throws|throws name|LockException block|{ } annotation|@ name|Override specifier|public name|HiveLock name|lock parameter_list|( name|HiveLockObject name|key parameter_list|, name|HiveLockMode name|mode parameter_list|, name|boolean name|keepAlive parameter_list|) throws|throws name|LockException block|{ throw|throw operator|new name|UnsupportedOperationException argument_list|() throw|; block|} annotation|@ name|Override specifier|public name|List argument_list|< name|HiveLock argument_list|> name|lock parameter_list|( name|List argument_list|< name|HiveLockObj argument_list|> name|objs parameter_list|, name|boolean name|keepAlive parameter_list|, name|DriverState name|driverState parameter_list|) throws|throws name|LockException block|{ throw|throw operator|new name|UnsupportedOperationException argument_list|() throw|; block|} comment|/** * Send a lock request to the metastore. This is intended for use by * {@link DbTxnManager}. * @param lock lock request * @param isBlocking if true, will block until locks have been acquired * @throws LockException * @return the result of the lock attempt */ name|LockState name|lock parameter_list|( name|LockRequest name|lock parameter_list|, name|String name|queryId parameter_list|, name|boolean name|isBlocking parameter_list|, name|List argument_list|< name|HiveLock argument_list|> name|acquiredLocks parameter_list|) throws|throws name|LockException block|{ name|Objects operator|. name|requireNonNull argument_list|( name|queryId argument_list|, literal|"queryId cannot be null" argument_list|) expr_stmt|; name|nextSleep operator|= literal|50 expr_stmt|; comment|/* * get from conf to pick up changes; make sure not to set too low and kill the metastore * MAX_SLEEP is the max time each backoff() will wait for, thus the total time to wait for * successful lock acquisition is approximately (see backoff()) maxNumWaits * MAX_SLEEP. */ name|MAX_SLEEP operator|= name|Math operator|. name|max argument_list|( literal|15000 argument_list|, name|conf operator|. name|getTimeVar argument_list|( name|HiveConf operator|. name|ConfVars operator|. name|HIVE_LOCK_SLEEP_BETWEEN_RETRIES argument_list|, name|TimeUnit operator|. name|MILLISECONDS argument_list|) argument_list|) expr_stmt|; name|int name|maxNumWaits init|= name|Math operator|. name|max argument_list|( literal|0 argument_list|, name|conf operator|. name|getIntVar argument_list|( name|HiveConf operator|. name|ConfVars operator|. name|HIVE_LOCK_NUMRETRIES argument_list|) argument_list|) decl_stmt|; try|try block|{ name|LOG operator|. name|info argument_list|( literal|"Requesting: queryId=" operator|+ name|queryId operator|+ literal|" " operator|+ name|lock argument_list|) expr_stmt|; name|LockResponse name|res init|= name|txnManager operator|. name|getMS argument_list|() operator|. name|lock argument_list|( name|lock argument_list|) decl_stmt|; comment|//link lockId to queryId name|LOG operator|. name|info argument_list|( literal|"Response to queryId=" operator|+ name|queryId operator|+ literal|" " operator|+ name|res argument_list|) expr_stmt|; if|if condition|( operator|! name|isBlocking condition|) block|{ if|if condition|( name|res operator|. name|getState argument_list|() operator|== name|LockState operator|. name|WAITING condition|) block|{ return|return name|LockState operator|. name|WAITING return|; block|} block|} name|int name|numRetries init|= literal|0 decl_stmt|; name|long name|startRetry init|= name|System operator|. name|currentTimeMillis argument_list|() decl_stmt|; while|while condition|( name|res operator|. name|getState argument_list|() operator|== name|LockState operator|. name|WAITING operator|&& name|numRetries operator|++ operator|< name|maxNumWaits condition|) block|{ name|backoff argument_list|() expr_stmt|; name|res operator|= name|txnManager operator|. name|getMS argument_list|() operator|. name|checkLock argument_list|( name|res operator|. name|getLockid argument_list|() argument_list|) expr_stmt|; block|} name|long name|retryDuration init|= name|System operator|. name|currentTimeMillis argument_list|() operator|- name|startRetry decl_stmt|; name|DbHiveLock name|hl init|= operator|new name|DbHiveLock argument_list|( name|res operator|. name|getLockid argument_list|() argument_list|, name|queryId argument_list|, name|lock operator|. name|getTxnid argument_list|() argument_list|, name|lock operator|. name|getComponent argument_list|() argument_list|) decl_stmt|; if|if condition|( name|locks operator|. name|size argument_list|() operator|> literal|0 condition|) block|{ name|boolean name|logMsg init|= literal|false decl_stmt|; for|for control|( name|DbHiveLock name|l range|: name|locks control|) block|{ if|if condition|( name|l operator|. name|txnId operator|!= name|hl operator|. name|txnId condition|) block|{ comment|//locks from different transactions detected (or from transaction and read-only query in autocommit) name|logMsg operator|= literal|true expr_stmt|; break|break; block|} elseif|else if|if condition|( name|l operator|. name|txnId operator|== literal|0 condition|) block|{ if|if condition|( operator|! name|l operator|. name|queryId operator|. name|equals argument_list|( name|hl operator|. name|queryId argument_list|) condition|) block|{ comment|//here means no open transaction, but different queries name|logMsg operator|= literal|true expr_stmt|; break|break; block|} block|} block|} if|if condition|( name|logMsg condition|) block|{ name|LOG operator|. name|warn argument_list|( literal|"adding new DbHiveLock(" operator|+ name|hl operator|+ literal|") while we are already tracking locks: " operator|+ name|locks argument_list|) expr_stmt|; block|} block|} name|locks operator|. name|add argument_list|( name|hl argument_list|) expr_stmt|; if|if condition|( name|res operator|. name|getState argument_list|() operator|!= name|LockState operator|. name|ACQUIRED condition|) block|{ if|if condition|( name|res operator|. name|getState argument_list|() operator|== name|LockState operator|. name|WAITING condition|) block|{ comment|/** * the {@link #unlock(HiveLock)} here is more about future proofing when support for * multi-statement txns is added. In that case it's reasonable for the client * to retry this part of txn or try something else w/o aborting the whole txn. * Also for READ_COMMITTED (when and if that is supported). */ name|unlock argument_list|( name|hl argument_list|) expr_stmt|; comment|//remove the locks in Waiting state name|LockException name|le init|= operator|new name|LockException argument_list|( literal|null argument_list|, name|ErrorMsg operator|. name|LOCK_ACQUIRE_TIMEDOUT argument_list|, name|lock operator|. name|toString argument_list|() argument_list|, name|Long operator|. name|toString argument_list|( name|retryDuration argument_list|) argument_list|, name|res operator|. name|toString argument_list|() argument_list|) decl_stmt|; if|if condition|( name|conf operator|. name|getBoolVar argument_list|( name|HiveConf operator|. name|ConfVars operator|. name|TXN_MGR_DUMP_LOCK_STATE_ON_ACQUIRE_TIMEOUT argument_list|) condition|) block|{ name|showLocksNewFormat argument_list|( name|le operator|. name|getMessage argument_list|() argument_list|) expr_stmt|; block|} throw|throw name|le throw|; block|} throw|throw operator|new name|LockException argument_list|( name|ErrorMsg operator|. name|LOCK_CANNOT_BE_ACQUIRED operator|. name|getMsg argument_list|() operator|+ literal|" " operator|+ name|res argument_list|) throw|; block|} name|acquiredLocks operator|. name|add argument_list|( name|hl argument_list|) expr_stmt|; name|Metrics name|metrics init|= name|MetricsFactory operator|. name|getInstance argument_list|() decl_stmt|; if|if condition|( name|metrics operator|!= literal|null condition|) block|{ try|try block|{ name|metrics operator|. name|incrementCounter argument_list|( name|MetricsConstant operator|. name|METASTORE_HIVE_LOCKS argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Error Reporting hive client metastore lock operation to Metrics system" argument_list|, name|e argument_list|) expr_stmt|; block|} block|} return|return name|res operator|. name|getState argument_list|() return|; block|} catch|catch parameter_list|( name|NoSuchTxnException name|e parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Metastore could not find " operator|+ name|JavaUtils operator|. name|txnIdToString argument_list|( name|lock operator|. name|getTxnid argument_list|() argument_list|) argument_list|) expr_stmt|; throw|throw operator|new name|LockException argument_list|( name|e argument_list|, name|ErrorMsg operator|. name|TXN_NO_SUCH_TRANSACTION argument_list|, name|JavaUtils operator|. name|txnIdToString argument_list|( name|lock operator|. name|getTxnid argument_list|() argument_list|) argument_list|) throw|; block|} catch|catch parameter_list|( name|TxnAbortedException name|e parameter_list|) block|{ name|LockException name|le init|= operator|new name|LockException argument_list|( name|e argument_list|, name|ErrorMsg operator|. name|TXN_ABORTED argument_list|, name|JavaUtils operator|. name|txnIdToString argument_list|( name|lock operator|. name|getTxnid argument_list|() argument_list|) argument_list|, name|e operator|. name|getMessage argument_list|() argument_list|) decl_stmt|; name|LOG operator|. name|error argument_list|( name|le operator|. name|getMessage argument_list|() argument_list|) expr_stmt|; throw|throw name|le throw|; block|} catch|catch parameter_list|( name|TException name|e parameter_list|) block|{ throw|throw operator|new name|LockException argument_list|( name|ErrorMsg operator|. name|METASTORE_COMMUNICATION_FAILED operator|. name|getMsg argument_list|() argument_list|, name|e argument_list|) throw|; block|} block|} specifier|private name|void name|showLocksNewFormat parameter_list|( name|String name|preamble parameter_list|) throws|throws name|LockException block|{ name|ShowLocksResponse name|rsp init|= name|getLocks argument_list|() decl_stmt|; comment|// write the results in the file name|ByteArrayOutputStream name|baos init|= operator|new name|ByteArrayOutputStream argument_list|( literal|1024 operator|* literal|2 argument_list|) decl_stmt|; name|DataOutputStream name|os init|= operator|new name|DataOutputStream argument_list|( name|baos argument_list|) decl_stmt|; try|try block|{ name|ShowLocksOperation operator|. name|dumpLockInfo argument_list|( name|os argument_list|, name|rsp argument_list|) expr_stmt|; name|os operator|. name|flush argument_list|() expr_stmt|; name|LOG operator|. name|info argument_list|( name|baos operator|. name|toString argument_list|() argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|ex parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"Dumping lock info for " operator|+ name|preamble operator|+ literal|" failed: " operator|+ name|ex operator|. name|getMessage argument_list|() argument_list|, name|ex argument_list|) expr_stmt|; block|} block|} comment|/** * Used to make another attempt to acquire a lock (in Waiting state) * @param extLockId * @return result of the attempt * @throws LockException */ name|LockState name|checkLock parameter_list|( name|long name|extLockId parameter_list|) throws|throws name|LockException block|{ try|try block|{ return|return name|txnManager operator|. name|getMS argument_list|() operator|. name|checkLock argument_list|( name|extLockId argument_list|) operator|. name|getState argument_list|() return|; block|} catch|catch parameter_list|( name|TException name|e parameter_list|) block|{ throw|throw operator|new name|LockException argument_list|( name|ErrorMsg operator|. name|METASTORE_COMMUNICATION_FAILED operator|. name|getMsg argument_list|() argument_list|, name|e argument_list|) throw|; block|} block|} annotation|@ name|Override specifier|public name|void name|unlock parameter_list|( name|HiveLock name|hiveLock parameter_list|) throws|throws name|LockException block|{ name|long name|lockId init|= operator|( operator|( name|DbHiveLock operator|) name|hiveLock operator|) operator|. name|lockId decl_stmt|; name|boolean name|removed init|= literal|false decl_stmt|; try|try block|{ name|LOG operator|. name|debug argument_list|( literal|"Unlocking " operator|+ name|hiveLock argument_list|) expr_stmt|; name|txnManager operator|. name|getMS argument_list|() operator|. name|unlock argument_list|( name|lockId argument_list|) expr_stmt|; comment|//important to remove after unlock() in case it fails name|removed operator|= name|locks operator|. name|remove argument_list|( name|hiveLock argument_list|) expr_stmt|; name|Metrics name|metrics init|= name|MetricsFactory operator|. name|getInstance argument_list|() decl_stmt|; if|if condition|( name|metrics operator|!= literal|null condition|) block|{ try|try block|{ name|metrics operator|. name|decrementCounter argument_list|( name|MetricsConstant operator|. name|METASTORE_HIVE_LOCKS argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"Error Reporting hive client metastore unlock operation to Metrics system" argument_list|, name|e argument_list|) expr_stmt|; block|} block|} name|LOG operator|. name|debug argument_list|( literal|"Removed a lock " operator|+ name|removed argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|NoSuchLockException name|e parameter_list|) block|{ comment|//if metastore has no record of this lock, it most likely timed out; either way comment|//there is no point tracking it here any longer name|removed operator|= name|locks operator|. name|remove argument_list|( name|hiveLock argument_list|) expr_stmt|; name|LOG operator|. name|error argument_list|( literal|"Metastore could find no record of lock " operator|+ name|JavaUtils operator|. name|lockIdToString argument_list|( name|lockId argument_list|) argument_list|) expr_stmt|; throw|throw operator|new name|LockException argument_list|( name|e argument_list|, name|ErrorMsg operator|. name|LOCK_NO_SUCH_LOCK argument_list|, name|JavaUtils operator|. name|lockIdToString argument_list|( name|lockId argument_list|) argument_list|) throw|; block|} catch|catch parameter_list|( name|TxnOpenException name|e parameter_list|) block|{ throw|throw operator|new name|RuntimeException argument_list|( literal|"Attempt to unlock lock " operator|+ name|JavaUtils operator|. name|lockIdToString argument_list|( name|lockId argument_list|) operator|+ literal|"associated with an open transaction, " operator|+ name|e operator|. name|getMessage argument_list|() argument_list|, name|e argument_list|) throw|; block|} catch|catch parameter_list|( name|TException name|e parameter_list|) block|{ throw|throw operator|new name|LockException argument_list|( name|ErrorMsg operator|. name|METASTORE_COMMUNICATION_FAILED operator|. name|getMsg argument_list|() argument_list|, name|e argument_list|) throw|; block|} finally|finally block|{ if|if condition|( name|removed condition|) block|{ name|LOG operator|. name|debug argument_list|( literal|"Removed a lock " operator|+ name|hiveLock argument_list|) expr_stmt|; block|} block|} block|} annotation|@ name|Override specifier|public name|void name|releaseLocks parameter_list|( name|List argument_list|< name|HiveLock argument_list|> name|hiveLocks parameter_list|) block|{ name|LOG operator|. name|info argument_list|( literal|"releaseLocks: " operator|+ name|hiveLocks argument_list|) expr_stmt|; for|for control|( name|HiveLock name|lock range|: name|hiveLocks control|) block|{ try|try block|{ name|unlock argument_list|( name|lock argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|LockException name|e parameter_list|) block|{ comment|// Not sure why this method doesn't throw any exceptions, comment|// but since the interface doesn't allow it we'll just swallow them and comment|// move on. comment|//This OK-ish since releaseLocks() is only called for RO/AC queries; it comment|//would be really bad to eat exceptions here for write operations block|} block|} block|} annotation|@ name|Override specifier|public name|List argument_list|< name|HiveLock argument_list|> name|getLocks parameter_list|( name|boolean name|verifyTablePartitions parameter_list|, name|boolean name|fetchData parameter_list|) throws|throws name|LockException block|{ return|return operator|new name|ArrayList argument_list|< name|HiveLock argument_list|> argument_list|( name|locks argument_list|) return|; block|} annotation|@ name|Override specifier|public name|List argument_list|< name|HiveLock argument_list|> name|getLocks parameter_list|( name|HiveLockObject name|key parameter_list|, name|boolean name|verifyTablePartitions parameter_list|, name|boolean name|fetchData parameter_list|) throws|throws name|LockException block|{ throw|throw operator|new name|UnsupportedOperationException argument_list|() throw|; block|} specifier|public name|ShowLocksResponse name|getLocks parameter_list|() throws|throws name|LockException block|{ return|return name|getLocks argument_list|( operator|new name|ShowLocksRequest argument_list|() argument_list|) return|; block|} specifier|public name|ShowLocksResponse name|getLocks parameter_list|( name|ShowLocksRequest name|showLocksRequest parameter_list|) throws|throws name|LockException block|{ try|try block|{ return|return name|txnManager operator|. name|getMS argument_list|() operator|. name|showLocks argument_list|( name|showLocksRequest argument_list|) return|; block|} catch|catch parameter_list|( name|TException name|e parameter_list|) block|{ throw|throw operator|new name|LockException argument_list|( name|ErrorMsg operator|. name|METASTORE_COMMUNICATION_FAILED operator|. name|getMsg argument_list|() argument_list|, name|e argument_list|) throw|; block|} block|} annotation|@ name|Override specifier|public name|void name|close parameter_list|() throws|throws name|LockException block|{ for|for control|( name|HiveLock name|lock range|: name|locks control|) block|{ name|unlock argument_list|( name|lock argument_list|) expr_stmt|; block|} name|locks operator|. name|clear argument_list|() expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|prepareRetry parameter_list|() throws|throws name|LockException block|{ comment|// NOP block|} annotation|@ name|Override specifier|public name|void name|refresh parameter_list|() block|{ comment|// NOP block|} specifier|static class|class name|DbHiveLock extends|extends name|HiveLock block|{ name|long name|lockId decl_stmt|; name|String name|queryId decl_stmt|; name|long name|txnId decl_stmt|; name|List argument_list|< name|LockComponent argument_list|> name|components decl_stmt|; name|DbHiveLock parameter_list|( name|long name|id parameter_list|) block|{ name|lockId operator|= name|id expr_stmt|; block|} name|DbHiveLock parameter_list|( name|long name|id parameter_list|, name|String name|queryId parameter_list|, name|long name|txnId parameter_list|, name|List argument_list|< name|LockComponent argument_list|> name|components parameter_list|) block|{ name|lockId operator|= name|id expr_stmt|; name|this operator|. name|queryId operator|= name|queryId expr_stmt|; name|this operator|. name|txnId operator|= name|txnId expr_stmt|; name|this operator|. name|components operator|= name|ImmutableList operator|. name|copyOf argument_list|( name|components argument_list|) expr_stmt|; block|} annotation|@ name|Override specifier|public name|HiveLockObject name|getHiveLockObject parameter_list|() block|{ throw|throw operator|new name|UnsupportedOperationException argument_list|() throw|; block|} annotation|@ name|Override specifier|public name|HiveLockMode name|getHiveLockMode parameter_list|() block|{ throw|throw operator|new name|UnsupportedOperationException argument_list|() throw|; block|} annotation|@ name|Override specifier|public name|boolean name|mayContainComponents parameter_list|() block|{ return|return literal|true return|; block|} annotation|@ name|Override specifier|public name|List argument_list|< name|LockComponent argument_list|> name|getHiveLockComponents parameter_list|() block|{ return|return name|components return|; block|} annotation|@ name|Override specifier|public name|boolean name|equals parameter_list|( name|Object name|other parameter_list|) block|{ if|if condition|( name|other operator|instanceof name|DbHiveLock condition|) block|{ return|return name|lockId operator|== operator|( operator|( name|DbHiveLock operator|) name|other operator|) operator|. name|lockId return|; block|} else|else block|{ return|return literal|false return|; block|} block|} annotation|@ name|Override specifier|public name|int name|hashCode parameter_list|() block|{ return|return call|( name|int call|) argument_list|( name|lockId operator|% name|Integer operator|. name|MAX_VALUE argument_list|) return|; block|} annotation|@ name|Override specifier|public name|String name|toString parameter_list|() block|{ return|return name|JavaUtils operator|. name|lockIdToString argument_list|( name|lockId argument_list|) operator|+ literal|" queryId=" operator|+ name|queryId operator|+ literal|" " operator|+ name|JavaUtils operator|. name|txnIdToString argument_list|( name|txnId argument_list|) return|; block|} block|} comment|/** * Clear the memory of the locks in this object. This won't clear the locks from the database. * It is for use with * {@link #DbLockManager(HiveConf, DbTxnManager)} .commitTxn} and * {@link #DbLockManager(HiveConf, DbTxnManager)} .rollbackTxn}. */ name|void name|clearLocalLockRecords parameter_list|() block|{ name|locks operator|. name|clear argument_list|() expr_stmt|; block|} comment|// Sleep before we send checkLock again, but do it with a back off comment|// off so we don't sit and hammer the metastore in a tight loop specifier|private name|void name|backoff parameter_list|() block|{ name|nextSleep operator|*= literal|2 expr_stmt|; if|if condition|( name|nextSleep operator|> name|MAX_SLEEP condition|) name|nextSleep operator|= name|MAX_SLEEP expr_stmt|; try|try block|{ name|Thread operator|. name|sleep argument_list|( name|nextSleep argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|InterruptedException name|e parameter_list|) block|{ } block|} block|} end_class end_unit
14.663265
813
0.793841
f171a4455f2c9c993e8a4a1cf7b105c449b3d99e
1,930
/* * The MIT License * * Copyright 2017 Y.K. Chan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jacobi.core.util; import org.junit.Assert; import org.junit.Test; /** * * @author Y.K. Chan */ public class RealTest { @Test public void shouldBeAbleToCheckNegligable() { double rt2 = Math.sqrt(2.0); Assert.assertTrue(Real.isNegl(rt2 * rt2 - 2.0)); Assert.assertTrue(Real.isNegl(2.0 - rt2 * rt2)); } @Test public void shouldBeAbleToComputePseudoLn() { double x = Math.E * Math.E; Assert.assertTrue(Real.isNegl(2.0 - Real.pseudoLn(x))); Assert.assertEquals(Real.LN_ZERO, Real.pseudoLn(0.0), 1e-12); } @Test(expected = IllegalArgumentException.class) public void shouldFailWhenPassingNegativeToPseudoLn() { Real.pseudoLn(-1); } }
34.464286
81
0.688601
e6c87b3ec1ec72595eedb48cad65811fbf30581a
347
package com.nacho; public class Microondas extends Electrodomestico { public Microondas(String marca, String modelo, int ancho, int largo, int profundidad, double consumo) { super(marca, modelo, ancho, largo, profundidad, consumo); } public void calentar(){ System.out.println("Calentando...."); } }
26.692308
108
0.659942
2b21f70ce2c62dc6dbcc47351b3c7a64036c1592
800
package zyz.algorithm.type.DynamicProgramming; /** * @author zyz * @title: 不同路径 * @seq: 12 * @address: https://leetcode-cn.com/problems/unique-paths/$ * @idea: * 动态规划练习 该题用dfs也可以做 */ public class UniquePaths_13 { public static void main(String[] args) { int m=3,n=2; // System.out.println(uniquePaths(m,n)); } public static int uniquePaths(int m, int n) { int[][] dp=new int[m][n]; for(int i=0;i<m;i++) dp[i][0]=1; for(int j=0;j<n;j++) dp[0][j]=1; for(int i=0;i<m;i++) { if(i==0) continue; for(int j=0;j<n;j++) { if(j==0) continue; dp[i][j]=dp[i-1][j]+dp[i][j-1]; } } return dp[m-1][n-1]; } }
20.512821
60
0.4625
838d6cc583f460cc15c957230b1622c2abcb8785
1,088
package gms.shared.utilities.geotess.util.colormap; import java.awt.Color; /** * Represents a range of floating point numbers of [minVal, maxVal] and corresponding * Colors on each end. Double values are placed into an appropriate range to be interpolated * between the two Colors of an instance of this class. * @author jwvicke * */ public class ColorRange { private Color minCol, maxCol; private double minVal, maxVal; public ColorRange(double minVal, double maxVal, Color minCol, Color maxCol) { this.minVal = minVal; this.maxVal = maxVal; this.minCol = minCol; this.maxCol = maxCol; } public Color getMinCol() { return minCol; } public void setMinCol(Color minCol) { this.minCol = minCol; } public Color getMaxCol() { return maxCol; } public void setMaxCol(Color maxCol) { this.maxCol = maxCol; } public double getMinVal() { return minVal; } public void setMinVal(double minVal) { this.minVal = minVal; } public double getMaxVal() { return maxVal; } public void setMaxVal(double maxVal) { this.maxVal = maxVal; } }
22.204082
93
0.70864
d82030633de01c3f9cc679c3b1f16538b9017044
502
package com.cyecize.summer.areas.validation.services; import com.cyecize.summer.areas.validation.interfaces.DataAdapter; import java.util.List; public interface DataAdapterStorageService { boolean hasDataAdapter(String genericType); <T extends DataAdapter<?>> DataAdapter<?> getDataAdapter(Class<T> dataAdapterType); <T extends DataAdapter<?>> DataAdapter<?> getDataAdapter(String fieldGenericType, Class<T> dataAdapterType); DataAdapter<?> getDataAdapter(String genericType); }
29.529412
112
0.784861
a9f9df77ef88ff2a9061e5cb6dce7d0f49302a43
3,570
package com.tower.countmanager.bean; import java.util.List; public class LoginBean { private String token; private String roleId; private String roleName; private String empId; private String empImg; private String empAccount; private String empName; private String dutyName; private String companyId; private String companyName; private String orgId; private String orgName; private String provinceName; private String cityName; private String districtName; private List<ManagerCounty> districtNames; //更新版本相关 private String appDesc; private String appVersion; private String appUrl; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public String getEmpImg() { return empImg; } public void setEmpImg(String empImg) { this.empImg = empImg; } public String getEmpAccount() { return empAccount; } public void setEmpAccount(String empAccount) { this.empAccount = empAccount; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getDutyName() { return dutyName; } public void setDutyName(String dutyName) { this.dutyName = dutyName; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getOrgId() { return orgId; } public void setOrgId(String orgId) { this.orgId = orgId; } public String getOrgName() { return orgName; } public void setOrgName(String orgName) { this.orgName = orgName; } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getDistrictName() { return districtName; } public void setDistrictName(String districtName) { this.districtName = districtName; } public List<ManagerCounty> getDistrictNames() { return districtNames; } public void setDistrictNames(List<ManagerCounty> districtNames) { this.districtNames = districtNames; } public String getAppDesc() { return appDesc; } public void setAppDesc(String appDesc) { this.appDesc = appDesc; } public String getAppVersion() { return appVersion; } public void setAppVersion(String appVersion) { this.appVersion = appVersion; } public String getAppUrl() { return appUrl; } public void setAppUrl(String appUrl) { this.appUrl = appUrl; } }
19.723757
69
0.637535
2ea73f399a46881bc13f68ebf68f33816e700f47
1,639
/* * Author: illuz <iilluzen[at]gmail.com> * File: AC_dfs_2^n.java * Create Date: 2015-02-08 11:18:01 * Descripton: */ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Solution { public List<List<Integer>> subsetsWithDup(int[] S) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> cur = new ArrayList<Integer>(); Arrays.sort(S); dfs(0, res, cur, S); return res; } private void dfs(int dep, List<List<Integer>> res, List<Integer> cur, int[] S) { if (dep == S.length) { res.add(new ArrayList<Integer>(cur)); } else { int upper = dep; while (upper >= 0 && upper < S.length - 1 && S[upper] == S[upper + 1]) { ++upper; } // no choose dfs(upper + 1, res, cur, S); // choose for (int i = dep; i <= upper; ++i) { cur.add(new Integer(S[dep])); dfs(upper + 1, res, cur, S); } for (int i = dep; i <= upper; ++i) cur.remove(cur.size() - 1); } } // debug public static void main(String[] args) { Scanner cin = new Scanner(System.in); Solution s = new Solution(); int[] input = {1, 2, 2}; List<List<Integer>> res = s.subsetsWithDup(input); for (List<Integer> i : res) { for (Integer j : i) System.out.print(j.toString() + ' '); System.out.println(""); } } }
27.779661
84
0.485662
c9e6ca4a1924653a5204d12bca88e6a1938db773
1,320
package com.gh4a.loader; import android.content.Context; import com.gh4a.Gh4Application; import org.eclipse.egit.github.core.CommitFile; import org.eclipse.egit.github.core.RepositoryId; import org.eclipse.egit.github.core.service.PullRequestService; import java.io.IOException; import java.util.List; public class PullRequestFilesLoader extends BaseLoader<List<CommitFile>> { private final String mRepoOwner; private final String mRepoName; private final int mPullRequestNumber; public PullRequestFilesLoader(Context context, String repoOwner, String repoName, int pullRequestNumber) { super(context); mRepoOwner = repoOwner; mRepoName = repoName; mPullRequestNumber = pullRequestNumber; } @Override public List<CommitFile> doLoadInBackground() throws IOException { return loadFiles(mRepoOwner, mRepoName, mPullRequestNumber); } public static List<CommitFile> loadFiles(String repoOwner, String repoName, int pullRequestNumber) throws IOException { PullRequestService pullRequestService = (PullRequestService) Gh4Application.get().getService(Gh4Application.PULL_SERVICE); return pullRequestService.getFiles(new RepositoryId(repoOwner, repoName), pullRequestNumber); } }
33
110
0.743939
ab7a74f4d79cfc6352ea7d9fb61d049017676912
1,272
package ceng.ceng351.musicdb; import java.sql.Timestamp; public class Listen { private int userID; private int songID; private Timestamp lastListenTime; private int listenCount; public Listen(int userID, int songID, Timestamp lastListenTime, int listenCount) { this.userID = userID; this.songID = songID; this.lastListenTime = lastListenTime; this.listenCount = listenCount; } public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public int getSongID() { return songID; } public void setSongID(int songID) { this.songID = songID; } public Timestamp getLastListenTime() { return lastListenTime; } public void setLastListenTime(Timestamp lastListenTime) { this.lastListenTime = lastListenTime; } public int getListenCount() { return listenCount; } public void setListenCount(int listenCount) { this.listenCount = listenCount; } @Override public String toString() { return userID + "\t" + songID + "\t" + lastListenTime + "\t" + listenCount; } }
22.714286
87
0.600629
35699bfe0b29ac20930ea9b7d8a830bd0b186d20
1,899
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.connector.jms.connection.websocket; import io.gravitee.connector.api.AbstractConnection; import io.gravitee.connector.jms.connection.JMSConsumer; import io.gravitee.gateway.api.buffer.Buffer; import io.gravitee.gateway.api.proxy.ws.WebSocketProxyRequest; import io.gravitee.gateway.api.stream.WriteStream; /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team */ public class WebsocketConnection extends AbstractConnection { protected final JMSConsumer consumer; protected final WebSocketProxyRequest proxyRequest; public WebsocketConnection( final JMSConsumer consumer, final WebSocketProxyRequest proxyRequest ) { this.consumer = consumer; this.proxyRequest = proxyRequest; consumer.subscribe( message -> { Buffer body = message.getBody(); if (body != null) { proxyRequest.write( new WebSocketFrame( io.vertx.core.http.WebSocketFrame.textFrame(body.toString(), true) ) ); } } ); proxyRequest.closeHandler(result -> consumer.close()); } @Override public WriteStream<Buffer> write(Buffer content) { return this; } @Override public void end() {} }
29.671875
80
0.711427
e49a16e0712fe35494d14b9f00be327daf766af8
612
package urv.emulator.topology.parser; import urv.emulator.topology.graph.GraphInformation; /** * This interface must be implemented in order to create * file parser classes. * * @author Marcel Arrufat * */ public interface Parser { /** * This method must load network file and create a new NetworkGraph. * NetworkGraph must contain node and edges information (both stored in * LinkedList). This information can be stored by using addNode and addEdge * methods * @param file local file from which NetworkGraph will be load * @return */ public GraphInformation loadNetwork(String file); }
27.818182
76
0.746732
4d06bc05e8247be6c023aa470bbe028a6d628f03
2,755
package com.skelly.mywesst.messages; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.skelly.mywesst.R; import com.skelly.mywesst.conversation.ConversationFragment; import com.skelly.mywesst.helpers.ItemClickSupport; import java.util.List; /** * Created by skelly on 9/17/16. */ public class MessagesFragment extends Fragment { private static final String TAG = "MessagesFragment"; protected RecyclerView mRecyclerView; protected MessagesAdapter mAdapter; protected RecyclerView.LayoutManager mLayoutManager; protected List<MessageThread> mMessageThreadList; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mMessageThreadList = MessagesData.getMessageThreadList(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.messages_fragment, container, false); rootView.setTag(TAG); mRecyclerView = (RecyclerView)rootView.findViewById(R.id.messages_recycler); // LinearLayoutManager lays out elements like a ListView mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new MessagesAdapter(getActivity(), mMessageThreadList); mRecyclerView.setAdapter(mAdapter); mRecyclerView.setNestedScrollingEnabled(false); mRecyclerView.setFocusable(false); ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() { @Override public void onItemClicked(RecyclerView recyclerView, int position, View v) { FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); ConversationFragment conversationFragment = new ConversationFragment(); fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right); fragmentTransaction.replace(R.id.fragment_container, conversationFragment, "ConversationFragment"); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }); return rootView; } }
37.739726
115
0.727768
1b9df3cfccf8d5d4ebcab866bec0208bffb174fe
3,409
package com.novoda.dungeoncrawler; import android.content.Context; import android.graphics.Color; import android.os.Handler; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.List; class AndroidDeviceDisplay implements Display { private static final int OPAQUE = 255; private static final int LED_SIZE = 24; private final List<Integer> state; private final LinearLayout linearLayout; private final Handler handler; AndroidDeviceDisplay(Context context, ViewGroup ledsContainer, int numberOfLeds) { this.state = new ArrayList<>(numberOfLeds); linearLayout = new LinearLayout(context); linearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); linearLayout.setOrientation(LinearLayout.HORIZONTAL); for (int i = 0; i < numberOfLeds; i++) { View ledView = new AndroidLedView(context); ledView.setLayoutParams(new LinearLayout.LayoutParams(LED_SIZE, LED_SIZE)); ledView.setId(999 + i); linearLayout.addView(ledView, i); state.add(i, Color.BLACK); } ledsContainer.addView(linearLayout); handler = new Handler(context.getMainLooper()); } @Override public void clear() { int numberOfLeds = state.size(); for (int i = 0; i < numberOfLeds; i++) { state.set(i, Color.BLACK); } } @Override public void show() { List<Integer> current = new ArrayList<>(state.size()); for (int i = 0; i < state.size(); i++) { current.add(i, state.get(i)); } handler.removeCallbacksAndMessages(null); handler.post(() -> { for (int i = 0; i < current.size(); i++) { int integer = current.get(i); AndroidLedView ledView = (AndroidLedView) linearLayout.getChildAt(i); if (ledView != null) { ledView.setBackgroundColor(integer); } } }); } @Override public void set(int position, CRGB rgb) { state.set(position, Color.argb(OPAQUE, rgb.red, rgb.green, rgb.blue)); } @Override public void set(int position, CHSV hsv) { state.set(position, Color.HSVToColor(OPAQUE, new float[]{hsv.hue, hsv.sat, hsv.val})); } @Override public void modifyHSV(int position, int hue, int saturation, int value) { // TODO is this correct set(position, new CHSV(hue, saturation, value)); } @Override public void modifyScale(int position, int scale) { transform(position, colourComponent -> (int) colourComponent); // TODO: Apply scale } private void transform(int position, Transformation transformation) { Color color = Color.valueOf(state.get(position)); int scaled = Color.argb(OPAQUE, transformation.apply(color.red()), transformation.apply(color.green()), transformation.apply(color.blue())); state.set(position, scaled); } @Override public void modifyMod(int position, int mod) { transform(position, colourComponent -> (int) colourComponent % mod); // TODO is this correct } private interface Transformation { int apply(float colourComponent); } }
33.752475
148
0.63919
00c35b35de40b5b770c16cb7b3d1ec185960bac1
1,556
/* * Copyright 2010 Aalto University, ComNet * Released under GPLv3. See LICENSE.txt for details. */ package routing.util; import java.util.ArrayList; import java.util.List; /** * Class for storing routing related information in a tree form for * user interface(s). */ public class RoutingInfo { private String text; private List<RoutingInfo> moreInfo = null; /** * Creates a routing info based on a text. * @param infoText The text of the info */ public RoutingInfo(String infoText) { this.text = infoText; } /** * Creates a routing info based on any object. Object's * toString() method's output is used as the info text. * @param o The object this info is based on */ public RoutingInfo(Object o) { this.text = o.toString(); } /** * Adds child info object for this routing info. * @param info The info object to add. */ public void addMoreInfo(RoutingInfo info) { if (this.moreInfo == null) { // lazy creation this.moreInfo = new ArrayList<RoutingInfo>(); } this.moreInfo.add(info); } /** * Returns the child routing infos of this info. * @return The children of this info or an empty list if this info * doesn't have any children. */ public List<RoutingInfo> getMoreInfo() { if (this.moreInfo == null) { return new ArrayList<RoutingInfo>(0); } return this.moreInfo; } /** * Returns the info text of this routing info. * @return The info text */ public String toString() { return this.text; } }
23.223881
68
0.651028
c7c249dc4d3ec76393b675e738014a7d2fd1ef0d
879
package fr.catcore.translatedlegacy.mixin; import net.minecraft.client.resource.language.I18n; import net.minecraft.level.Level; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyArg; @Mixin(Level.class) public class LevelMixin { @ModifyArg(method = "saveLevel", index = 0, at = @At(value = "INVOKE", target = "Lnet/minecraft/util/ProgressListener;notifyIgnoreGameRunning(Ljava/lang/String;)V")) private String saveLevel$translate(String string) { return I18n.translate("menu.saving"); } @ModifyArg(method = "saveLevel", index = 0, at = @At(value = "INVOKE", target = "Lnet/minecraft/util/ProgressListener;notifySubMessage(Ljava/lang/String;)V")) private String saveLevel$translate2(String string) { return I18n.translate("menu.saving"); } }
38.217391
169
0.74289
e3c01724683dec24373fc219208f0c6a8450ce66
4,579
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.text.*; import javax.servlet.annotation.WebServlet; /** * * @author wms */ @WebServlet(urlPatterns = {"/inventins "}) public class inventins extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String prod_name=null; int d_id=0; int prid=0; String val = request.getParameter("p_id"); String pname= request.getParameter("pname"); String dname = request.getParameter("dname"); String p_name=request.getParameter("p_name"); String batch= request.getParameter("b_no"); String type = request.getParameter("type"); String mfg= request.getParameter("mfg"); String exp= request.getParameter("exp"); String quantity= request.getParameter("quantity"); String sp= request.getParameter("sp"); String pp= request.getParameter("pp"); Float pricep = Float.valueOf(pp); Float prices = Float.valueOf(sp); try { /* TODO output your page here. You may use following sample code. */ Class.forName("com.mysql.jdbc.Driver"); ResultSet rs,RS; String name = null; Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/pro","root","123456"); out.println(dname); Statement stmt2 = conn.createStatement(); String sq1="Select SUPPLIER_ID from suppliers where SUPPLIER_NAME=\""+dname+"\""; rs= stmt2.executeQuery(sq1); if(rs.next()) { d_id = rs.getInt("SUPPLIER_ID"); out.println(d_id); } if(val.equals("p_id")) { prod_name= p_name; String sql3 = "Insert into products (PRODUCT_NAME) values (?)"; PreparedStatement ps1 = conn.prepareStatement(sql3); ps1.setString(1,prod_name);} else { if(val.equals("p_id1")) { prod_name= pname ; } String sql2="Select PRODUCT_ID from products where PRODUCT_NAME =\""+prod_name+"\""; RS= stmt2.executeQuery(sql2); if(RS.next()) { prid = RS.getInt("PRODUCT_ID"); out.println(prid); } } String sql = "insert into inventory (BATCH_NUMBER,SUPPLIER_ID,PRODUCT_ID,MFG_DATE,EXP_DATE,QUANTITY,UNIT_PURCHASE_PRICE,UNIT_SELL_PRICE,TYPE) values (?,?,?,?,?,?,?,?,?)"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1,batch); pst.setInt(2,d_id); pst.setInt(3,prid); pst.setString(4,mfg); pst.setString(5,exp); pst.setString(6,quantity); pst.setFloat(7,pricep); pst.setFloat(8,prices); pst.setString(9,type); pst.executeUpdate(); } catch(Exception e){ out.println("SQLException caught: " + e.getMessage()); } } }
32.942446
189
0.519983
cbea8ffb341d55cc87c9c95273973f63b6faf4c3
522
package com.example.demo; import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class MultipleCoreImplemSampleApplicationTest { public static void main(final String[] args) { SpringApplication.run(MultipleCoreImplemSampleApplicationTest.class, args); } @Test public void contextLoads() { // Permet juste de charger tous les contexts Spring et vérifier que l'application démarre. } }
26.1
94
0.791188
af7b5ad4b79751796cb7258678aa05b2b9d2390b
1,559
package solutions.leetcode; import static org.junit.Assert.assertEquals; import base.Solution; import base.TestCases; import structures.TwoComposite; import testcases.leetcode.ImplStrStrTestCases; /* * https://leetcode.com/problems/implement-strstr/#/description Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. * * */ public class ImplStrStr extends Solution<TwoComposite<String, String>, Integer> { @Override protected Integer runTest(TwoComposite<String, String> input) { return this.strStr(input.var1, input.var2); } @Override protected void printOutputData(Integer output) { System.out.println(output); } @Override protected void testOutput(Integer outputTest, Integer output) { assertEquals(outputTest, output); } @Override protected TestCases<TwoComposite<String, String>, Integer> genTestCases() { return new ImplStrStrTestCases(); } public int strStr(String haystack, String needle) { int nLen = needle.length(); if (nLen == 0) return 0; int hLen = haystack.length() - nLen + 1; for ( int i = 0; i < hLen; i ++ ){ boolean preFlag = haystack.charAt(i) == needle.charAt(0) && haystack.charAt(i + nLen - 1) == needle.charAt(nLen-1); if (preFlag && haystack.substring(i, i+nLen).equals(needle)) return i; } return -1; } }
25.557377
105
0.632457
24d440d0fc8c3083b0032edae12d237396288946
626
package co.edu.sena.operadores; public class OperadoresLogicos { public static void main(String [] a) { if(5 <8 ^ 7<9) { System.out.println("verdadero"); }else { System.out.println("falso"); } if(5 <8 && 7<9) { System.out.println("verdadero"); }else { System.out.println("falso"); } if(5 <8 || 7<9) { System.out.println("verdadero"); }else { System.out.println("falso"); } boolean codicion= true; System.out.println(!codicion); if(!(5 <8) || !(7<9)) { System.out.println("verdadero"); }else { System.out.println("falso"); } } }
14.55814
39
0.555911
2e0841232fdc872c0b4bd5a00b91b9d809f18256
1,222
package br.com.zup.estrelas.maven.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Carro { @Id private String placa; @Column(nullable = false) private String nome; private String cor; private String fabricante; @Column(name = "ano_fabricacao") private int anoFabricacao; public Carro() { } public Carro(String placa, String nome, String cor, String fabricante, int anoFabricacao) { this.placa = placa; this.nome = nome; this.cor = cor; this.fabricante = fabricante; this.anoFabricacao = anoFabricacao; } public String getPlaca() { return placa; } public void setPlaca(String placa) { this.placa = placa; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCor() { return cor; } public void setCor(String cor) { this.cor = cor; } public String getFabricante() { return fabricante; } public void setFabricante(String fabricante) { this.fabricante = fabricante; } public int getAnoFabricacao() { return anoFabricacao; } public void setAnoFabricacao(int anoFabricacao) { this.anoFabricacao = anoFabricacao; } }
16.972222
92
0.715221
3d141ac8ad2d7e2712d0f6f1bc8aaa13f262c41c
5,013
package org.edx.mobile.view; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; import org.edx.mobile.R; import org.edx.mobile.logger.Logger; import org.edx.mobile.model.course.CourseComponent; import org.edx.mobile.model.course.HtmlBlockModel; import org.edx.mobile.services.ViewPagerDownloadManager; import org.edx.mobile.view.custom.AuthenticatedWebView; import org.edx.mobile.view.custom.URLInterceptorWebViewClient; import roboguice.inject.InjectView; public class CourseUnitWebViewFragment extends CourseUnitFragment { protected final Logger logger = new Logger(getClass().getName()); @InjectView(R.id.auth_webview) private AuthenticatedWebView authWebView; public static CourseUnitWebViewFragment newInstance(HtmlBlockModel unit) { CourseUnitWebViewFragment fragment = new CourseUnitWebViewFragment(); Bundle args = new Bundle(); args.putSerializable(Router.EXTRA_COURSE_UNIT, unit); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_authenticated_webview, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); authWebView.initWebView(getActivity(), true, false); authWebView.getWebViewClient().setPageStatusListener(new URLInterceptorWebViewClient.IPageStatusListener() { @Override public void onPageStarted() { } @Override public void onPageFinished() { ViewPagerDownloadManager.instance.done(CourseUnitWebViewFragment.this, true); } @Override public void onPageLoadError(WebView view, int errorCode, String description, String failingUrl) { if (failingUrl != null && failingUrl.equals(view.getUrl())) { ViewPagerDownloadManager.instance.done(CourseUnitWebViewFragment.this, false); } } @Override @TargetApi(Build.VERSION_CODES.M) public void onPageLoadError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse, boolean isMainRequestFailure) { if (isMainRequestFailure) { ViewPagerDownloadManager.instance.done(CourseUnitWebViewFragment.this, false); } } @Override public void onPageLoadProgressChanged(WebView view, int progress) { } }); if (ViewPagerDownloadManager.USING_UI_PRELOADING) { if (ViewPagerDownloadManager.instance.inInitialPhase(unit)) { ViewPagerDownloadManager.instance.addTask(this); } else { authWebView.loadUrl(true, unit.getBlockUrl()); } } } @Override public void run() { if (this.isRemoving() || this.isDetached()) { ViewPagerDownloadManager.instance.done(this, false); } else { authWebView.loadUrl(true, unit.getBlockUrl()); } } //the problem with viewpager is that it loads this fragment //and calls onResume even it is not visible. //which breaks the normal behavior of activity/fragment //lifecycle. @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (ViewPagerDownloadManager.USING_UI_PRELOADING) { return; } if (ViewPagerDownloadManager.instance.inInitialPhase(unit)) { return; } if (isVisibleToUser) { if (authWebView != null) { authWebView.loadUrl(false, unit.getBlockUrl()); } } else if (authWebView != null) { authWebView.tryToClearWebView(); } } @Override public void onResume() { super.onResume(); authWebView.onResume(); if (hasComponentCallback != null) { final CourseComponent component = hasComponentCallback.getComponent(); if (component != null && component.equals(unit)) { authWebView.loadUrl(false, unit.getBlockUrl()); } } } @Override public void onPause() { super.onPause(); authWebView.onPause(); } @Override public void onDestroy() { super.onDestroy(); authWebView.onDestroy(); } @Override public void onDestroyView() { super.onDestroyView(); authWebView.onDestroyView(); } }
33.644295
116
0.645522
a90dfa741a71883143364c9c8719898e94fcd4e2
3,687
/*- * #%L * anchor-image * %% * Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ package org.anchoranalysis.image.voxel.iterator.intersecting; import java.util.Optional; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.anchoranalysis.image.voxel.iterator.predicate.PredicateTwoBytes; import org.anchoranalysis.image.voxel.object.ObjectMask; import org.anchoranalysis.spatial.point.Point3i; /** * Like {@link CountVoxelsIntersectingBounded} but specifically counts areas of intersection between * two {@link ObjectMask}s. * * @author Owen Feehan */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class CountVoxelsIntersectingObjects { /** * Determines whether there are any intersecting voxels on two object-masks. * * <p>This is an <i>immutable</i> operation. * * <p>The algorithm exits as soon as an intersecting voxel is encountered i.e. as early as * possible. * * @param object1 first-object * @param object2 second-object * @return true if at least one voxel exists that is <i>on</i> in both object-masks. */ public static boolean hasIntersectingVoxels(ObjectMask object1, ObjectMask object2) { PredicateTwoBytes predicate = voxelInBothObjects(object1, object2); Optional<Point3i> firstPoint = IterateVoxelsIntersectingBounded.withTwoBuffersUntil( object1.boundedVoxels(), object2.boundedVoxels(), predicate.deriveUnsignedBytePredicate()); return firstPoint.isPresent(); } /** * Counts the number of intersecting-voxels between two object-masks. * * <p>This is an <i>immutable</i> operation. * * @param object1 first-object * @param object2 second-object * @return number of <i>on</i>-voxels the two object-masks have in common. */ public static int countIntersectingVoxels(ObjectMask object1, ObjectMask object2) { return CountVoxelsIntersectingBounded.countByte( object1.boundedVoxels(), object2.boundedVoxels(), voxelInBothObjects(object1, object2)); } /** Is a voxel <i>on</i> in both object-masks? */ private static PredicateTwoBytes voxelInBothObjects(ObjectMask object1, ObjectMask object2) { final byte byteOn1 = object1.binaryValuesByte().getOn(); final byte byteOn2 = object2.binaryValuesByte().getOn(); return (first, second) -> first == byteOn1 && second == byteOn2; } }
41.426966
100
0.703824
f85c3b1bb8c273c79a64f5614ccf9b6fc7962aeb
1,673
/* * [The "BSD licence"] Copyright (c) 2013-2015 Dandelion All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of Dandelion * 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 AUTHOR ``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 AUTHOR 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. */ /** * <p> * DataTable implementations of asset generators. * </p> * * @author Thibault Duchateau */ package com.github.dandelion.datatables.core.generator;
50.69697
79
0.767484
dd36f07722f499a35876a9956ff133fe4e210e83
1,687
package tools; import java.io.File; import java.util.LinkedList; import java.util.List; import model.Coord; import model.Couleur; import model.Pieces; /** * @author francoise.perrin * Inspiration Jacques SARAYDARYAN, Adrien GUENARD * * Classe qui fabrique une liste de pieces de jeu d'echec * de la couleur pass�e en param�tre * */ public class ChessPiecesFactory { /** * private pour ne pas instancier d'objets */ private ChessPiecesFactory() { } /** * @param pieceCouleur * @return liste de pi�ces de jeu d'�chec */ public static List<Pieces> newPieces(Couleur pieceCouleur){ List<Pieces> pieces = null; pieces = new LinkedList<Pieces>(); String initCouleur = (Couleur.BLANC == pieceCouleur ? "B_" : "N_" ); if (pieceCouleur != null){ for (int i = 0; i < ChessPiecePos.values().length; i++) { if (pieceCouleur.equals(ChessPiecePos.values()[i].couleur)) { for (int j = 0; j < (ChessPiecePos.values()[i].coords).length; j++) { File g=new File(""); //String className = "model.Tour"; // attention au chemin String className = "model." + ChessPiecePos.values()[i].nom; // attention au chemin Coord pieceCoord = ChessPiecePos.values()[i].coords[j]; pieces.add((Pieces) Introspection.newInstance (className, new Object[] {pieceCouleur, pieceCoord})); } } } } return pieces; } /** * Tests unitaires * @param args */ public static void main(String[] args) { System.out.println(ChessPiecesFactory.newPieces(Couleur.BLANC)); } }
26.359375
132
0.605809
87e122a91bfa9a818e250ad78a838ea42d825bad
20,585
package org.truenewx.tnxjee.repo.jpa.codegen; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.sql.*; import java.time.Instant; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.slf4j.Logger; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.datasource.DataSourceUtils; import org.truenewx.tnxjee.core.Strings; import org.truenewx.tnxjee.core.message.MessageResolver; import org.truenewx.tnxjee.core.spec.HttpRequestMethod; import org.truenewx.tnxjee.core.util.ClassUtil; import org.truenewx.tnxjee.core.util.LogUtil; import org.truenewx.tnxjee.core.util.StringUtil; import org.truenewx.tnxjee.core.util.XmlUtil; import org.truenewx.tnxjee.core.util.tuple.Binary; import org.truenewx.tnxjee.core.util.tuple.Binate; import org.truenewx.tnxjee.model.ValueModel; import org.truenewx.tnxjee.model.codegen.ModelBasedGeneratorSupport; import org.truenewx.tnxjee.model.entity.Entity; import org.truenewx.tnxjee.model.entity.relation.RelationKey; import org.truenewx.tnxjee.model.spec.enums.Ethnicity; import org.truenewx.tnxjee.model.spec.user.DefaultUserIdentity; import org.truenewx.tnxjee.repo.jpa.converter.*; import org.truenewx.tnxjee.repo.jpa.converter.spec.DefaultUserIdentityAttributeConverter; import org.truenewx.tnxjee.repo.jpa.converter.spec.EthnicityConverter; import org.truenewx.tnxjee.repo.jpa.converter.spec.HttpRequestMethodConverter; /** * JPA实体映射文件生成器实现 * * @author jianglei */ public class JpaEntityMappingGeneratorImpl extends ModelBasedGeneratorSupport implements JpaEntityMappingGenerator { private static final String INFO_COLUMN_NOT_EXISTS = "info.tnxjee.repo.jpa.codegen.column_not_exists"; private static final String INFO_CONFIRM_MAPS_ID = "info.tnxjee.repo.jpa.codegen.confirm_maps_id"; private static final String INFO_UNSUPPORTED_PROPERTY = "info.tnxjee.repo.jpa.codegen.unsupported_property"; @Autowired private MessageResolver messageResolver; @Autowired private DataSource dataSource; @Autowired private JpaEnumConverterGenerator enumConverterGenerator; private String templateLocation = "META-INF/template/entity-mapping.xml"; private String targetLocation = "META-INF/jpa/"; private final Logger logger = LogUtil.getLogger(getClass()); public JpaEntityMappingGeneratorImpl(String modelBasePackage) { super(modelBasePackage); } public void setTemplateLocation(String templateLocation) { this.templateLocation = templateLocation; } public void setTargetLocation(String targetLocation) { // 确保以/结尾 if (!targetLocation.endsWith(Strings.SLASH)) { targetLocation += Strings.SLASH; } this.targetLocation = targetLocation; } @Override public void generate(String... modules) throws Exception { generate(this.modelBasePackage, (module, entityClass) -> { try { String tableName = "t_" + StringUtil.prependUnderLineToUpperChar(entityClass.getSimpleName(), true); generate(module, entityClass, tableName); } catch (Exception e) { throw new RuntimeException(e); } }, modules); } @Override public void generate(Class<? extends Entity> entityClass, String tableName) throws Exception { String module = getModule(entityClass); generate(module, entityClass, tableName); } private void generate(String module, Class<? extends Entity> entityClass, String tableName) throws Exception { ClassPathResource resource = getMappingResource(module, entityClass); if (resource != null) { Connection connection = DataSourceUtils.getConnection(this.dataSource); DatabaseMetaData metaData = connection.getMetaData(); ResultSet rs = metaData.getTables(null, null, tableName, new String[]{ "TABLE" }); if (!rs.next()) { this.logger.warn("====== Table {} does not exist, entity mapping file for {} can not been generated.", tableName, entityClass.getName()); return; } Document doc = readTemplate(); Element rootElement = doc.getRootElement(); Element entityElement = rootElement.addElement("entity") .addAttribute("class", entityClass.getName()); entityElement.addElement("table").addAttribute("name", tableName); Element attributesElement = entityElement.addElement("attributes"); // JPA实体类仅声明字段有效,父类字段无效 List<Field> refFields = new ArrayList<>(); Field[] fields = entityClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (supports(field)) { Class<?> fieldType = field.getType(); if (i == 0) { // 首个字段视为主键 if (RelationKey.class.isAssignableFrom(fieldType)) { if (!fieldType.isMemberClass()) { // 主键类型不是内部类,则需要生成主键类型的映射文件 generateEmbeddableMapping(fieldType); } Element idElement = attributesElement.addElement("embedded-id") .addAttribute("name", field.getName()); addEmbeddedAttributeElements(metaData, tableName, idElement, field, false); } else { Element idElement = attributesElement.addElement("id") .addAttribute("name", field.getName()); JpaEntityColumn column = getColumn(metaData, tableName, field, null); addColumnElement(idElement, column, false); if (Boolean.TRUE.equals(column.getAutoIncrement())) { idElement.addElement("generated-value").addAttribute("strategy", "IDENTITY"); } } } else { JpaEntityColumn column = getColumn(metaData, tableName, field, null); Binate<Boolean, String> basicConverter = getBasicConverter(fieldType, column); if (basicConverter.getLeft()) { Element basicElement = attributesElement.addElement("basic").addAttribute("name", field.getName()); addColumnElement(basicElement, column, true); String converter = basicConverter.getRight(); // 字段类型为Instant时,未指定特殊的数据类型,则不生成属性转换器配置 if (fieldType == Instant.class && column.getDefinition() == null) { converter = null; } addConvertElement(basicElement, converter); } else { // 引用字段暂存,在所有简单字段类型生成后,再最后生成关联关系配置,以符合映射文件xml约束 refFields.add(field); } } } } for (Field field : refFields) { addRefElement(metaData, tableName, attributesElement, field); } File file = getSourceFile(resource); XmlUtil.write(doc, file); connection.close(); } } private void addConvertElement(Element parentElement, String converter) { if (converter != null) { parentElement.addElement("convert").addAttribute("converter", converter); } } private ClassPathResource getMappingResource(String module, Class<?> clazz) { ClassPathResource dir = new ClassPathResource(this.targetLocation); if (module != null) { dir = (ClassPathResource) dir.createRelative(module + Strings.SLASH); } String filename = clazz.getSimpleName() + ".xml"; ClassPathResource resource = (ClassPathResource) dir.createRelative(filename); if (resource.exists()) { this.logger.info("====== Entity mapping file for {} already exists, which is ignored.", clazz.getName()); return null; } return resource; } private Document readTemplate() throws DocumentException, IOException { SAXReader reader = new SAXReader(); ClassPathResource template = new ClassPathResource(this.templateLocation); InputStream in = template.getInputStream(); Document doc = reader.read(in); in.close(); return doc; } private boolean supports(Field field) { return !Modifier.isStatic(field.getModifiers()); } private void addEmbeddedAttributeElements(DatabaseMetaData metaData, String tableName, Element parentElement, Field field, boolean notId) throws Exception { String columnNamePrefix = null; if (notId) { columnNamePrefix = StringUtil.prependUnderLineToUpperChar(field.getName(), true) + Strings.UNDERLINE; } Field[] valueFields = field.getType().getDeclaredFields(); for (Field valueField : valueFields) { if (supports(valueField)) { Element attributeElement = parentElement.addElement("attribute-override") .addAttribute("name", valueField.getName()); JpaEntityColumn column = getColumn(metaData, tableName, valueField, columnNamePrefix); addColumnElement(attributeElement, column, notId); } } } private JpaEntityColumn getColumn(DatabaseMetaData metaData, String tableName, Field field, String columnNamePrefix) throws SQLException { String columnName = StringUtil.prependUnderLineToUpperChar(field.getName(), true); if (columnNamePrefix != null) { columnName = columnNamePrefix + columnName; } JpaEntityColumn column = new JpaEntityColumn(columnName); ResultSet rs = metaData.getColumns(null, null, tableName, columnName); if (rs.next()) { Class<?> fieldType = field.getType(); column.setAutoIncrement(getBoolean(rs.getString("IS_AUTOINCREMENT"))); if (!fieldType.isPrimitive()) { column.setNullable(getBoolean(rs.getString("IS_NULLABLE"))); } if (fieldType == String.class) { // 字段类型为字符串,则需获取其长度 column.setLength(rs.getInt("COLUMN_SIZE")); } column.setDefinition(getColumnDefinition(fieldType, rs.getInt("DATA_TYPE"))); if (fieldType == BigDecimal.class || fieldType == double.class || fieldType == float.class) { // 小数需获取精度 column.setPrecision(rs.getInt("COLUMN_SIZE")); column.setScale(rs.getInt("DECIMAL_DIGITS")); } } else { column.setExists(false); } return column; } private Boolean getBoolean(String value) { if ("yes".equalsIgnoreCase(value)) { return true; } else if ("no".equalsIgnoreCase(value)) { return false; } else { return null; } } private String getColumnDefinition(Class<?> fieldType, int dataType) { switch (dataType) { case Types.CHAR: return "char"; case Types.DATE: return "date"; case Types.TIME: if (fieldType == Instant.class || fieldType == LocalDateTime.class) { return null; } return "time"; default: return null; } } private void addColumnElement(Element parentElement, JpaEntityColumn column, boolean withNullable) { if (!column.isExists()) { addComment(parentElement, INFO_COLUMN_NOT_EXISTS, column.getName()); } Element columnElement = parentElement.addElement("column").addAttribute("name", column.getName()); if (withNullable && column.getNullable() != null) { columnElement.addAttribute("nullable", column.getNullable().toString()); } if (column.getLength() != null) { columnElement.addAttribute("length", column.getLength().toString()); } if (column.getDefinition() != null) { columnElement.addAttribute("column-definition", column.getDefinition()); } if (column.getPrecision() != null) { columnElement.addAttribute("precision", column.getPrecision().toString()); } if (column.getScale() != null) { columnElement.addAttribute("scale", column.getScale().toString()); } } private void addComment(Element element, String messageCode, Object... args) { element.addComment(this.messageResolver.resolveMessage(messageCode, args)); } private Binate<Boolean, String> getBasicConverter(Class<?> fieldType, JpaEntityColumn column) throws Exception { String converter = null; boolean basic = BeanUtils.isSimpleValueType(fieldType); // 不是基础类型或者是枚举类型/Instant,则尝试获取转换器,可取得转换器,则说明也是基础类型 if (!basic || fieldType.isEnum() || fieldType == Instant.class) { converter = getConverter(fieldType, column); if (converter != null) { basic = true; } } return new Binary<>(basic, converter); } private String getConverter(Class<?> fieldType, JpaEntityColumn column) throws Exception { if (fieldType == Instant.class) { if (column == null || "char".equals(column.getDefinition())) { return InstantZonedMillisSecondStringAttributeConverter.class.getName(); } } if (fieldType == Ethnicity.class) { return EthnicityConverter.class.getName(); } if (fieldType == HttpRequestMethod.class) { return HttpRequestMethodConverter.class.getName(); } if (fieldType == DefaultUserIdentity.class) { return DefaultUserIdentityAttributeConverter.class.getName(); } if (fieldType == Map.class) { return MapToJsonAttributeConverter.class.getName(); } if (fieldType.isArray()) { Class<?> componentType = fieldType.getComponentType(); if (componentType == String.class) { return StringArrayAttributeConverter.class.getName(); } if (componentType == int.class) { return IntArrayAttributeConverter.class.getName(); } if (componentType == long.class) { return LongArrayAttributeConverter.class.getName(); } } return this.enumConverterGenerator.generate(fieldType); } private void addRefElement(DatabaseMetaData metaData, String tableName, Element attributesElement, Field field) throws Exception { String propertyName = field.getName(); Class<?> fieldType = field.getType(); if (ClassUtil.isAggregation(fieldType)) { // 集合类型字段,为一对多或多对多引用 // 暂时不支持,提醒手工配置 addUnsupportedPropertyComment(attributesElement, propertyName); } else { // 单个引用字段,为一对一或多对一引用 if (Entity.class.isAssignableFrom(fieldType)) { // 实体类型生成引用配置 String columnName = StringUtil.prependUnderLineToUpperChar(propertyName, true) + "_id"; ResultSet rs = metaData.getColumns(null, null, tableName, columnName); if (rs.next()) { // 存在外键字段,为多对一引用 Element refElement = attributesElement.addElement("many-to-one") .addAttribute("name", propertyName); Boolean optional = getBoolean(rs.getString("IS_NULLABLE")); if (optional != null) { refElement.addAttribute("optional", optional.toString()); } String mapsId = getMapsId(attributesElement, field); if (mapsId != null) { refElement.addAttribute("maps-id", mapsId); addComment(refElement, INFO_CONFIRM_MAPS_ID); } refElement.addElement("join-column").addAttribute("name", columnName); } else { // 不存在外键字段,为一对一引用 Element refElement = attributesElement.addElement("one-to-one") .addAttribute("name", propertyName) .addAttribute("optional", Boolean.FALSE.toString()); // 一对一映射默认不能为空 refElement.addElement("primary-key-join-column"); } } else if (ValueModel.class.isAssignableFrom(fieldType)) { // 值模型生成内嵌配置 generateEmbeddableMapping(fieldType); Element embeddedElement = attributesElement.addElement("embedded") .addAttribute("name", propertyName); addEmbeddedAttributeElements(metaData, tableName, embeddedElement, field, true); } else { // 其它自定义类型提醒手工设置 addUnsupportedPropertyComment(attributesElement, propertyName); } } } private void addUnsupportedPropertyComment(Element element, String propertyName) { addComment(element, INFO_UNSUPPORTED_PROPERTY, propertyName); } private String getMapsId(Element attributesElement, Field field) throws Exception { Element embeddedIdElement = attributesElement.element("embedded-id"); if (embeddedIdElement != null) { String idPropertyName = embeddedIdElement.attributeValue("name"); Class<?> entityClass = field.getDeclaringClass(); Field idField = entityClass.getDeclaredField(idPropertyName); Class<?> idFieldType = idField.getType(); Field mapsIdField = ClassUtil.findField(idFieldType, field.getName() + "Id"); if (mapsIdField != null) { return mapsIdField.getName(); } } return null; } private void generateEmbeddableMapping(Class<?> embeddableClass) throws Exception { String module = getModule(embeddableClass); ClassPathResource resource = getMappingResource(module, embeddableClass); if (resource != null) { Document doc = readTemplate(); Element rootElement = doc.getRootElement(); Element entityElement = rootElement.addElement("embeddable") .addAttribute("class", embeddableClass.getName()); Element attributesElement = entityElement.addElement("attributes"); Field[] fields = embeddableClass.getDeclaredFields(); for (Field field : fields) { if (supports(field)) { Class<?> fieldType = field.getType(); Binate<Boolean, String> basicConverter = getBasicConverter(fieldType, null); if (basicConverter.getLeft()) { // 值模型暂时只支持基础类型的属性映射 String converter = basicConverter.getRight(); if (converter != null) { // 内嵌类型映射只需生成属性转换器配置 Element basicElement = attributesElement.addElement("basic").addAttribute("name", field.getName()); addConvertElement(basicElement, converter); } } } } // 内嵌类型映射只在包含有效的属性配置时,才生成映射文件 if (attributesElement.elements().size() > 0) { File file = getSourceFile(resource); XmlUtil.write(doc, file); } } } private File getSourceFile(ClassPathResource resource) throws IOException { File root = new ClassPathResource("/").getFile(); // classpath根 root = root.getParentFile().getParentFile(); // 工程根 return new File(root, "src/main/resources/" + resource.getPath()); } }
45.441501
120
0.608841
cc4e14467f5f6a8952565336b2faf0213a050e37
208
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; class SolutionTest { @Test void sample() { assertEquals(4.0, Multiply.multiply(2.0, 2.0), 0.1); } }
18.909091
60
0.706731
426ce4adb6baefa9130a6fbcf4ef639ccb823e9d
2,744
/* * Copyright 2014 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.jvm; import org.gradle.api.GradleException; import org.gradle.api.JavaVersion; import org.gradle.api.internal.DocumentationRegistry; import org.gradle.util.DeprecationLogger; import org.gradle.util.GradleVersion; public class UnsupportedJavaRuntimeException extends GradleException { private static final DocumentationRegistry DOCUMENTATION_REGISTRY = new DocumentationRegistry(); public static final String JAVA7_DEPRECATION_WARNING = "Support for running Gradle using Java 7"; private static final String JAVA7_DEPRECATION_WARNING_DOC = "Please see " + DOCUMENTATION_REGISTRY.getDocumentationFor("java_plugin", "sec:java_cross_compilation") + " for more details."; public UnsupportedJavaRuntimeException(String message) { super(message); } public static void javaDeprecationWarning() { if (!JavaVersion.current().isJava8Compatible()) { DeprecationLogger.nagUserWithDeprecatedBuildInvocationFeature(JAVA7_DEPRECATION_WARNING, JAVA7_DEPRECATION_WARNING_DOC); } } public static void assertUsingVersion(String component, JavaVersion minVersion) throws UnsupportedJavaRuntimeException { JavaVersion current = JavaVersion.current(); if (current.compareTo(minVersion) >= 0) { return; } throw new UnsupportedJavaRuntimeException(String.format("%s %s requires Java %s or later to run. You are currently using Java %s.", component, GradleVersion.current().getVersion(), minVersion.getMajorVersion(), current.getMajorVersion())); } public static void assertUsingVersion(String component, JavaVersion minVersion, JavaVersion configuredVersion) throws UnsupportedJavaRuntimeException { if (configuredVersion.compareTo(minVersion) >= 0) { return; } throw new UnsupportedJavaRuntimeException(String.format("%s %s requires Java %s or later to run. Your build is currently configured to use Java %s.", component, GradleVersion.current().getVersion(), minVersion.getMajorVersion(), configuredVersion.getMajorVersion())); } }
48.140351
206
0.748542
39590f8f771db26cef8ba17567822ec4d940f798
1,313
package me.batizhao.cloud.service; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import me.batizhao.cloud.domain.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; /** * @author batizhao * @since 2017/2/24 */ @Service public class OaClientService { private static final Logger LOGGER = LoggerFactory.getLogger(OaClientService.class); @Autowired private RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "fallback") public User startProcess(String name, String email, String phoneNumber) { User user = new User(name, email, phoneNumber); return this.restTemplate.postForObject("http://flow-engine-server/start-process", user, User.class); } /** * hystrix fallback方法 * @return 默认的用户 */ public User fallback(String name, String email, String phoneNumber) { OaClientService.LOGGER.info("异常发生,进入fallback方法,接收的参数:name = {}", name); User user = new User(); user.setId(-1L); user.setName("john"); user.setEmail("[email protected]"); user.setPhoneNumber("13917891868"); return user; } }
30.534884
108
0.709063
cb6f6fed369d4696ba161c92d0d5ef96908a808c
3,173
package ir.sharifi.spring.view.main.component.test.leaveTime; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.data.value.ValueChangeMode; import com.vaadin.flow.spring.annotation.SpringComponent; import com.vaadin.flow.spring.annotation.UIScope; import ir.sharifi.spring.model.model.test.MemberLeaveTime; import ir.sharifi.spring.repository.security.SecurityUserRepository; import ir.sharifi.spring.repository.test.MemberLeaveTimeRepository; import ir.sharifi.spring.service.security.SecurityUtils; import ir.sharifi.spring.service.test.MemberLeaveTimeService; import ir.sharifi.spring.view.main.component.test.memberWorkTime.WorkTimeSecurityHelper; import org.springframework.security.access.annotation.Secured; import java.util.stream.Collectors; @SpringComponent @UIScope @Secured("LEAVE_TIME_READ") public class LeaveTimeLayout extends VerticalLayout { private final MemberLeaveTimeRepository repo; private final MemberLeaveTimeService memberLeaveTimeService; private final SecurityUserRepository userRepository; final Grid<MemberLeaveTime> grid; private final Button addNewBtn; public LeaveTimeLayout(MemberLeaveTimeRepository repo, LeaveTimeEdit editor, MemberLeaveTimeService memberLeaveTimeService, SecurityUserRepository userRepository) { this.repo = repo; this.memberLeaveTimeService = memberLeaveTimeService; this.userRepository = userRepository; this.grid = new Grid<>(MemberLeaveTime.class); this.addNewBtn = new Button("Add New Request", VaadinIcon.PLUS.create()); add(grid); grid.setHeight("300px"); grid.setColumns( "amount", "status","expirationDate"); grid.addColumn(leaveTime->leaveTime.getTransactions().stream().map(t->String.valueOf(t.getAmount())).collect(Collectors.joining(","))) .setHeader("Transactions"); grid.addColumn(memberLeaveTime -> memberLeaveTime.getUser().getFullName()) .setHeader("User Name"); // Connect selected Customer to editor or hide if none is selected grid.asSingleSelect().addValueChangeListener(e -> { editor.edit(e.getValue()); // editor.edit(null); }); // Instantiate and edit new Customer the new button is clicked addNewBtn.addClickListener(e -> editor.edit(new MemberLeaveTime())); // Listen changes made by the editor, refresh data from backend editor.setChangeHandler(() -> { editor.setVisible(false); listCustomers(); }); // Initialize listing listCustomers(); } private void listCustomers() { if(SecurityUtils.isAccessGranted(WorkTimeSecurityHelper.class)) grid.setItems(memberLeaveTimeService.getModels()); else grid.setItems(memberLeaveTimeService.getByUser(SecurityUtils.getUser())); } }
39.6625
168
0.739679
0b30cab6a779a06f7183b203f9c78eba4a3186d7
316
package com.myapp.bootstrap; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; public class ExampleServerBootstrapBean implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { } }
24.307692
90
0.822785
e295c4d0dfc11a5dbcef950300879db769731de2
876
package mirrg.minecraft.regioneditor.gui.guis; import java.awt.Dialog.ModalityType; import mirrg.boron.util.i18n.I18n; import mirrg.minecraft.regioneditor.util.gui.WindowWrapper; public abstract class GuiBase { protected WindowWrapper windowWrapper; protected I18n i18n; public GuiBase(WindowWrapper owner, I18n i18n, String title, ModalityType modalityType) { this.i18n = i18n; windowWrapper = WindowWrapper.createWindow(owner, title, modalityType); } protected abstract void initComponenets(); public void show() { initComponenets(); windowWrapper.getWindow().pack(); if (windowWrapper.parent != null) { windowWrapper.getWindow().setLocationRelativeTo(windowWrapper.parent.getWindow()); } windowWrapper.getWindow().setVisible(true); } protected String localize(String unlocalizedString) { return i18n.localize(unlocalizedString); } }
23.052632
88
0.775114
cc117f0160e5c8c836ca6d5a19841252d5be805f
4,909
package org.jabref.model.study; import java.time.LocalDate; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * This class represents a scientific study. * * This class defines all aspects of a scientific study relevant to the application. It is a proxy for the file based study definition. */ @JsonPropertyOrder({"authors", "title", "last-search-date", "research-questions", "queries", "databases"}) public class Study { private List<String> authors; private String title; @JsonProperty("last-search-date") private LocalDate lastSearchDate; @JsonProperty("research-questions") private List<String> researchQuestions; private List<StudyQuery> queries; private List<StudyDatabase> databases; public Study(List<String> authors, String title, List<String> researchQuestions, List<StudyQuery> queryEntries, List<StudyDatabase> databases) { this.authors = authors; this.title = title; this.researchQuestions = researchQuestions; this.queries = queryEntries; this.databases = databases; } /** * Used for Jackson deserialization */ public Study() { } public List<String> getAuthors() { return authors; } public void setAuthors(List<String> authors) { this.authors = authors; } public List<StudyQuery> getQueries() { return queries; } public void setQueries(List<StudyQuery> queries) { this.queries = queries; } public LocalDate getLastSearchDate() { return lastSearchDate; } public void setLastSearchDate(LocalDate date) { lastSearchDate = date; } public List<StudyDatabase> getDatabases() { return databases; } public void setDatabases(List<StudyDatabase> databases) { this.databases = databases; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<String> getResearchQuestions() { return researchQuestions; } public void setResearchQuestions(List<String> researchQuestions) { this.researchQuestions = researchQuestions; } @Override public String toString() { return "Study{" + "authors=" + authors + ", studyName='" + title + '\'' + ", lastSearchDate=" + lastSearchDate + ", researchQuestions=" + researchQuestions + ", queries=" + queries + ", libraries=" + databases + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Study study = (Study) o; if (getAuthors() != null ? !getAuthors().equals(study.getAuthors()) : study.getAuthors() != null) { return false; } if (getTitle() != null ? !getTitle().equals(study.getTitle()) : study.getTitle() != null) { return false; } if (getLastSearchDate() != null ? !getLastSearchDate().equals(study.getLastSearchDate()) : study.getLastSearchDate() != null) { return false; } if (getResearchQuestions() != null ? !getResearchQuestions().equals(study.getResearchQuestions()) : study.getResearchQuestions() != null) { return false; } if (getQueries() != null ? !getQueries().equals(study.getQueries()) : study.getQueries() != null) { return false; } return getDatabases() != null ? getDatabases().equals(study.getDatabases()) : study.getDatabases() == null; } public boolean equalsBesideLastSearchDate(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Study study = (Study) o; if (getAuthors() != null ? !getAuthors().equals(study.getAuthors()) : study.getAuthors() != null) { return false; } if (getTitle() != null ? !getTitle().equals(study.getTitle()) : study.getTitle() != null) { return false; } if (getResearchQuestions() != null ? !getResearchQuestions().equals(study.getResearchQuestions()) : study.getResearchQuestions() != null) { return false; } if (getQueries() != null ? !getQueries().equals(study.getQueries()) : study.getQueries() != null) { return false; } return getDatabases() != null ? getDatabases().equals(study.getDatabases()) : study.getDatabases() == null; } @Override public int hashCode() { return Objects.hashCode(this); } }
30.490683
148
0.598696
82c92f44ba5ddcf66fc35585734635c0aecd1cc7
111
// "f "abcd"" "true" public class Test { void foo(){ Syste.out.print("abcd"); } void bar1(){foo();} }
15.857143
28
0.531532
86d38783d888690fc7f3cb1e567aae0939d68082
5,487
package net.minecraft.entity.passive.horse; import java.util.EnumSet; import javax.annotation.Nullable; import net.minecraft.entity.AgeableEntity; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityPredicate; import net.minecraft.entity.EntityType; import net.minecraft.entity.ILivingEntityData; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.SpawnReason; import net.minecraft.entity.ai.goal.Goal; import net.minecraft.entity.ai.goal.PanicGoal; import net.minecraft.entity.ai.goal.TargetGoal; import net.minecraft.entity.merchant.villager.WanderingTraderEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.IWorld; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public class TraderLlamaEntity extends LlamaEntity { private int despawnDelay = 47999; public TraderLlamaEntity(EntityType<? extends TraderLlamaEntity> p_i50234_1_, World p_i50234_2_) { super(p_i50234_1_, p_i50234_2_); } @OnlyIn(Dist.CLIENT) public boolean isTraderLlama() { return true; } protected LlamaEntity createChild() { return EntityType.TRADER_LLAMA.create(this.world); } public void writeAdditional(CompoundNBT compound) { super.writeAdditional(compound); compound.putInt("DespawnDelay", this.despawnDelay); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ public void readAdditional(CompoundNBT compound) { super.readAdditional(compound); if (compound.contains("DespawnDelay", 99)) { this.despawnDelay = compound.getInt("DespawnDelay"); } } protected void registerGoals() { super.registerGoals(); this.goalSelector.addGoal(1, new PanicGoal(this, 2.0D)); this.targetSelector.addGoal(1, new TraderLlamaEntity.FollowTraderGoal(this)); } protected void mountTo(PlayerEntity player) { Entity entity = this.getLeashHolder(); if (!(entity instanceof WanderingTraderEntity)) { super.mountTo(player); } } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ public void livingTick() { super.livingTick(); if (!this.world.isRemote) { this.tryDespawn(); } } private void tryDespawn() { if (this.canDespawn()) { this.despawnDelay = this.isLeashedToTrader() ? ((WanderingTraderEntity)this.getLeashHolder()).getDespawnDelay() - 1 : this.despawnDelay - 1; if (this.despawnDelay <= 0) { this.clearLeashed(true, false); this.remove(); } } } private boolean canDespawn() { return !this.isTame() && !this.isLeashedToStranger() && !this.isOnePlayerRiding(); } private boolean isLeashedToTrader() { return this.getLeashHolder() instanceof WanderingTraderEntity; } private boolean isLeashedToStranger() { return this.getLeashed() && !this.isLeashedToTrader(); } @Nullable public ILivingEntityData onInitialSpawn(IWorld worldIn, DifficultyInstance difficultyIn, SpawnReason reason, @Nullable ILivingEntityData spawnDataIn, @Nullable CompoundNBT dataTag) { if (reason == SpawnReason.EVENT) { this.setGrowingAge(0); } if (spawnDataIn == null) { spawnDataIn = new AgeableEntity.AgeableData(); ((AgeableEntity.AgeableData)spawnDataIn).func_226259_a_(false); } return super.onInitialSpawn(worldIn, difficultyIn, reason, spawnDataIn, dataTag); } public class FollowTraderGoal extends TargetGoal { private final LlamaEntity field_220800_b; private LivingEntity field_220801_c; private int field_220802_d; public FollowTraderGoal(LlamaEntity p_i50458_2_) { super(p_i50458_2_, false); this.field_220800_b = p_i50458_2_; this.setMutexFlags(EnumSet.of(Goal.Flag.TARGET)); } /** * Returns whether execution should begin. You can also read and cache any state necessary for execution in this * method as well. */ public boolean shouldExecute() { if (!this.field_220800_b.getLeashed()) { return false; } else { Entity entity = this.field_220800_b.getLeashHolder(); if (!(entity instanceof WanderingTraderEntity)) { return false; } else { WanderingTraderEntity wanderingtraderentity = (WanderingTraderEntity)entity; this.field_220801_c = wanderingtraderentity.getRevengeTarget(); int i = wanderingtraderentity.getRevengeTimer(); return i != this.field_220802_d && this.isSuitableTarget(this.field_220801_c, EntityPredicate.DEFAULT); } } } /** * Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.goalOwner.setAttackTarget(this.field_220801_c); Entity entity = this.field_220800_b.getLeashHolder(); if (entity instanceof WanderingTraderEntity) { this.field_220802_d = ((WanderingTraderEntity)entity).getRevengeTimer(); } super.startExecuting(); } } }
33.87037
185
0.688172
8ba4105af09cdcc56ba88ca777f8c6299eab9f13
3,882
package mcjty.intwheel.playerdata; import mcjty.intwheel.network.PacketHandler; import mcjty.intwheel.network.PacketSyncConfigToServer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; import net.minecraftforge.common.util.Constants; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PlayerWheelConfiguration { private Map<String, Integer> hotkeys = new HashMap<>(); private Map<String, Boolean> enabledActions = new HashMap<>(); private List<String> orderedActions = new ArrayList<>(); public PlayerWheelConfiguration() { } public Map<String, Integer> getHotkeys() { return hotkeys; } public void addHotkey(int key, String id) { hotkeys.put(id, key); } public void removeHotkey(String id) { hotkeys.remove(id); } public void enable(String id) { enabledActions.put(id, Boolean.TRUE); } public void disable(String id) { enabledActions.put(id, Boolean.FALSE); } public List<String> getOrderedActions() { return orderedActions; } public void setOrderActions(List<String> actions) { orderedActions = new ArrayList<>(actions); } /** * Can return null if the status is not known yet for this player * @param id * @return */ public Boolean isEnabled(String id) { return enabledActions.get(id); } public void copyFrom(PlayerWheelConfiguration source) { hotkeys = new HashMap<>(source.hotkeys); enabledActions = new HashMap<>(source.enabledActions); orderedActions = new ArrayList<>(source.orderedActions); } public void saveNBTData(NBTTagCompound compound) { NBTTagList list = new NBTTagList(); for (Map.Entry<String, Integer> entry : hotkeys.entrySet()) { NBTTagCompound tc = new NBTTagCompound(); tc.setString("id", entry.getKey()); tc.setInteger("key", entry.getValue()); list.appendTag(tc); } compound.setTag("hotkeys", list); list = new NBTTagList(); for (Map.Entry<String, Boolean> entry : enabledActions.entrySet()) { NBTTagCompound tc = new NBTTagCompound(); tc.setString("id", entry.getKey()); tc.setBoolean("enabled", entry.getValue()); list.appendTag(tc); } compound.setTag("enabled", list); list = new NBTTagList(); for (String action : orderedActions) { list.appendTag(new NBTTagString(action)); } compound.setTag("order", list); } public void loadNBTData(NBTTagCompound compound) { hotkeys = new HashMap<>(); NBTTagList list = compound.getTagList("hotkeys", Constants.NBT.TAG_COMPOUND); for (int i = 0 ; i < list.tagCount() ; i++) { NBTTagCompound tc = (NBTTagCompound) list.get(i); hotkeys.put(tc.getString("id"), tc.getInteger("key")); } enabledActions = new HashMap<>(); list = compound.getTagList("enabled", Constants.NBT.TAG_COMPOUND); for (int i = 0 ; i < list.tagCount() ; i++) { NBTTagCompound tc = (NBTTagCompound) list.get(i); enabledActions.put(tc.getString("id"), tc.getBoolean("enabled")); } orderedActions = new ArrayList<>(); list = compound.getTagList("order", Constants.NBT.TAG_STRING); for (int i = 0 ; i < list.tagCount() ; i++) { NBTTagString tc = (NBTTagString) list.get(i); orderedActions.add(tc.getString()); } } public void sendToServer() { NBTTagCompound tc = new NBTTagCompound(); saveNBTData(tc); PacketHandler.INSTANCE.sendToServer(new PacketSyncConfigToServer(tc)); } }
31.306452
85
0.626224
562ea58caf454667c25ee6e796609f50e5936e0d
183
package org.diplomatiq.diplomatiqbackend.filters; public enum DiplomatiqAuthenticationScheme { AuthenticationSessionSignatureV1, DeviceSignatureV1, SessionSignatureV1, }
22.875
49
0.825137
8e0f3c55ac983b9f62d4901a28f50c72d0f3c60b
6,466
/* * MIT License * * Copyright (c) 2017-2019 nuls.io * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package io.nuls.protocol.cache; import io.nuls.cache.manager.EhCacheManager; import io.nuls.core.tools.log.Log; import io.nuls.kernel.model.BlockHeader; import io.nuls.kernel.model.NulsDigestData; import io.nuls.kernel.model.Transaction; import io.nuls.protocol.model.SmallBlock; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.*; /** * 临时缓存管理器测试类,测试临时缓存的存、取、删、清理、销毁功能 * <p> * Temporary cache manager test class, test temporary cache storage, fetch, delete, clean, destroy function. * * @author: Niels Wang */ public class TemporaryCacheManagerTest { private TemporaryCacheManager manager; /** * 获取TemporaryCacheManager对象,TemporaryCacheManager是用单例模式实现的,只需要调用getInstance方法就能获取虚拟机内唯一的实例 * <p> * To obtain the TemporaryCacheManager object, TemporaryCacheManager is implemented in singleton mode, * and the only instance in the virtual machine can be obtained by calling the getInstance method. */ @Before public void init() { manager = TemporaryCacheManager.getInstance(); } /** * 测试小区快的缓存处理流程: * 1. 先测试放入缓存,不出现异常视为成功 * 2. 测试获取刚放入的小区快,获取的结果不能为空且和刚仿佛的是相同内容 * 3. 测试删除之前放入的小区快,删除后再获取应该得到null * 4. 重新把小区快放回缓存中,调用清理方法,清理后缓存中应该没有任何小区块或者交易 * test the cache processing process of the smallblock: * 1. The first test is put into the cache, and no exceptions are deemed to be successful. * 2. Test to get the newly inserted smallblock fast, the results can not be empty and the same content as if it is just as if. * 3. Before the test is deleted, the cells should be put into the smallblock quickly. After deleting, it should be null. * 4. Reattach the smallblock to the cache, call the cleaning method, and there should be no blocks or transactions in the cache. */ @Test public void cacheSmallBlock() { SmallBlock smallBlock = new SmallBlock(); BlockHeader header = new BlockHeader(); NulsDigestData hash = NulsDigestData.calcDigestData("abcdefg".getBytes()); header.setHash(hash); manager.cacheSmallBlock(smallBlock); assertTrue(true); this.getSmallBlock(hash, smallBlock); this.removeSmallBlock(hash); manager.cacheSmallBlock(smallBlock); this.clear(); } /** * 测试获取已存在缓存中的小区块 * <p> * The test gets the small block in the cache. * * @param hash 已存入的小区快的摘要对象,A quick summary of the community that has been deposited. * @param smallBlock 已存入缓存的小区快,The cached community is fast. */ private void getSmallBlock(NulsDigestData hash, SmallBlock smallBlock) { SmallBlock sb = manager.getSmallBlockByHash(NulsDigestData.calcDigestData("abcdefg".getBytes())); assertEquals(sb.getHeader().getHash(), smallBlock.getHeader().getHash()); } /** * 测试交易的缓存处理流程: * 1. 先测试放入缓存,不出现异常视为成功 * 2. 测试获取刚放入的交易,获取的结果不能为空且和刚仿佛的是相同内容 * 3. 测试删除之前放入的交易,删除后再获取应该得到null * 4. 重新把交易放回缓存中,调用清理方法,清理后缓存中应该没有任何小区块或者交易 * the cache processing flow of test transaction: * 1. The first test is put into the cache, and no exceptions are deemed to be successful. * 2. Test to obtain the newly placed transaction, the results obtained cannot be empty and the same content as the new one. * 3. Delete the transaction that was put in before the test is deleted, and then get null after deleting. * 4. Return the transaction to the cache, call the cleaning method, and there should be no blocks or transactions in the cache. */ @Test public void cacheTx() { Transaction tx = new CacheTestTx(); tx.setTime(1234567654L); try { tx.setHash(NulsDigestData.calcDigestData(tx.serializeForHash())); } catch (IOException e) { Log.error(e); } manager.cacheTx(tx); assertTrue(true); getTx(tx.getHash(), tx); } /** * 测试获取已存在缓存中的交易 * <p> * The test gets the transaction in the cache. * * @param hash 已存入的交易的摘要对象,A quick summary of the transaction that has been deposited. * @param tx 已存入缓存的交易,The cached Transaction is fast. */ private void getTx(NulsDigestData hash, Transaction tx) { Transaction txGoted = manager.getTx(hash); assertNotNull(tx); assertEquals(tx.getTime(), txGoted.getTime()); } /** * 根据区块摘要对象从缓存中移除对应的小区块,判断移除是否成功 * Remove the corresponding block from the cache according to the block summary object, and determine whether the removal is successful. */ public void removeSmallBlock(NulsDigestData hash) { SmallBlock smallBlock = manager.getSmallBlockByHash(hash); assertNotNull(smallBlock); } /** * 清理缓存,验证结果 * clear the cache and verify the results */ public void clear() { manager.clear(); assertEquals(manager.getSmallBlockCount(), 0); assertEquals(manager.getTxCount(), 0); } /** * 销毁缓存,验证结果 * destroy the cache and verify the results */ @Test public void destroy() { manager.destroy(); assertNull(EhCacheManager.getInstance().getCache("temp-small-block-cache")); assertNull(EhCacheManager.getInstance().getCache("temp-tx-cache")); } }
36.325843
140
0.691772
6ff945bf3fbc8e99adf72c6ebd13b55d79866d69
2,230
package org.plugins.rpghorses.horseinfo; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Horse; import org.bukkit.entity.Llama; import org.plugins.rpghorses.RPGHorsesMain; public abstract class AbstractHorseInfo { private EntityType entityType; private Horse.Style style; private Horse.Color color; public AbstractHorseInfo(EntityType entityType, Horse.Style style, Horse.Color color) { this.entityType = entityType; this.style = style; this.color = color; } public static AbstractHorseInfo getFromEntity(Entity entity) { if (entity.getType() == EntityType.HORSE) { Horse horse = (Horse) entity; Horse.Color color = horse.getColor(); Horse.Style style = horse.getStyle(); if (RPGHorsesMain.getVersion().getWeight() < 11) { return new LegacyHorseInfo(style, color, horse.getVariant()); } else { return new HorseInfo(EntityType.HORSE, style, color); } } else if (RPGHorsesMain.getVersion().getWeight() >= 11 && entity.getType() == EntityType.LLAMA) { Llama llama = (Llama) entity; Horse.Color color = Horse.Color.WHITE; try { color = Horse.Color.valueOf(llama.getColor().name()); } catch (IllegalArgumentException e) {} return new HorseInfo(EntityType.LLAMA, Horse.Style.NONE, color); } return new HorseInfo(entity.getType(), Horse.Style.NONE, Horse.Color.BROWN); } public EntityType getEntityType() { return entityType; } public void setEntityType(EntityType entityType) { this.entityType = entityType; } public Horse.Style getStyle() { return style; } public void setStyle(Horse.Style style) { this.style = style; } public Horse.Color getColor() { return color; } public void setColor(Horse.Color color) { this.color = color; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AbstractHorseInfo)) return false; AbstractHorseInfo that = (AbstractHorseInfo) o; if (RPGHorsesMain.getVersion().getWeight() < 11 && ((LegacyHorseInfo) this).getVariant() != ((LegacyHorseInfo) that).getVariant()) { return false; } return entityType == that.entityType && style == that.style && color == that.color; } }
27.530864
134
0.708969
f7054b7d4762f8fb5937d5b745224ef9dd376a33
195,427
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import javax.cache.Cache; import javax.cache.CacheException; import javax.cache.expiry.Duration; import javax.cache.expiry.ExpiryPolicy; import javax.cache.expiry.TouchedExpiryPolicy; import javax.cache.processor.EntryProcessor; import javax.cache.processor.EntryProcessorException; import javax.cache.processor.EntryProcessorResult; import javax.cache.processor.MutableEntry; import junit.framework.AssertionFailedError; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteEvents; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteTransactions; import org.apache.ignite.cache.CacheEntry; import org.apache.ignite.cache.CacheEntryProcessor; import org.apache.ignite.cache.CachePeekMode; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cache.query.QueryCursor; import org.apache.ignite.cache.query.ScanQuery; import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.events.CacheEvent; import org.apache.ignite.events.Event; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgniteKernal; import org.apache.ignite.internal.IgnitionEx; import org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager; import org.apache.ignite.internal.processors.resource.GridSpringResourceContext; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.lang.GridAbsPredicate; import org.apache.ignite.internal.util.lang.GridAbsPredicateX; import org.apache.ignite.internal.util.lang.IgnitePair; import org.apache.ignite.internal.util.typedef.CIX1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.PA; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteBiPredicate; import org.apache.ignite.lang.IgniteClosure; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.resources.CacheNameResource; import org.apache.ignite.resources.IgniteInstanceResource; import org.apache.ignite.resources.LoggerResource; import org.apache.ignite.resources.ServiceResource; import org.apache.ignite.services.Service; import org.apache.ignite.services.ServiceContext; import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.transactions.Transaction; import org.apache.ignite.transactions.TransactionConcurrency; import org.apache.ignite.transactions.TransactionIsolation; import org.jetbrains.annotations.Nullable; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMode.LOCAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheMode.REPLICATED; import static org.apache.ignite.cache.CachePeekMode.ALL; import static org.apache.ignite.cache.CachePeekMode.OFFHEAP; import static org.apache.ignite.cache.CachePeekMode.ONHEAP; import static org.apache.ignite.cache.CachePeekMode.PRIMARY; import static org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_LOCKED; import static org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_SWAPPED; import static org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_UNLOCKED; import static org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_UNSWAPPED; import static org.apache.ignite.testframework.GridTestUtils.assertThrows; import static org.apache.ignite.testframework.GridTestUtils.waitForCondition; import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC; import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC; import static org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED; import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ; import static org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE; import static org.apache.ignite.transactions.TransactionState.COMMITTED; /** * Full API cache test. */ @SuppressWarnings("TransientFieldInNonSerializableClass") public abstract class GridCacheAbstractFullApiSelfTest extends GridCacheAbstractSelfTest { /** Test timeout */ private static final long TEST_TIMEOUT = 60 * 1000; /** Service name. */ private static final String SERVICE_NAME1 = "testService1"; /** */ public static final CacheEntryProcessor<String, Integer, String> ERR_PROCESSOR = new CacheEntryProcessor<String, Integer, String>() { /** */ private static final long serialVersionUID = 0L; @Override public String process(MutableEntry<String, Integer> e, Object... args) { throw new RuntimeException("Failed!"); } }; /** Increment processor for invoke operations. */ public static final EntryProcessor<String, Integer, String> INCR_PROCESSOR = new IncrementEntryProcessor(); /** Increment processor for invoke operations with IgniteEntryProcessor. */ public static final CacheEntryProcessor<String, Integer, String> INCR_IGNITE_PROCESSOR = new CacheEntryProcessor<String, Integer, String>() { /** */ private static final long serialVersionUID = 0L; @Override public String process(MutableEntry<String, Integer> e, Object... args) { return INCR_PROCESSOR.process(e, args); } }; /** Increment processor for invoke operations. */ public static final EntryProcessor<String, Integer, String> RMV_PROCESSOR = new RemoveEntryProcessor(); /** Increment processor for invoke operations with IgniteEntryProcessor. */ public static final CacheEntryProcessor<String, Integer, String> RMV_IGNITE_PROCESSOR = new CacheEntryProcessor<String, Integer, String>() { /** */ private static final long serialVersionUID = 0L; @Override public String process(MutableEntry<String, Integer> e, Object... args) { return RMV_PROCESSOR.process(e, args); } }; /** Dflt grid. */ protected transient Ignite dfltIgnite; /** */ private Map<String, CacheConfiguration[]> cacheCfgMap; /** {@inheritDoc} */ @Override protected long getTestTimeout() { return TEST_TIMEOUT; } /** {@inheritDoc} */ @Override protected int gridCount() { return 1; } /** {@inheritDoc} */ @Override protected boolean swapEnabled() { return true; } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); ((TcpCommunicationSpi)cfg.getCommunicationSpi()).setSharedMemoryPort(-1); ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setForceServerMode(true); int[] evtTypes = cfg.getIncludeEventTypes(); if (evtTypes == null || evtTypes.length == 0) cfg.setIncludeEventTypes(EventType.EVT_CACHE_OBJECT_READ); else { for (int evtType : evtTypes) { if (evtType == EventType.EVT_CACHE_OBJECT_READ) return cfg; } int[] updatedEvtTypes = Arrays.copyOf(evtTypes, evtTypes.length + 1); updatedEvtTypes[updatedEvtTypes.length - 1] = EventType.EVT_CACHE_OBJECT_READ; } return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { initStoreStrategy(); if (cacheStartType() == CacheStartMode.STATIC) super.beforeTestsStarted(); else { cacheCfgMap = Collections.synchronizedMap(new HashMap<String, CacheConfiguration[]>()); if (cacheStartType() == CacheStartMode.NODES_THEN_CACHES) { super.beforeTestsStarted(); for (Map.Entry<String, CacheConfiguration[]> entry : cacheCfgMap.entrySet()) { Ignite ignite = grid(entry.getKey()); for (CacheConfiguration cfg : entry.getValue()) ignite.getOrCreateCache(cfg); } awaitPartitionMapExchange(); } else { int cnt = gridCount(); assert cnt >= 1 : "At least one grid must be started"; for (int i = 0; i < cnt; i++) { Ignite ignite = startGrid(i); CacheConfiguration[] cacheCfgs = cacheCfgMap.get(ignite.name()); for (CacheConfiguration cfg : cacheCfgs) ignite.createCache(cfg); } if (cnt > 1) checkTopology(cnt); awaitPartitionMapExchange(); } cacheCfgMap = null; } for (int i = 0; i < gridCount(); i++) info("Grid " + i + ": " + grid(i).localNode().id()); } /** * Checks that any invoke returns result. * * @throws Exception if something goes bad. * * TODO https://issues.apache.org/jira/browse/IGNITE-4380. */ public void _testInvokeAllMultithreaded() throws Exception { final IgniteCache<String, Integer> cache = jcache(); final int threadCnt = 4; final int cnt = 5000; // Concurrent invoke can not be used for ATOMIC cache in CLOCK mode. if (atomicityMode() == ATOMIC && cacheMode() != LOCAL && false) return; final Set<String> keys = Collections.singleton("myKey"); GridTestUtils.runMultiThreaded(new Runnable() { @Override public void run() { for (int i = 0; i < cnt; i++) { final Map<String, EntryProcessorResult<String>> res = cache.invokeAll(keys, INCR_PROCESSOR); assertEquals(1, res.size()); } } }, threadCnt, "testInvokeAllMultithreaded"); assertEquals(cnt * threadCnt, (int)cache.get("myKey")); } /** * Checks that skipStore flag gets overridden inside a transaction. */ public void testWriteThroughTx() { String key = "writeThroughKey"; storeStgy.removeFromStore(key); try (final Transaction transaction = grid(0).transactions().txStart()) { IgniteCache<String, Integer> cache = jcache(0); // retrieve market type from the grid Integer old = cache.withSkipStore().get(key); assertNull(old); // update the grid cache.put(key, 2); // finally commit the transaction transaction.commit(); } assertEquals(2, storeStgy.getFromStore(key)); } /** * Checks that skipStore flag gets overridden inside a transaction. */ public void testNoReadThroughTx() { String key = "writeThroughKey"; IgniteCache<String, Integer> cache = jcache(0); storeStgy.resetStore(); cache.put(key, 1); storeStgy.putToStore(key, 2); try (final Transaction transaction = grid(0).transactions().txStart()) { Integer old = cache.get(key); assertEquals((Integer)1, old); // update the grid cache.put(key, 2); // finally commit the transaction transaction.commit(); } assertEquals(0, storeStgy.getReads()); } /** {@inheritDoc} */ @Override protected Ignite startGrid(String igniteInstanceName, GridSpringResourceContext ctx) throws Exception { if (cacheCfgMap == null) return super.startGrid(igniteInstanceName, ctx); IgniteConfiguration cfg = getConfiguration(igniteInstanceName); cacheCfgMap.put(igniteInstanceName, cfg.getCacheConfiguration()); cfg.setCacheConfiguration(); if (!isRemoteJvm(igniteInstanceName)) return IgnitionEx.start(optimize(cfg), ctx); else return startRemoteGrid(igniteInstanceName, optimize(cfg), ctx); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { IgniteCache<String, Integer> cache = jcache(); assertEquals(0, cache.localSize()); assertEquals(0, cache.size()); super.beforeTest(); assertEquals(0, cache.localSize()); assertEquals(0, cache.size()); dfltIgnite = grid(0); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { super.afterTest(); IgniteCache<String, Integer> cache = jcache(); assertEquals(0, cache.localSize()); assertEquals(0, cache.size()); assertEquals(0, cache.size(ONHEAP)); dfltIgnite = null; } /** * @return A not near-only cache. */ protected IgniteCache<String, Integer> fullCache() { return jcache(); } /** * @throws Exception In case of error. */ public void testSize() throws Exception { assert jcache().localSize() == 0; int size = 10; final Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < size; i++) map.put("key" + i, i); // Put in primary nodes to avoid near readers which will prevent entry from being cleared. Map<ClusterNode, Collection<String>> mapped = grid(0).<String>affinity(null).mapKeysToNodes(map.keySet()); for (int i = 0; i < gridCount(); i++) { Collection<String> keys = mapped.get(grid(i).localNode()); if (!F.isEmpty(keys)) { for (String key : keys) jcache(i).put(key, map.get(key)); } } map.remove("key0"); mapped = grid(0).<String>affinity(null).mapKeysToNodes(map.keySet()); for (int i = 0; i < gridCount(); i++) { // Will actually delete entry from map. CU.invalidate(jcache(i), "key0"); assertNull("Failed check for grid: " + i, jcache(i).localPeek("key0", ONHEAP)); Collection<String> keysCol = mapped.get(grid(i).localNode()); assert jcache(i).localSize() != 0 || F.isEmpty(keysCol); } for (int i = 0; i < gridCount(); i++) executeOnLocalOrRemoteJvm(i, new CheckCacheSizeTask(map)); for (int i = 0; i < gridCount(); i++) { Collection<String> keysCol = mapped.get(grid(i).localNode()); assertEquals("Failed check for grid: " + i, !F.isEmpty(keysCol) ? keysCol.size() : 0, jcache(i).localSize(PRIMARY)); } int globalPrimarySize = map.size(); for (int i = 0; i < gridCount(); i++) assertEquals(globalPrimarySize, jcache(i).size(PRIMARY)); int times = 1; if (cacheMode() == REPLICATED) times = gridCount(); else if (cacheMode() == PARTITIONED) times = Math.min(gridCount(), jcache().getConfiguration(CacheConfiguration.class).getBackups() + 1); int globalSize = globalPrimarySize * times; for (int i = 0; i < gridCount(); i++) assertEquals(globalSize, jcache(i).size(ALL)); } /** * @throws Exception In case of error. */ public void testContainsKey() throws Exception { jcache().put("testContainsKey", 1); checkContainsKey(true, "testContainsKey"); checkContainsKey(false, "testContainsKeyWrongKey"); } /** * @throws Exception If failed. */ public void testContainsKeyTx() throws Exception { if (!txEnabled()) return; IgniteCache<String, Integer> cache = jcache(); IgniteTransactions txs = ignite(0).transactions(); for (int i = 0; i < 10; i++) { String key = String.valueOf(i); try (Transaction tx = txs.txStart()) { assertNull(key, cache.get(key)); assertFalse(cache.containsKey(key)); tx.commit(); } try (Transaction tx = txs.txStart()) { assertNull(key, cache.get(key)); cache.put(key, i); assertTrue(cache.containsKey(key)); tx.commit(); } } } /** * @throws Exception If failed. */ public void testContainsKeysTx() throws Exception { if (!txEnabled()) return; IgniteCache<String, Integer> cache = jcache(); IgniteTransactions txs = ignite(0).transactions(); Set<String> keys = new HashSet<>(); for (int i = 0; i < 10; i++) { String key = String.valueOf(i); keys.add(key); } try (Transaction tx = txs.txStart()) { for (String key : keys) assertNull(key, cache.get(key)); assertFalse(cache.containsKeys(keys)); tx.commit(); } try (Transaction tx = txs.txStart()) { for (String key : keys) assertNull(key, cache.get(key)); for (String key : keys) cache.put(key, 0); assertTrue(cache.containsKeys(keys)); tx.commit(); } } /** * @throws Exception If failed. */ public void testRemoveInExplicitLocks() throws Exception { if (lockingEnabled()) { IgniteCache<String, Integer> cache = jcache(); cache.put("a", 1); Lock lock = cache.lockAll(ImmutableSet.of("a", "b", "c", "d")); lock.lock(); try { cache.remove("a"); // Make sure single-key operation did not remove lock. cache.putAll(F.asMap("b", 2, "c", 3, "d", 4)); } finally { lock.unlock(); } } } /** * @throws Exception If failed. */ public void testRemoveAllSkipStore() throws Exception { IgniteCache<String, Integer> jcache = jcache(); jcache.putAll(F.asMap("1", 1, "2", 2, "3", 3)); jcache.withSkipStore().removeAll(); assertEquals((Integer)1, jcache.get("1")); assertEquals((Integer)2, jcache.get("2")); assertEquals((Integer)3, jcache.get("3")); } /** * @throws IgniteCheckedException If failed. */ public void testAtomicOps() throws IgniteCheckedException { IgniteCache<String, Integer> c = jcache(); final int cnt = 10; for (int i = 0; i < cnt; i++) assertNull(c.getAndPutIfAbsent("k" + i, i)); for (int i = 0; i < cnt; i++) { boolean wrong = i % 2 == 0; String key = "k" + i; boolean res = c.replace(key, wrong ? i + 1 : i, -1); assertEquals(wrong, !res); } for (int i = 0; i < cnt; i++) { boolean success = i % 2 != 0; String key = "k" + i; boolean res = c.remove(key, -1); assertTrue(success == res); } } /** * @throws Exception In case of error. */ public void testGet() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); assert cache.get("key1") == 1; assert cache.get("key2") == 2; assert cache.get("wrongKey") == null; } /** * @throws Exception In case of error. */ public void testGetEntry() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); CacheEntry<String, Integer> key1e = cache.getEntry("key1"); CacheEntry<String, Integer> key2e = cache.getEntry("key2"); CacheEntry<String, Integer> wrongKeye = cache.getEntry("wrongKey"); assert key1e.getValue() == 1; assert key1e.getKey().equals("key1"); assert key1e.version() != null; assert key2e.getValue() == 2; assert key2e.getKey().equals("key2"); assert key2e.version() != null; assert wrongKeye == null; } /** * @throws Exception In case of error. */ public void testGetAsync() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); IgniteFuture<Integer> fut1 = cache.getAsync("key1"); IgniteFuture<Integer> fut2 = cache.getAsync("key2"); IgniteFuture<Integer> fut3 = cache.getAsync("wrongKey"); assert fut1.get() == 1; assert fut2.get() == 2; assert fut3.get() == null; } /** * @throws Exception In case of error. */ public void testGetAsyncOld() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cacheAsync.get("key1"); IgniteFuture<Integer> fut1 = cacheAsync.future(); cacheAsync.get("key2"); IgniteFuture<Integer> fut2 = cacheAsync.future(); cacheAsync.get("wrongKey"); IgniteFuture<Integer> fut3 = cacheAsync.future(); assert fut1.get() == 1; assert fut2.get() == 2; assert fut3.get() == null; } /** * @throws Exception In case of error. */ public void testGetAll() throws Exception { Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; final IgniteCache<String, Integer> cache = jcache(); try { cache.put("key1", 1); cache.put("key2", 2); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.getAll(null).isEmpty(); return null; } }, NullPointerException.class, null); assert cache.getAll(Collections.<String>emptySet()).isEmpty(); Map<String, Integer> map1 = cache.getAll(ImmutableSet.of("key1", "key2", "key9999")); info("Retrieved map1: " + map1); assert 2 == map1.size() : "Invalid map: " + map1; assertEquals(1, (int)map1.get("key1")); assertEquals(2, (int)map1.get("key2")); assertNull(map1.get("key9999")); Map<String, Integer> map2 = cache.getAll(ImmutableSet.of("key1", "key2", "key9999")); info("Retrieved map2: " + map2); assert 2 == map2.size() : "Invalid map: " + map2; assertEquals(1, (int)map2.get("key1")); assertEquals(2, (int)map2.get("key2")); assertNull(map2.get("key9999")); // Now do the same checks but within transaction. if (txShouldBeUsed()) { try (Transaction tx0 = transactions().txStart()) { assert cache.getAll(Collections.<String>emptySet()).isEmpty(); map1 = cache.getAll(ImmutableSet.of("key1", "key2", "key9999")); info("Retrieved map1: " + map1); assert 2 == map1.size() : "Invalid map: " + map1; assertEquals(1, (int)map1.get("key1")); assertEquals(2, (int)map1.get("key2")); assertNull(map1.get("key9999")); map2 = cache.getAll(ImmutableSet.of("key1", "key2", "key9999")); info("Retrieved map2: " + map2); assert 2 == map2.size() : "Invalid map: " + map2; assertEquals(1, (int)map2.get("key1")); assertEquals(2, (int)map2.get("key2")); assertNull(map2.get("key9999")); tx0.commit(); } } } /** * @throws Exception In case of error. */ public void testGetEntries() throws Exception { Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; final IgniteCache<String, Integer> cache = jcache(); try { cache.put("key1", 1); cache.put("key2", 2); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.getEntries(null).isEmpty(); return null; } }, NullPointerException.class, null); assert cache.getEntries(Collections.<String>emptySet()).isEmpty(); Collection<CacheEntry<String, Integer>> c1 = cache.getEntries(ImmutableSet.of("key1", "key2", "key9999")); info("Retrieved c1: " + c1); assert 2 == c1.size() : "Invalid collection: " + c1; boolean b1 = false; boolean b2 = false; for (CacheEntry<String, Integer> e : c1) { if (e.getKey().equals("key1") && e.getValue().equals(1)) b1 = true; if (e.getKey().equals("key2") && e.getValue().equals(2)) b2 = true; } assertTrue(b1 && b2); Collection<CacheEntry<String, Integer>> c2 = cache.getEntries(ImmutableSet.of("key1", "key2", "key9999")); info("Retrieved c2: " + c2); assert 2 == c2.size() : "Invalid collection: " + c2; b1 = false; b2 = false; for (CacheEntry<String, Integer> e : c2) { if (e.getKey().equals("key1") && e.getValue().equals(1)) b1 = true; if (e.getKey().equals("key2") && e.getValue().equals(2)) b2 = true; } assertTrue(b1 && b2); // Now do the same checks but within transaction. if (txShouldBeUsed()) { try (Transaction tx0 = transactions().txStart()) { assert cache.getEntries(Collections.<String>emptySet()).isEmpty(); c1 = cache.getEntries(ImmutableSet.of("key1", "key2", "key9999")); info("Retrieved c1: " + c1); assert 2 == c1.size() : "Invalid collection: " + c1; b1 = false; b2 = false; for (CacheEntry<String, Integer> e : c1) { if (e.getKey().equals("key1") && e.getValue().equals(1)) b1 = true; if (e.getKey().equals("key2") && e.getValue().equals(2)) b2 = true; } assertTrue(b1 && b2); c2 = cache.getEntries(ImmutableSet.of("key1", "key2", "key9999")); info("Retrieved c2: " + c2); assert 2 == c2.size() : "Invalid collection: " + c2; b1 = false; b2 = false; for (CacheEntry<String, Integer> e : c2) { if (e.getKey().equals("key1") && e.getValue().equals(1)) b1 = true; if (e.getKey().equals("key2") && e.getValue().equals(2)) b2 = true; } assertTrue(b1 && b2); tx0.commit(); } } } /** * @throws Exception In case of error. */ public void testGetAllWithNulls() throws Exception { final IgniteCache<String, Integer> cache = jcache(); final Set<String> c = new HashSet<>(); c.add("key1"); c.add(null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.getAll(c); return null; } }, NullPointerException.class, null); } /** * @throws Exception If failed. */ public void testGetTxNonExistingKey() throws Exception { if (txShouldBeUsed()) { try (Transaction ignored = transactions().txStart()) { assert jcache().get("key999123") == null; } } } /** * @throws Exception In case of error. */ public void testGetAllAsync() throws Exception { final IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.getAllAsync(null); return null; } }, NullPointerException.class, null); IgniteFuture<Map<String, Integer>> fut2 = cache.getAllAsync(Collections.<String>emptySet()); IgniteFuture<Map<String, Integer>> fut3 = cache.getAllAsync(ImmutableSet.of("key1", "key2")); assert fut2.get().isEmpty(); assert fut3.get().size() == 2 : "Invalid map: " + fut3.get(); assert fut3.get().get("key1") == 1; assert fut3.get().get("key2") == 2; } /** * @throws Exception In case of error. */ public void testGetAllAsyncOld() throws Exception { final IgniteCache<String, Integer> cache = jcache(); final IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cache.put("key1", 1); cache.put("key2", 2); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cacheAsync.getAll(null); return null; } }, NullPointerException.class, null); cacheAsync.getAll(Collections.<String>emptySet()); IgniteFuture<Map<String, Integer>> fut2 = cacheAsync.future(); cacheAsync.getAll(ImmutableSet.of("key1", "key2")); IgniteFuture<Map<String, Integer>> fut3 = cacheAsync.future(); assert fut2.get().isEmpty(); assert fut3.get().size() == 2 : "Invalid map: " + fut3.get(); assert fut3.get().get("key1") == 1; assert fut3.get().get("key2") == 2; } /** * @throws Exception In case of error. */ public void testPut() throws Exception { IgniteCache<String, Integer> cache = jcache(); assert cache.getAndPut("key1", 1) == null; assert cache.getAndPut("key2", 2) == null; // Check inside transaction. assert cache.get("key1") == 1; assert cache.get("key2") == 2; // Put again to check returned values. assert cache.getAndPut("key1", 1) == 1; assert cache.getAndPut("key2", 2) == 2; checkContainsKey(true, "key1"); checkContainsKey(true, "key2"); assert cache.get("key1") != null; assert cache.get("key2") != null; assert cache.get("wrong") == null; // Check outside transaction. checkContainsKey(true, "key1"); checkContainsKey(true, "key2"); assert cache.get("key1") == 1; assert cache.get("key2") == 2; assert cache.get("wrong") == null; assertEquals((Integer)1, cache.getAndPut("key1", 10)); assertEquals((Integer)2, cache.getAndPut("key2", 11)); } /** * @throws Exception In case of error. */ public void testPutTx() throws Exception { if (txShouldBeUsed()) { IgniteCache<String, Integer> cache = jcache(); try (Transaction tx = transactions().txStart()) { assert cache.getAndPut("key1", 1) == null; assert cache.getAndPut("key2", 2) == null; // Check inside transaction. assert cache.get("key1") == 1; assert cache.get("key2") == 2; // Put again to check returned values. assert cache.getAndPut("key1", 1) == 1; assert cache.getAndPut("key2", 2) == 2; assert cache.get("key1") != null; assert cache.get("key2") != null; assert cache.get("wrong") == null; tx.commit(); } // Check outside transaction. checkContainsKey(true, "key1"); checkContainsKey(true, "key2"); assert cache.get("key1") == 1; assert cache.get("key2") == 2; assert cache.get("wrong") == null; assertEquals((Integer)1, cache.getAndPut("key1", 10)); assertEquals((Integer)2, cache.getAndPut("key2", 11)); } } /** * @throws Exception If failed. */ public void testTransformOptimisticReadCommitted() throws Exception { checkTransform(OPTIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testTransformOptimisticRepeatableRead() throws Exception { checkTransform(OPTIMISTIC, REPEATABLE_READ); } /** * @throws Exception If failed. */ public void testTransformPessimisticReadCommitted() throws Exception { checkTransform(PESSIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testTransformPessimisticRepeatableRead() throws Exception { checkTransform(PESSIMISTIC, REPEATABLE_READ); } /** * @throws Exception If failed. */ public void testIgniteTransformOptimisticReadCommitted() throws Exception { checkIgniteTransform(OPTIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testIgniteTransformOptimisticRepeatableRead() throws Exception { checkIgniteTransform(OPTIMISTIC, REPEATABLE_READ); } /** * @throws Exception If failed. */ public void testIgniteTransformPessimisticReadCommitted() throws Exception { checkIgniteTransform(PESSIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testIgniteTransformPessimisticRepeatableRead() throws Exception { checkIgniteTransform(PESSIMISTIC, REPEATABLE_READ); } /** * @param concurrency Concurrency. * @param isolation Isolation. * @throws Exception If failed. */ private void checkIgniteTransform(TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key2", 1); cache.put("key3", 3); Transaction tx = txShouldBeUsed() ? ignite(0).transactions().txStart(concurrency, isolation) : null; try { assertEquals("null", cache.invoke("key1", INCR_IGNITE_PROCESSOR)); assertEquals("1", cache.invoke("key2", INCR_IGNITE_PROCESSOR)); assertEquals("3", cache.invoke("key3", RMV_IGNITE_PROCESSOR)); if (tx != null) tx.commit(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (tx != null) tx.close(); } assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertNull(cache.get("key3")); for (int i = 0; i < gridCount(); i++) assertNull("Failed for cache: " + i, jcache(i).localPeek("key3", ONHEAP)); cache.remove("key1"); cache.put("key2", 1); cache.put("key3", 3); assertEquals("null", cache.invoke("key1", INCR_IGNITE_PROCESSOR)); assertEquals("1", cache.invoke("key2", INCR_IGNITE_PROCESSOR)); assertEquals("3", cache.invoke("key3", RMV_IGNITE_PROCESSOR)); assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertNull(cache.get("key3")); for (int i = 0; i < gridCount(); i++) assertNull(jcache(i).localPeek("key3", ONHEAP)); } /** * @param concurrency Concurrency. * @param isolation Isolation. * @throws Exception If failed. */ private void checkTransform(TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key2", 1); cache.put("key3", 3); Transaction tx = txShouldBeUsed() ? ignite(0).transactions().txStart(concurrency, isolation) : null; try { assertEquals("null", cache.invoke("key1", INCR_PROCESSOR)); assertEquals("1", cache.invoke("key2", INCR_PROCESSOR)); assertEquals("3", cache.invoke("key3", RMV_PROCESSOR)); if (tx != null) tx.commit(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (tx != null) tx.close(); } assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertNull(cache.get("key3")); for (int i = 0; i < gridCount(); i++) assertNull("Failed for cache: " + i, jcache(i).localPeek("key3", ONHEAP)); cache.remove("key1"); cache.put("key2", 1); cache.put("key3", 3); assertEquals("null", cache.invoke("key1", INCR_PROCESSOR)); assertEquals("1", cache.invoke("key2", INCR_PROCESSOR)); assertEquals("3", cache.invoke("key3", RMV_PROCESSOR)); assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertNull(cache.get("key3")); for (int i = 0; i < gridCount(); i++) assertNull(jcache(i).localPeek("key3", ONHEAP)); } /** * @throws Exception If failed. */ public void testTransformAllOptimisticReadCommitted() throws Exception { checkTransformAll(OPTIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testTransformAllOptimisticRepeatableRead() throws Exception { checkTransformAll(OPTIMISTIC, REPEATABLE_READ); } /** * @throws Exception If failed. */ public void testTransformAllPessimisticReadCommitted() throws Exception { checkTransformAll(PESSIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testTransformAllPessimisticRepeatableRead() throws Exception { checkTransformAll(PESSIMISTIC, REPEATABLE_READ); } /** * @param concurrency Transaction concurrency. * @param isolation Transaction isolation. * @throws Exception If failed. */ private void checkTransformAll(TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception { final IgniteCache<String, Integer> cache = jcache(); cache.put("key2", 1); cache.put("key3", 3); if (txShouldBeUsed()) { Map<String, EntryProcessorResult<String>> res; try (Transaction tx = ignite(0).transactions().txStart(concurrency, isolation)) { res = cache.invokeAll(F.asSet("key1", "key2", "key3"), INCR_PROCESSOR); tx.commit(); } assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertEquals((Integer)4, cache.get("key3")); assertEquals("null", res.get("key1").get()); assertEquals("1", res.get("key2").get()); assertEquals("3", res.get("key3").get()); assertEquals(3, res.size()); cache.remove("key1"); cache.put("key2", 1); cache.put("key3", 3); } Map<String, EntryProcessorResult<String>> res = cache.invokeAll(F.asSet("key1", "key2", "key3"), RMV_PROCESSOR); for (int i = 0; i < gridCount(); i++) { assertNull(jcache(i).localPeek("key1", ONHEAP)); assertNull(jcache(i).localPeek("key2", ONHEAP)); assertNull(jcache(i).localPeek("key3", ONHEAP)); } assertEquals("null", res.get("key1").get()); assertEquals("1", res.get("key2").get()); assertEquals("3", res.get("key3").get()); assertEquals(3, res.size()); cache.remove("key1"); cache.put("key2", 1); cache.put("key3", 3); res = cache.invokeAll(F.asSet("key1", "key2", "key3"), INCR_PROCESSOR); assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertEquals((Integer)4, cache.get("key3")); assertEquals("null", res.get("key1").get()); assertEquals("1", res.get("key2").get()); assertEquals("3", res.get("key3").get()); assertEquals(3, res.size()); cache.remove("key1"); cache.put("key2", 1); cache.put("key3", 3); res = cache.invokeAll(F.asMap("key1", INCR_PROCESSOR, "key2", INCR_PROCESSOR, "key3", INCR_PROCESSOR)); assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertEquals((Integer)4, cache.get("key3")); assertEquals("null", res.get("key1").get()); assertEquals("1", res.get("key2").get()); assertEquals("3", res.get("key3").get()); assertEquals(3, res.size()); } /** * @throws Exception If failed. */ public void testTransformAllWithNulls() throws Exception { final IgniteCache<String, Integer> cache = jcache(); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.invokeAll((Set<String>)null, INCR_PROCESSOR); return null; } }, NullPointerException.class, null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.invokeAll(F.asSet("key1"), null); return null; } }, NullPointerException.class, null); { final Set<String> keys = new LinkedHashSet<>(2); keys.add("key1"); keys.add(null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.invokeAll(keys, INCR_PROCESSOR); return null; } }, NullPointerException.class, null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.invokeAll(F.asSet("key1"), null); return null; } }, NullPointerException.class, null); } } /** * @throws Exception If failed. */ public void testTransformSequentialOptimisticNoStart() throws Exception { checkTransformSequential0(false, OPTIMISTIC); } /** * @throws Exception If failed. */ public void testTransformSequentialPessimisticNoStart() throws Exception { checkTransformSequential0(false, PESSIMISTIC); } /** * @throws Exception If failed. */ public void testTransformSequentialOptimisticWithStart() throws Exception { checkTransformSequential0(true, OPTIMISTIC); } /** * @throws Exception If failed. */ public void testTransformSequentialPessimisticWithStart() throws Exception { checkTransformSequential0(true, PESSIMISTIC); } /** * @param startVal Whether to put value. * @param concurrency Concurrency. * @throws Exception If failed. */ private void checkTransformSequential0(boolean startVal, TransactionConcurrency concurrency) throws Exception { IgniteCache<String, Integer> cache = jcache(); final String key = primaryKeysForCache(cache, 1).get(0); Transaction tx = txShouldBeUsed() ? ignite(0).transactions().txStart(concurrency, READ_COMMITTED) : null; try { if (startVal) cache.put(key, 2); else assertEquals(null, cache.get(key)); Integer expRes = startVal ? 2 : null; assertEquals(String.valueOf(expRes), cache.invoke(key, INCR_PROCESSOR)); expRes = startVal ? 3 : 1; assertEquals(String.valueOf(expRes), cache.invoke(key, INCR_PROCESSOR)); expRes++; assertEquals(String.valueOf(expRes), cache.invoke(key, INCR_PROCESSOR)); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } Integer exp = (startVal ? 2 : 0) + 3; assertEquals(exp, cache.get(key)); for (int i = 0; i < gridCount(); i++) { if (ignite(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) assertEquals(exp, peek(jcache(i), key)); } } /** * @throws Exception If failed. */ public void testTransformAfterRemoveOptimistic() throws Exception { checkTransformAfterRemove(OPTIMISTIC); } /** * @throws Exception If failed. */ public void testTransformAfterRemovePessimistic() throws Exception { checkTransformAfterRemove(PESSIMISTIC); } /** * @param concurrency Concurrency. * @throws Exception If failed. */ private void checkTransformAfterRemove(TransactionConcurrency concurrency) throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key", 4); Transaction tx = txShouldBeUsed() ? ignite(0).transactions().txStart(concurrency, READ_COMMITTED) : null; try { cache.remove("key"); cache.invoke("key", INCR_PROCESSOR); cache.invoke("key", INCR_PROCESSOR); cache.invoke("key", INCR_PROCESSOR); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assertEquals((Integer)3, cache.get("key")); } /** * @throws Exception If failed. */ public void testTransformReturnValueGetOptimisticReadCommitted() throws Exception { checkTransformReturnValue(false, OPTIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testTransformReturnValueGetOptimisticRepeatableRead() throws Exception { checkTransformReturnValue(false, OPTIMISTIC, REPEATABLE_READ); } /** * @throws Exception If failed. */ public void testTransformReturnValueGetPessimisticReadCommitted() throws Exception { checkTransformReturnValue(false, PESSIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testTransformReturnValueGetPessimisticRepeatableRead() throws Exception { checkTransformReturnValue(false, PESSIMISTIC, REPEATABLE_READ); } /** * @throws Exception If failed. */ public void testTransformReturnValuePutInTx() throws Exception { checkTransformReturnValue(true, OPTIMISTIC, READ_COMMITTED); } /** * @param put Whether to put value. * @param concurrency Concurrency. * @param isolation Isolation. * @throws Exception If failed. */ private void checkTransformReturnValue(boolean put, TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception { IgniteCache<String, Integer> cache = jcache(); if (!put) cache.put("key", 1); Transaction tx = txShouldBeUsed() ? ignite(0).transactions().txStart(concurrency, isolation) : null; try { if (put) cache.put("key", 1); cache.invoke("key", INCR_PROCESSOR); assertEquals((Integer)2, cache.get("key")); if (tx != null) { // Second get inside tx. Make sure read value is not transformed twice. assertEquals((Integer)2, cache.get("key")); tx.commit(); } } finally { if (tx != null) tx.close(); } } /** * @throws Exception In case of error. */ public void testGetAndPutAsyncOld() throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cache.put("key1", 1); cache.put("key2", 2); cacheAsync.getAndPut("key1", 10); IgniteFuture<Integer> fut1 = cacheAsync.future(); cacheAsync.getAndPut("key2", 11); IgniteFuture<Integer> fut2 = cacheAsync.future(); assertEquals((Integer)1, fut1.get(5000)); assertEquals((Integer)2, fut2.get(5000)); assertEquals((Integer)10, cache.get("key1")); assertEquals((Integer)11, cache.get("key2")); } /** * @throws Exception In case of error. */ public void testGetAndPutAsync() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); IgniteFuture<Integer> fut1 = cache.getAndPutAsync("key1", 10); IgniteFuture<Integer> fut2 = cache.getAndPutAsync("key2", 11); assertEquals((Integer)1, fut1.get(5000)); assertEquals((Integer)2, fut2.get(5000)); assertEquals((Integer)10, cache.get("key1")); assertEquals((Integer)11, cache.get("key2")); } /** * @throws Exception In case of error. */ public void testPutAsyncOld0() throws Exception { IgniteCache<String, Integer> cacheAsync = jcache().withAsync(); cacheAsync.getAndPut("key1", 0); IgniteFuture<Integer> fut1 = cacheAsync.future(); cacheAsync.getAndPut("key2", 1); IgniteFuture<Integer> fut2 = cacheAsync.future(); assert fut1.get(5000) == null; assert fut2.get(5000) == null; } /** * @throws Exception In case of error. */ public void testPutAsync0() throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteFuture<Integer> fut1 = cache.getAndPutAsync("key1", 0); IgniteFuture<Integer> fut2 = cache.getAndPutAsync("key2", 1); assert fut1.get(5000) == null; assert fut2.get(5000) == null; } /** * @throws Exception If failed. */ public void testInvokeAsyncOld() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key2", 1); cache.put("key3", 3); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); assertNull(cacheAsync.invoke("key1", INCR_PROCESSOR)); IgniteFuture<?> fut0 = cacheAsync.future(); assertNull(cacheAsync.invoke("key2", INCR_PROCESSOR)); IgniteFuture<?> fut1 = cacheAsync.future(); assertNull(cacheAsync.invoke("key3", RMV_PROCESSOR)); IgniteFuture<?> fut2 = cacheAsync.future(); fut0.get(); fut1.get(); fut2.get(); assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertNull(cache.get("key3")); for (int i = 0; i < gridCount(); i++) assertNull(jcache(i).localPeek("key3", ONHEAP)); } /** * @throws Exception If failed. */ public void testInvokeAsync() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key2", 1); cache.put("key3", 3); IgniteFuture<?> fut0 = cache.invokeAsync("key1", INCR_PROCESSOR); IgniteFuture<?> fut1 = cache.invokeAsync("key2", INCR_PROCESSOR); IgniteFuture<?> fut2 = cache.invokeAsync("key3", RMV_PROCESSOR); fut0.get(); fut1.get(); fut2.get(); assertEquals((Integer)1, cache.get("key1")); assertEquals((Integer)2, cache.get("key2")); assertNull(cache.get("key3")); for (int i = 0; i < gridCount(); i++) assertNull(jcache(i).localPeek("key3", ONHEAP)); } /** * @throws Exception If failed. */ public void testInvoke() throws Exception { final IgniteCache<String, Integer> cache = jcache(); assertEquals("null", cache.invoke("k0", INCR_PROCESSOR)); assertEquals((Integer)1, cache.get("k0")); assertEquals("1", cache.invoke("k0", INCR_PROCESSOR)); assertEquals((Integer)2, cache.get("k0")); cache.put("k1", 1); assertEquals("1", cache.invoke("k1", INCR_PROCESSOR)); assertEquals((Integer)2, cache.get("k1")); assertEquals("2", cache.invoke("k1", INCR_PROCESSOR)); assertEquals((Integer)3, cache.get("k1")); EntryProcessor<String, Integer, Integer> c = new RemoveAndReturnNullEntryProcessor(); assertNull(cache.invoke("k1", c)); assertNull(cache.get("k1")); for (int i = 0; i < gridCount(); i++) assertNull(jcache(i).localPeek("k1", ONHEAP)); final EntryProcessor<String, Integer, Integer> errProcessor = new FailedEntryProcessor(); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.invoke("k1", errProcessor); return null; } }, EntryProcessorException.class, "Test entry processor exception."); } /** * @throws Exception In case of error. */ public void testPutx() throws Exception { if (txShouldBeUsed()) checkPut(true); } /** * @throws Exception In case of error. */ public void testPutxNoTx() throws Exception { checkPut(false); } /** * @param inTx Whether to start transaction. * @throws Exception If failed. */ private void checkPut(boolean inTx) throws Exception { Transaction tx = inTx ? transactions().txStart() : null; IgniteCache<String, Integer> cache = jcache(); try { cache.put("key1", 1); cache.put("key2", 2); // Check inside transaction. assert cache.get("key1") == 1; assert cache.get("key2") == 2; if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } checkSize(F.asSet("key1", "key2")); // Check outside transaction. checkContainsKey(true, "key1"); checkContainsKey(true, "key2"); checkContainsKey(false, "wrong"); assert cache.get("key1") == 1; assert cache.get("key2") == 2; assert cache.get("wrong") == null; } /** * @throws Exception If failed. */ public void testPutAsyncOld() throws Exception { Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; IgniteCache<String, Integer> cacheAsync = jcache().withAsync(); try { jcache().put("key2", 1); cacheAsync.put("key1", 10); IgniteFuture<?> fut1 = cacheAsync.future(); cacheAsync.put("key2", 11); IgniteFuture<?> fut2 = cacheAsync.future(); IgniteFuture<Transaction> f = null; if (tx != null) { tx = (Transaction)tx.withAsync(); tx.commit(); f = tx.future(); } assertNull(fut1.get()); assertNull(fut2.get()); assert f == null || f.get().state() == COMMITTED; } finally { if (tx != null) tx.close(); } checkSize(F.asSet("key1", "key2")); assert jcache().get("key1") == 10; assert jcache().get("key2") == 11; } /** * @throws Exception If failed. */ public void testPutAsync() throws Exception { Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; try { jcache().put("key2", 1); IgniteFuture<?> fut1 = jcache().putAsync("key1", 10); IgniteFuture<?> fut2 = jcache().putAsync("key2", 11); IgniteFuture<Void> f = null; if (tx != null) f = tx.commitAsync(); assertNull(fut1.get()); assertNull(fut2.get()); try { if (f != null) f.get(); } catch (Throwable t) { assert false : "Unexpected exception " + t; } } finally { if (tx != null) tx.close(); } checkSize(F.asSet("key1", "key2")); assert jcache().get("key1") == 10; assert jcache().get("key2") == 11; } /** * @throws Exception In case of error. */ public void testPutAll() throws Exception { Map<String, Integer> map = F.asMap("key1", 1, "key2", 2); IgniteCache<String, Integer> cache = jcache(); cache.putAll(map); checkSize(F.asSet("key1", "key2")); assert cache.get("key1") == 1; assert cache.get("key2") == 2; map.put("key1", 10); map.put("key2", 20); cache.putAll(map); checkSize(F.asSet("key1", "key2")); assert cache.get("key1") == 10; assert cache.get("key2") == 20; } /** * @throws Exception In case of error. */ public void testNullInTx() throws Exception { if (!txShouldBeUsed()) return; final IgniteCache<String, Integer> cache = jcache(); for (int i = 0; i < 100; i++) { final String key = "key-" + i; assertNull(cache.get(key)); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { IgniteTransactions txs = transactions(); try (Transaction tx = txs.txStart()) { cache.put(key, 1); cache.put(null, 2); tx.commit(); } return null; } }, NullPointerException.class, null); assertNull(cache.get(key)); cache.put(key, 1); assertEquals(1, (int)cache.get(key)); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { IgniteTransactions txs = transactions(); try (Transaction tx = txs.txStart()) { cache.put(key, 2); cache.remove(null); tx.commit(); } return null; } }, NullPointerException.class, null); assertEquals(1, (int)cache.get(key)); cache.put(key, 2); assertEquals(2, (int)cache.get(key)); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { IgniteTransactions txs = transactions(); Map<String, Integer> map = new LinkedHashMap<>(); map.put("k1", 1); map.put("k2", 2); map.put(null, 3); try (Transaction tx = txs.txStart()) { cache.put(key, 1); cache.putAll(map); tx.commit(); } return null; } }, NullPointerException.class, null); assertNull(cache.get("k1")); assertNull(cache.get("k2")); assertEquals(2, (int)cache.get(key)); cache.put(key, 3); assertEquals(3, (int)cache.get(key)); } } /** * @throws Exception In case of error. */ public void testPutAllWithNulls() throws Exception { final IgniteCache<String, Integer> cache = jcache(); { final Map<String, Integer> m = new LinkedHashMap<>(2); m.put("key1", 1); m.put(null, 2); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.putAll(m); return null; } }, NullPointerException.class, null); cache.put("key1", 1); assertEquals(1, (int)cache.get("key1")); } { final Map<String, Integer> m = new LinkedHashMap<>(2); m.put("key3", 3); m.put("key4", null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.putAll(m); return null; } }, NullPointerException.class, null); m.put("key4", 4); cache.putAll(m); assertEquals(3, (int)cache.get("key3")); assertEquals(4, (int)cache.get("key4")); } assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.put("key1", null); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.getAndPut("key1", null); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.put(null, 1); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.replace(null, 1); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.getAndReplace(null, 1); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.replace("key", null); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.getAndReplace("key", null); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.replace(null, 1, 2); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.replace("key", null, 2); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); assertThrows(log, new Callable<Object>() { @Nullable @Override public Object call() throws Exception { cache.replace("key", 1, null); return null; } }, NullPointerException.class, A.NULL_MSG_PREFIX); } /** * @throws Exception In case of error. */ public void testPutAllAsyncOld() throws Exception { Map<String, Integer> map = F.asMap("key1", 1, "key2", 2); IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cacheAsync.putAll(map); IgniteFuture<?> f1 = cacheAsync.future(); map.put("key1", 10); map.put("key2", 20); cacheAsync.putAll(map); IgniteFuture<?> f2 = cacheAsync.future(); assertNull(f2.get()); assertNull(f1.get()); checkSize(F.asSet("key1", "key2")); assert cache.get("key1") == 10; assert cache.get("key2") == 20; } /** * @throws Exception In case of error. */ public void testPutAllAsync() throws Exception { Map<String, Integer> map = F.asMap("key1", 1, "key2", 2); IgniteCache<String, Integer> cache = jcache(); IgniteFuture<?> f1 = cache.putAllAsync(map); map.put("key1", 10); map.put("key2", 20); IgniteFuture<?> f2 = cache.putAllAsync(map); assertNull(f2.get()); assertNull(f1.get()); checkSize(F.asSet("key1", "key2")); assert cache.get("key1") == 10; assert cache.get("key2") == 20; } /** * @throws Exception In case of error. */ public void testGetAndPutIfAbsent() throws Exception { Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; IgniteCache<String, Integer> cache = jcache(); try { assert cache.getAndPutIfAbsent("key", 1) == null; assert cache.get("key") != null; assert cache.get("key") == 1; assert cache.getAndPutIfAbsent("key", 2) != null; assert cache.getAndPutIfAbsent("key", 2) == 1; assert cache.get("key") != null; assert cache.get("key") == 1; if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assert cache.getAndPutIfAbsent("key", 2) != null; for (int i = 0; i < gridCount(); i++) { info("Peek on node [i=" + i + ", id=" + grid(i).localNode().id() + ", val=" + grid(i).cache(null).localPeek("key", ONHEAP) + ']'); } assertEquals((Integer)1, cache.getAndPutIfAbsent("key", 2)); assert cache.get("key") != null; assert cache.get("key") == 1; // Check swap. cache.put("key2", 1); cache.localEvict(Collections.singleton("key2")); assertEquals((Integer)1, cache.getAndPutIfAbsent("key2", 3)); // Check db. if (!isMultiJvm()) { storeStgy.putToStore("key3", 3); assertEquals((Integer)3, cache.getAndPutIfAbsent("key3", 4)); assertEquals((Integer)3, cache.get("key3")); } assertEquals((Integer)1, cache.get("key2")); cache.localEvict(Collections.singleton("key2")); // Same checks inside tx. tx = txShouldBeUsed() ? transactions().txStart() : null; try { assertEquals((Integer)1, cache.getAndPutIfAbsent("key2", 3)); if (tx != null) tx.commit(); assertEquals((Integer)1, cache.get("key2")); } finally { if (tx != null) tx.close(); } } /** * @throws Exception If failed. */ public void testGetAndPutIfAbsentAsyncOld() throws Exception { Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); try { cacheAsync.getAndPutIfAbsent("key", 1); IgniteFuture<Integer> fut1 = cacheAsync.future(); assertNull(fut1.get()); assertEquals((Integer)1, cache.get("key")); cacheAsync.getAndPutIfAbsent("key", 2); IgniteFuture<Integer> fut2 = cacheAsync.future(); assertEquals((Integer)1, fut2.get()); assertEquals((Integer)1, cache.get("key")); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } // Check swap. cache.put("key2", 1); cache.localEvict(Collections.singleton("key2")); cacheAsync.getAndPutIfAbsent("key2", 3); assertEquals((Integer)1, cacheAsync.<Integer>future().get()); // Check db. if (!isMultiJvm()) { storeStgy.putToStore("key3", 3); cacheAsync.getAndPutIfAbsent("key3", 4); assertEquals((Integer)3, cacheAsync.<Integer>future().get()); } cache.localEvict(Collections.singleton("key2")); // Same checks inside tx. tx = txShouldBeUsed() ? transactions().txStart() : null; try { cacheAsync.getAndPutIfAbsent("key2", 3); assertEquals(1, cacheAsync.future().get()); if (tx != null) tx.commit(); assertEquals((Integer)1, cache.get("key2")); } finally { if (tx != null) tx.close(); } } /** * @throws Exception If failed. */ public void testGetAndPutIfAbsentAsync() throws Exception { Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; IgniteCache<String, Integer> cache = jcache(); try { IgniteFuture<Integer> fut1 = cache.getAndPutIfAbsentAsync("key", 1); assertNull(fut1.get()); assertEquals((Integer)1, cache.get("key")); IgniteFuture<Integer> fut2 = cache.getAndPutIfAbsentAsync("key", 2); assertEquals((Integer)1, fut2.get()); assertEquals((Integer)1, cache.get("key")); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } // Check swap. cache.put("key2", 1); cache.localEvict(Collections.singleton("key2")); assertEquals((Integer)1, cache.getAndPutIfAbsentAsync("key2", 3).get()); // Check db. if (!isMultiJvm()) { storeStgy.putToStore("key3", 3); assertEquals((Integer)3, cache.getAndPutIfAbsentAsync("key3", 4).get()); } cache.localEvict(Collections.singleton("key2")); // Same checks inside tx. tx = txShouldBeUsed() ? transactions().txStart() : null; try { assertEquals(1, (int)cache.getAndPutIfAbsentAsync("key2", 3).get()); if (tx != null) tx.commit(); assertEquals((Integer)1, cache.get("key2")); } finally { if (tx != null) tx.close(); } } /** * @throws Exception If failed. */ public void testPutIfAbsent() throws Exception { IgniteCache<String, Integer> cache = jcache(); assertNull(cache.get("key")); assert cache.putIfAbsent("key", 1); assert cache.get("key") != null && cache.get("key") == 1; assert !cache.putIfAbsent("key", 2); assert cache.get("key") != null && cache.get("key") == 1; // Check swap. cache.put("key2", 1); cache.localEvict(Collections.singleton("key2")); assertFalse(cache.putIfAbsent("key2", 3)); // Check db. if (!isMultiJvm()) { storeStgy.putToStore("key3", 3); assertFalse(cache.putIfAbsent("key3", 4)); } cache.localEvict(Collections.singleton("key2")); // Same checks inside tx. Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; try { assertFalse(cache.putIfAbsent("key2", 3)); if (tx != null) tx.commit(); assertEquals((Integer)1, cache.get("key2")); } finally { if (tx != null) tx.close(); } } /** * @throws Exception In case of error. */ public void testPutxIfAbsentAsync() throws Exception { if (txShouldBeUsed()) checkPutxIfAbsentAsync(true); } /** * @throws Exception In case of error. */ public void testPutxIfAbsentAsyncNoTx() throws Exception { checkPutxIfAbsentAsync(false); } /** * @param inTx In tx flag. * @throws Exception If failed. */ private void checkPutxIfAbsentAsyncOld(boolean inTx) throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cacheAsync.putIfAbsent("key", 1); IgniteFuture<Boolean> fut1 = cacheAsync.future(); assert fut1.get(); assert cache.get("key") != null && cache.get("key") == 1; cacheAsync.putIfAbsent("key", 2); IgniteFuture<Boolean> fut2 = cacheAsync.future(); assert !fut2.get(); assert cache.get("key") != null && cache.get("key") == 1; // Check swap. cache.put("key2", 1); cache.localEvict(Collections.singleton("key2")); cacheAsync.putIfAbsent("key2", 3); assertFalse(cacheAsync.<Boolean>future().get()); // Check db. if (!isMultiJvm()) { storeStgy.putToStore("key3", 3); cacheAsync.putIfAbsent("key3", 4); assertFalse(cacheAsync.<Boolean>future().get()); } cache.localEvict(Collections.singletonList("key2")); // Same checks inside tx. Transaction tx = inTx ? transactions().txStart() : null; try { cacheAsync.putIfAbsent("key2", 3); assertFalse(cacheAsync.<Boolean>future().get()); if (!isMultiJvm()) { cacheAsync.putIfAbsent("key3", 4); assertFalse(cacheAsync.<Boolean>future().get()); } if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assertEquals((Integer)1, cache.get("key2")); if (!isMultiJvm()) assertEquals((Integer)3, cache.get("key3")); } /** * @param inTx In tx flag. * @throws Exception If failed. */ private void checkPutxIfAbsentAsync(boolean inTx) throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteFuture<Boolean> fut1 = cache.putIfAbsentAsync("key", 1); assert fut1.get(); assert cache.get("key") != null && cache.get("key") == 1; IgniteFuture<Boolean> fut2 = cache.putIfAbsentAsync("key", 2); assert !fut2.get(); assert cache.get("key") != null && cache.get("key") == 1; // Check swap. cache.put("key2", 1); cache.localEvict(Collections.singleton("key2")); assertFalse(cache.putIfAbsentAsync("key2", 3).get()); // Check db. if (!isMultiJvm()) { storeStgy.putToStore("key3", 3); assertFalse(cache.putIfAbsentAsync("key3", 4).get()); } cache.localEvict(Collections.singletonList("key2")); // Same checks inside tx. Transaction tx = inTx ? transactions().txStart() : null; try { assertFalse(cache.putIfAbsentAsync("key2", 3).get()); if (!isMultiJvm()) assertFalse(cache.putIfAbsentAsync("key3", 4).get()); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assertEquals((Integer)1, cache.get("key2")); if (!isMultiJvm()) assertEquals((Integer)3, cache.get("key3")); } /** * @throws Exception In case of error. */ public void testPutIfAbsentAsyncConcurrentOld() throws Exception { IgniteCache<String, Integer> cacheAsync = jcache().withAsync(); cacheAsync.putIfAbsent("key1", 1); IgniteFuture<Boolean> fut1 = cacheAsync.future(); cacheAsync.putIfAbsent("key2", 2); IgniteFuture<Boolean> fut2 = cacheAsync.future(); assert fut1.get(); assert fut2.get(); } /** * @throws Exception In case of error. */ public void testPutIfAbsentAsyncConcurrent() throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteFuture<Boolean> fut1 = cache.putIfAbsentAsync("key1", 1); IgniteFuture<Boolean> fut2 = cache.putIfAbsentAsync("key2", 2); assert fut1.get(); assert fut2.get(); } /** * @throws Exception If failed. */ public void testGetAndReplace() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key", 1); assert cache.get("key") == 1; info("key 1 -> 2"); assert cache.getAndReplace("key", 2) == 1; assert cache.get("key") == 2; assert cache.getAndReplace("wrong", 0) == null; assert cache.get("wrong") == null; info("key 0 -> 3"); assert !cache.replace("key", 0, 3); assert cache.get("key") == 2; info("key 0 -> 3"); assert !cache.replace("key", 0, 3); assert cache.get("key") == 2; info("key 2 -> 3"); assert cache.replace("key", 2, 3); assert cache.get("key") == 3; info("evict key"); cache.localEvict(Collections.singleton("key")); info("key 3 -> 4"); assert cache.replace("key", 3, 4); assert cache.get("key") == 4; if (!isMultiJvm()) { storeStgy.putToStore("key2", 5); info("key2 5 -> 6"); assert cache.replace("key2", 5, 6); } for (int i = 0; i < gridCount(); i++) { info("Peek key on grid [i=" + i + ", nodeId=" + grid(i).localNode().id() + ", peekVal=" + grid(i).cache(null).localPeek("key", ONHEAP) + ']'); info("Peek key2 on grid [i=" + i + ", nodeId=" + grid(i).localNode().id() + ", peekVal=" + grid(i).cache(null).localPeek("key2", ONHEAP) + ']'); } if (!isMultiJvm()) assertEquals((Integer)6, cache.get("key2")); cache.localEvict(Collections.singleton("key")); Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; try { assert cache.replace("key", 4, 5); if (tx != null) tx.commit(); assert cache.get("key") == 5; } finally { if (tx != null) tx.close(); } } /** * @throws Exception If failed. */ public void testReplace() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key", 1); assert cache.get("key") == 1; assert cache.replace("key", 2); assert cache.get("key") == 2; assert !cache.replace("wrong", 2); cache.localEvict(Collections.singleton("key")); assert cache.replace("key", 4); assert cache.get("key") == 4; if (!isMultiJvm()) { storeStgy.putToStore("key2", 5); assert cache.replace("key2", 6); assertEquals((Integer)6, cache.get("key2")); } cache.localEvict(Collections.singleton("key")); Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; try { assert cache.replace("key", 5); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assert cache.get("key") == 5; } /** * @throws Exception If failed. */ public void testGetAndReplaceAsyncOld() throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cache.put("key", 1); assert cache.get("key") == 1; cacheAsync.getAndReplace("key", 2); assert cacheAsync.<Integer>future().get() == 1; assert cache.get("key") == 2; cacheAsync.getAndReplace("wrong", 0); assert cacheAsync.future().get() == null; assert cache.get("wrong") == null; cacheAsync.replace("key", 0, 3); assert !cacheAsync.<Boolean>future().get(); assert cache.get("key") == 2; cacheAsync.replace("key", 0, 3); assert !cacheAsync.<Boolean>future().get(); assert cache.get("key") == 2; cacheAsync.replace("key", 2, 3); assert cacheAsync.<Boolean>future().get(); assert cache.get("key") == 3; cache.localEvict(Collections.singleton("key")); cacheAsync.replace("key", 3, 4); assert cacheAsync.<Boolean>future().get(); assert cache.get("key") == 4; if (!isMultiJvm()) { storeStgy.putToStore("key2", 5); cacheAsync.replace("key2", 5, 6); assert cacheAsync.<Boolean>future().get(); assertEquals((Integer)6, cache.get("key2")); } cache.localEvict(Collections.singleton("key")); Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; try { cacheAsync.replace("key", 4, 5); assert cacheAsync.<Boolean>future().get(); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assert cache.get("key") == 5; } /** * @throws Exception If failed. */ public void testGetAndReplaceAsync() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key", 1); assert cache.get("key") == 1; assert cache.getAndReplaceAsync("key", 2).get() == 1; assert cache.get("key") == 2; assert cache.getAndReplaceAsync("wrong", 0).get() == null; assert cache.get("wrong") == null; assert !cache.replaceAsync("key", 0, 3).get(); assert cache.get("key") == 2; assert !cache.replaceAsync("key", 0, 3).get(); assert cache.get("key") == 2; assert cache.replaceAsync("key", 2, 3).get(); assert cache.get("key") == 3; cache.localEvict(Collections.singleton("key")); assert cache.replaceAsync("key", 3, 4).get(); assert cache.get("key") == 4; if (!isMultiJvm()) { storeStgy.putToStore("key2", 5); assert cache.replaceAsync("key2", 5, 6).get(); assertEquals((Integer)6, cache.get("key2")); } cache.localEvict(Collections.singleton("key")); Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; try { assert cache.replaceAsync("key", 4, 5).get(); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assert cache.get("key") == 5; } /** * @throws Exception If failed. */ public void testReplacexAsyncOld() throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cache.put("key", 1); assert cache.get("key") == 1; cacheAsync.replace("key", 2); assert cacheAsync.<Boolean>future().get(); info("Finished replace."); assertEquals((Integer)2, cache.get("key")); cacheAsync.replace("wrond", 2); assert !cacheAsync.<Boolean>future().get(); cache.localEvict(Collections.singleton("key")); cacheAsync.replace("key", 4); assert cacheAsync.<Boolean>future().get(); assert cache.get("key") == 4; if (!isMultiJvm()) { storeStgy.putToStore("key2", 5); cacheAsync.replace("key2", 6); assert cacheAsync.<Boolean>future().get(); assert cache.get("key2") == 6; } cache.localEvict(Collections.singleton("key")); Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; try { cacheAsync.replace("key", 5); assert cacheAsync.<Boolean>future().get(); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assert cache.get("key") == 5; } /** * @throws Exception If failed. */ public void testReplacexAsync() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key", 1); assert cache.get("key") == 1; assert cache.replaceAsync("key", 2).get(); info("Finished replace."); assertEquals((Integer)2, cache.get("key")); assert !cache.replaceAsync("wrond", 2).get(); cache.localEvict(Collections.singleton("key")); assert cache.replaceAsync("key", 4).get(); assert cache.get("key") == 4; if (!isMultiJvm()) { storeStgy.putToStore("key2", 5); assert cache.replaceAsync("key2", 6).get(); assert cache.get("key2") == 6; } cache.localEvict(Collections.singleton("key")); Transaction tx = txShouldBeUsed() ? transactions().txStart() : null; try { assert cache.replaceAsync("key", 5).get(); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } assert cache.get("key") == 5; } /** * @throws Exception In case of error. */ public void testGetAndRemove() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); assert !cache.remove("key1", 0); assert cache.get("key1") != null && cache.get("key1") == 1; assert cache.remove("key1", 1); assert cache.get("key1") == null; assert cache.getAndRemove("key2") == 2; assert cache.get("key2") == null; assert cache.getAndRemove("key2") == null; } /** * @throws Exception If failed. */ public void testGetAndRemoveObject() throws Exception { IgniteCache<String, TestValue> cache = ignite(0).cache(null); TestValue val1 = new TestValue(1); TestValue val2 = new TestValue(2); cache.put("key1", val1); cache.put("key2", val2); assert !cache.remove("key1", new TestValue(0)); TestValue oldVal = cache.get("key1"); assert oldVal != null && F.eq(val1, oldVal); assert cache.remove("key1"); assert cache.get("key1") == null; TestValue oldVal2 = cache.getAndRemove("key2"); assert F.eq(val2, oldVal2); assert cache.get("key2") == null; assert cache.getAndRemove("key2") == null; } /** * @throws Exception If failed. */ public void testGetAndPutObject() throws Exception { IgniteCache<String, TestValue> cache = ignite(0).cache(null); TestValue val1 = new TestValue(1); TestValue val2 = new TestValue(2); cache.put("key1", val1); TestValue oldVal = cache.get("key1"); assertEquals(val1, oldVal); oldVal = cache.getAndPut("key1", val2); assertEquals(val1, oldVal); TestValue updVal = cache.get("key1"); assertEquals(val2, updVal); } /** * TODO: GG-11241. * * @throws Exception If failed. */ public void testDeletedEntriesFlag() throws Exception { if (cacheMode() != LOCAL && cacheMode() != REPLICATED) { final int cnt = 3; IgniteCache<String, Integer> cache = jcache(); for (int i = 0; i < cnt; i++) cache.put(String.valueOf(i), i); for (int i = 0; i < cnt; i++) cache.remove(String.valueOf(i)); for (int g = 0; g < gridCount(); g++) executeOnLocalOrRemoteJvm(g, new CheckEntriesDeletedTask(cnt)); } } /** * @throws Exception If failed. */ public void testRemoveLoad() throws Exception { int cnt = 10; Set<String> keys = new HashSet<>(); for (int i = 0; i < cnt; i++) keys.add(String.valueOf(i)); jcache().removeAll(keys); for (String key : keys) storeStgy.putToStore(key, Integer.parseInt(key)); for (int g = 0; g < gridCount(); g++) grid(g).cache(null).localLoadCache(null); for (int g = 0; g < gridCount(); g++) { for (int i = 0; i < cnt; i++) { String key = String.valueOf(i); if (grid(0).affinity(null).mapKeyToPrimaryAndBackups(key).contains(grid(g).localNode())) assertEquals((Integer)i, peek(jcache(g), key)); else assertNull(peek(jcache(g), key)); } } } /** * @throws Exception If failed. */ public void testRemoveLoadAsync() throws Exception { if (isMultiJvm()) return; int cnt = 10; Set<String> keys = new HashSet<>(); for (int i = 0; i < cnt; i++) keys.add(String.valueOf(i)); jcache().removeAllAsync(keys).get(); for (String key : keys) storeStgy.putToStore(key, Integer.parseInt(key)); for (int g = 0; g < gridCount(); g++) grid(g).cache(null).localLoadCacheAsync(null).get(); for (int g = 0; g < gridCount(); g++) { for (int i = 0; i < cnt; i++) { String key = String.valueOf(i); if (grid(0).affinity(null).mapKeyToPrimaryAndBackups(key).contains(grid(g).localNode())) assertEquals((Integer)i, peek(jcache(g), key)); else assertNull(peek(jcache(g), key)); } } } /** * @throws Exception In case of error. */ public void testRemoveAsyncOld() throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cache.put("key1", 1); cache.put("key2", 2); cacheAsync.remove("key1", 0); assert !cacheAsync.<Boolean>future().get(); assert cache.get("key1") != null && cache.get("key1") == 1; cacheAsync.remove("key1", 1); assert cacheAsync.<Boolean>future().get(); assert cache.get("key1") == null; cacheAsync.getAndRemove("key2"); assert cacheAsync.<Integer>future().get() == 2; assert cache.get("key2") == null; cacheAsync.getAndRemove("key2"); assert cacheAsync.future().get() == null; } /** * @throws Exception In case of error. */ public void testRemoveAsync() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); assert !cache.removeAsync("key1", 0).get(); assert cache.get("key1") != null && cache.get("key1") == 1; assert cache.removeAsync("key1", 1).get(); assert cache.get("key1") == null; assert cache.getAndRemoveAsync("key2").get() == 2; assert cache.get("key2") == null; assert cache.getAndRemoveAsync("key2").get() == null; } /** * @throws Exception In case of error. */ public void testRemove() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); assert cache.remove("key1"); assert cache.get("key1") == null; assert !cache.remove("key1"); } /** * @throws Exception In case of error. */ public void testRemovexAsyncOld() throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cache.put("key1", 1); cacheAsync.remove("key1"); assert cacheAsync.<Boolean>future().get(); assert cache.get("key1") == null; cacheAsync.remove("key1"); assert !cacheAsync.<Boolean>future().get(); } /** * @throws Exception In case of error. */ public void testRemovexAsync() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); assert cache.removeAsync("key1").get(); assert cache.get("key1") == null; assert !cache.removeAsync("key1").get(); } /** * @throws Exception In case of error. */ public void testGlobalRemoveAll() throws Exception { globalRemoveAll(false); } /** * @throws Exception In case of error. */ public void testGlobalRemoveAllAsync() throws Exception { globalRemoveAll(true); } /** * @param async If {@code true} uses asynchronous operation. * @throws Exception In case of error. */ private void globalRemoveAllOld(boolean async) throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); cache.put("key3", 3); checkSize(F.asSet("key1", "key2", "key3")); IgniteCache<String, Integer> asyncCache = cache.withAsync(); if (async) { asyncCache.removeAll(F.asSet("key1", "key2")); asyncCache.future().get(); } else cache.removeAll(F.asSet("key1", "key2")); checkSize(F.asSet("key3")); checkContainsKey(false, "key1"); checkContainsKey(false, "key2"); checkContainsKey(true, "key3"); // Put values again. cache.put("key1", 1); cache.put("key2", 2); cache.put("key3", 3); if (async) { IgniteCache<String, Integer> asyncCache0 = jcache(gridCount() > 1 ? 1 : 0).withAsync(); asyncCache0.removeAll(); asyncCache0.future().get(); } else jcache(gridCount() > 1 ? 1 : 0).removeAll(); assertEquals(0, cache.localSize()); long entryCnt = hugeRemoveAllEntryCount(); for (int i = 0; i < entryCnt; i++) cache.put(String.valueOf(i), i); for (int i = 0; i < entryCnt; i++) assertEquals(Integer.valueOf(i), cache.get(String.valueOf(i))); if (async) { asyncCache.removeAll(); asyncCache.future().get(); } else cache.removeAll(); for (int i = 0; i < entryCnt; i++) assertNull(cache.get(String.valueOf(i))); } /** * @param async If {@code true} uses asynchronous operation. * @throws Exception In case of error. */ private void globalRemoveAll(boolean async) throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); cache.put("key3", 3); checkSize(F.asSet("key1", "key2", "key3")); if (async) cache.removeAllAsync(F.asSet("key1", "key2")).get(); else cache.removeAll(F.asSet("key1", "key2")); checkSize(F.asSet("key3")); checkContainsKey(false, "key1"); checkContainsKey(false, "key2"); checkContainsKey(true, "key3"); // Put values again. cache.put("key1", 1); cache.put("key2", 2); cache.put("key3", 3); if (async) jcache(gridCount() > 1 ? 1 : 0).removeAllAsync().get(); else jcache(gridCount() > 1 ? 1 : 0).removeAll(); assertEquals(0, cache.localSize()); long entryCnt = hugeRemoveAllEntryCount(); for (int i = 0; i < entryCnt; i++) cache.put(String.valueOf(i), i); for (int i = 0; i < entryCnt; i++) assertEquals(Integer.valueOf(i), cache.get(String.valueOf(i))); if (async) cache.removeAllAsync().get(); else cache.removeAll(); for (int i = 0; i < entryCnt; i++) assertNull(cache.get(String.valueOf(i))); } /** * @return Count of entries to be removed in removeAll() test. */ protected long hugeRemoveAllEntryCount() { return 1000L; } /** * @throws Exception In case of error. */ public void testRemoveAllWithNulls() throws Exception { final IgniteCache<String, Integer> cache = jcache(); final Set<String> c = new LinkedHashSet<>(); c.add("key1"); c.add(null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.removeAll(c); return null; } }, NullPointerException.class, null); assertEquals(0, grid(0).cache(null).localSize()); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.removeAll(null); return null; } }, NullPointerException.class, null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.remove(null); return null; } }, NullPointerException.class, null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.getAndRemove(null); return null; } }, NullPointerException.class, null); GridTestUtils.assertThrows(log, new Callable<Void>() { @Override public Void call() throws Exception { cache.remove("key1", null); return null; } }, NullPointerException.class, null); } /** * @throws Exception In case of error. */ public void testRemoveAllDuplicates() throws Exception { jcache().removeAll(ImmutableSet.of("key1", "key1", "key1")); } /** * @throws Exception In case of error. */ public void testRemoveAllDuplicatesTx() throws Exception { if (txShouldBeUsed()) { try (Transaction tx = transactions().txStart()) { jcache().removeAll(ImmutableSet.of("key1", "key1", "key1")); tx.commit(); } } } /** * @throws Exception In case of error. */ public void testRemoveAllEmpty() throws Exception { jcache().removeAll(); } /** * @throws Exception In case of error. */ public void testRemoveAllAsyncOld() throws Exception { IgniteCache<String, Integer> cache = jcache(); IgniteCache<String, Integer> cacheAsync = cache.withAsync(); cache.put("key1", 1); cache.put("key2", 2); cache.put("key3", 3); checkSize(F.asSet("key1", "key2", "key3")); cacheAsync.removeAll(F.asSet("key1", "key2")); assertNull(cacheAsync.future().get()); checkSize(F.asSet("key3")); checkContainsKey(false, "key1"); checkContainsKey(false, "key2"); checkContainsKey(true, "key3"); } /** * @throws Exception In case of error. */ public void testRemoveAllAsync() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); cache.put("key3", 3); checkSize(F.asSet("key1", "key2", "key3")); assertNull(cache.removeAllAsync(F.asSet("key1", "key2")).get()); checkSize(F.asSet("key3")); checkContainsKey(false, "key1"); checkContainsKey(false, "key2"); checkContainsKey(true, "key3"); } /** * @throws Exception In case of error. */ public void testLoadAll() throws Exception { IgniteCache<String, Integer> cache = jcache(); Set<String> keys = new HashSet<>(primaryKeysForCache(cache, 2)); for (String key : keys) assertNull(cache.localPeek(key, ONHEAP)); Map<String, Integer> vals = new HashMap<>(); int i = 0; for (String key : keys) { cache.put(key, i); vals.put(key, i); i++; } for (String key : keys) assertEquals(vals.get(key), peek(cache, key)); cache.clear(); for (String key : keys) assertNull(peek(cache, key)); loadAll(cache, keys, true); for (String key : keys) assertEquals(vals.get(key), peek(cache, key)); } /** * @throws Exception If failed. */ public void testRemoveAfterClear() throws Exception { IgniteEx ignite = grid(0); boolean affNode = ignite.context().cache().internalCache(null).context().affinityNode(); if (!affNode) { if (gridCount() < 2) return; ignite = grid(1); } IgniteCache<Integer, Integer> cache = ignite.cache(null); int key = 0; Collection<Integer> keys = new ArrayList<>(); for (int k = 0; k < 2; k++) { while (!ignite.affinity(null).isPrimary(ignite.localNode(), key)) key++; keys.add(key); key++; } info("Keys: " + keys); for (Integer k : keys) cache.put(k, k); cache.clear(); for (int g = 0; g < gridCount(); g++) { Ignite grid0 = grid(g); grid0.cache(null).removeAll(); assertTrue(grid0.cache(null).localSize() == 0); } } /** * @throws Exception In case of error. */ public void testClear() throws Exception { IgniteCache<String, Integer> cache = jcache(); Set<String> keys = new HashSet<>(primaryKeysForCache(cache, 3)); for (String key : keys) assertNull(cache.get(key)); Map<String, Integer> vals = new HashMap<>(keys.size()); int i = 0; for (String key : keys) { cache.put(key, i); vals.put(key, i); i++; } for (String key : keys) assertEquals(vals.get(key), peek(cache, key)); cache.clear(); for (String key : keys) assertNull(peek(cache, key)); for (i = 0; i < gridCount(); i++) jcache(i).clear(); for (i = 0; i < gridCount(); i++) assert jcache(i).localSize() == 0; for (Map.Entry<String, Integer> entry : vals.entrySet()) cache.put(entry.getKey(), entry.getValue()); for (String key : keys) assertEquals(vals.get(key), peek(cache, key)); String first = F.first(keys); if (lockingEnabled()) { Lock lock = cache.lock(first); lock.lock(); try { cache.clear(); GridCacheContext<String, Integer> cctx = context(0); GridCacheEntryEx entry = cctx.isNear() ? cctx.near().dht().peekEx(first) : cctx.cache().peekEx(first); assertNotNull(entry); } finally { lock.unlock(); } } else { cache.clear(); cache.put(first, vals.get(first)); } cache.clear(); assert cache.localSize() == 0 : "Values after clear."; i = 0; for (String key : keys) { cache.put(key, i); vals.put(key, i); i++; } cache.put("key1", 1); cache.put("key2", 2); cache.localEvict(Sets.union(ImmutableSet.of("key1", "key2"), keys)); assert cache.localSize(ONHEAP) == 0; cache.clear(); assert cache.localPeek("key1", ONHEAP) == null; assert cache.localPeek("key2", ONHEAP) == null; } /** * @param keys0 Keys to check. * @throws IgniteCheckedException If failed. */ protected void checkUnlocked(final Collection<String> keys0) throws IgniteCheckedException { GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { try { for (int i = 0; i < gridCount(); i++) { GridCacheAdapter<Object, Object> cache = ((IgniteKernal)ignite(i)).internalCache(); for (String key : keys0) { GridCacheEntryEx entry = cache.peekEx(key); if (entry != null) { if (entry.lockedByAny()) { info("Entry is still locked [i=" + i + ", entry=" + entry + ']'); return false; } } if (cache.isNear()) { entry = cache.context().near().dht().peekEx(key); if (entry != null) { if (entry.lockedByAny()) { info("Entry is still locked [i=" + i + ", entry=" + entry + ']'); return false; } } } } } return true; } catch (GridCacheEntryRemovedException ignore) { info("Entry was removed, will retry"); return false; } } }, 10_000); } /** * @throws Exception If failed. */ public void testGlobalClearAll() throws Exception { globalClearAll(false, false); } /** * @throws Exception If failed. */ public void testGlobalClearAllAsyncOld() throws Exception { globalClearAll(true, true); } /** * @throws Exception If failed. */ public void testGlobalClearAllAsync() throws Exception { globalClearAll(true, false); } /** * @param async If {@code true} uses async method. * @param oldAsync Use old async API. * @throws Exception If failed. */ protected void globalClearAll(boolean async, boolean oldAsync) throws Exception { // Save entries only on their primary nodes. If we didn't do so, clearLocally() will not remove all entries // because some of them were blocked due to having readers. for (int i = 0; i < gridCount(); i++) { for (String key : primaryKeysForCache(jcache(i), 3, 100_000)) jcache(i).put(key, 1); } if (async) { if(oldAsync) { IgniteCache<String, Integer> asyncCache = jcache().withAsync(); asyncCache.clear(); asyncCache.future().get(); } else jcache().clearAsync().get(); } else jcache().clear(); for (int i = 0; i < gridCount(); i++) assert jcache(i).localSize() == 0; } /** * @throws Exception In case of error. */ @SuppressWarnings("BusyWait") public void testLockUnlock() throws Exception { if (lockingEnabled()) { final CountDownLatch lockCnt = new CountDownLatch(1); final CountDownLatch unlockCnt = new CountDownLatch(1); grid(0).events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { switch (evt.type()) { case EVT_CACHE_OBJECT_LOCKED: lockCnt.countDown(); break; case EVT_CACHE_OBJECT_UNLOCKED: unlockCnt.countDown(); break; } return true; } }, EVT_CACHE_OBJECT_LOCKED, EVT_CACHE_OBJECT_UNLOCKED); IgniteCache<String, Integer> cache = jcache(); String key = primaryKeysForCache(cache, 1).get(0); cache.put(key, 1); assert !cache.isLocalLocked(key, false); Lock lock = cache.lock(key); lock.lock(); try { lockCnt.await(); assert cache.isLocalLocked(key, false); } finally { lock.unlock(); } unlockCnt.await(); for (int i = 0; i < 100; i++) if (cache.isLocalLocked(key, false)) Thread.sleep(10); else break; assert !cache.isLocalLocked(key, false); } } /** * @throws Exception In case of error. */ @SuppressWarnings("BusyWait") public void testLockUnlockAll() throws Exception { if (lockingEnabled()) { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); assert !cache.isLocalLocked("key1", false); assert !cache.isLocalLocked("key2", false); Lock lock1_2 = cache.lockAll(ImmutableSet.of("key1", "key2")); lock1_2.lock(); try { assert cache.isLocalLocked("key1", false); assert cache.isLocalLocked("key2", false); } finally { lock1_2.unlock(); } for (int i = 0; i < 100; i++) if (cache.isLocalLocked("key1", false) || cache.isLocalLocked("key2", false)) Thread.sleep(10); else break; assert !cache.isLocalLocked("key1", false); assert !cache.isLocalLocked("key2", false); lock1_2.lock(); try { assert cache.isLocalLocked("key1", false); assert cache.isLocalLocked("key2", false); } finally { lock1_2.unlock(); } for (int i = 0; i < 100; i++) if (cache.isLocalLocked("key1", false) || cache.isLocalLocked("key2", false)) Thread.sleep(10); else break; assert !cache.isLocalLocked("key1", false); assert !cache.isLocalLocked("key2", false); } } /** * @throws Exception In case of error. */ public void testPeek() throws Exception { Ignite ignite = primaryIgnite("key"); IgniteCache<String, Integer> cache = ignite.cache(null); assert peek(cache, "key") == null; cache.put("key", 1); cache.replace("key", 2); assertEquals(2, peek(cache, "key").intValue()); } /** * @throws Exception If failed. */ public void testPeekTxRemoveOptimistic() throws Exception { checkPeekTxRemove(OPTIMISTIC); } /** * @throws Exception If failed. */ public void testPeekTxRemovePessimistic() throws Exception { checkPeekTxRemove(PESSIMISTIC); } /** * @param concurrency Concurrency. * @throws Exception If failed. */ private void checkPeekTxRemove(TransactionConcurrency concurrency) throws Exception { if (txShouldBeUsed()) { Ignite ignite = primaryIgnite("key"); IgniteCache<String, Integer> cache = ignite.cache(null); cache.put("key", 1); try (Transaction tx = ignite.transactions().txStart(concurrency, READ_COMMITTED)) { cache.remove("key"); assertNull(cache.get("key")); // localPeek ignores transactions. assertNotNull(peek(cache, "key")); // localPeek ignores transactions. tx.commit(); } } } /** * @throws Exception If failed. */ public void testPeekRemove() throws Exception { IgniteCache<String, Integer> cache = primaryCache("key"); cache.put("key", 1); cache.remove("key"); assertNull(peek(cache, "key")); } /** * TODO GG-11133. * @throws Exception In case of error. */ public void testEvictExpired() throws Exception { final IgniteCache<String, Integer> cache = jcache(); final String key = primaryKeysForCache(cache, 1).get(0); cache.put(key, 1); assertEquals((Integer)1, cache.get(key)); long ttl = 500; final ExpiryPolicy expiry = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl)); grid(0).cache(null).withExpiryPolicy(expiry).put(key, 1); final Affinity<String> aff = ignite(0).affinity(null); boolean wait = waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { for (int i = 0; i < gridCount(); i++) { if (peek(jcache(i), key) != null) return false; } return true; } }, ttl + 1000); assertTrue("Failed to wait for entry expiration.", wait); // Expired entry should not be swapped. cache.localEvict(Collections.singleton(key)); assertNull(peek(cache, "key")); assertNull(cache.localPeek(key, ONHEAP)); assertTrue(cache.localSize() == 0); load(cache, key, true); for (int i = 0; i < gridCount(); i++) { if (aff.isPrimary(grid(i).cluster().localNode(), key)) assertEquals((Integer)1, peek(jcache(i), key)); if (aff.isBackup(grid(i).cluster().localNode(), key)) assertEquals((Integer)1, peek(jcache(i), key)); } } /** * TODO GG-11133. * * @throws Exception If failed. */ public void testPeekExpired() throws Exception { final IgniteCache<String, Integer> c = jcache(); final String key = primaryKeysForCache(c, 1).get(0); info("Using key: " + key); c.put(key, 1); assertEquals(Integer.valueOf(1), peek(c, key)); int ttl = 500; final ExpiryPolicy expiry = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl)); c.withExpiryPolicy(expiry).put(key, 1); Thread.sleep(ttl + 100); GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return peek(c, key) == null; } }, 2000); assert peek(c, key) == null; assert c.localSize() == 0 : "Cache is not empty."; } /** * TODO GG-11133. * * @throws Exception If failed. */ public void testPeekExpiredTx() throws Exception { if (txShouldBeUsed()) { final IgniteCache<String, Integer> c = jcache(); final String key = "1"; int ttl = 500; try (Transaction tx = grid(0).transactions().txStart()) { final ExpiryPolicy expiry = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl)); grid(0).cache(null).withExpiryPolicy(expiry).put(key, 1); tx.commit(); } GridTestUtils.waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return peek(c, key) == null; } }, 2000); assertNull(peek(c, key)); assert c.localSize() == 0; } } /** * @throws Exception If failed. */ public void testTtlTx() throws Exception { if (txShouldBeUsed()) checkTtl(true, false); } /** * @throws Exception If failed. */ public void testTtlNoTx() throws Exception { checkTtl(false, false); } /** * @throws Exception If failed. */ public void testTtlNoTxOldEntry() throws Exception { checkTtl(false, true); } /** * @param inTx In tx flag. * @param oldEntry {@code True} to check TTL on old entry, {@code false} on new. * @throws Exception If failed. */ private void checkTtl(boolean inTx, boolean oldEntry) throws Exception { // TODO GG-11133. if (true) return; int ttl = 1000; final ExpiryPolicy expiry = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl)); final IgniteCache<String, Integer> c = jcache(); final String key = primaryKeysForCache(jcache(), 1).get(0); IgnitePair<Long> entryTtl; if (oldEntry) { c.put(key, 1); entryTtl = entryTtl(fullCache(), key); assertNotNull(entryTtl.get1()); assertNotNull(entryTtl.get2()); assertEquals((Long)0L, entryTtl.get1()); assertEquals((Long)0L, entryTtl.get2()); } long startTime = System.currentTimeMillis(); if (inTx) { // Rollback transaction for the first time. Transaction tx = transactions().txStart(); try { jcache().withExpiryPolicy(expiry).put(key, 1); } finally { tx.rollback(); } if (oldEntry) { entryTtl = entryTtl(fullCache(), key); assertEquals((Long)0L, entryTtl.get1()); assertEquals((Long)0L, entryTtl.get2()); } } // Now commit transaction and check that ttl and expire time have been saved. Transaction tx = inTx ? transactions().txStart() : null; try { jcache().withExpiryPolicy(expiry).put(key, 1); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } long[] expireTimes = new long[gridCount()]; for (int i = 0; i < gridCount(); i++) { if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) { IgnitePair<Long> curEntryTtl = entryTtl(jcache(i), key); assertNotNull(curEntryTtl.get1()); assertNotNull(curEntryTtl.get2()); assertEquals(ttl, (long)curEntryTtl.get1()); assertTrue(curEntryTtl.get2() > startTime); expireTimes[i] = curEntryTtl.get2(); } } // One more update from the same cache entry to ensure that expire time is shifted forward. U.sleep(100); tx = inTx ? transactions().txStart() : null; try { jcache().withExpiryPolicy(expiry).put(key, 2); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } for (int i = 0; i < gridCount(); i++) { if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) { IgnitePair<Long> curEntryTtl = entryTtl(jcache(i), key); assertNotNull(curEntryTtl.get1()); assertNotNull(curEntryTtl.get2()); assertEquals(ttl, (long)curEntryTtl.get1()); assertTrue(curEntryTtl.get2() > startTime); expireTimes[i] = curEntryTtl.get2(); } } // And one more direct update to ensure that expire time is shifted forward. U.sleep(100); tx = inTx ? transactions().txStart() : null; try { jcache().withExpiryPolicy(expiry).put(key, 3); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } for (int i = 0; i < gridCount(); i++) { if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) { IgnitePair<Long> curEntryTtl = entryTtl(jcache(i), key); assertNotNull(curEntryTtl.get1()); assertNotNull(curEntryTtl.get2()); assertEquals(ttl, (long)curEntryTtl.get1()); assertTrue(curEntryTtl.get2() > startTime); expireTimes[i] = curEntryTtl.get2(); } } // And one more update to ensure that ttl is not changed and expire time is not shifted forward. U.sleep(100); log.info("Put 4"); tx = inTx ? transactions().txStart() : null; try { jcache().put(key, 4); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } log.info("Put 4 done"); for (int i = 0; i < gridCount(); i++) { if (grid(i).affinity(null).isPrimaryOrBackup(grid(i).localNode(), key)) { IgnitePair<Long> curEntryTtl = entryTtl(jcache(i), key); assertNotNull(curEntryTtl.get1()); assertNotNull(curEntryTtl.get2()); assertEquals(ttl, (long)curEntryTtl.get1()); assertEquals(expireTimes[i], (long)curEntryTtl.get2()); } } // Avoid reloading from store. storeStgy.removeFromStore(key); assertTrue(GridTestUtils.waitForCondition(new GridAbsPredicateX() { @SuppressWarnings("unchecked") @Override public boolean applyx() { try { Integer val = c.get(key); if (val != null) { info("Value is in cache [key=" + key + ", val=" + val + ']'); return false; } // Get "cache" field from GridCacheProxyImpl. GridCacheAdapter c0 = cacheFromCtx(c); if (!c0.context().deferredDelete()) { GridCacheEntryEx e0 = c0.peekEx(key); return e0 == null || (e0.rawGet() == null && e0.valueBytes() == null); } else return true; } catch (GridCacheEntryRemovedException e) { throw new RuntimeException(e); } } }, Math.min(ttl * 10, getTestTimeout()))); IgniteCache fullCache = fullCache(); if (!isMultiJvmObject(fullCache)) { GridCacheAdapter internalCache = internalCache(fullCache); if (internalCache.isLocal()) return; } assert c.get(key) == null; // Ensure that old TTL and expire time are not longer "visible". entryTtl = entryTtl(fullCache(), key); assertNotNull(entryTtl.get1()); assertNotNull(entryTtl.get2()); assertEquals(0, (long)entryTtl.get1()); assertEquals(0, (long)entryTtl.get2()); // Ensure that next update will not pick old expire time. tx = inTx ? transactions().txStart() : null; try { jcache().put(key, 10); if (tx != null) tx.commit(); } finally { if (tx != null) tx.close(); } U.sleep(2000); entryTtl = entryTtl(fullCache(), key); assertEquals((Integer)10, c.get(key)); assertNotNull(entryTtl.get1()); assertNotNull(entryTtl.get2()); assertEquals(0, (long)entryTtl.get1()); assertEquals(0, (long)entryTtl.get2()); } /** * @throws Exception In case of error. */ public void testLocalEvict() throws Exception { IgniteCache<String, Integer> cache = jcache(); List<String> keys = primaryKeysForCache(cache, 3); String key1 = keys.get(0); String key2 = keys.get(1); String key3 = keys.get(2); cache.put(key1, 1); cache.put(key2, 2); cache.put(key3, 3); assert peek(cache, key1) == 1; assert peek(cache, key2) == 2; assert peek(cache, key3) == 3; cache.localEvict(F.asList(key1, key2)); assert cache.localPeek(key1, ONHEAP) == null; assert cache.localPeek(key2, ONHEAP) == null; assert peek(cache, key3) == 3; loadAll(cache, ImmutableSet.of(key1, key2), true); Affinity<String> aff = ignite(0).affinity(null); for (int i = 0; i < gridCount(); i++) { if (aff.isPrimaryOrBackup(grid(i).cluster().localNode(), key1)) assertEquals((Integer)1, peek(jcache(i), key1)); if (aff.isPrimaryOrBackup(grid(i).cluster().localNode(), key2)) assertEquals((Integer)2, peek(jcache(i), key2)); if (aff.isPrimaryOrBackup(grid(i).cluster().localNode(), key3)) assertEquals((Integer)3, peek(jcache(i), key3)); } } /** * JUnit. */ public void testCacheProxy() { IgniteCache<String, Integer> cache = jcache(); assert cache instanceof IgniteCacheProxy; } /** * TODO GG-11133. * * @throws Exception If failed. */ public void testCompactExpired() throws Exception { final IgniteCache<String, Integer> cache = jcache(); final String key = F.first(primaryKeysForCache(cache, 1)); cache.put(key, 1); long ttl = 500; final ExpiryPolicy expiry = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl)); grid(0).cache(null).withExpiryPolicy(expiry).put(key, 1); waitForCondition(new GridAbsPredicate() { @Override public boolean apply() { return cache.localPeek(key) == null; } }, ttl + 1000); // Peek will actually remove entry from cache. assertNull(cache.localPeek(key)); assertEquals(0, cache.localSize()); // Clear readers, if any. cache.remove(key); } /** * JUnit. * * @throws Exception If failed. */ public void testOptimisticTxMissingKey() throws Exception { if (txShouldBeUsed()) { try (Transaction tx = transactions().txStart(OPTIMISTIC, READ_COMMITTED)) { // Remove missing key. assertFalse(jcache().remove(UUID.randomUUID().toString())); tx.commit(); } } } /** * JUnit. * * @throws Exception If failed. */ public void testOptimisticTxMissingKeyNoCommit() throws Exception { if (txShouldBeUsed()) { try (Transaction tx = transactions().txStart(OPTIMISTIC, READ_COMMITTED)) { // Remove missing key. assertFalse(jcache().remove(UUID.randomUUID().toString())); tx.setRollbackOnly(); } } } /** * @throws Exception If failed. */ public void testOptimisticTxReadCommittedInTx() throws Exception { checkRemovexInTx(OPTIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testOptimisticTxRepeatableReadInTx() throws Exception { checkRemovexInTx(OPTIMISTIC, REPEATABLE_READ); } /** * @throws Exception If failed. */ public void testPessimisticTxReadCommittedInTx() throws Exception { checkRemovexInTx(PESSIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testPessimisticTxRepeatableReadInTx() throws Exception { checkRemovexInTx(PESSIMISTIC, REPEATABLE_READ); } /** * @param concurrency Concurrency. * @param isolation Isolation. * @throws Exception If failed. */ private void checkRemovexInTx(TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception { if (txShouldBeUsed()) { final int cnt = 10; CU.inTx(ignite(0), jcache(), concurrency, isolation, new CIX1<IgniteCache<String, Integer>>() { @Override public void applyx(IgniteCache<String, Integer> cache) { for (int i = 0; i < cnt; i++) cache.put("key" + i, i); } }); CU.inTx(ignite(0), jcache(), concurrency, isolation, new CIX1<IgniteCache<String, Integer>>() { @Override public void applyx(IgniteCache<String, Integer> cache) { for (int i = 0; i < cnt; i++) assertEquals(new Integer(i), cache.get("key" + i)); } }); CU.inTx(ignite(0), jcache(), concurrency, isolation, new CIX1<IgniteCache<String, Integer>>() { @Override public void applyx(IgniteCache<String, Integer> cache) { for (int i = 0; i < cnt; i++) assertTrue("Failed to remove key: key" + i, cache.remove("key" + i)); } }); CU.inTx(ignite(0), jcache(), concurrency, isolation, new CIX1<IgniteCache<String, Integer>>() { @Override public void applyx(IgniteCache<String, Integer> cache) { for (int i = 0; i < cnt; i++) assertNull(cache.get("key" + i)); } }); } } /** * JUnit. * * @throws Exception If failed. */ public void testPessimisticTxMissingKey() throws Exception { if (txShouldBeUsed()) { try (Transaction tx = transactions().txStart(PESSIMISTIC, READ_COMMITTED)) { // Remove missing key. assertFalse(jcache().remove(UUID.randomUUID().toString())); tx.commit(); } } } /** * JUnit. * * @throws Exception If failed. */ public void testPessimisticTxMissingKeyNoCommit() throws Exception { if (txShouldBeUsed()) { try (Transaction tx = transactions().txStart(PESSIMISTIC, READ_COMMITTED)) { // Remove missing key. assertFalse(jcache().remove(UUID.randomUUID().toString())); tx.setRollbackOnly(); } } } /** * @throws Exception If failed. */ public void testPessimisticTxRepeatableRead() throws Exception { if (txShouldBeUsed()) { try (Transaction ignored = transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) { jcache().put("key", 1); assert jcache().get("key") == 1; } } } /** * @throws Exception If failed. */ public void testPessimisticTxRepeatableReadOnUpdate() throws Exception { if (txShouldBeUsed()) { try (Transaction ignored = transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) { jcache().put("key", 1); assert jcache().getAndPut("key", 2) == 1; } } } /** * @throws Exception In case of error. */ public void testToMap() throws Exception { IgniteCache<String, Integer> cache = jcache(); cache.put("key1", 1); cache.put("key2", 2); Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < gridCount(); i++) { for (Cache.Entry<String, Integer> entry : jcache(i)) map.put(entry.getKey(), entry.getValue()); } assert map.size() == 2; assert map.get("key1") == 1; assert map.get("key2") == 2; } /** * @param keys Expected keys. * @throws Exception If failed. */ protected void checkSize(final Collection<String> keys) throws Exception { if (nearEnabled()) assertEquals(keys.size(), jcache().localSize(CachePeekMode.ALL)); else { for (int i = 0; i < gridCount(); i++) executeOnLocalOrRemoteJvm(i, new CheckEntriesTask(keys)); } } /** * @param keys Expected keys. * @throws Exception If failed. */ protected void checkKeySize(final Collection<String> keys) throws Exception { if (nearEnabled()) assertEquals("Invalid key size: " + jcache().localSize(ALL), keys.size(), jcache().localSize(ALL)); else { for (int i = 0; i < gridCount(); i++) executeOnLocalOrRemoteJvm(i, new CheckKeySizeTask(keys)); } } /** * @param exp Expected value. * @param key Key. * @throws Exception If failed. */ private void checkContainsKey(boolean exp, String key) throws Exception { if (nearEnabled()) assertEquals(exp, jcache().containsKey(key)); else { boolean contains = false; for (int i = 0; i < gridCount(); i++) if (containsKey(jcache(i), key)) { contains = true; break; } assertEquals("Key: " + key, exp, contains); } } /** * @param key Key. * @return Ignite instance for primary node. */ protected Ignite primaryIgnite(String key) { ClusterNode node = grid(0).affinity(null).mapKeyToNode(key); if (node == null) throw new IgniteException("Failed to find primary node."); UUID nodeId = node.id(); for (int i = 0; i < gridCount(); i++) { if (grid(i).localNode().id().equals(nodeId)) return ignite(i); } throw new IgniteException("Failed to find primary node."); } /** * @param key Key. * @return Cache. */ protected IgniteCache<String, Integer> primaryCache(String key) { return primaryIgnite(key).cache(null); } /** * @param cache Cache. * @param cnt Keys count. * @param startFrom Begin value ofthe key. * @return Collection of keys for which given cache is primary. */ protected List<String> primaryKeysForCache(IgniteCache<String, Integer> cache, int cnt, int startFrom) { return executeOnLocalOrRemoteJvm(cache, new CheckPrimaryKeysTask(startFrom, cnt)); } /** * @param cache Cache. * @param cnt Keys count. * @return Collection of keys for which given cache is primary. * @throws IgniteCheckedException If failed. */ protected List<String> primaryKeysForCache(IgniteCache<String, Integer> cache, int cnt) throws IgniteCheckedException { return primaryKeysForCache(cache, cnt, 1); } /** * @param cache Cache. * @param key Entry key. * @return Pair [ttl, expireTime]; both values null if entry not found */ protected IgnitePair<Long> entryTtl(IgniteCache cache, String key) { return executeOnLocalOrRemoteJvm(cache, new EntryTtlTask(key, true)); } /** * @throws Exception If failed. */ public void testIterator() throws Exception { IgniteCache<Integer, Integer> cache = grid(0).cache(null); final int KEYS = 1000; for (int i = 0; i < KEYS; i++) cache.put(i, i); // Try to initialize readers in case when near cache is enabled. for (int i = 0; i < gridCount(); i++) { cache = grid(i).cache(null); for (int k = 0; k < KEYS; k++) assertEquals((Object)k, cache.get(k)); } int cnt = 0; for (Cache.Entry e : cache) cnt++; assertEquals(KEYS, cnt); } /** * @throws Exception If failed. */ public void testIgniteCacheIterator() throws Exception { IgniteCache<String, Integer> cache = jcache(0); Iterator<Cache.Entry<String, Integer>> it = cache.iterator(); boolean hasNext = it.hasNext(); if (hasNext) assertFalse("Cache has value: " + it.next(), hasNext); final int SIZE = 10_000; Map<String, Integer> entries = new HashMap<>(); Map<String, Integer> putMap = new HashMap<>(); for (int i = 0; i < SIZE; ++i) { String key = Integer.toString(i); putMap.put(key, i); entries.put(key, i); if (putMap.size() == 500) { cache.putAll(putMap); info("Puts finished: " + (i + 1)); putMap.clear(); } } cache.putAll(putMap); checkIteratorHasNext(); checkIteratorCache(entries); checkIteratorRemove(cache, entries); checkIteratorEmpty(cache); } /** * @throws Exception If failed. */ public void testIteratorLeakOnCancelCursor() throws Exception { IgniteCache<String, Integer> cache = jcache(0); final int SIZE = 10_000; Map<String, Integer> putMap = new HashMap<>(); for (int i = 0; i < SIZE; ++i) { String key = Integer.toString(i); putMap.put(key, i); if (putMap.size() == 500) { cache.putAll(putMap); info("Puts finished: " + (i + 1)); putMap.clear(); } } cache.putAll(putMap); QueryCursor<Cache.Entry<String, Integer>> cur = cache.query(new ScanQuery<String, Integer>()); cur.iterator().next(); cur.close(); waitForIteratorsCleared(cache, 10); } /** * If hasNext() is called repeatedly, it should return the same result. */ private void checkIteratorHasNext() { Iterator<Cache.Entry<String, Integer>> iter = jcache(0).iterator(); assertEquals(iter.hasNext(), iter.hasNext()); while (iter.hasNext()) iter.next(); assertFalse(iter.hasNext()); } /** * @param cache Cache. * @param entries Expected entries in the cache. */ private void checkIteratorRemove(IgniteCache<String, Integer> cache, Map<String, Integer> entries) { // Check that we can remove element. String rmvKey = Integer.toString(5); removeCacheIterator(cache, rmvKey); entries.remove(rmvKey); assertFalse(cache.containsKey(rmvKey)); assertNull(cache.get(rmvKey)); checkIteratorCache(entries); // Check that we cannot call Iterator.remove() without next(). final Iterator<Cache.Entry<String, Integer>> iter = jcache(0).iterator(); assertTrue(iter.hasNext()); iter.next(); iter.remove(); GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Void call() throws Exception { iter.remove(); return null; } }, IllegalStateException.class, null); } /** * @param cache Cache. * @param key Key to remove. */ private void removeCacheIterator(IgniteCache<String, Integer> cache, String key) { Iterator<Cache.Entry<String, Integer>> iter = cache.iterator(); int delCnt = 0; while (iter.hasNext()) { Cache.Entry<String, Integer> cur = iter.next(); if (cur.getKey().equals(key)) { iter.remove(); delCnt++; } } assertEquals(1, delCnt); } /** * @param entries Expected entries in the cache. */ private void checkIteratorCache(Map<String, Integer> entries) { for (int i = 0; i < gridCount(); ++i) checkIteratorCache(jcache(i), entries); } /** * @param cache Cache. * @param entries Expected entries in the cache. */ private void checkIteratorCache(IgniteCache<String, Integer> cache, Map<String, Integer> entries) { Iterator<Cache.Entry<String, Integer>> iter = cache.iterator(); int cnt = 0; while (iter.hasNext()) { Cache.Entry<String, Integer> cur = iter.next(); assertTrue(entries.containsKey(cur.getKey())); assertEquals(entries.get(cur.getKey()), cur.getValue()); cnt++; } assertEquals(entries.size(), cnt); } /** * Checks iterators are cleared. */ private void checkIteratorsCleared() { for (int j = 0; j < gridCount(); j++) executeOnLocalOrRemoteJvm(j, new CheckIteratorTask()); } /** * Checks iterators are cleared. */ private void waitForIteratorsCleared(IgniteCache<String, Integer> cache, int secs) throws InterruptedException { for (int i = 0; i < secs; i++) { try { cache.size(); // Trigger weak queue poll. checkIteratorsCleared(); } catch (AssertionFailedError e) { if (i == 9) { for (int j = 0; j < gridCount(); j++) executeOnLocalOrRemoteJvm(j, new PrintIteratorStateTask()); throw e; } log.info("Iterators not cleared, will wait"); Thread.sleep(1000); } } } /** * Checks iterators are cleared after using. * * @param cache Cache. * @throws Exception If failed. */ private void checkIteratorEmpty(IgniteCache<String, Integer> cache) throws Exception { int cnt = 5; for (int i = 0; i < cnt; ++i) { Iterator<Cache.Entry<String, Integer>> iter = cache.iterator(); iter.next(); assert iter.hasNext(); } System.gc(); waitForIteratorsCleared(cache, 10); } /** * @throws Exception If failed. */ public void testLocalClearKey() throws Exception { addKeys(); String keyToRmv = "key" + 25; Ignite g = primaryIgnite(keyToRmv); g.<String, Integer>cache(null).localClear(keyToRmv); checkLocalRemovedKey(keyToRmv); g.<String, Integer>cache(null).put(keyToRmv, 1); String keyToEvict = "key" + 30; g = primaryIgnite(keyToEvict); g.<String, Integer>cache(null).localEvict(Collections.singleton(keyToEvict)); g.<String, Integer>cache(null).localClear(keyToEvict); checkLocalRemovedKey(keyToEvict); } /** * @param keyToRmv Removed key. */ protected void checkLocalRemovedKey(String keyToRmv) { for (int i = 0; i < 500; ++i) { String key = "key" + i; boolean found = primaryIgnite(key).cache(null).localPeek(key) != null; if (keyToRmv.equals(key)) { Collection<ClusterNode> nodes = grid(0).affinity(null).mapKeyToPrimaryAndBackups(key); for (int j = 0; j < gridCount(); ++j) { if (nodes.contains(grid(j).localNode()) && grid(j) != primaryIgnite(key)) assertTrue("Not found on backup removed key ", grid(j).cache(null).localPeek(key) != null); } assertFalse("Found removed key " + key, found); } else assertTrue("Not found key " + key, found); } } /** * @throws Exception If failed. */ public void testLocalClearKeys() throws Exception { Map<String, List<String>> keys = addKeys(); Ignite g = grid(0); Set<String> keysToRmv = new HashSet<>(); for (int i = 0; i < gridCount(); ++i) { List<String> gridKeys = keys.get(grid(i).name()); if (gridKeys.size() > 2) { keysToRmv.add(gridKeys.get(0)); keysToRmv.add(gridKeys.get(1)); g = grid(i); break; } } assert keysToRmv.size() > 1; info("Will clear keys on node: " + g.cluster().localNode().id()); g.<String, Integer>cache(null).localClearAll(keysToRmv); for (int i = 0; i < 500; ++i) { String key = "key" + i; Ignite ignite = primaryIgnite(key); boolean found = ignite.cache(null).localPeek(key) != null; if (keysToRmv.contains(key)) assertFalse("Found removed key [key=" + key + ", node=" + ignite.cluster().localNode().id() + ']', found); else assertTrue("Not found key " + key, found); } } /** * Add 500 keys to cache only on primaries nodes. * * @return Map grid's name to its primary keys. */ protected Map<String, List<String>> addKeys() { // Save entries only on their primary nodes. If we didn't do so, clearLocally() will not remove all entries // because some of them were blocked due to having readers. Map<String, List<String>> keys = new HashMap<>(); for (int i = 0; i < gridCount(); ++i) keys.put(grid(i).name(), new ArrayList<String>()); for (int i = 0; i < 500; ++i) { String key = "key" + i; Ignite g = primaryIgnite(key); g.cache(null).put(key, "value" + i); keys.get(g.name()).add(key); } return keys; } /** * @throws Exception If failed. */ public void testGlobalClearKey() throws Exception { testGlobalClearKey(false, Arrays.asList("key25"), false); } /** * @throws Exception If failed. */ public void testGlobalClearKeyAsyncOld() throws Exception { testGlobalClearKey(true, Arrays.asList("key25"), true); } /** * @throws Exception If failed. */ public void testGlobalClearKeyAsync() throws Exception { testGlobalClearKey(true, Arrays.asList("key25"), false); } /** * @throws Exception If failed. */ public void testGlobalClearKeys() throws Exception { testGlobalClearKey(false, Arrays.asList("key25", "key100", "key150"), false); } /** * @throws Exception If failed. */ public void testGlobalClearKeysAsyncOld() throws Exception { testGlobalClearKey(true, Arrays.asList("key25", "key100", "key150"), true); } /** * @throws Exception If failed. */ public void testGlobalClearKeysAsync() throws Exception { testGlobalClearKey(true, Arrays.asList("key25", "key100", "key150"), false); } /** * @param async If {@code true} uses async method. * @param keysToRmv Keys to remove. * @param oldAsync Use old async API. * @throws Exception If failed. */ protected void testGlobalClearKey(boolean async, Collection<String> keysToRmv, boolean oldAsync) throws Exception { // Save entries only on their primary nodes. If we didn't do so, clearLocally() will not remove all entries // because some of them were blocked due to having readers. for (int i = 0; i < 500; ++i) { String key = "key" + i; Ignite g = primaryIgnite(key); g.cache(null).put(key, "value" + i); } if (async) { if (oldAsync) { IgniteCache<String, Integer> asyncCache = jcache().withAsync(); if (keysToRmv.size() == 1) asyncCache.clear(F.first(keysToRmv)); else asyncCache.clearAll(new HashSet<>(keysToRmv)); asyncCache.future().get(); } else { if (keysToRmv.size() == 1) jcache().clearAsync(F.first(keysToRmv)).get(); else jcache().clearAllAsync(new HashSet<>(keysToRmv)).get(); } } else { if (keysToRmv.size() == 1) jcache().clear(F.first(keysToRmv)); else jcache().clearAll(new HashSet<>(keysToRmv)); } for (int i = 0; i < 500; ++i) { String key = "key" + i; boolean found = false; for (int j = 0; j < gridCount(); j++) { if (jcache(j).localPeek(key) != null) found = true; } if (!keysToRmv.contains(key)) assertTrue("Not found key " + key, found); else assertFalse("Found removed key " + key, found); } } /** * @throws Exception If failed. */ public void testWithSkipStore() throws Exception { IgniteCache<String, Integer> cache = grid(0).cache(null); IgniteCache<String, Integer> cacheSkipStore = cache.withSkipStore(); List<String> keys = primaryKeysForCache(cache, 10); for (int i = 0; i < keys.size(); ++i) storeStgy.putToStore(keys.get(i), i); assertFalse(cacheSkipStore.iterator().hasNext()); for (String key : keys) { assertNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); } for (String key : keys) { cacheSkipStore.remove(key); assertNotNull(cache.get(key)); } cache.removeAll(new HashSet<>(keys)); for (String key : keys) assertNull(cache.get(key)); final int KEYS = 250; // Put/remove data from multiple nodes. keys = new ArrayList<>(KEYS); for (int i = 0; i < KEYS; i++) keys.add("key_" + i); for (int i = 0; i < keys.size(); ++i) cache.put(keys.get(i), i); for (int i = 0; i < keys.size(); ++i) { String key = keys.get(i); assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertEquals(i, storeStgy.getFromStore(key)); } for (int i = 0; i < keys.size(); ++i) { String key = keys.get(i); Integer val1 = -1; cacheSkipStore.put(key, val1); assertEquals(i, storeStgy.getFromStore(key)); assertEquals(val1, cacheSkipStore.get(key)); Integer val2 = -2; assertEquals(val1, cacheSkipStore.invoke(key, new SetValueProcessor(val2))); assertEquals(i, storeStgy.getFromStore(key)); assertEquals(val2, cacheSkipStore.get(key)); } for (String key : keys) { cacheSkipStore.remove(key); assertNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); } for (String key : keys) { cache.remove(key); assertNull(cacheSkipStore.get(key)); assertNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); storeStgy.putToStore(key, 0); Integer val = -1; assertNull(cacheSkipStore.invoke(key, new SetValueProcessor(val))); assertEquals(0, storeStgy.getFromStore(key)); assertEquals(val, cacheSkipStore.get(key)); cache.remove(key); storeStgy.putToStore(key, 0); assertTrue(cacheSkipStore.putIfAbsent(key, val)); assertEquals(val, cacheSkipStore.get(key)); assertEquals(0, storeStgy.getFromStore(key)); cache.remove(key); storeStgy.putToStore(key, 0); assertNull(cacheSkipStore.getAndPut(key, val)); assertEquals(val, cacheSkipStore.get(key)); assertEquals(0, storeStgy.getFromStore(key)); cache.remove(key); } assertFalse(cacheSkipStore.iterator().hasNext()); assertTrue(storeStgy.getStoreSize() == 0); assertTrue(cache.size(ALL) == 0); // putAll/removeAll from multiple nodes. Map<String, Integer> data = new LinkedHashMap<>(); for (int i = 0; i < keys.size(); i++) data.put(keys.get(i), i); cacheSkipStore.putAll(data); for (String key : keys) { assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); } cache.putAll(data); for (String key : keys) { assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); } cacheSkipStore.removeAll(data.keySet()); for (String key : keys) { assertNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); } cacheSkipStore.putAll(data); for (String key : keys) { assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); } cacheSkipStore.removeAll(data.keySet()); for (String key : keys) { assertNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); } cache.removeAll(data.keySet()); for (String key : keys) { assertNull(cacheSkipStore.get(key)); assertNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); } assertTrue(storeStgy.getStoreSize() == 0); // Miscellaneous checks. String newKey = "New key"; assertFalse(storeStgy.isInStore(newKey)); cacheSkipStore.put(newKey, 1); assertFalse(storeStgy.isInStore(newKey)); cache.put(newKey, 1); assertTrue(storeStgy.isInStore(newKey)); Iterator<Cache.Entry<String, Integer>> it = cacheSkipStore.iterator(); assertTrue(it.hasNext()); Cache.Entry<String, Integer> entry = it.next(); String rmvKey = entry.getKey(); assertTrue(storeStgy.isInStore(rmvKey)); it.remove(); assertNull(cacheSkipStore.get(rmvKey)); assertTrue(storeStgy.isInStore(rmvKey)); assertTrue(cache.size(ALL) == 0); assertTrue(cacheSkipStore.size(ALL) == 0); cache.remove(rmvKey); assertTrue(storeStgy.getStoreSize() == 0); } /** * @throws Exception If failed. */ public void testWithSkipStoreRemoveAll() throws Exception { if (atomicityMode() == TRANSACTIONAL || (atomicityMode() == ATOMIC && nearEnabled())) // TODO IGNITE-373. return; IgniteCache<String, Integer> cache = grid(0).cache(null); IgniteCache<String, Integer> cacheSkipStore = cache.withSkipStore(); Map<String, Integer> data = new HashMap<>(); for (int i = 0; i < 100; i++) data.put("key_" + i, i); cache.putAll(data); for (String key : data.keySet()) { assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); } cacheSkipStore.removeAll(); for (String key : data.keySet()) { assertNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); } cache.removeAll(); for (String key : data.keySet()) { assertNull(cacheSkipStore.get(key)); assertNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); } } /** * @throws Exception If failed. */ public void testWithSkipStoreTx() throws Exception { if (txShouldBeUsed()) { IgniteCache<String, Integer> cache = grid(0).cache(null); IgniteCache<String, Integer> cacheSkipStore = cache.withSkipStore(); final int KEYS = 250; // Put/remove data from multiple nodes. List<String> keys = new ArrayList<>(KEYS); for (int i = 0; i < KEYS; i++) keys.add("key_" + i); Map<String, Integer> data = new LinkedHashMap<>(); for (int i = 0; i < keys.size(); i++) data.put(keys.get(i), i); checkSkipStoreWithTransaction(cache, cacheSkipStore, data, keys, OPTIMISTIC, READ_COMMITTED); checkSkipStoreWithTransaction(cache, cacheSkipStore, data, keys, OPTIMISTIC, REPEATABLE_READ); checkSkipStoreWithTransaction(cache, cacheSkipStore, data, keys, OPTIMISTIC, SERIALIZABLE); checkSkipStoreWithTransaction(cache, cacheSkipStore, data, keys, PESSIMISTIC, READ_COMMITTED); checkSkipStoreWithTransaction(cache, cacheSkipStore, data, keys, PESSIMISTIC, REPEATABLE_READ); checkSkipStoreWithTransaction(cache, cacheSkipStore, data, keys, PESSIMISTIC, SERIALIZABLE); } } /** * @param cache Cache instance. * @param cacheSkipStore Cache skip store projection. * @param data Data set. * @param keys Keys list. * @param txConcurrency Concurrency mode. * @param txIsolation Isolation mode. * @throws Exception If failed. */ private void checkSkipStoreWithTransaction(IgniteCache<String, Integer> cache, IgniteCache<String, Integer> cacheSkipStore, Map<String, Integer> data, List<String> keys, TransactionConcurrency txConcurrency, TransactionIsolation txIsolation) throws Exception { info("Test tx skip store [concurrency=" + txConcurrency + ", isolation=" + txIsolation + ']'); cache.removeAll(data.keySet()); checkEmpty(cache, cacheSkipStore); IgniteTransactions txs = cache.unwrap(Ignite.class).transactions(); Integer val = -1; // Several put check. try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { for (String key : keys) cacheSkipStore.put(key, val); for (String key : keys) { assertEquals(val, cacheSkipStore.get(key)); assertEquals(val, cache.get(key)); assertFalse(storeStgy.isInStore(key)); } tx.commit(); } for (String key : keys) { assertEquals(val, cacheSkipStore.get(key)); assertEquals(val, cache.get(key)); assertFalse(storeStgy.isInStore(key)); } assertEquals(0, storeStgy.getStoreSize()); // cacheSkipStore putAll(..)/removeAll(..) check. try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { cacheSkipStore.putAll(data); tx.commit(); } for (String key : keys) { val = data.get(key); assertEquals(val, cacheSkipStore.get(key)); assertEquals(val, cache.get(key)); assertFalse(storeStgy.isInStore(key)); } storeStgy.putAllToStore(data); try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { cacheSkipStore.removeAll(data.keySet()); tx.commit(); } for (String key : keys) { assertNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); cache.remove(key); } assertTrue(storeStgy.getStoreSize() == 0); // cache putAll(..)/removeAll(..) check. try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { cache.putAll(data); for (String key : keys) { assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); } cache.removeAll(data.keySet()); for (String key : keys) { assertNull(cacheSkipStore.get(key)); assertNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); } tx.commit(); } assertTrue(storeStgy.getStoreSize() == 0); // putAll(..) from both cacheSkipStore and cache. try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { Map<String, Integer> subMap = new HashMap<>(); for (int i = 0; i < keys.size() / 2; i++) subMap.put(keys.get(i), i); cacheSkipStore.putAll(subMap); subMap.clear(); for (int i = keys.size() / 2; i < keys.size(); i++) subMap.put(keys.get(i), i); cache.putAll(subMap); for (String key : keys) { assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); } tx.commit(); } for (int i = 0; i < keys.size() / 2; i++) { String key = keys.get(i); assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); } for (int i = keys.size() / 2; i < keys.size(); i++) { String key = keys.get(i); assertNotNull(cacheSkipStore.get(key)); assertNotNull(cache.get(key)); assertTrue(storeStgy.isInStore(key)); } cache.removeAll(data.keySet()); for (String key : keys) { assertNull(cacheSkipStore.get(key)); assertNull(cache.get(key)); assertFalse(storeStgy.isInStore(key)); } // Check that read-through is disabled when cacheSkipStore is used. for (int i = 0; i < keys.size(); i++) storeStgy.putToStore(keys.get(i), i); assertTrue(cacheSkipStore.size(ALL) == 0); assertTrue(cache.size(ALL) == 0); assertTrue(storeStgy.getStoreSize() != 0); try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { assertTrue(cacheSkipStore.getAll(data.keySet()).size() == 0); for (String key : keys) { assertNull(cacheSkipStore.get(key)); if (txIsolation == READ_COMMITTED) { assertNotNull(cache.get(key)); assertNotNull(cacheSkipStore.get(key)); } } tx.commit(); } cache.removeAll(data.keySet()); val = -1; try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { for (String key : data.keySet()) { storeStgy.putToStore(key, 0); assertNull(cacheSkipStore.invoke(key, new SetValueProcessor(val))); } tx.commit(); } for (String key : data.keySet()) { assertEquals(0, storeStgy.getFromStore(key)); assertEquals(val, cacheSkipStore.get(key)); assertEquals(val, cache.get(key)); } cache.removeAll(data.keySet()); try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { for (String key : data.keySet()) { storeStgy.putToStore(key, 0); assertTrue(cacheSkipStore.putIfAbsent(key, val)); } tx.commit(); } for (String key : data.keySet()) { assertEquals(0, storeStgy.getFromStore(key)); assertEquals(val, cacheSkipStore.get(key)); assertEquals(val, cache.get(key)); } cache.removeAll(data.keySet()); try (Transaction tx = txs.txStart(txConcurrency, txIsolation)) { for (String key : data.keySet()) { storeStgy.putToStore(key, 0); assertNull(cacheSkipStore.getAndPut(key, val)); } tx.commit(); } for (String key : data.keySet()) { assertEquals(0, storeStgy.getFromStore(key)); assertEquals(val, cacheSkipStore.get(key)); assertEquals(val, cache.get(key)); } cache.removeAll(data.keySet()); checkEmpty(cache, cacheSkipStore); } /** * @param cache Cache instance. * @param cacheSkipStore Cache skip store projection. * @throws Exception If failed. */ private void checkEmpty(IgniteCache<String, Integer> cache, IgniteCache<String, Integer> cacheSkipStore) throws Exception { assertTrue(cache.size(ALL) == 0); assertTrue(cacheSkipStore.size(ALL) == 0); assertTrue(storeStgy.getStoreSize() == 0); } /** * @return Cache start mode. */ protected CacheStartMode cacheStartType() { String mode = System.getProperty("cache.start.mode"); if (CacheStartMode.NODES_THEN_CACHES.name().equalsIgnoreCase(mode)) return CacheStartMode.NODES_THEN_CACHES; if (CacheStartMode.ONE_BY_ONE.name().equalsIgnoreCase(mode)) return CacheStartMode.ONE_BY_ONE; return CacheStartMode.STATIC; } /** * @throws Exception If failed. */ public void testGetOutTx() throws Exception { checkGetOutTx(false); } /** * @throws Exception If failed. */ public void testGetOutTxAsync() throws Exception { checkGetOutTx(true); } /** * @throws Exception If failed. */ private void checkGetOutTx(boolean async) throws Exception { final AtomicInteger lockEvtCnt = new AtomicInteger(); IgnitePredicate<Event> lsnr = new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { lockEvtCnt.incrementAndGet(); return true; } }; try { IgniteCache<String, Integer> cache = grid(0).cache(null); List<String> keys = primaryKeysForCache(cache, 2); assertEquals(2, keys.size()); cache.put(keys.get(0), 0); cache.put(keys.get(1), 1); grid(0).events().localListen(lsnr, EVT_CACHE_OBJECT_LOCKED, EVT_CACHE_OBJECT_UNLOCKED); try (Transaction tx = transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) { Integer val0; if (async) val0 = cache.getAsync(keys.get(0)).get(); else val0 = cache.get(keys.get(0)); assertEquals(0, val0.intValue()); Map<String, Integer> allOutTx; if (async) allOutTx = cache.getAllOutTxAsync(F.asSet(keys.get(1))).get(); else allOutTx = cache.getAllOutTx(F.asSet(keys.get(1))); assertEquals(1, allOutTx.size()); assertTrue(allOutTx.containsKey(keys.get(1))); assertEquals(1, allOutTx.get(keys.get(1)).intValue()); } assertTrue(GridTestUtils.waitForCondition(new PA() { @Override public boolean apply() { info("Lock event count: " + lockEvtCnt.get()); if (atomicityMode() == ATOMIC) return lockEvtCnt.get() == 0; if (cacheMode() == PARTITIONED && nearEnabled()) { if (!grid(0).configuration().isClientMode()) return lockEvtCnt.get() == 4; } return lockEvtCnt.get() == 2; } }, 15000)); } finally { grid(0).events().stopLocalListen(lsnr, EVT_CACHE_OBJECT_LOCKED, EVT_CACHE_OBJECT_UNLOCKED); } } /** * @throws Exception If failed. */ public void testTransformException() throws Exception { final IgniteCache<String, Integer> cache = jcache(); assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { IgniteFuture fut = cache.invokeAsync("key2", ERR_PROCESSOR).chain(new IgniteClosure<IgniteFuture, Object>() { @Override public Object apply(IgniteFuture o) { return o.get(); } }); fut.get(); return null; } }, EntryProcessorException.class, null); } /** * @throws Exception If failed. */ public void testLockInsideTransaction() throws Exception { if (txEnabled()) { GridTestUtils.assertThrows( log, new Callable<Object>() { @Override public Object call() throws Exception { try (Transaction tx = ignite(0).transactions().txStart()) { jcache(0).lock("key").lock(); } return null; } }, CacheException.class, "Explicit lock can't be acquired within a transaction." ); GridTestUtils.assertThrows( log, new Callable<Object>() { @Override public Object call() throws Exception { try (Transaction tx = ignite(0).transactions().txStart()) { jcache(0).lockAll(Arrays.asList("key1", "key2")).lock(); } return null; } }, CacheException.class, "Explicit lock can't be acquired within a transaction." ); } } /** * @throws Exception If failed. */ public void testTransformResourceInjection() throws Exception { ClusterGroup servers = grid(0).cluster().forServers(); if(F.isEmpty(servers.nodes())) return; grid(0).services( grid(0).cluster()).deployNodeSingleton(SERVICE_NAME1, new DummyServiceImpl()); IgniteCache<String, Integer> cache = jcache(); Ignite ignite = ignite(0); doTransformResourceInjection(ignite, cache, false, false); doTransformResourceInjection(ignite, cache, true, false); doTransformResourceInjection(ignite, cache, true, true); if (txEnabled()) { doTransformResourceInjectionInTx(ignite, cache, false, false); doTransformResourceInjectionInTx(ignite, cache, true, false); doTransformResourceInjectionInTx(ignite, cache, true, true); } } /** * @param ignite Node. * @param cache Cache. * @param async Use async API. * @param oldAsync Use old async API. * @throws Exception If failed. */ private void doTransformResourceInjectionInTx(Ignite ignite, IgniteCache<String, Integer> cache, boolean async, boolean oldAsync) throws Exception { for (TransactionConcurrency concurrency : TransactionConcurrency.values()) { for (TransactionIsolation isolation : TransactionIsolation.values()) { IgniteTransactions txs = ignite.transactions(); try (Transaction tx = txs.txStart(concurrency, isolation)) { doTransformResourceInjection(ignite, cache, async, oldAsync); tx.commit(); } } } } /** * @param ignite Node. * @param cache Cache. * @param async Use async API. * @param oldAsync Use old async API. * @throws Exception If failed. */ private void doTransformResourceInjection(Ignite ignite, IgniteCache<String, Integer> cache, boolean async, boolean oldAsync) throws Exception { final Collection<ResourceType> required = Arrays.asList(ResourceType.IGNITE_INSTANCE, ResourceType.CACHE_NAME, ResourceType.LOGGER); final CacheEventListener lsnr = new CacheEventListener(); IgniteEvents evts = ignite.events(ignite.cluster()); UUID opId = evts.remoteListen(lsnr, null, EventType.EVT_CACHE_OBJECT_READ); try { checkResourceInjectionOnInvoke(cache, required, async, oldAsync); checkResourceInjectionOnInvokeAll(cache, required, async, oldAsync); checkResourceInjectionOnInvokeAllMap(cache, required, async, oldAsync); } finally { evts.stopRemoteListen(opId); } } /** * Tests invokeAll method for map of pairs (key, entryProcessor). * * @param cache Cache. * @param required Expected injected resources. * @param async Use async API. * @param oldAsync Use old async API. */ private void checkResourceInjectionOnInvokeAllMap(IgniteCache<String, Integer> cache, Collection<ResourceType> required, boolean async, boolean oldAsync) { Map<String, EntryProcessorResult<Integer>> results; Map<String, EntryProcessor<String, Integer, Integer>> map = new HashMap<>(); map.put(UUID.randomUUID().toString(), new ResourceInjectionEntryProcessor()); map.put(UUID.randomUUID().toString(), new ResourceInjectionEntryProcessor()); map.put(UUID.randomUUID().toString(), new ResourceInjectionEntryProcessor()); map.put(UUID.randomUUID().toString(), new ResourceInjectionEntryProcessor()); if (async) { if (oldAsync) { IgniteCache<String, Integer> acache = cache.withAsync(); acache.invokeAll(map); results = acache.<Map<String, EntryProcessorResult<Integer>>>future().get(); } else results = cache.invokeAllAsync(map).get(); } else results = cache.invokeAll(map); assertEquals(map.size(), results.size()); for (EntryProcessorResult<Integer> res : results.values()) { Collection<ResourceType> notInjected = ResourceInfoSet.valueOf(res.get()).notInjected(required); if (!notInjected.isEmpty()) fail("Can't inject resource(s): " + Arrays.toString(notInjected.toArray())); } } /** * Tests invokeAll method for set of keys. * * @param cache Cache. * @param required Expected injected resources. * @param async Use async API. * @param oldAsync Use old async API. */ private void checkResourceInjectionOnInvokeAll(IgniteCache<String, Integer> cache, Collection<ResourceType> required, boolean async, boolean oldAsync) { Set<String> keys = new HashSet<>(Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString())); Map<String, EntryProcessorResult<Integer>> results; if (async) { if (oldAsync) { IgniteCache<String, Integer> acache = cache.withAsync(); acache.invokeAll(keys, new ResourceInjectionEntryProcessor()); results = acache.<Map<String, EntryProcessorResult<Integer>>>future().get(); } else results = cache.invokeAllAsync(keys, new ResourceInjectionEntryProcessor()).get(); } else results = cache.invokeAll(keys, new ResourceInjectionEntryProcessor()); assertEquals(keys.size(), results.size()); for (EntryProcessorResult<Integer> res : results.values()) { Collection<ResourceType> notInjected1 = ResourceInfoSet.valueOf(res.get()).notInjected(required); if (!notInjected1.isEmpty()) fail("Can't inject resource(s): " + Arrays.toString(notInjected1.toArray())); } } /** * Tests invoke for single key. * * @param cache Cache. * @param required Expected injected resources. * @param async Use async API. * @param oldAsync Use old async API. */ private void checkResourceInjectionOnInvoke(IgniteCache<String, Integer> cache, Collection<ResourceType> required, boolean async, boolean oldAsync) { String key = UUID.randomUUID().toString(); Integer flags; if (async) { if (oldAsync) { IgniteCache<String, Integer> acache = cache.withAsync(); acache.invoke(key, new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor()); flags = acache.<Integer>future().get(); } else flags = cache.invokeAsync(key, new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor()).get(); } else flags = cache.invoke(key, new GridCacheAbstractFullApiSelfTest.ResourceInjectionEntryProcessor()); if (cache.isAsync()) flags = cache.<Integer>future().get(); assertTrue("Processor result is null", flags != null); Collection<ResourceType> notInjected = ResourceInfoSet.valueOf(flags).notInjected(required); if (!notInjected.isEmpty()) fail("Can't inject resource(s): " + Arrays.toString(notInjected.toArray())); } /** * Sets given value, returns old value. */ public static final class SetValueProcessor implements EntryProcessor<String, Integer, Integer> { /** */ private Integer newVal; /** * @param newVal New value to set. */ SetValueProcessor(Integer newVal) { this.newVal = newVal; } /** {@inheritDoc} */ @Override public Integer process(MutableEntry<String, Integer> entry, Object... arguments) throws EntryProcessorException { Integer val = entry.getValue(); entry.setValue(newVal); return val; } } /** * */ public enum CacheStartMode { /** Start caches together nodes (not dynamically) */ STATIC, /** */ NODES_THEN_CACHES, /** */ ONE_BY_ONE } /** * */ private static class RemoveEntryProcessor implements EntryProcessor<String, Integer, String>, Serializable { /** {@inheritDoc} */ @Override public String process(MutableEntry<String, Integer> e, Object... args) { assertNotNull(e.getKey()); Integer old = e.getValue(); e.remove(); return String.valueOf(old); } } /** * */ private static class IncrementEntryProcessor implements EntryProcessor<String, Integer, String>, Serializable { /** {@inheritDoc} */ @Override public String process(MutableEntry<String, Integer> e, Object... args) { assertNotNull(e.getKey()); Integer old = e.getValue(); e.setValue(old == null ? 1 : old + 1); return String.valueOf(old); } } /** * */ public static class ResourceInjectionEntryProcessor extends ResourceInjectionEntryProcessorBase<String, Integer> { /** */ protected transient Ignite ignite; /** */ protected transient String cacheName; /** */ protected transient IgniteLogger log; /** */ protected transient DummyService svc; /** * @param ignite Ignite. */ @IgniteInstanceResource public void setIgnite(Ignite ignite) { assert ignite != null; checkSet(); infoSet.set(ResourceType.IGNITE_INSTANCE, true); this.ignite = ignite; } /** * @param cacheName Cache name. */ @CacheNameResource public void setCacheName(String cacheName) { checkSet(); infoSet.set(ResourceType.CACHE_NAME, true); this.cacheName = cacheName; } /** * @param log Logger. */ @LoggerResource public void setLoggerResource(IgniteLogger log) { assert log != null; checkSet(); infoSet.set(ResourceType.LOGGER, true); this.log = log; } /** * @param svc Service. */ @ServiceResource(serviceName = SERVICE_NAME1) public void setDummyService(DummyService svc) { assert svc != null; checkSet(); infoSet.set(ResourceType.SERVICE, true); this.svc = svc; } /** {@inheritDoc} */ @Override public Integer process(MutableEntry<String, Integer> e, Object... args) { Integer oldVal = e.getValue(); e.setValue(ThreadLocalRandom.current().nextInt() + (oldVal == null ? 0 : oldVal)); return super.process(e, args); } } /** * */ private static class CheckEntriesTask extends TestIgniteIdxRunnable { /** Keys. */ private final Collection<String> keys; /** * @param keys Keys. */ public CheckEntriesTask(Collection<String> keys) { this.keys = keys; } /** {@inheritDoc} */ @Override public void run(int idx) throws Exception { GridCacheContext<String, Integer> ctx = ((IgniteKernal)ignite).<String, Integer>internalCache().context(); int size = 0; if (ctx.isNear()) ctx = ctx.near().dht().context(); for (String key : keys) { if (ctx.affinity().keyLocalNode(key, ctx.discovery().topologyVersionEx())) { GridCacheEntryEx e = ctx.cache().entryEx(key); assert e != null : "Entry is null [idx=" + idx + ", key=" + key + ", ctx=" + ctx + ']'; assert !e.deleted() : "Entry is deleted: " + e; size++; ctx.evicts().touch(e, null); } } assertEquals("Incorrect size on cache #" + idx, size, ignite.cache(ctx.name()).localSize(ALL)); } } /** * */ private static class CheckCacheSizeTask extends TestIgniteIdxRunnable { /** */ private final Map<String, Integer> map; /** * @param map Map. */ CheckCacheSizeTask(Map<String, Integer> map) { this.map = map; } /** {@inheritDoc} */ @Override public void run(int idx) throws Exception { GridCacheContext<String, Integer> ctx = ((IgniteKernal)ignite).<String, Integer>internalCache().context(); int size = 0; for (String key : map.keySet()) if (ctx.affinity().keyLocalNode(key, ctx.discovery().topologyVersionEx())) size++; assertEquals("Incorrect key size on cache #" + idx, size, ignite.cache(ctx.name()).localSize(ALL)); } } /** * */ private static class CheckPrimaryKeysTask implements TestCacheCallable<String, Integer, List<String>> { /** Start from. */ private final int startFrom; /** Count. */ private final int cnt; /** * @param startFrom Start from. * @param cnt Count. */ public CheckPrimaryKeysTask(int startFrom, int cnt) { this.startFrom = startFrom; this.cnt = cnt; } /** {@inheritDoc} */ @Override public List<String> call(Ignite ignite, IgniteCache<String, Integer> cache) throws Exception { List<String> found = new ArrayList<>(); Affinity<Object> affinity = ignite.affinity(cache.getName()); for (int i = startFrom; i < startFrom + 100_000; i++) { String key = "key" + i; if (affinity.isPrimary(ignite.cluster().localNode(), key)) { found.add(key); if (found.size() == cnt) return found; } } throw new IgniteException("Unable to find " + cnt + " keys as primary for cache."); } } /** * */ public static class EntryTtlTask implements TestCacheCallable<String, Integer, IgnitePair<Long>> { /** Entry key. */ private final String key; /** Check cache for nearness, use DHT cache if it is near. */ private final boolean useDhtForNearCache; /** * @param key Entry key. * @param useDhtForNearCache Check cache for nearness, use DHT cache if it is near. */ public EntryTtlTask(String key, boolean useDhtForNearCache) { this.key = key; this.useDhtForNearCache = useDhtForNearCache; } /** {@inheritDoc} */ @Override public IgnitePair<Long> call(Ignite ignite, IgniteCache<String, Integer> cache) throws Exception { GridCacheAdapter<?, ?> internalCache = internalCache0(cache); if (useDhtForNearCache && internalCache.context().isNear()) internalCache = internalCache.context().near().dht(); GridCacheEntryEx entry = internalCache.peekEx(key); return entry != null ? new IgnitePair<>(entry.ttl(), entry.expireTime()) : new IgnitePair<Long>(null, null); } } /** * */ private static class CheckIteratorTask extends TestIgniteIdxCallable<Void> { /** * @param idx Index. */ @Override public Void call(int idx) throws Exception { GridCacheContext<String, Integer> ctx = ((IgniteKernal)ignite).<String, Integer>internalCache().context(); GridCacheQueryManager queries = ctx.queries(); ConcurrentMap<UUID, Map<Long, GridFutureAdapter<?>>> map = GridTestUtils.getFieldValue(queries, GridCacheQueryManager.class, "qryIters"); for (Map<Long, GridFutureAdapter<?>> map1 : map.values()) assertTrue("Iterators not removed for grid " + idx, map1.isEmpty()); return null; } } /** * */ private static class PrintIteratorStateTask extends TestIgniteIdxCallable<Void> { /** */ @LoggerResource private IgniteLogger log; /** * @param idx Index. */ @Override public Void call(int idx) throws Exception { GridCacheContext<String, Integer> ctx = ((IgniteKernal)ignite).<String, Integer>internalCache().context(); GridCacheQueryManager queries = ctx.queries(); ConcurrentMap<UUID, Map<Long, GridFutureAdapter<?>>> map = GridTestUtils.getFieldValue(queries, GridCacheQueryManager.class, "qryIters"); for (Map<Long, GridFutureAdapter<?>> map1 : map.values()) { if (!map1.isEmpty()) { log.warning("Iterators leak detected at grid: " + idx); for (Map.Entry<Long, GridFutureAdapter<?>> entry : map1.entrySet()) log.warning(entry.getKey() + "; " + entry.getValue()); } } return null; } } /** * */ private static class RemoveAndReturnNullEntryProcessor implements EntryProcessor<String, Integer, Integer>, Serializable { /** {@inheritDoc} */ @Override public Integer process(MutableEntry<String, Integer> e, Object... args) { e.remove(); return null; } } /** * */ private static class SwapEvtsLocalListener implements IgnitePredicate<Event> { /** */ @LoggerResource private IgniteLogger log; /** Swap events. */ private final AtomicInteger swapEvts; /** Unswap events. */ private final AtomicInteger unswapEvts; /** * @param swapEvts Swap events. * @param unswapEvts Unswap events. */ public SwapEvtsLocalListener(AtomicInteger swapEvts, AtomicInteger unswapEvts) { this.swapEvts = swapEvts; this.unswapEvts = unswapEvts; } /** {@inheritDoc} */ @Override public boolean apply(Event evt) { log.info("Received event: " + evt); switch (evt.type()) { case EVT_CACHE_OBJECT_SWAPPED: swapEvts.incrementAndGet(); break; case EVT_CACHE_OBJECT_UNSWAPPED: unswapEvts.incrementAndGet(); break; } return true; } } /** * */ private static class CheckEntriesDeletedTask extends TestIgniteIdxRunnable { /** */ private final int cnt; /** * @param cnt Keys count. */ public CheckEntriesDeletedTask(int cnt) { this.cnt = cnt; } /** {@inheritDoc} */ @Override public void run(int idx) throws Exception { for (int i = 0; i < cnt; i++) { String key = String.valueOf(i); GridCacheContext<String, Integer> ctx = ((IgniteKernal)ignite).<String, Integer>internalCache().context(); GridCacheEntryEx entry = ctx.isNear() ? ctx.near().dht().peekEx(key) : ctx.cache().peekEx(key); if (ignite.affinity(null).mapKeyToPrimaryAndBackups(key).contains(((IgniteKernal)ignite).localNode())) { assertNotNull(entry); assertTrue(entry.deleted()); } else assertNull(entry); } } } /** * */ private static class CheckKeySizeTask extends TestIgniteIdxRunnable { /** Keys. */ private final Collection<String> keys; /** * @param keys Keys. */ public CheckKeySizeTask(Collection<String> keys) { this.keys = keys; } /** {@inheritDoc} */ @Override public void run(int idx) throws Exception { GridCacheContext<String, Integer> ctx = ((IgniteKernal)ignite).<String, Integer>internalCache().context(); int size = 0; for (String key : keys) if (ctx.affinity().keyLocalNode(key, ctx.discovery().topologyVersionEx())) size++; assertEquals("Incorrect key size on cache #" + idx, size, ignite.cache(null).localSize(ALL)); } } /** * */ private static class FailedEntryProcessor implements EntryProcessor<String, Integer, Integer>, Serializable { /** {@inheritDoc} */ @Override public Integer process(MutableEntry<String, Integer> e, Object... args) { throw new EntryProcessorException("Test entry processor exception."); } } /** * */ private static class TestValue implements Serializable { /** */ private int val; /** * @param val Value. */ TestValue(int val) { this.val = val; } /** * @return Value. */ public int value() { return val; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TestValue)) return false; TestValue value = (TestValue)o; if (val != value.val) return false; return true; } /** {@inheritDoc} */ @Override public int hashCode() { return val; } } /** * Dummy Service. */ public interface DummyService { /** * */ public void noop(); } /** * No-op test service. */ public static class DummyServiceImpl implements DummyService, Service { /** */ private static final long serialVersionUID = 0L; /** {@inheritDoc} */ @Override public void noop() { // No-op. } /** {@inheritDoc} */ @Override public void cancel(ServiceContext ctx) { System.out.println("Cancelling service: " + ctx.name()); } /** {@inheritDoc} */ @Override public void init(ServiceContext ctx) throws Exception { System.out.println("Initializing service: " + ctx.name()); } /** {@inheritDoc} */ @Override public void execute(ServiceContext ctx) { System.out.println("Executing service: " + ctx.name()); } } /** * */ public static class CacheEventListener implements IgniteBiPredicate<UUID, CacheEvent>, IgnitePredicate<CacheEvent> { /** */ public final LinkedBlockingQueue<CacheEvent> evts = new LinkedBlockingQueue<>(); /** {@inheritDoc} */ @Override public boolean apply(UUID uuid, CacheEvent evt) { evts.add(evt); return true; } /** {@inheritDoc} */ @Override public boolean apply(CacheEvent evt) { evts.add(evt); return true; } } }
28.990803
125
0.548517
834bf1949911e480063191229eeb106157d9fceb
490
package kerio.connect.admin.common.enums; public enum ItemName { Name, ///< Entity Name Description, ///< Entity Description Email, ///< Entity Email Address FullName, ///< Entity Full Name TimeItem, ///< Entity Time - it cannot be simply Time because of C++ conflict - see bug 34684 comment #3 DateItem, ///< Entity Date - I expect same problem with Date as with Time DomainName ///< differs from name (eg. cannot contains underscore) }
35
111
0.653061
d00ff28d19599e53580f7f3441b46a2b5b96b0ec
2,853
package controle.telas; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import controle.dao.ManufaturaDao; import controle.modelos.Manufatura; import controle.uteis.Interface; import controle.uteis.MascaraDatas; import controle.uteis.Uteis; public class ConsultarManufaturaAction extends ConsultarManufatura { private List<Manufatura> listManufatura; private ManufaturaDao dao = new ManufaturaDao(); private static final DateTimeFormatter padrao = DateTimeFormatter.ofPattern("dd/MM/yyyy"); public ConsultarManufaturaAction(Shell pai) { super(pai); adicionarEventosButton(); adicionarEventosText(); adicionarEventosTable(); preencherDatas(); shell.open(); Interface.manterJanelaModal(shell); } private void adicionarEventosButton() { btnCancelar.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.close(); } }); btnPesquisar.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (Interface.verificarPreenchimentoCampos(shell)) { mostrarDados(); } } }); } private void preencherDatas(){ LocalDate primeiroDia = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()); LocalDate ultimoDia = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()); txtDataBase.setText(primeiroDia.format(padrao)); txtDataTeto.setText(ultimoDia.format(padrao)); } private void adicionarEventosText() { txtDataBase.addFocusListener(MascaraDatas.getFormatarDatas()); txtDataTeto.addFocusListener(MascaraDatas.getFormatarDatas()); } private void adicionarEventosTable() { table.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent e) { int index = table.getSelectionIndex(); if(index >= 0){ new ManufaturarProdutoFinalAction(shell, listManufatura.get(index)); } else{ Uteis.exibirMensagem(shell, "Selecione um registro!"); } } }); } private void mostrarDados() { LocalDate dataBase = LocalDate.parse(txtDataBase.getText(), padrao); LocalDate dataTeto = LocalDate.parse(txtDataTeto.getText(), padrao); listManufatura = dao.pesquisarPorData(dataBase, dataTeto); listManufatura.forEach(m -> { TableItem ti = new TableItem(table, SWT.None); ti.setText(0, m.getDate().format(padrao)); ti.setText(1,m.getTotalMateriaPrima().toString()); ti.setText(2, m.getTotalProdutoFinal().toString()); }); } }
30.351064
91
0.761654
d079b6c6084657d99a69c0f52e4f3a0cecf30ed5
3,143
package com.citraining.core.report.impl; import org.apache.sling.api.resource.ResourceResolverFactory; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.citraining.core.report.BuildReport; import com.day.commons.datasource.poolservice.DataSourcePool; @Component(service = BuildReport.class) public class BuildReportImpl implements BuildReport { @Reference private ResourceResolverFactory resolverFactory; @Reference private DataSourcePool dataSourcePool; protected final Logger logger = LoggerFactory.getLogger(BuildReportImpl.class); public String jasperBuildReport() { try{ return "Report was successfully created"; } catch (Exception e){ logger.info(e.getMessage()); } return "ERROR"; } // Write the Jasper Report to the DAM /* * // Save the uploaded file into the AEM DAM using AssetManager APIs private String writeToDam(InputStream is, String fileName) { try { * ResourceResolver resourceResolver = CommonUtil .getResourceResolver(resolverFactory); com.day.cq.dam.api.AssetManager assetMgr = * resourceResolver .adaptTo(com.day.cq.dam.api.AssetManager.class); String newFile = "/content/dam/reports/" + fileName; * assetMgr.createAsset(newFile, is, "application/pdf", true); // Return the path to the file was stored return newFile; } catch (Exception e) { * logger.info("Error IS " + e.getMessage()); } return null; } // Returns a connection using the configured DataSourcePool private Connection * getConnection() { try { // Inject the DataSourcePool right here! DataSource dataSource = (DataSource) dataSourcePool * .getDataSource("customer"); Connection connection = dataSource.getConnection(); return connection; } catch (Exception e) { e.printStackTrace(); * } return null; } public boolean generateReport(String reportName) { Connection connection = getConnection(); JasperReportBuilder jsperReport = * DynamicReports.report(); jsperReport .columns( Columns.column("Customer Id", "custId", DataTypes.integerType()), Columns.column("First Name", * "custFirst", DataTypes.stringType()), Columns.column("Last Name", "custLast", DataTypes.stringType()), Columns.column("Description", * "custDesc", DataTypes.stringType())) .title(Components.text(reportName).setHorizontalAlignment( HorizontalAlignment.CENTER)) * .pageFooter(Components.pageXofY()) .setDataSource( "SELECT custId, custFirst, custLast, custDesc FROM customer", connection); try { * jsperReport.show(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); InputStream inputStream = new * ByteArrayInputStream( byteArrayOutputStream.toByteArray()); // int length = inputStream.available(); // logger.info("IS IS THIS BIG " + * length); // Persist the PDF Report in the AEM DAM String reportDetails = writeToDam(inputStream, "JasperReport.pdf"); // jsperReport.toPdf(new * FileOutputStream("D:/report.pdf")); } catch (DRException e) { e.printStackTrace(); return false; } return true; } */ }
55.140351
148
0.751829
cfbeb011cc498e87ab7c83f9949759c9377f479f
2,673
package com.agoni.my.shop.web.admin.service.impl; import com.agoni.my.shop.commons.dto.BaseResult; import com.agoni.my.shop.commons.validator.BeanValidator; import com.agoni.my.shop.domain.TbContentCategory; import com.agoni.my.shop.web.admin.abstracts.AbstractBaseTreeServiceImpl; import com.agoni.my.shop.web.admin.dao.TbContentCategoryDao; import com.agoni.my.shop.web.admin.service.TbContentCategoryService; import com.agoni.my.shop.web.admin.service.TbContentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; /** * @Title TbContentCategoryServiceImpl * @Description: * @Author Soulmate * @Version 1.0 * @Date 2019/6/12 15:54 */ @Service @Transactional(readOnly = true,rollbackFor = Exception.class) public class TbContentCategoryServiceImpl extends AbstractBaseTreeServiceImpl<TbContentCategory, TbContentCategoryDao> implements TbContentCategoryService { @Autowired private TbContentService tbContentService; /** * 保存分类 * @param entity * @return */ @Override @Transactional(readOnly = false) public BaseResult save(TbContentCategory entity) { String validator = BeanValidator.validator(entity); if (validator != null) { return BaseResult.fail(validator); } else { TbContentCategory parent = entity.getParent(); //如果没有选择父级节点则默认设置为根目录 if (parent == null || parent.getId() == null) { // 0 代表根目录 parent.setId(0L); //根目录一定是父级目录 entity.setTypeOfParent(true); } entity.setUpdated(new Date()); //新增 if (entity.getId() == null) { entity.setCreated(new Date()); //判断当前新增的节点有没有父级节点 if (parent.getId() != 0L) { TbContentCategory currentCategoryParent = getById(parent.getId()); if (currentCategoryParent != null) { //为父级节点设置 isParent 为 true currentCategoryParent.setTypeOfParent(true); update(currentCategoryParent); } } // 父级节点为 0 ,表示为根目录 else { // 根目录一定是父级目录 entity.setTypeOfParent(true); } dao.insert(entity); } //修改 else { update(entity); } return BaseResult.success("保存信息成功"); } } }
31.447059
156
0.600823
47e27fba7041fb37c0d73a35b9480b4742539dfe
1,613
package com.thenatekirby.compote.integration.jei; import com.thenatekirby.compote.Compote; import mezz.jei.api.IModPlugin; import mezz.jei.api.JeiPlugin; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.registration.IRecipeCatalystRegistration; import mezz.jei.api.registration.IRecipeCategoryRegistration; import mezz.jei.api.registration.IRecipeRegistration; import mezz.jei.api.runtime.IJeiRuntime; import net.minecraft.block.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import javax.annotation.Nonnull; // ====---------------------------------------------------------------------------==== @JeiPlugin public class CompoteJEIPlugin implements IModPlugin { @Nonnull @Override public ResourceLocation getPluginUid() { return new ResourceLocation(Compote.MOD_ID, "jei_plugin"); } @Override public void registerCategories(IRecipeCategoryRegistration registration) { IGuiHelper guiHelper = registration.getJeiHelpers().getGuiHelper(); registration.addRecipeCategories(new CompoteRecipeCategory(guiHelper,144, 54)); } @Override public void registerRecipes(IRecipeRegistration registration) { registration.addRecipes(CompostingRecipeBuilder.getCompostingRecipes(), CompoteRecipeCategory.UID); } @Override public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) { registration.addRecipeCatalyst(new ItemStack(Blocks.COMPOSTER), CompoteRecipeCategory.UID); } @Override public void onRuntimeAvailable(IJeiRuntime jeiRuntime) { } }
34.319149
107
0.745195
6e9d000c0d66e1c41242a9d5129d42565bcdfba1
1,015
/* * Copyright 2006-2008 Web Cohesion * * 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.codehaus.enunciate.samples.schema; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAnyAttribute; /** * @author Ryan Heaton */ public class UnsupportedTypeDefBean { @XmlMixed public String mixedProperty; @XmlAnyElement public String anyElementProperty; @XmlAnyAttribute public String anyAttributeProperty; }
29
75
0.764532
1183f2c1ccd677a5f17ae4c951358ad472b60aed
236
package ch.itenengineering.timer.ejb; import javax.ejb.Stateless; @Stateless public class TimerBean implements TimerRemote { public void start(String name, long interval) { } public void stop(String name) { } } // end of class
15.733333
48
0.745763
a83ca62e111c0b7cfa99a45325c6b15e2c6e1321
348
package com.nerdynarwhal.hello.api; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor public class Saying { @JsonProperty @Getter private Long id; @JsonProperty @Getter private String content; }
18.315789
53
0.79023
be2ad936200b78fde79b95112816042e2933d672
841
package edu.gemini.spModel.target.offset; /** * A data object that describes an offset position and includes methods * for extracting positions. */ public final class OffsetPos extends OffsetPosBase { public static final Factory<OffsetPos> FACTORY = new Factory<OffsetPos>() { public OffsetPos create(String tag) { return new OffsetPos(tag); } public OffsetPos create(String tag, double p, double q) { return new OffsetPos(tag, p, q); } }; /** * Create an OffsetPos with the given tag and coordinates */ public OffsetPos(String tag, double xaxis, double yaxis) { super(tag, xaxis, yaxis); } /** * Create an OffsetPos with the given tag and (0,0) coordinates. */ public OffsetPos(String tag) { super(tag); } }
25.484848
79
0.626635
590432542aedaffeca5d751e07fc543ec74aae38
1,723
/* * Copyright 2014 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.api.internal.artifacts.ivyservice.resolveengine.result; import org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphNode; import org.gradle.api.internal.artifacts.ivyservice.resolveengine.graph.DependencyGraphVisitor; public class ResolutionResultDependencyGraphVisitor implements DependencyGraphVisitor { private final ResolutionResultBuilder newModelBuilder; public ResolutionResultDependencyGraphVisitor(ResolutionResultBuilder newModelBuilder) { this.newModelBuilder = newModelBuilder; } public void start(DependencyGraphNode root) { newModelBuilder.start(root.toId(), root.getComponentId()); } public void visitNode(DependencyGraphNode resolvedConfiguration) { newModelBuilder.resolvedModuleVersion(resolvedConfiguration.getSelection()); } public void visitEdge(DependencyGraphNode resolvedConfiguration) { newModelBuilder.resolvedConfiguration(resolvedConfiguration.toId(), resolvedConfiguration.getOutgoingEdges()); } public void finish(DependencyGraphNode root) { } }
38.288889
118
0.778874
834ee45e1a92bb3a87d363f372304cfd6ce81606
11,557
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.network.implementation; import com.azure.core.management.SubResource; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.network.NetworkManager; import com.azure.resourcemanager.network.fluent.models.IpAddressAvailabilityResultInner; import com.azure.resourcemanager.network.fluent.models.SubnetInner; import com.azure.resourcemanager.network.fluent.models.VirtualNetworkInner; import com.azure.resourcemanager.network.models.AddressSpace; import com.azure.resourcemanager.network.models.DdosProtectionPlan; import com.azure.resourcemanager.network.models.DhcpOptions; import com.azure.resourcemanager.network.models.Network; import com.azure.resourcemanager.network.models.NetworkPeerings; import com.azure.resourcemanager.network.models.Subnet; import com.azure.resourcemanager.network.models.TagsObject; import com.azure.resourcemanager.resources.fluentcore.model.Creatable; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; /** Implementation for Network and its create and update interfaces. */ class NetworkImpl extends GroupableParentResourceWithTagsImpl<Network, VirtualNetworkInner, NetworkImpl, NetworkManager> implements Network, Network.Definition, Network.Update { private final ClientLogger logger = new ClientLogger(getClass()); private Map<String, Subnet> subnets; private NetworkPeeringsImpl peerings; private Creatable<DdosProtectionPlan> ddosProtectionPlanCreatable; NetworkImpl(String name, final VirtualNetworkInner innerModel, final NetworkManager networkManager) { super(name, innerModel, networkManager); } @Override protected void initializeChildrenFromInner() { // Initialize subnets this.subnets = new TreeMap<>(); List<SubnetInner> inners = this.innerModel().subnets(); if (inners != null) { for (SubnetInner inner : inners) { SubnetImpl subnet = new SubnetImpl(inner, this); this.subnets.put(inner.name(), subnet); } } this.peerings = new NetworkPeeringsImpl(this); } // Verbs @Override public Mono<Network> refreshAsync() { return super .refreshAsync() .map( network -> { NetworkImpl impl = (NetworkImpl) network; impl.initializeChildrenFromInner(); return impl; }); } @Override protected Mono<VirtualNetworkInner> getInnerAsync() { return this .manager() .serviceClient() .getVirtualNetworks() .getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override protected Mono<VirtualNetworkInner> applyTagsToInnerAsync() { return this .manager() .serviceClient() .getVirtualNetworks() .updateTagsAsync(resourceGroupName(), name(), new TagsObject().withTags(innerModel().tags())); } @Override public boolean isPrivateIPAddressAvailable(String ipAddress) { IpAddressAvailabilityResultInner result = checkIPAvailability(ipAddress); return (result != null) ? result.available() : false; } @Override public boolean isPrivateIPAddressInNetwork(String ipAddress) { IpAddressAvailabilityResultInner result = checkIPAvailability(ipAddress); return (result != null) ? true : false; } // Helpers private IpAddressAvailabilityResultInner checkIPAvailability(String ipAddress) { if (ipAddress == null) { return null; } IpAddressAvailabilityResultInner result = null; try { result = this .manager() .serviceClient() .getVirtualNetworks() .checkIpAddressAvailability(this.resourceGroupName(), this.name(), ipAddress); } catch (ManagementException e) { if (!e.getValue().getCode().equalsIgnoreCase("PrivateIPAddressNotInAnySubnet")) { throw logger.logExceptionAsError(e); // Rethrow if the exception reason is anything other than IP address not found } } return result; } NetworkImpl withSubnet(SubnetImpl subnet) { this.subnets.put(subnet.name(), subnet); return this; } // Setters (fluent) @Override public NetworkImpl withDnsServer(String ipAddress) { if (this.innerModel().dhcpOptions() == null) { this.innerModel().withDhcpOptions(new DhcpOptions()); } if (this.innerModel().dhcpOptions().dnsServers() == null) { this.innerModel().dhcpOptions().withDnsServers(new ArrayList<String>()); } this.innerModel().dhcpOptions().dnsServers().add(ipAddress); return this; } @Override public NetworkImpl withSubnet(String name, String cidr) { return this.defineSubnet(name).withAddressPrefix(cidr).attach(); } @Override public NetworkImpl withSubnets(Map<String, String> nameCidrPairs) { this.subnets.clear(); for (Entry<String, String> pair : nameCidrPairs.entrySet()) { this.withSubnet(pair.getKey(), pair.getValue()); } return this; } @Override public NetworkImpl withoutSubnet(String name) { this.subnets.remove(name); return this; } @Override public NetworkImpl withAddressSpace(String cidr) { if (this.innerModel().addressSpace() == null) { this.innerModel().withAddressSpace(new AddressSpace()); } if (this.innerModel().addressSpace().addressPrefixes() == null) { this.innerModel().addressSpace().withAddressPrefixes(new ArrayList<String>()); } this.innerModel().addressSpace().addressPrefixes().add(cidr); return this; } @Override public SubnetImpl defineSubnet(String name) { SubnetInner inner = new SubnetInner().withName(name); return new SubnetImpl(inner, this); } @Override public NetworkImpl withoutAddressSpace(String cidr) { if (cidr != null && this.innerModel().addressSpace() != null && this.innerModel().addressSpace().addressPrefixes() != null) { this.innerModel().addressSpace().addressPrefixes().remove(cidr); } return this; } // Getters @Override public List<String> addressSpaces() { List<String> addressSpaces = new ArrayList<String>(); if (this.innerModel().addressSpace() == null) { return Collections.unmodifiableList(addressSpaces); } else if (this.innerModel().addressSpace().addressPrefixes() == null) { return Collections.unmodifiableList(addressSpaces); } else { return Collections.unmodifiableList(this.innerModel().addressSpace().addressPrefixes()); } } @Override public List<String> dnsServerIPs() { List<String> ips = new ArrayList<String>(); if (this.innerModel().dhcpOptions() == null) { return Collections.unmodifiableList(ips); } else if (this.innerModel().dhcpOptions().dnsServers() == null) { return Collections.unmodifiableList(ips); } else { return this.innerModel().dhcpOptions().dnsServers(); } } @Override public Map<String, Subnet> subnets() { return Collections.unmodifiableMap(this.subnets); } @Override protected void beforeCreating() { // Ensure address spaces if (this.addressSpaces().size() == 0) { this.withAddressSpace("10.0.0.0/16"); } if (isInCreateMode()) { // Create a subnet as needed, covering the entire first address space if (this.subnets.size() == 0) { this.withSubnet("subnet1", this.addressSpaces().get(0)); } } // Reset and update subnets this.innerModel().withSubnets(innersFromWrappers(this.subnets.values())); } @Override public SubnetImpl updateSubnet(String name) { return (SubnetImpl) this.subnets.get(name); } @Override protected Mono<VirtualNetworkInner> createInner() { if (ddosProtectionPlanCreatable != null && this.taskResult(ddosProtectionPlanCreatable.key()) != null) { DdosProtectionPlan ddosProtectionPlan = this.<DdosProtectionPlan>taskResult(ddosProtectionPlanCreatable.key()); withExistingDdosProtectionPlan(ddosProtectionPlan.id()); } return this .manager() .serviceClient() .getVirtualNetworks() .createOrUpdateAsync(this.resourceGroupName(), this.name(), this.innerModel()) .map( virtualNetworkInner -> { NetworkImpl.this.ddosProtectionPlanCreatable = null; return virtualNetworkInner; }); } @Override public NetworkPeerings peerings() { return this.peerings; } @Override public boolean isDdosProtectionEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableDdosProtection()); } @Override public boolean isVmProtectionEnabled() { return ResourceManagerUtils.toPrimitiveBoolean(innerModel().enableVmProtection()); } @Override public String ddosProtectionPlanId() { return innerModel().ddosProtectionPlan() == null ? null : innerModel().ddosProtectionPlan().id(); } @Override public NetworkImpl withNewDdosProtectionPlan() { innerModel().withEnableDdosProtection(true); DdosProtectionPlan.DefinitionStages.WithGroup ddosProtectionPlanWithGroup = manager() .ddosProtectionPlans() .define(this.manager().resourceManager().internalContext().randomResourceName(name(), 20)) .withRegion(region()); if (super.creatableGroup != null && isInCreateMode()) { ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withNewResourceGroup(super.creatableGroup); } else { ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withExistingResourceGroup(resourceGroupName()); } this.addDependency(ddosProtectionPlanCreatable); return this; } @Override public NetworkImpl withExistingDdosProtectionPlan(String planId) { innerModel().withEnableDdosProtection(true).withDdosProtectionPlan(new SubResource().withId(planId)); return this; } @Override public NetworkImpl withoutDdosProtectionPlan() { innerModel().withEnableDdosProtection(false).withDdosProtectionPlan(null); return this; } @Override public NetworkImpl withVmProtection() { innerModel().withEnableVmProtection(true); return this; } @Override public NetworkImpl withoutVmProtection() { innerModel().withEnableVmProtection(false); return this; } }
35.021212
120
0.652245
aeb02aaa1c6acf19630c1cfaa3efa09b61a01401
8,835
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.simpleinstrument; import java.util.Collections; import java.util.Set; import javax.time.calendar.Clock; import javax.time.calendar.ZonedDateTime; import org.apache.commons.lang.Validate; import com.google.common.collect.Sets; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve; import com.opengamma.analytics.financial.simpleinstruments.derivative.SimpleInstrument; import com.opengamma.analytics.financial.simpleinstruments.pricing.SimpleFXFutureDataBundle; import com.opengamma.analytics.financial.simpleinstruments.pricing.SimpleFXFuturePresentValueCalculator; import com.opengamma.core.config.ConfigSource; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.core.security.Security; import com.opengamma.core.value.MarketDataRequirementNames; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.OpenGammaCompilationContext; import com.opengamma.financial.OpenGammaExecutionContext; import com.opengamma.financial.analytics.conversion.SimpleFutureConverter; import com.opengamma.financial.analytics.ircurve.YieldCurveFunction; import com.opengamma.financial.currency.ConfigDBCurrencyPairsSource; import com.opengamma.financial.currency.CurrencyPair; import com.opengamma.financial.currency.CurrencyPairs; import com.opengamma.financial.security.future.FXFutureSecurity; import com.opengamma.id.ExternalId; import com.opengamma.util.money.Currency; import com.opengamma.util.money.CurrencyAmount; /** * */ public class SimpleFXFuturePresentValueFunction extends AbstractFunction.NonCompiledInvoker { private static final SimpleFutureConverter CONVERTER = new SimpleFutureConverter(); private static final SimpleFXFuturePresentValueCalculator CALCULATOR = new SimpleFXFuturePresentValueCalculator(); private final String _payCurveName; private final String _receiveCurveName; public SimpleFXFuturePresentValueFunction(final String payCurveName, final String receiveCurveName) { Validate.notNull(payCurveName, "pay curve name"); Validate.notNull(receiveCurveName, "receive curve name"); _payCurveName = payCurveName; _receiveCurveName = receiveCurveName; } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final FXFutureSecurity security = (FXFutureSecurity) target.getSecurity(); final Clock snapshotClock = executionContext.getValuationClock(); final ZonedDateTime now = snapshotClock.zonedDateTime(); final Currency payCurrency = security.getNumerator(); final Object payCurveObject = inputs.getValue(YieldCurveFunction.getCurveRequirement(payCurrency, _payCurveName, null, null)); if (payCurveObject == null) { throw new OpenGammaRuntimeException("Could not get " + _payCurveName + " curve"); } final Currency receiveCurrency = security.getDenominator(); final Object receiveCurveObject = inputs.getValue(YieldCurveFunction.getCurveRequirement(receiveCurrency, _receiveCurveName, null, null)); if (receiveCurveObject == null) { throw new OpenGammaRuntimeException("Could not get " + _receiveCurveName + " curve"); } final ConfigSource configSource = OpenGammaExecutionContext.getConfigSource(executionContext); final ConfigDBCurrencyPairsSource currencyPairsSource = new ConfigDBCurrencyPairsSource(configSource); final CurrencyPairs currencyPairs = currencyPairsSource.getCurrencyPairs(CurrencyPairs.DEFAULT_CURRENCY_PAIRS); final CurrencyPair currencyPair = currencyPairs.getCurrencyPair(payCurrency, receiveCurrency); final Currency currencyBase = currencyPair.getBase(); final ExternalId underlyingIdentifier = getSpotIdentifier(security, currencyPair); final Object spotObject = inputs.getValue(new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE, underlyingIdentifier)); if (spotObject == null) { throw new OpenGammaRuntimeException("Could not get market data for " + underlyingIdentifier); } double spot = (Double) spotObject; if (!receiveCurrency.equals(currencyBase) && receiveCurrency.equals(security.getCurrency())) { spot = 1. / spot; } final YieldAndDiscountCurve payCurve = (YieldAndDiscountCurve) payCurveObject; final YieldAndDiscountCurve receiveCurve = (YieldAndDiscountCurve) receiveCurveObject; final SimpleFXFutureDataBundle data = new SimpleFXFutureDataBundle(payCurve, receiveCurve, spot); final SimpleInstrument instrument = security.accept(CONVERTER).toDerivative(now); final CurrencyAmount pv = instrument.accept(CALCULATOR, data); final ValueProperties properties = createValueProperties() .with(ValuePropertyNames.PAY_CURVE, _payCurveName) .with(ValuePropertyNames.RECEIVE_CURVE, _receiveCurveName) .with(ValuePropertyNames.CURRENCY, pv.getCurrency().getCode()).get(); final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.PRESENT_VALUE, target.toSpecification(), properties); return Collections.singleton(new ComputedValue(spec, pv.getAmount())); } @Override public ComputationTargetType getTargetType() { return ComputationTargetType.SECURITY; } @Override public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) { if (target.getType() != ComputationTargetType.SECURITY) { return false; } final Security security = target.getSecurity(); return security instanceof FXFutureSecurity; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final ValueProperties properties = createValueProperties() .with(ValuePropertyNames.PAY_CURVE, _payCurveName) .with(ValuePropertyNames.RECEIVE_CURVE, _receiveCurveName) .with(ValuePropertyNames.CURRENCY, ((FXFutureSecurity) target.getSecurity()).getDenominator().getCode()).get(); return Collections.singleton(new ValueSpecification(ValueRequirementNames.PRESENT_VALUE, target.toSpecification(), properties)); } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final FXFutureSecurity future = (FXFutureSecurity) target.getSecurity(); final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context); final ConfigDBCurrencyPairsSource currencyPairsSource = new ConfigDBCurrencyPairsSource(configSource); final CurrencyPairs currencyPairs = currencyPairsSource.getCurrencyPairs(CurrencyPairs.DEFAULT_CURRENCY_PAIRS); final CurrencyPair currencyPair = currencyPairs.getCurrencyPair(future.getNumerator(), future.getDenominator()); final ExternalId underlyingIdentifier = getSpotIdentifier(future, currencyPair); final ValueRequirement payYieldCurve = YieldCurveFunction.getCurveRequirement(future.getNumerator(), _payCurveName, null, null); final ValueRequirement receiveYieldCurve = YieldCurveFunction.getCurveRequirement(future.getDenominator(), _receiveCurveName, null, null); final ValueRequirement spot = new ValueRequirement(MarketDataRequirementNames.MARKET_VALUE, underlyingIdentifier); return Sets.newHashSet(payYieldCurve, receiveYieldCurve, spot); } private ExternalId getSpotIdentifier(final FXFutureSecurity future, final CurrencyPair currencyPair) { ExternalId bloombergId; final Currency payCurrency = future.getNumerator(); final Currency receiveCurrency = future.getDenominator(); if (payCurrency.equals(currencyPair.getBase())) { bloombergId = ExternalSchemes.bloombergTickerSecurityId(payCurrency.getCode() + receiveCurrency.getCode() + " Curncy"); } else { bloombergId = ExternalSchemes.bloombergTickerSecurityId(receiveCurrency.getCode() + payCurrency.getCode() + " Curncy"); } return bloombergId; } }
55.917722
190
0.810413
90936f120dc77928f97619e50255f4f5b98a897c
2,410
package ch.itenengineering.jpa.relation.many2many.ejb; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import ch.itenengineering.jpa.relation.many2many.domain.Course; import ch.itenengineering.jpa.relation.many2many.domain.Student; @Stateless public class ManagerBeanM2M implements ManagerM2M { @PersistenceContext(unitName = "TestPU") private EntityManager em; @Override public void clear() { em.createNativeQuery("delete from R_MANY2MANY_STUDENT_COURSE").executeUpdate(); em.createQuery("delete from m2mStudent").executeUpdate(); em.createQuery("delete from m2mCourse").executeUpdate(); } @Override public void book(int studentId, int courseId) { // get managed course instance Course course = (Course) find(Course.class, courseId); // get managed student Student student = (Student) find(Student.class, studentId); // book course student.getCourses().add(course); merge(student); // alternative via native query // Query query = em.createNativeQuery( // "insert into r_many2many_student_course (student_id, course_id) values (:sid, :cid)" // ); // query.setParameter("sid", studentId); // query.setParameter("cid", courseId); // query.executeUpdate(); } @Override public void cancel(int studentId, int courseId) { // get managed course instance Course course = (Course) find(Course.class, courseId); // get managed student Student student = (Student) find(Student.class, studentId); // cancel course student.getCourses().remove(course); merge(student); // alternative via native query // Query query = em.createNativeQuery( // "delete from r_many2many_student_course where student_id=:sid and course_id=:cid" // ); // query.setParameter("sid", studentId); // query.setParameter("cid", courseId); // query.executeUpdate(); } @Override public Object persist(Object entity) { em.persist(entity); return entity; } @Override public Object merge(Object entity) { return em.merge(entity); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Object find(Class clazz, Object primaryKey) { return em.find(clazz, primaryKey); } @Override @SuppressWarnings("rawtypes") public void remove(Class clazz, Object primaryKey) { Object obj = find(clazz, primaryKey); if (obj != null) { em.remove(obj); } } } // end of class
25.913978
89
0.727386
a5067c5721f36ceaf871b0b4a286eebcd5de0c68
319
package slogo.compiler.math; import slogo.compiler.parser.Command; public class SineCommand extends Command { public SineCommand(String declaration) { super(declaration); desiredArgs = 1; } @Override public double executeCommand() { return Math.sin(Math.toRadians(args.get(0).execute())); } }
18.764706
59
0.717868
36a24eac0e2802695af117979a386fd93046e7af
474
class L3_21{ public static void main(String[] args){ int n = 10;//linha valor (n); } static void valor(int n){ for (int N = 0; N < n; N = N+1){ if (N*n == Math.pow(N,2)) System.out.print(":"); else System.out.print("*"); for (int M = 1; M < n; M = M+1){ if (M*N == Math.pow(M,2)) System.out.print(":"); else System.out.print("*"); } System.out.println(); } } }
15.290323
41
0.438819
7e690354d539919a5f7fb78fdf51b237044a19f3
867
package com.github.jiangxch.courselearningmanagement.provider.entity; import com.github.jiangxch.courselearningmanagement.provider.entity.common.BaseAliasEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Id; @EqualsAndHashCode(callSuper = true) @Data @ToString(callSuper = true) @Entity(value = "course", noClassnameStored = true) public class CourseEntity extends BaseAliasEntity { @Id private String id; // 学校名称 private String schoolName; // 学院名称 private String academyName; // 专业名称 private String majorName; // 课程名称 private String courseName; /** * 是否是该专业必修课程 * @see com.github.jiangxch.courselearningmanagement.common.enums.common.YesOrNoEnum */ private Integer isObligatory; }
28.9
91
0.756632
dd86afcf290cf7d7d1d2e65324ab5e0a90351b37
21,853
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.server.healthchecks; import java.util.ArrayList; import org.testng.Assert; import org.testng.annotations.Test; public class TestHoltWintersComputer { // Atmospheric concentrations of CO2 are expressed in parts per million (ppm) and // reported in the preliminary 1997 SIO manometric mole fraction scale. // A time series of 468 observations; monthly from 1959 to 1997. private static double[] CO2 = {315.42, 316.31, 316.5, 317.56, 318.13, 318, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43, 316.27, 316.81, 317.42, 318.87, 319.87, 319.43, 318.01, 315.74, 314, 313.68, 314.84, 316.03, 316.73, 317.54, 318.38, 319.31, 320.42, 319.61, 318.42, 316.63, 314.83, 315.16, 315.94, 316.85, 317.78, 318.4, 319.53, 320.42, 320.85, 320.45, 319.45, 317.25, 316.11, 315.27, 316.53, 317.53, 318.58, 318.92, 319.7, 321.22, 322.08, 321.31, 319.58, 317.61, 316.05, 315.83, 316.91, 318.2, 319.41, 320.07, 320.74, 321.4, 322.06, 321.73, 320.27, 318.54, 316.54, 316.71, 317.53, 318.55, 319.27, 320.28, 320.73, 321.97, 322, 321.71, 321.05, 318.71, 317.66, 317.14, 318.7, 319.25, 320.46, 321.43, 322.23, 323.54, 323.91, 323.59, 322.24, 320.2, 318.48, 317.94, 319.63, 320.87, 322.17, 322.34, 322.88, 324.25, 324.83, 323.93, 322.38, 320.76, 319.1, 319.24, 320.56, 321.8, 322.4, 322.99, 323.73, 324.86, 325.4, 325.2, 323.98, 321.95, 320.18, 320.09, 321.16, 322.74, 323.83, 324.26, 325.47, 326.5, 327.21, 326.54, 325.72, 323.5, 322.22, 321.62, 322.69, 323.95, 324.89, 325.82, 326.77, 327.97, 327.91, 327.5, 326.18, 324.53, 322.93, 322.9, 323.85, 324.96, 326.01, 326.51, 327.01, 327.62, 328.76, 328.4, 327.2, 325.27, 323.2, 323.4, 324.63, 325.85, 326.6, 327.47, 327.58, 329.56, 329.9, 328.92, 327.88, 326.16, 324.68, 325.04, 326.34, 327.39, 328.37, 329.4, 330.14, 331.33, 332.31, 331.9, 330.7, 329.15, 327.35, 327.02, 327.99, 328.48, 329.18, 330.55, 331.32, 332.48, 332.92, 332.08, 331.01, 329.23, 327.27, 327.21, 328.29, 329.41, 330.23, 331.25, 331.87, 333.14, 333.8, 333.43, 331.73, 329.9, 328.4, 328.17, 329.32, 330.59, 331.58, 332.39, 333.33, 334.41, 334.71, 334.17, 332.89, 330.77, 329.14, 328.78, 330.14, 331.52, 332.75, 333.24, 334.53, 335.9, 336.57, 336.1, 334.76, 332.59, 331.42, 330.98, 332.24, 333.68, 334.8, 335.22, 336.47, 337.59, 337.84, 337.72, 336.37, 334.51, 332.6, 332.38, 333.75, 334.78, 336.05, 336.59, 337.79, 338.71, 339.3, 339.12, 337.56, 335.92, 333.75, 333.7, 335.12, 336.56, 337.84, 338.19, 339.91, 340.6, 341.29, 341, 339.39, 337.43, 335.72, 335.84, 336.93, 338.04, 339.06, 340.3, 341.21, 342.33, 342.74, 342.08, 340.32, 338.26, 336.52, 336.68, 338.19, 339.44, 340.57, 341.44, 342.53, 343.39, 343.96, 343.18, 341.88, 339.65, 337.81, 337.69, 339.09, 340.32, 341.2, 342.35, 342.93, 344.77, 345.58, 345.14, 343.81, 342.21, 339.69, 339.82, 340.98, 342.82, 343.52, 344.33, 345.11, 346.88, 347.25, 346.62, 345.22, 343.11, 340.9, 341.18, 342.8, 344.04, 344.79, 345.82, 347.25, 348.17, 348.74, 348.07, 346.38, 344.51, 342.92, 342.62, 344.06, 345.38, 346.11, 346.78, 347.68, 349.37, 350.03, 349.37, 347.76, 345.73, 344.68, 343.99, 345.48, 346.72, 347.84, 348.29, 349.23, 350.8, 351.66, 351.07, 349.33, 347.92, 346.27, 346.18, 347.64, 348.78, 350.25, 351.54, 352.05, 353.41, 354.04, 353.62, 352.22, 350.27, 348.55, 348.72, 349.91, 351.18, 352.6, 352.92, 353.53, 355.26, 355.52, 354.97, 353.75, 351.52, 349.64, 349.83, 351.14, 352.37, 353.5, 354.55, 355.23, 356.04, 357, 356.07, 354.67, 352.76, 350.82, 351.04, 352.69, 354.07, 354.59, 355.63, 357.03, 358.48, 359.22, 358.12, 356.06, 353.92, 352.05, 352.11, 353.64, 354.89, 355.88, 356.63, 357.72, 359.07, 359.58, 359.17, 356.94, 354.92, 352.94, 353.23, 354.09, 355.33, 356.63, 357.1, 358.32, 359.41, 360.23, 359.55, 357.53, 355.48, 353.67, 353.95, 355.3, 356.78, 358.34, 358.89, 359.95, 361.25, 361.67, 360.94, 359.55, 357.49, 355.84, 356, 357.59, 359.05, 359.98, 361.03, 361.66, 363.48, 363.82, 363.3, 361.94, 359.5, 358.11, 357.8, 359.61, 360.74, 362.09, 363.29, 364.06, 364.76, 365.45, 365.01, 363.7, 361.54, 359.51, 359.65, 360.8, 362.38, 363.23, 364.06, 364.61, 366.4, 366.84, 365.68, 364.52, 362.57, 360.24, 360.83, 362.49, 364.34}; @Test(groups = "fast") public void testExponentialSmoothing() throws Exception { // seasonal <- c(315.42,316.31,316.5,317.56,318.13,318.0,316.39,314.65,313.68,313.18,314.66,315.430) // smooth<-HoltWinters(co2, alpha=0.513, beta=0.009, gamma=0.47, l.start = 316.31, b.start = 0.8899, s.start=seasonal) final double[] smooth = {632.6199, 470.6517138117, 390.639939945329, 352.519079609679, 334.05271282566, 324.807110616726, 318.573956221258, 314.677346244792, 312.39009345864, 310.861014290286, 311.945207992319, 312.371655579909, 240.017367520252, 315.999938806999, 333.983110569806, 334.573652058746, 330.176145953271, 325.418803950448, 320.265797767209, 316.277923555616, 313.942130284222, 312.506783696153, 313.709914980136, 314.153694426107, 258.206391730428, 308.290378178855, 326.885384043855, 331.962337737318, 330.929290097554, 327.103001449562, 322.613435964528, 318.636022780413, 315.706535518878, 314.599835917296, 314.852731831459, 315.280998039128, 272.282177787016, 304.331883209043, 321.345478091202, 328.538310633349, 330.171617131195, 328.322976268678, 324.619536686661, 320.249920320124, 317.244394499389, 315.529275937077, 315.971697295194, 316.296858684042, 283.346469866347, 302.98422072885, 317.671212389663, 326.113577819763, 329.047705401723, 328.158953398938, 325.356206604106, 321.661069754128, 318.886532205992, 317.064216795264, 317.455197113874, 317.692846472184, 292.154629456775, 302.946635542762, 314.64191077189, 322.955434013277, 327.402348850349, 327.582871640154, 325.503397666745, 322.716275219386, 319.794407417494, 318.667408728304, 318.67979890366, 319.193316689245, 299.375812881207, 304.928083659635, 313.712321323853, 321.753808998084, 326.72502020431, 328.25053069795, 327.248874473571, 324.407553092775, 321.938371074557, 320.392491730605, 320.401652401664, 320.630749432352, 305.834180562268, 307.994072136799, 313.927190729432, 320.735554358964, 325.632592487852, 327.869754407699, 327.263146742103, 324.775341352022, 322.68273488419, 321.409209096453, 322.055645456275, 322.248601338102, 310.884213984301, 310.194413931785, 314.169070141805, 320.118714147262, 324.736760334325, 327.094362791044, 327.41708516041, 325.972395010836, 324.077810417074, 323.067359201408, 323.550821712839, 323.61751224833, 314.862944082395, 313.238133300115, 315.633856128485, 320.69415238368, 325.002445622681, 327.651552860155, 328.111038194394, 327.162123359016, 325.575662456814, 325.151306487157, 325.579580295781, 325.829220002201, 318.901905001978, 316.293265081289, 317.717734357679, 321.516936555609, 325.400156354577, 327.512541380195, 328.315946190695, 327.28112061486, 326.310521800961, 325.911466894706, 326.833960290654, 327.346665843318, 322.037659395571, 319.273468562948, 319.472460111632, 321.950681048952, 324.576662236975, 327.025313452676, 328.115857310526, 327.633280454239, 326.786521061241, 326.43425146936, 327.419237126136, 328.237334186122, 324.452278576477, 321.559555189106, 321.201396026417, 322.706348845415, 325.654117377815, 327.546621857208, 328.16684580671, 327.73318920143, 327.072944962815, 327.526085521386, 328.917589149749, 330.006457871525, 327.211037511667, 324.736912268583, 323.904838549138, 325.50309930338, 327.380672604739, 329.022872060225, 330.098029166384, 329.893526195008, 329.542717573599, 330.149632681378, 331.259457934922, 332.050712533749, 329.691720930135, 327.21668620672, 326.110222730836, 327.132232717243, 328.599570986785, 329.497872317528, 329.937766244086, 329.705541203304, 329.200744621037, 329.769052036626, 331.183665611647, 332.144567593348, 330.96437149966, 329.30385962159, 327.957527918885, 328.381863229994, 329.345109617861, 329.948666675291, 330.54256194394, 330.054006865444, 329.421400778979, 330.356911632473, 331.932085037167, 333.121395360026, 332.551731113159, 331.430379835043, 330.070865880351, 330.393415500582, 330.943224253799, 331.004152748724, 330.942909095066, 330.572275038568, 329.958455970874, 330.769127112302, 332.387182587005, 333.822578233372, 333.768766476992, 333.106613644051, 331.887023365704, 332.101458085541, 332.515826636703, 332.621564870345, 332.478082160766, 331.916712349297, 331.354369359081, 332.394809914161, 334.295263315773, 335.864159651928, 336.21322065248, 335.658880246251, 334.763946321689, 334.801720130697, 334.791154583771, 334.27955610589, 333.872714893958, 333.084625321266, 332.803484944026, 333.400237239287, 335.391560859964, 337.180141353755, 337.630824661524, 337.248707039198, 336.766127820506, 336.732675566155, 336.393008840308, 335.924895274756, 335.201805893582, 334.121861316618, 333.685688502361, 334.260679663157, 336.375469058004, 338.220193243978, 339.273129757172, 339.213651458151, 338.963104696317, 339.142166975354, 338.78016206581, 338.203791045496, 337.112201796518, 335.890145981813, 334.950747875711, 335.773704508002, 338.083381713966, 339.920590626881, 340.944169507801, 340.776684517701, 341.28994680413, 341.086623246293, 340.881841158384, 340.060142908929, 338.471478383165, 336.878165930895, 335.698461241271, 336.404723298707, 338.560782940852, 340.654974426319, 342.044228648093, 342.436128655376, 342.798253217822, 342.824882411587, 342.43339773409, 341.497618167013, 339.714049827284, 338.195661649153, 336.944143952512, 337.567549759719, 339.516070139068, 341.40715434494, 342.821711757154, 343.265776494822, 343.854487368459, 343.750951097639, 343.830235623758, 343.063453155581, 341.613453835047, 339.968700243772, 339.01064910723, 339.39181159411, 341.396628395153, 343.166287816669, 344.867022657463, 345.643320410699, 346.053997948597, 346.413119211818, 346.40165604462, 345.26834136604, 343.491693455507, 341.632567143605, 339.937201593777, 340.419656532292, 342.416404781232, 344.6312798229, 345.994745089896, 346.869871761194, 347.519575435691, 348.570068051888, 348.219627101074, 347.050206591945, 345.204930163649, 343.017424051004, 341.224955253042, 342.053016459494, 343.879748222312, 345.781641156983, 347.117322782918, 348.145435340979, 348.82665925502, 349.408092251015, 349.466448691589, 348.446114497885, 346.599359159737, 344.48923895177, 342.624883569032, 343.392073446952, 345.158916633018, 347.013273609633, 348.279820563417, 349.533620777834, 350.344501040087, 351.213409395373, 351.232443789435, 350.239698568993, 348.41357101892, 346.209826802644, 344.788162892905, 344.940562692825, 346.988934520356, 348.88927594126, 350.234843872773, 351.558339231898, 353.053274202373, 354.166159384658, 354.226713767753, 353.033058433444, 351.122703446852, 349.215161913299, 347.423759066478, 347.355325174001, 349.350919677559, 351.04726172599, 352.563805146728, 353.908864695997, 354.694435498363, 355.794420125094, 356.113304004422, 354.900509469872, 352.85148780474, 350.841304340091, 348.880599939235, 348.684174221674, 350.387718620794, 352.091091372097, 353.66670122155, 354.678291293767, 355.874365207485, 357.396966633718, 357.288225047247, 356.392870432551, 354.339738205741, 351.992520709745, 350.101036886733, 349.977331445376, 351.552769322099, 353.351679596376, 355.059149634289, 355.931416500777, 356.926794887742, 358.679485942274, 359.424193695314, 358.579442637743, 356.620539207018, 353.927097583756, 351.634256808929, 351.439376171881, 352.834657443724, 354.369788226891, 355.705277340788, 356.950664709566, 358.033115316245, 359.50536159388, 360.129309100566, 359.048818032355, 357.367043896943, 354.871787835235, 352.707385565795, 352.479334579464, 353.949317583912, 355.077950020344, 356.195290918059, 357.460360251311, 358.52368989585, 360.024110550963, 360.529473201228, 359.730964945696, 357.767659309011, 355.478166572936, 353.331793387935, 353.27658893962, 354.567065824552, 356.027493138665, 357.448166671531, 358.772657279137, 360.126014336259, 361.555924657948, 362.302060196834, 361.369180795528, 359.273538270846, 357.312955432328, 355.344615283229, 355.458651102567, 356.706277566473, 358.260508661198, 359.744185835545, 360.563976785835, 362.039781626051, 363.345204547803, 364.254595537704, 363.482179465035, 361.688630437851, 359.706171170514, 357.626088364335, 357.756688403044, 358.836817340932, 360.321892344401, 361.495723210675, 362.561157748697, 363.988465632368, 365.655552079543, 365.913646640652, 365.191568496771, 363.505036383706, 361.396122392161, 359.662391862308, 359.371605649972, 360.746363990939, 361.784688061872, 363.094215846737, 363.957595259186, 364.912548144631, 366.16410535331, 367.104446317609, 366.552997910417, 364.598629718524, 362.337088864328, 360.581050077616, 360.291044484372, 361.748188404933, 363.266870699878}; final double alpha = 0.513; final double beta = 0.009; final double gamma = 0.47; final HoltWintersComputer computer = new HoltWintersComputer(alpha, beta, gamma, 12); Assert.assertEquals(computer.getAlpha(), alpha); Assert.assertEquals(computer.getBeta(), beta); Assert.assertEquals(computer.getGamma(), gamma); compare(computer, CO2, smooth, 1); } @Test(groups = "fast") public void testSimpleExponentialSmoothing() throws Exception { // series<-ts(c(315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43)) final double[] series = {315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43}; // smooth<-HoltWinters(co2, alpha=0.8, beta=FALSE, gamma=FALSE) // predict(smooth, 1) final double[] smooth = {315.4200, 316.1320, 316.4264, 317.3333, 317.9707, 317.9941, 316.7108, 315.0622, 313.9564, 313.3353, 314.3951, 315.223}; final HoltWintersComputer computer = new HoltWintersComputer(0.8); Assert.assertEquals(computer.getAlpha(), 0.8); compare(computer, series, smooth, 0); } @Test(groups = "fast") public void testDoubleExponentialSmoothing() throws Exception { // series<-ts(c(315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43)) final double[] series = {315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43}; // smooth<-HoltWinters(series, alpha=0.8, beta=0.2, gamma=FALSE, l.start = 316.31, b.start = 0.8899) final double[] smooth = {317.1999, 317.4179, 318.3322, 318.9387, 318.8058, 317.1047, 314.9798, 313.5708, 312.8265, 314.1550}; final HoltWintersComputer computer = new HoltWintersComputer(0.8, 0.2); Assert.assertEquals(computer.getAlpha(), 0.8); Assert.assertEquals(computer.getBeta(), 0.2); compare(computer, series, smooth, 1); } private ArrayList<Double> compare(final HoltWintersComputer computer, final double[] series, final double[] smooth, final int start) { final ArrayList<Double> results = new ArrayList<Double>(); for (final double value : series) { computer.addNextValue(value); final double forecast = computer.getForecast(1); results.add(forecast); } int i = 0; for (final double smoothValue : smooth) { //Assert.assertEquals(results.get(start + i), smoothValue, 0.0002, String.format("%dth value doesn't match", i)); i++; } return results; } }
81.846442
152
0.543724
c73cee7dc470d42e82e906792397821bdf0e0493
1,743
/* ************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation * ************************************************************************* */ package org.eclipse.birt.data.engine.api; /** * Provides definition of subquery: a supplemental use of rows returned by a data set * or a group. A subquery does not have its own data set, but rather it provides an alternate view * of data of an existing group or query by applying additional transforms on top of such data. */ public interface ISubqueryDefinition extends IBaseQueryDefinition { /** * Gets the name of the subquery. Each Subquery must have a name that uniquely * identifies it within the main query that contains it. * @return Name of the subquery */ public String getName(); /** * Subquery can apply to the group in which the sub query is added, or to * the each row of current query definition. If it is the previous case, all * rows of current group will be the data source of sub query, but in latter * case, only the current row of parent query will be the data source. A * note is the false value will be valid when it is added into the query * definition, and it will have no any effect if it is on group. * * @return true, sub query is applied on group, false, applied on current * row of parent query */ public boolean applyOnGroup( ); }
39.613636
98
0.667814
3ad2382c215834d84de331eb6322e720fd03f406
17,088
package com.github.martonr.picalc.gui.controller; import com.github.martonr.picalc.engine.calculators.CalculatorParameters; import com.github.martonr.picalc.engine.service.ServiceCalculation; import com.github.martonr.picalc.engine.service.ServiceCalculationTask.Results; import javafx.application.Platform; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.RadioButton; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.effect.ColorAdjust; import javafx.scene.effect.Effect; import java.io.BufferedWriter; import java.math.RoundingMode; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Paths; import java.text.DecimalFormat; import java.time.LocalDateTime; import java.util.Locale; /** * Controller class for the DPI power index calculation view */ public final class ControllerCalculationDpi { /** * Input field for the player name */ @FXML private TextField playerNameText; /** * Input field for the player weight */ @FXML private TextField playerWeightText; /** * Remove a selected player */ @FXML private Button removeButton; /** * Add a new player */ @FXML private Button addButton; /** * Graphical indicator for a running computation */ @FXML private ProgressIndicator progressCircle; /** * Text feedback on the computation */ @FXML private Label progressText; /** * Button that save the calculation results to disk */ @FXML private Button saveResultsButton; /** * When selected power index values will be computed exactly */ @FXML private RadioButton exactSelect; /** * When selected power index values will be estimated with Monte-Carlo method */ @FXML private RadioButton estimateSelect; @FXML private ToggleGroup computationType; /** * Input field for the estimation count */ @FXML private TextField countText; /** * Starts the calculation */ @FXML private Button calculateButton; /** * Stops the calculation */ @FXML private Button stopButton; /** * The table shows the currently added players to the user */ @FXML private TableView<Player> indexTable; @FXML private TableColumn<Player, String> playerColumn; @FXML private TableColumn<Player, Number> weightColumn; @FXML private TableColumn<Player, Number> dpiColumn; /** * Calculation service that executes the calculation */ private final ServiceCalculation service = new ServiceCalculation(); private Results dpiCalculationResult; /** * Observable collection that stores the currently added Players */ private final ObservableList<Player> currentPlayers = FXCollections.observableArrayList(); /** * Color adjustment used to signal a bad input in a text field */ private final ColorAdjust error = new ColorAdjust(0.03, 0.04, 0.0, 0.0); @FXML private void initialize() { initalizeListeners(); initializeTableView(); } /** * Add cell value formatters and default column widths */ private void initializeTableView() { indexTable.setItems(currentPlayers); playerColumn.setCellValueFactory(item -> item.getValue().nameProperty()); weightColumn.setCellValueFactory(item -> item.getValue().weightProperty()); dpiColumn.setCellValueFactory(item -> item.getValue().dpiProperty()); weightColumn.setCellFactory(param -> new TableCell<>() { @Override protected void updateItem(Number item, boolean empty) { if (empty) setText(""); else setText(String.format("%.2f", item.doubleValue())); } }); dpiColumn.setCellFactory(param -> new TableCell<>() { @Override protected void updateItem(Number item, boolean empty) { if (empty) setText(""); else setText(String.format("%.4f", item.doubleValue())); } }); // Divide to 3 equal columns playerColumn.prefWidthProperty().bind(indexTable.widthProperty().divide(3)); weightColumn.prefWidthProperty().bind(indexTable.widthProperty().divide(3)); dpiColumn.prefWidthProperty().bind(indexTable.widthProperty().divide(3)); } /** * Set up some basic interface behaviour logic */ private void initalizeListeners() { currentPlayers.addListener((ListChangeListener<Player>) c -> { if (c.getList().isEmpty()) { removeButton.setDisable(true); calculateButton.setDisable(true); } else { removeButton.setDisable(false); calculateButton.setDisable(false); } }); indexTable.focusedProperty().addListener((observable, oldValue, newValue) -> { if (!newValue) indexTable.getSelectionModel().clearSelection(); }); exactSelect.selectedProperty().addListener((observable, oldValue, newValue) -> { if (newValue) { changeTextFieldLook(countText, null, "Number of estimations", true); countText.clear(); countText.setDisable(true); } }); estimateSelect.selectedProperty().addListener((observable, oldValue, newValue) -> { if (newValue) { changeTextFieldLook(countText, null, "Number of estimations", true); countText.setDisable(false); } }); } /** * Parses the input then adds a new Player * * @param event ActionEvent, not used */ @FXML private void addPlayer(ActionEvent event) { // Default name String name = playerNameText.getText(); if (name.isBlank()) name = "Player " + (currentPlayers.size() + 1); try { double weight = parseDoubleFromTextField(playerWeightText); if (weight < 0) { changeTextFieldLook(playerWeightText, error, "Minimum is 0", true); return; } currentPlayers.add(new Player(name, weight)); changeTextFieldLook(playerNameText, null, "Player name", true); changeTextFieldLook(playerWeightText, null, "Player weight", true); saveResultsButton.setDisable(true); saveResultsButton.setVisible(false); } catch (Exception ignored) { // Input was not an integer } } /** * Removes a currently selected Player * * @param event ActionEvent, not used */ @FXML private void removePlayer(ActionEvent event) { TableView.TableViewSelectionModel<Player> selection = indexTable.getSelectionModel(); if (!selection.isEmpty()) { currentPlayers.remove(selection.getSelectedIndex()); selection.clearSelection(); saveResultsButton.setDisable(true); saveResultsButton.setVisible(false); } } /** * Start the calculation * * @param event ActionEvent, not used */ @FXML private void startCalculation(ActionEvent event) { try { // Parse the text field values int count = 1; if (estimateSelect.isSelected()) { count = parseIntegerFromTextField(countText); if (count < 1) { changeTextFieldLook(countText, error, "Minimum 1", true); return; } } // Store weights in an array final int n = currentPlayers.size(); double[] weights = new double[n]; for (int i = 0; i < n; ++i) { weights[i] = currentPlayers.get(i).getWeight(); } addButton.setDisable(true); removeButton.setDisable(true); calculateButton.setDisable(true); stopButton.setDisable(false); saveResultsButton.setDisable(true); saveResultsButton.setVisible(false); changeTextFieldLook(countText, null, "Number of estimations", false); progressCircle.setVisible(true); progressText.setText("Calculating..."); CalculatorParameters parameters = new CalculatorParameters(); parameters.n = n; parameters.weights = weights; parameters.monteCarloCount = 0; if (estimateSelect.isSelected()) { parameters.monteCarloCount = count; } service.calculateDPI(parameters, this::updateTableWithResults); } catch (Exception ignored) { // Input was not an integer } } /** * Stop the calculation * * @param event ActionEvent, not used */ @FXML private void stopCalculation(ActionEvent event) { service.cleanupTasks(); } /** * Takes the calculation results and updates the players' power index values * * @param result Result object is a container for the calculation results */ private void updateTableWithResults(Results result) { Platform.runLater(() -> { progressCircle.setVisible(false); if (result == null) { progressText.setText("Calculation stopped."); } else { progressText.setText("Finished in " + result.time + " seconds."); int n = currentPlayers.size(); double[] dpi = result.dpi; for (int i = 0; i < n; ++i) { currentPlayers.get(i).setDpi(dpi[i]); } this.dpiCalculationResult = result; dpiColumn.setVisible(true); saveResultsButton.setDisable(false); saveResultsButton.setVisible(true); indexTable.refresh(); } addButton.setDisable(false); removeButton.setDisable(false); calculateButton.setDisable(false); stopButton.setDisable(true); playerNameText.requestFocus(); System.gc(); }); } /** * Save the simulation results to a file */ @FXML private void saveCalculationResultsToDisk() { double[] dpi = this.dpiCalculationResult.dpi; int players = dpi.length; try { Files.createDirectories(Paths.get("./results/")); } catch (FileAlreadyExistsException ex) { // Directory exists } catch (Exception ignored) { // Failed to create a directory return; } BufferedWriter bw = null; LocalDateTime date = LocalDateTime.now(); DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.ENGLISH); df.applyPattern("#0.00000"); df.setRoundingMode(RoundingMode.HALF_UP); int year = date.getYear(); int month = date.getMonthValue(); int day = date.getDayOfMonth(); int hour = date.getHour(); int minute = date.getMinute(); int count = 0; try { while (bw == null) { try { bw = Files.newBufferedWriter(Files.createFile( Paths.get("./results/" + year + "_" + month + "_" + day + "_" + hour + "_" + minute + "_calculationdpi_result_" + count + ".csv"))); } catch (FileAlreadyExistsException ex) { // File with this name exists count++; // Too many files with the same name... if (count > 1000) return; } catch (Exception ignored) { // Failed to create the file return; } } // Create the header StringBuilder sb = new StringBuilder("weight,"); sb.append("dpi\n"); // Save the values for (int i = 0; i < players; ++i) { sb.append(String.format("%.3f", currentPlayers.get(i).getWeight())).append(","); sb.append(df.format(dpi[i])).append("\n"); bw.write(sb.toString()); // Reuse StringBuilder buffer sb.setLength(0); } bw.flush(); bw.close(); progressText.setText("Results saved to file."); } catch (Exception ignored) { // Failed to write the file } } /** * Parses a double from a text field input * * @param field TextField to parse from * @return The parsed double * @throws NumberFormatException If the input can't be parsed as a double */ private double parseDoubleFromTextField(TextField field) throws NumberFormatException { try { return Double.parseDouble(field.getText()); } catch (Exception ignored) { changeTextFieldLook(field, error, "Must be a number", true); throw new NumberFormatException(); } } /** * Parses an integer from a text field input * * @param field TextField to parse from * @return The parsed integer * @throws NumberFormatException If the input can't be parsed as an integer */ private int parseIntegerFromTextField(TextField field) throws NumberFormatException { try { return Integer.parseInt(field.getText()); } catch (Exception ignored) { changeTextFieldLook(field, error, "Must be an integer", true); throw new NumberFormatException(); } } /** * Changes a TextField, applying an effect to it, changing the prompt message and potentially * clearing the contents * * @param field Target TextField * @param effect Chosen Effect to apply to the TextField * @param message String message to display in the prompt * @param clear If true, the TextField contents will be cleared (to see the prompt message) */ private void changeTextFieldLook(TextField field, Effect effect, String message, boolean clear) { field.setEffect(effect); field.setPromptText(message); if (clear) field.clear(); } public void shutdown() { service.shutdown(); } /** * Container class for the TableView, stores an instance of a Player A Player has a name, a * weight value and a DPI index, if those have been calculated */ public static class Player { /** * Properties holding a Player's values */ private StringProperty name = new SimpleStringProperty(this, "name"); private DoubleProperty weight = new SimpleDoubleProperty(this, "weight"); private DoubleProperty dpi = new SimpleDoubleProperty(this, "dpi"); /** * Returns a new instance of a Player container A Player needs to have a name and a set * weight value Power index values can be calculated later * * @param name The player's name * @param weight The player's weight */ public Player(String name, double weight) { this.name.setValue(name); this.weight.setValue(weight); this.dpi.setValue(0); } public final StringProperty nameProperty() { return name; } public final DoubleProperty weightProperty() { return weight; } public final DoubleProperty dpiProperty() { return dpi; } public final String getName() { return name.get(); } public final void setName(String name) { this.name.set(name); } public final double getWeight() { return weight.get(); } public final void setWeight(int vote) { this.weight.set(vote); } public final double getDpi() { return dpi.get(); } public final void setDpi(double dpi) { this.dpi.set(dpi); } } }
31.239488
99
0.589185
65a4c0dbd6d15b3cc4cd45b508ff23f7e1795be7
3,173
package gui; /** * GameView for DroidBall. Responsible for displaying the grid * in a GUI interface. * @version 1.0 * @author Chris Curreri */ import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import map.GridNode; public class GameView extends JFrame{ private static final long serialVersionUID = 1L; private JPanel gridPanel, headerPanel, buttonPanel; public JButton start = new JButton("Start"); public JButton stop = new JButton("Stop"); public GameView(GridNode[][] grid) { setTitle("DroidBall"); setLayout(new BorderLayout()); add(gridPanel = gridPanel(grid), BorderLayout.CENTER); add(headerPanel = headerPanel("DroidBall- AI Platform", SwingConstants.CENTER), BorderLayout.NORTH); add(buttonPanel = buttonPanel(new JButton[]{start, stop}), BorderLayout.SOUTH); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(300,100,1000,800); setVisible(true); } //////////////////////////////////////////////////////////////////////// // GUI Actions //////////////////////////////////////////////////////////////////////// public void updateGrid(GridNode[][] grid) { remove(gridPanel); add(gridPanel = gridPanel(grid), BorderLayout.CENTER); revalidate(); } public void updateHeader(String text) { ((JLabel) headerPanel.getComponent(0)).setText(text); } public String getHeaderText() { return ((JLabel) headerPanel.getComponent(0)).getText(); } //////////////////////////////////////////////////////////////////////// // GUI Components //////////////////////////////////////////////////////////////////////// /** * Creates the panel for the 2D grid. * @param grid -the grid being displayed * @return panel that contains the grid display */ private JPanel gridPanel(GridNode[][] grid) { JPanel gridPanel = new JPanel(new GridLayout(grid[0].length, grid.length)); for(int i=0; i<grid[0].length; i++) { for(int j=0; j<grid.length; j++) { gridPanel.add(nodeLabel(grid[j][grid[0].length - i - 1])); } } return gridPanel; } /** * Creates the JLabel for individual GridNodes * @param node -the node that will be displayed * @return panel displaying the node */ private JLabel nodeLabel(GridNode node) { JLabel nodePanel = new JLabel(node.toString(), SwingConstants.CENTER); nodePanel.setForeground(node.color); nodePanel.setBackground(Color.WHITE); nodePanel.setOpaque(true); return nodePanel; } /** * Creates the panel responsible for the header display. * @param text -the header's text * @param alignment -the header's alignment * @return panel containing the header */ private JPanel headerPanel(String text, int alignment) { JPanel headerPanel = new JPanel(); headerPanel.add(new JLabel(text,alignment)); return headerPanel; } private JPanel buttonPanel(JButton buttons[]) { JPanel buttonPanel = new JPanel(new GridLayout()); for(int i=0; i<buttons.length; i++) { buttonPanel.add(buttons[i]); } return buttonPanel; } }
26.889831
102
0.645131
5bfbd7d6c25ec183ee459020e07b29241cf2532c
1,346
package com.shiyq.wuye.entity.DO; import java.io.Serializable; import lombok.Data; /** * 物业收费记录信息表 */ @Data public class PropertyChargeVisit implements Serializable { /** * 自增主键 */ private Integer id; /** * 收费项信息 */ private PropertyChargeItem propertyChargeItem; /** * 住房对象信息 */ private HouseInfo houseInfo; /** * 收费项目ID */ private Integer itemId; /** * 收费项目名 */ private String itemName; /** * 房间ID */ private Integer houseId; /** * 楼宇号 */ private String buildingNum; /** * 单元号 */ private String unitNum; /** * 房间号 */ private String houseNum; /** * 客户姓名 */ private String userName; /** * 客户手机号 */ private String phone; /** * 费用 */ private Integer price; /** * 上月读数 */ private Integer prevMonthCount; /** * 本月读数 */ private Integer currMonthCount; /** * 本次用量 */ private Integer useCount; /** * 录入时间 */ private String visitDate; /** * 抄表时间 */ private String readDate; /** * 抄表人 */ private String readName; /** * 记录状态(0已缴费 1未交费) */ private String visitStatus; private static final long serialVersionUID = 1L; }
12.348624
58
0.514116
7943ab1c3cbdc2c97ad9b3bd6d0da18e41a0a261
3,825
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import model.Circuit; import model.DeliveryRequest; import model.CityMap; import model.Delivery; /** * * @author lgalle */ public interface State { /** * Loads a city map by parsing the xml and updating the model. * Updates the controller's state. * This method is implemented in all the states, except the StateInit. * @param path * @param c */ public abstract void loadCityMap(String path, Controller c); /** * Loads a delivery request by parsing the xml and updating the model. * Updates the controller's state. * This method is implemented in all the states, except the StateInit and * StateDefault, since a city map must be loaded for a delivery to get * loaded. * @param path * @param c */ public abstract void loadDeliveryRequest(String path, Controller c); /** * Computes circuits from a delivery request. * Updates the controller's state. * This method is only implemented the states StateDeliveryRequestLoaded * and StateCircuitsComputed, since a city map and a delivery request have * to be loaded to compute circuits. * @param c */ public abstract void computeCircuits(Controller c); /** * Adds a delivery to a circuit. * Updates the controller's state. * This method is only implemented the state StateCircuitsComputed, since * a delivery can only be added to a circuit once the circuits have been * computed * @param d * @param c */ public abstract void addDelivery(Delivery d, Circuit c); /** * Deletes a delivery from a circuit. * Updates the controller's state. * This method is only implemented the state StateCircuitsComputed, since * a delivery can only be deleted from a circuit once the circuits have been * computed * @param d * @param c */ public abstract void deleteDelivery(Delivery d, Circuit c); /** * Moves a delivery from a circuit to another circuit. * Updates the controller's state. * This method is only implemented the state StateCircuitsComputed, since * a delivery can only be moved from a circuit to another once the circuits * have been computed. * This functionality has not yet been integrated to the interface * @param d * @param oc * @param tc */ public abstract void changeCircuit(Delivery d, Circuit oc, Circuit tc); /** * Places a delivery one step before in the deliveries order of the * circuit. * Updates the controller's state. * This method is only implemented the state StateCircuitsComputed, since * a delivery place in the list can only be changed once the circuits * have been computed. * @param d * @param c */ public abstract void moveDeliveryBefore(Delivery d, Circuit c); /** * Places a delivery one step after in the deliveries order of the * circuit. * Updates the controller's state. * This method is only implemented the state StateCircuitsComputed, since * a delivery place in the list can only be changed once the circuits * have been computed. * @param d * @param c */ public abstract void moveDeliveryAfter(Delivery d, Circuit c); /** * Un-does a command. */ public abstract void undoCde(); /** * Re-does a command. */ public abstract void redoCde(); }
32.415254
81
0.639216
06ee752316679be9aea3e6afac183e77634ba833
2,689
package kz.ncanode.kalkan; import kz.gov.pki.kalkan.jce.provider.KalkanProvider; import kz.gov.pki.kalkan.jce.provider.cms.CMSException; import kz.gov.pki.kalkan.jce.provider.cms.CMSSignedData; import kz.gov.pki.kalkan.jce.provider.cms.SignerInformation; import kz.gov.pki.kalkan.jce.provider.cms.SignerInformationStore; import kz.gov.pki.kalkan.xmldsig.KncaXS; import kz.ncanode.ioc.ServiceProvider; import kz.ncanode.log.OutLogServiceProvider; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.varia.NullAppender; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; import java.security.cert.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Обёртка для загрузки провайдера Kalkan */ public class KalkanServiceProvider implements ServiceProvider { private KalkanProvider provider = null; private OutLogServiceProvider out = null; public KalkanServiceProvider(OutLogServiceProvider out) { this.out = out; this.out.write("Initializing Kalkan crypto..."); provider = new KalkanProvider(); Security.addProvider(provider); BasicConfigurator.configure(new NullAppender()); KncaXS.loadXMLSecurity(); this.out.write("Kalkan crypto initialized. Version: " + getVersion()); } public String getVersion() { return KalkanProvider.class.getPackage().getImplementationVersion(); } public Provider get() { return provider; } /** * Возвращает сертификаты, которым был подписан переданный документ */ public List<X509Certificate> getCertificatesFromCmsSignedData(CMSSignedData cms) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, CertStoreException { List<X509Certificate> certs = new ArrayList<>(); SignerInformationStore signers = cms.getSignerInfos(); String providerName = this.provider.getName(); CertStore clientCerts = cms.getCertificatesAndCRLs("Collection", providerName); for (Object signerObj : signers.getSigners()) { SignerInformation signer = (SignerInformation) signerObj; X509CertSelector signerConstraints = signer.getSID(); Collection<? extends Certificate> certCollection = clientCerts.getCertificates(signerConstraints); for (Certificate certificate : certCollection) { X509Certificate cert = (X509Certificate) certificate; certs.add(cert); } } return certs; } }
34.922078
110
0.714764
ba80d3d47a2a9fb7171e360aad9bf14a6ed71fb9
10,932
package com.yugabyte.yw.commissioner; import akka.actor.ActorSystem; import com.amazonaws.SDKGlobalConfiguration; import com.cronutils.utils.VisibleForTesting; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; import com.google.inject.Singleton; import com.yugabyte.yw.common.AWSUtil; import com.yugabyte.yw.common.AZUtil; import com.yugabyte.yw.common.GCPUtil; import com.yugabyte.yw.common.BackupUtil; import com.yugabyte.yw.common.ShellResponse; import com.yugabyte.yw.common.TableManagerYb; import com.yugabyte.yw.common.Util; import com.yugabyte.yw.common.config.RuntimeConfigFactory; import com.yugabyte.yw.common.customer.config.CustomerConfigService; import com.yugabyte.yw.common.PlatformServiceException; import com.yugabyte.yw.forms.BackupTableParams; import com.yugabyte.yw.models.Backup; import com.yugabyte.yw.models.Backup.BackupState; import com.yugabyte.yw.models.Customer; import com.yugabyte.yw.models.CustomerConfig; import com.yugabyte.yw.models.Universe; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import lombok.extern.slf4j.Slf4j; import play.libs.Json; import scala.concurrent.ExecutionContext; @Singleton @Slf4j public class BackupGarbageCollector { private final ActorSystem actorSystem; private final ExecutionContext executionContext; private final TableManagerYb tableManagerYb; private final CustomerConfigService customerConfigService; private final BackupUtil backupUtil; private final RuntimeConfigFactory runtimeConfigFactory; private static final String YB_BACKUP_GARBAGE_COLLECTOR_INTERVAL = "yb.backupGC.gc_run_interval"; private AtomicBoolean running = new AtomicBoolean(false); private static final String AZ = Util.AZ; private static final String GCS = Util.GCS; private static final String S3 = Util.S3; private static final String NFS = Util.NFS; @Inject public BackupGarbageCollector( ExecutionContext executionContext, ActorSystem actorSystem, CustomerConfigService customerConfigService, RuntimeConfigFactory runtimeConfigFactory, TableManagerYb tableManagerYb, BackupUtil backupUtil) { this.actorSystem = actorSystem; this.executionContext = executionContext; this.customerConfigService = customerConfigService; this.runtimeConfigFactory = runtimeConfigFactory; this.tableManagerYb = tableManagerYb; this.backupUtil = backupUtil; } public void start() { Duration gcInterval = this.gcRunInterval(); this.actorSystem .scheduler() .schedule(Duration.ZERO, gcInterval, this::scheduleRunner, this.executionContext); } private Duration gcRunInterval() { return runtimeConfigFactory .staticApplicationConf() .getDuration(YB_BACKUP_GARBAGE_COLLECTOR_INTERVAL); } @VisibleForTesting void scheduleRunner() { if (!running.compareAndSet(false, true)) { log.info("Previous Backup Garbage Collector still running"); return; } log.info("Running Backup Garbage Collector"); try { List<Customer> customersList = Customer.getAll(); // Delete the backups associated with customer storage config which are in QueuedForDeletion // state. // After Deleting all associated backups we can delete the storage config. customersList.forEach( (customer) -> { List<CustomerConfig> configList = CustomerConfig.getAllStorageConfigsQueuedForDeletion(customer.uuid); configList.forEach( (config) -> { try { List<Backup> backupList = Backup.findAllBackupsQueuedForDeletionWithCustomerConfig( config.configUUID, customer.uuid); backupList.forEach(backup -> deleteBackup(customer.uuid, backup.backupUUID)); } catch (Exception e) { log.error( "Error occured while deleting backups associated with {} storage config", config.configName); } finally { config.delete(); log.info("Customer Storage config {} is deleted", config.configName); } }); }); customersList.forEach( (customer) -> { List<Backup> backupList = Backup.findAllBackupsQueuedForDeletion(customer.uuid); if (backupList != null) { backupList.forEach((backup) -> deleteBackup(customer.uuid, backup.backupUUID)); } }); } catch (Exception e) { log.error("Error running backup garbage collector", e); } finally { running.set(false); } } public synchronized void deleteBackup(UUID customerUUID, UUID backupUUID) { Backup backup = Backup.maybeGet(customerUUID, backupUUID).orElse(null); // Backup is already deleted. if (backup == null || backup.state == BackupState.Deleted) { if (backup != null) { backup.delete(); } return; } try { // Disable cert checking while connecting with s3 // Enabling it can potentially fail when s3 compatible storages like // Dell ECS are provided and custom certs are needed to connect // Reference: https://yugabyte.atlassian.net/browse/PLAT-2497 System.setProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "true"); UUID storageConfigUUID = backup.getBackupInfo().storageConfigUUID; CustomerConfig customerConfig = customerConfigService.getOrBadRequest(backup.customerUUID, storageConfigUUID); if (isCredentialUsable(customerConfig)) { List<String> backupLocations = null; log.info("Backup {} deletion started", backupUUID); backup.transitionState(BackupState.DeleteInProgress); try { switch (customerConfig.name) { case S3: backupLocations = getBackupLocations(backup); AWSUtil.deleteKeyIfExists(customerConfig.data, backupLocations.get(0)); AWSUtil.deleteStorage(customerConfig.data, backupLocations); backup.delete(); break; case GCS: backupLocations = getBackupLocations(backup); GCPUtil.deleteKeyIfExists(customerConfig.data, backupLocations.get(0)); GCPUtil.deleteStorage(customerConfig.data, backupLocations); backup.delete(); break; case AZ: backupLocations = getBackupLocations(backup); AZUtil.deleteKeyIfExists(customerConfig.data, backupLocations.get(0)); AZUtil.deleteStorage(customerConfig.data, backupLocations); backup.delete(); break; case NFS: if (isUniversePresent(backup)) { BackupTableParams backupParams = backup.getBackupInfo(); List<BackupTableParams> backupList = backupParams.backupList == null ? ImmutableList.of(backupParams) : backupParams.backupList; if (deleteNFSBackup(backupList)) { backup.delete(); log.info("Backup {} is successfully deleted", backupUUID); } else { backup.transitionState(BackupState.FailedToDelete); } } else { backup.delete(); log.info("NFS Backup {} is deleted as universe is not present", backup.backupUUID); } break; default: backup.transitionState(Backup.BackupState.FailedToDelete); log.error( "Backup {} deletion failed due to invalid Config type {} provided", backup.backupUUID, customerConfig.name); } } catch (Exception e) { log.error(" Error in deleting backup " + backup.backupUUID.toString(), e); backup.transitionState(Backup.BackupState.FailedToDelete); } } else { log.error( "Error while deleting backup {} due to invalid storage config {} : {}", backup.backupUUID, storageConfigUUID); backup.transitionState(BackupState.FailedToDelete); } } catch (Exception e) { log.error("Error while deleting backup " + backup.backupUUID, e); backup.transitionState(BackupState.FailedToDelete); } finally { // Re-enable cert checking as it applies globally System.setProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY, "false"); } } private Boolean isUniversePresent(Backup backup) { Optional<Universe> universe = Universe.maybeGet(backup.getBackupInfo().universeUUID); return universe.isPresent(); } private boolean deleteNFSBackup(List<BackupTableParams> backupList) { boolean success = true; for (BackupTableParams childBackupParams : backupList) { if (!deleteChildNFSBackups(childBackupParams)) { success = false; } } return success; } private boolean deleteChildNFSBackups(BackupTableParams backupTableParams) { ShellResponse response = tableManagerYb.deleteBackup(backupTableParams); JsonNode jsonNode = null; try { jsonNode = Json.parse(response.message); } catch (Exception e) { log.error( "Delete Backup failed for {}. Response code={}, Output={}.", backupTableParams.storageLocation, response.code, response.message); return false; } if (response.code != 0 || jsonNode.has("error")) { log.error( "Delete Backup failed for {}. Response code={}, hasError={}.", backupTableParams.storageLocation, response.code, jsonNode.has("error")); return false; } else { log.info("NFS Backup deleted successfully STDOUT: " + response.message); return true; } } private static List<String> getBackupLocations(Backup backup) { BackupTableParams backupParams = backup.getBackupInfo(); List<String> backupLocations = new ArrayList<>(); if (backupParams.backupList != null) { for (BackupTableParams params : backupParams.backupList) { backupLocations.add(params.storageLocation); } } else { backupLocations.add(backupParams.storageLocation); } return backupLocations; } private Boolean isCredentialUsable(CustomerConfig config) { Boolean isValid = true; try { backupUtil.validateStorageConfig(config); } catch (Exception e) { isValid = false; } return isValid; } }
37.31058
99
0.661727
e29c15a37fa8110b3fa42135aef96638531485ec
2,834
package com.elezeta.roguecave.data; public enum SpriteID { naught, humanbody1, humanbody2, humanbody3, humanbody4, humanbody5, humanbody6, humanbody7, humanbody8, humanbody9, humanshortsfemale, humanshortsmale, humantopfemale, humanbeardlong1, humanbeardlong2, humanbeardlong3, humanbeardshort1, humanbeardshort2, humanbeardshort3, humanbeardshort4, humanbeardshort5, humanbeardshort6, humaneyebrows1, humaneyebrows2, humaneyebrows3, humaneyecolor1, humaneyecolor2, humaneyecolor3, humaneyecolor4, humaneyecolor5, humaneyecolor6, humaneyecolor7, humaneyeskin1, humaneyeskin2, humaneyeskin3, humaneyewhite1, humaneyewhite2, humaneyewhite3, humaneyewhite4, humanhairlong1, humanhairlong2, humanhairlong3, humanhairlong4, humanhairdropback1, humanhairdropback2, humanhairdropfront1, humanhairdropfront2, humanhairshort1, humanhairshort2, humanhairshort3, humanhairshort4, humanhairshort5, humanhairshort6, humanhairshort7, humanarmor1, humanarmsback1, humanarmsfront1, humanboots1, humanhelmetfull1, humanhelmethalf1, humanhelmethalf2, humanlegs1, humanamulet1, humanringleft1, humanringright1, humanarrowsfront1, humanarrowsback1, humanshieldfront1, humanshieldback1, humanbowfront1, humanbowback1, humandaggerfront1, humandaggerback1, humanswordfront1, humanswordback1, humanwandfront1, humanwandback1, humanmacefront1, humanmaceback1, humanaxefront1, humanaxeback1, upgradehuman, upgradebody, upgrademaxhp, voidTile, stoneTile, stoneWall, meleeWeapon1, meleeWeapon2, meleeWeapon3, meleeWeapon4, meleeWeapon5, meleeWeapon6, meleeWeapon7, meleeWeapon8, meleeWeapon9, meleeWeapon10, meleeWeapon11, meleeWeapon12, meleeWeapon13, meleeWeapon14, meleeWeapon15, meleeWeapon16, meleeWeapon17, meleeWeapon18, meleeWeapon19, meleeWeapon20, meleeWeapon21, meleeWeapon22, meleeWeapon23, meleeWeapon24, meleeWeapon25, meleeWeapon26, meleeWeapon27, meleeWeapon28, meleeWeapon29, meleeWeapon30, meleeWeapon31, meleeWeapon32, meleeWeapon33, meleeWeapon34, meleeWeapon35, meleeWeapon36, meleeWeapon37, meleeWeapon38, shield1, shield2, shield3, shield4, shield5, shield6, shield7, shield8, shield9, shield10, shield11, shield12, shield13, shield14, spell1, spell2, key, rangedWeapon1, rangedAmmo1, flyingArrow1, flyingSlash1, flyingHit1, attack1, attack2, attack3, attack4, attack5, attack6, fire, water, mobRabbit, potion1, amulet1, helmet1, armor1, legs1, boots1, arms1, ring1, ring2, pickuparmor1, pickuplegs1, pickupboots1, pickuparms1, pickupamulet1, pickuphelmet1, pickuphelmet2, pickupring1, pickupbow1, pickuparrow1, pickupmace1, pickupwand1, pickupaxe1, pickupsword1, pickupshield1, pickupdagger1, pickupkey1, pickuppotion1, }
13.690821
35
0.790049
c2981623d3888b5891e131bba70b17c49e65d606
473
package voidpointer.spigot.voidwhitelist.event; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public final class WhitelistDisabledEvent extends Event { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlerList() { return handlers; } public WhitelistDisabledEvent() { super(true); } @Override public HandlerList getHandlers() { return handlers; } }
22.52381
66
0.712474
bc9ecb24a92ef926be468ef8610c54afdd9ec816
12,288
/* * Kodkod -- Copyright (c) 2005-present, Emina Torlak * Pardinus -- Copyright (c) 2013-present, Nuno Macedo, INESC TEC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package kodkod.examples.pardinus.temporal; import kodkod.ast.*; import kodkod.engine.Solution; import kodkod.engine.Solver; import kodkod.engine.config.ExtendedOptions; import kodkod.engine.decomp.DModel; import kodkod.engine.satlab.SATFactory; import kodkod.instance.Bounds; import kodkod.instance.PardinusBounds; import kodkod.instance.TupleFactory; import kodkod.instance.TupleSet; import kodkod.instance.Universe; import java.util.ArrayList; import java.util.List; /** * @author Eduardo Pessoa, Nuno Macedo // [HASLab] temporal model finding */ public class RingT extends DModel { public enum Variant1 { BADLIVENESS, GOODLIVENESS, GOODSAFETY; } public enum Variant2 { STATIC, VARIABLE; } // model parameters // number of processes and time instants private final int n_ps; // whether to check liveness property or safety, to enforce loopless // paths and assume variable processes private final Variant1 variant; private final Variant2 variable; // partition 1 relations private Relation pfirst, plast, pord, Process, succ, id, Id; // partition 2 relations private Relation toSend, elected; private Universe u; public RingT(String args[]) { this.n_ps = Integer.valueOf(args[0]); this.variant = Variant1.valueOf(args[1]); this.variable = Variant2.valueOf(args[2]); Process = Relation.unary("Process"); succ = Relation.binary("succ"); pfirst = Relation.unary("pfirst"); plast = Relation.unary("plast"); pord = Relation.binary("pord"); id = Relation.binary("id_"); Id = Relation.unary("Id"); toSend = Relation.binary_variable("toSend"); elected = Relation.unary_variable("elected"); } /** * Returns the declaration constraints. * * @return <pre> * sig Time {} * sig Process { * toSend: Process -> Time, * elected: set Time } * </pre> */ public Formula declarations() { final Formula electedDomRange = elected.in(Process).always();/* * TEMPORAL * OP */ final Formula sendDomRange; if (variable == Variant2.VARIABLE) sendDomRange = toSend.in(Process.product(Id)).always();/* * TEMPORAL * OP */ else sendDomRange = toSend.in(Process.product(Process)).always();/* * TEMPORAL * OP */ return Formula.and(electedDomRange, sendDomRange); } /** * Returns the init predicate. * * @return <pre> * pred init (t: Time) {all p: Process | p.toSend.t = p} * </pre> */ public Formula init() { final Variable p = Variable.unary("p"); final Formula f; if (variable == Variant2.VARIABLE) f = p.join(toSend).eq(p.join(id)).forAll(p.oneOf(Process)); else f = p.join(toSend).eq(p).forAll(p.oneOf(Process)); return f; } /** * Returns the step predicate. * * @return <pre> * pred step (t, t�: Time, p: Process) { * let from = p.toSend, to = p.succ.toSend | * some id: p.toSend.t { * p.toSend.t� = p.toSend.t - id * p.succ.toSend .t� = p.succ.toSend .t + (id - PO/prevs(p.succ)) } } * </pre> */ public Formula step(Expression p) { final Expression from = p.join(toSend); final Expression to = p.join(succ).join(toSend); final Expression fromPost = p.join(toSend.prime());/* TEMPORAL OP */ final Expression toPost = p.join(succ).join(toSend.prime());/* * TEMPORAL * OP */ final Variable idv = Variable.unary("id"); final Expression prevs; if (variable == Variant2.VARIABLE) prevs = (p.join(succ).join(id)).join((pord.transpose()).closure()); else prevs = (p.join(succ)).join((pord.transpose()).closure()); final Formula f1 = fromPost.eq(from.difference(idv)); final Formula f2 = toPost.eq(to.union(idv.difference(prevs))); return f1.and(f2).forSome(idv.oneOf(from)); } /** * Returns the skip predicate * * @return <pre>pred skip (t, t�: Time, p: Process) {p.toSend.t = p.toSend.t�} * * <pre> */ public Formula skip(Expression p) { return p.join(toSend).eq(p.join(toSend.prime())); }/* TEMPORAL OP */ /** * Returns the Traces fact. * * @return <pre> * fact Traces { * init (TO/first ()) * all t: Time - TO/last() | let t� = TO/next (t) | * all p: Process | step (t, t�, p) or step (t, t�, succ.p) or skip (t, t�, p) } * </pre> */ public Formula traces() { final Variable p = Variable.unary("p"); final Formula f = step(p).or(step(succ.join(p))).or(skip(p)); final Formula fAll = f.forAll(p.oneOf(Process)); return init().and(fAll.always());/* TEMPORAL OP */ } /** * * Return DefineElected fact. * * @return <pre> * fact DefineElected { * no elected.TO/first() * all t: Time - TO/first()| * elected.t = {p: Process | p in p.toSend.t - p.toSend.(TO/prev(t))} } * </pre> */ public Formula defineElected() { final Formula f1 = elected.no(); final Variable p = Variable.unary("p"); final Formula c; if (variable == Variant2.VARIABLE) // c = // (p.join(id)).in(p.join(toSend).join(t).difference(p.join(toSend).join(t.join(tord.transpose())))); // {p: Process | (after { p.id in p.toSend }) and p.id not in // p.toSend} } c = (p.join(id)).in(p.join(toSend)).after().and(p.join(id).in(p.join(toSend)).not());/* * TEMPORAL * OP */ else // c = // p.in(p.join(toSend).join(t).difference(p.join(toSend).join(t.join(tord.transpose())))); c = p.in(p.join(toSend)).after().and((p.in(p.join(toSend))).not());/* * TEMPORAL * OP */ final Expression comprehension = c.comprehension(p.oneOf(Process)); final Formula f2 = elected.prime().eq(comprehension).always();/* * TEMPORAL * OP */ return f1.and(f2); } /** * Returns the progress predicate. * * @return <pre> * pred progress () { * all t: Time - TO/last() | let t� = TO/next (t) | * some Process.toSend.t => some p: Process | not skip (t, t�, p) } * </pre> */ /* * pred Progress { always {some Process.toSend => after { some p: Process | * not skip [p]} } } */ public Formula progress() { final Variable p = Variable.unary("p"); final Formula f1 = (Process.join(toSend).some()).implies(skip(p).not().forSome(p.oneOf(Process))); return f1.always();/* TEMPORAL OP */ } /** * Returns the AtLeastOneElected assertion. * * @return <pre> * assert AtLeastOneElected { progress () => some elected.Time } * </pre> */ public Formula atLeastOneElectedLoop() {// GOODLIVENESS return (Process.some().and(progress())).implies(elected.some().eventually());/* * TEMPORAL * OP */ } public Formula atLeastOneElected() { // //BADLIVENESS return (Process.some()).implies(elected.some().eventually());/* * TEMPORAL * OP */ } /** * Returns the atMostOneElected assertion * * @return <pre> * assert AtMostOneElected {lone elected.Time} * </pre> */ public Formula atMostOneElected() { // GOODSAFETY return elected.lone().always();/* TEMPORAL OP */ } /** * Returns the declarations and facts of the model * * @return the declarations and facts of the model */ public Formula invariants() { return declarations().and(traces()).and(defineElected()); } /** * Returns the conjunction of the invariants and the negation of * atMostOneElected. * * @return invariants() && !atMostOneElected() */ public Formula checkAtMostOneElected() { return invariants().and(atMostOneElected().not()); } public Formula checkAtLeastOneElected() { return invariants().and(atLeastOneElected().not()); } public Formula checkAtLeastOneElectedLoop() { return invariants().and(atLeastOneElectedLoop().not()); } public Formula variableConstraints() { final Formula ordProcess; if (variable == Variant2.VARIABLE) { final Formula f0 = id.function(Process, Id); final Formula f1 = Process.some(); final Variable p1 = Variable.unary("p"); final Formula f2 = (id.join(p1).lone()).forAll(p1.oneOf(Id)); ordProcess = f2.and(f1).and(f0).and(pord.totalOrder(Id, pfirst, plast)); } else ordProcess = pord.totalOrder(Process, pfirst, plast); final Formula succFunction = succ.function(Process, Process); final Variable p = Variable.unary("p"); final Formula ring = Process.in(p.join(succ.closure())).forAll(p.oneOf(Process)); return Formula.and(ordProcess, succFunction, ring); } public Formula finalFormula() { if (!(variant == Variant1.GOODSAFETY)) if (variant == Variant1.GOODLIVENESS) return (checkAtLeastOneElectedLoop()); else return (checkAtLeastOneElected()); else return (checkAtMostOneElected()); } public PardinusBounds bounds1() { final List<String> atoms = new ArrayList<String>(n_ps); // add the process atoms for (int i = 0; i < n_ps; i++) atoms.add("Process" + i); // if variable processes, must consider Ids as a workaround to // totalorder if (variable == Variant2.VARIABLE) { for (int i = 0; i < n_ps; i++) atoms.add("Id" + i); } u = new Universe(atoms); final TupleFactory f = u.factory(); final PardinusBounds b = new PardinusBounds(u); final TupleSet pb = f.range(f.tuple("Process0"), f.tuple("Process" + (n_ps - 1))); b.bound(Process, pb); b.bound(succ, pb.product(pb)); if (variable == Variant2.VARIABLE) { final TupleSet ib = f.range(f.tuple("Id0"), f.tuple("Id" + (n_ps - 1))); b.bound(Id, ib); b.bound(id, pb.product(ib)); b.bound(pfirst, ib); b.bound(plast, ib); b.bound(pord, ib.product(ib)); } else { b.bound(pfirst, pb); b.bound(plast, pb); b.bound(pord, pb.product(pb)); } return b; } public Bounds bounds2() { final TupleFactory f = u.factory(); final Bounds b = new Bounds(u); final TupleSet pb = f.range(f.tuple("Process0"), f.tuple("Process" + (n_ps - 1))); if (variable == Variant2.VARIABLE) { final TupleSet ib = f.range(f.tuple("Id0"), f.tuple("Id" + (n_ps - 1))); b.bound(toSend, pb.product(ib)); } else { b.bound(toSend, pb.product(pb)); } b.bound(elected, pb); return b; } @Override public Formula partition1() { return variableConstraints(); } @Override public Formula partition2() { return finalFormula(); } @Override public String shortName() { // TODO Auto-generated method stub return null; } @Override public int getBitwidth() { return 1; } public static void main(String[] args) { RingT model = new RingT(new String[] { "3", "BADLIVENESS", "STATIC" }); ExtendedOptions opt = new ExtendedOptions(); opt.setSolver(SATFactory.Glucose); opt.setMaxTraceLength(10); Solver solver = new Solver(opt); PardinusBounds bnds = model.bounds1(); bnds.merge(model.bounds2()); Solution sol = solver.solve(model.partition1().and(model.partition2()), bnds); System.out.println(sol); return; } }
27.863946
104
0.632731
553a5d06ff59c3038c9636a85543c74126374fc3
12,250
package com.mygdx.game.mario.game.screens; import java.io.IOException; import java.util.ArrayList; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Vector2; import com.mygdx.game.mario.MarioResourceManager; import com.mygdx.game.mario.MarioSoundManager; import com.mygdx.game.mario.Settings; import com.mygdx.game.mario.game.GameLoader; import com.mygdx.game.mario.game.GameRenderer; import com.mygdx.game.mario.game.TileMap; import com.mygdx.game.mario.game.screens.transition.ScreenTransition; import com.mygdx.game.mario.game.screens.transition.ScreenTransitionFade; import com.mygdx.game.mario.game.screens.transition.ScreenTransitionSlide; import com.mygdx.game.mario.objects.Creature; import com.mygdx.game.mario.objects.mario.Mario; public class LevelCompleteScreen extends AbstractGameScreen { private Mario mario; private TileMap map; private TileMap backgroundMap; private TileMap foregroundMap; private GameRenderer renderer; public int period = 20; private SpriteBatch batch; private boolean lockInputs=true; private int blink=0; private Vector2 initialPt,finalPt; ArrayList<Vector2> pearls; private int pearlSize=10; OrthographicCamera camera; /** * Screen which appears when level is completed or mario enters new level * It shows overview of stage * @param game */ public LevelCompleteScreen(AbstractGame game) { super(game); batch=new SpriteBatch(); renderer = new GameRenderer(game); Creature.WAKE_UP_VALUE_DOWN_RIGHT=game.WIDTH/8; //Settings.loadPreferences((((AndroidGame)game)).getSharedPreferences(PreferenceConstants.PREFERENCE_NAME, 0)); pearls=new ArrayList<Vector2>(); pearlSize=MarioResourceManager.instance.gui.pearl1.getRegionWidth(); lockInputs=true; Settings.save(); loadGame(); camera= new OrthographicCamera();//game.WIDTH, game.HEIGHT);//Gdx.graphics.getWidth(), -Gdx.graphics.getHeight()); camera.setToOrtho(true, 2*game.WIDTH, 2*game.HEIGHT); camera.translate(0,-game.HEIGHT/2); camera.update(); } public void loadGame() { try { renderer = new GameRenderer(game); renderer.setDrawHudEnabled(false); renderer.setBackground(null);//MarioResourceManager.loadImage("backgrounds/smb.png")); //bmpLevel=MarioResourceManager.loadImage("gui/"+Settings.world+".png"); //Log.e("D","Loading LevelComplete screen "); map = GameLoader.loadMap("assets-mario/maps/world"+Settings.world+"/map.txt",MarioSoundManager.instance); //renderer.setBackground(MarioResourceManager.guiBackground); mario = new Mario(); mario.setX(32); mario.setY(32); map.setPlayer(mario); // set the games main player to mario if (Settings.level==0){ lockInputs=false; Vector2 p=map.bookMarks().get(0); initialPt=p; mario.setX(TileMap.tilesToPixels(p.x)); mario.setY(TileMap.tilesToPixels(p.y+1)-mario.getHeight());//); pearls.add(new Vector2((int)(mario.getX()),(int) mario.getY())); finalPt=p; return; } if (map.bookMarks().size()>=Settings.level){ Vector2 p=map.bookMarks().get(Settings.level-1); initialPt=p; mario.setX(TileMap.tilesToPixels(p.x)); mario.setY(TileMap.tilesToPixels(p.y+1)-mario.getHeight());//); finalPt=map.bookMarks().get(Settings.level); if (Settings.level >= 2) { Vector2 p1 = map.bookMarks().get(0); Vector2 p2 = map.bookMarks().get(1); for (int i = TileMap.tilesToPixels(p1.x); i < TileMap .tilesToPixels(p2.x); i += pearlSize) { pearls.add(new Vector2(i, TileMap .tilesToPixels(p1.y))); } for (int i = TileMap.tilesToPixels(p1.y); i < TileMap .tilesToPixels(p2.y); i += pearlSize) { pearls.add(new Vector2(TileMap.tilesToPixels(p2.x), i)); } }if (Settings.level >= 3) { Vector2 p1 = map.bookMarks().get(1); Vector2 p2 = map.bookMarks().get(2); for (int i = TileMap.tilesToPixels(p1.x); i < TileMap .tilesToPixels(p2.x); i += pearlSize) { pearls.add(new Vector2(i, TileMap .tilesToPixels(p1.y))); } for (int i = TileMap.tilesToPixels(p1.y); i < TileMap .tilesToPixels(p2.y); i += pearlSize) { pearls.add(new Vector2(TileMap.tilesToPixels(p2.x), i)); } } pearls.add(new Vector2((int)(mario.getX()),(int) mario.getY()));//+mario.getHeight()/2))); }else{ finalPt=new Vector2(map.getWidth(),map.getHeight()); } } catch (IOException e) { System.out.println("Invalid Map."); //Log.e("Errrr", "invalid map"); } } @Override public void update(float deltaTime) { updateRunning(deltaTime); } private void updateRunning(float deltaTime) { // if (state != GameState.Running)return; Vector2 pt=pearls.get(pearls.size()-1); if (mario.getX()<TileMap.tilesToPixels(finalPt.x)){ mario.setX(mario.getX()+2); if (mario.getX()-pt.x>pearlSize){ pearls.add(new Vector2((int) mario.getX(),pt.y)); } }else if(mario.getY()<TileMap.tilesToPixels(finalPt.y+1)-mario.getHeight()){ mario.setY(mario.getY()+1); if (Math.abs(mario.getY()-pt.y)>=pearlSize){ pearls.add(new Vector2(pt.x,(int) mario.getY())); } }else{ } if (mario.getX()>=TileMap.tilesToPixels(finalPt.x)){ lockInputs=false; } } @Override public void render() { Gdx.gl.glClearColor(0x64 / 255.0f, 0x95 / 255.0f, 0xed / 255.0f, 0xff / 255.0f); // Clears the screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Render game world to screen batch.setProjectionMatrix(camera.combined); batch.begin(); drawRunningUI(); batch.end(); } private void drawRunningUI() { batch.draw(MarioResourceManager.guiBackground, 0, -game.HEIGHT/2,2*game.WIDTH, 2*game.HEIGHT); renderer.draw(batch,map, backgroundMap, foregroundMap,2*game.WIDTH, game.HEIGHT); //batch.draw(MarioResourceManager.guiBackground, 0, 0,game.HEIGHT/2, game.HEIGHT); //tmpCanvas.translate(0, frameBuffer.getHeight()/2); //renderer.draw(tmpCanvas, map, backgroundMap, foregroundMap, // (int) (2*frameBuffer.getWidth()), frameBuffer.getHeight()); //tmpCanvas.restore(); float x, y; x=game.WIDTH-MarioResourceManager.instance.gui.logo.getRegionWidth()/2; y=15-game.HEIGHT/2; batch.draw(MarioResourceManager.instance.gui.logo, x, y); //tmpCanvas.drawBitmap(MarioResourceManager.logo, frameBuffer.getWidth()-MarioResourceManager.logo.getWidth()/2, 15, null); //tmpCanvas.drawBitmap(bmpLevel, frameBuffer.getWidth()+MarioResourceManager.logo.getWidth()/2-15, 10, null); blink++; if (blink>=30){ x=game.WIDTH-MarioResourceManager.instance.gui.TapToStart.getRegionWidth()/2; y=2*game.HEIGHT-MarioResourceManager.instance.gui.TapToStart.getRegionHeight()-game.HEIGHT+20; batch.draw(MarioResourceManager.instance.gui.TapToStart, x, y); // tmpCanvas.drawBitmap(MarioResourceManager.instance.gui.tTapToStart,x, 2*frameBuffer.getHeight()-2*MarioResourceManager.TapToStart.getHeight(), null); } if (blink==80)blink=0; TextureRegion bmp; if (blink % 20 <10){ bmp=MarioResourceManager.instance.gui.pearl1; }else{ bmp=MarioResourceManager.instance.gui.pearl2; } for (int i=0; i<pearls.size(); i++){ batch.draw(bmp,pearls.get(i).x+GameRenderer.xOffset,pearls.get(i).y+GameRenderer.yOffset); } batch.draw(MarioResourceManager.instance.creatures.levelComplete, pearls.get(0).x-4+GameRenderer.xOffset,pearls.get(0).y-4); batch.draw(MarioResourceManager.instance.creatures.levelComplete, TileMap.tilesToPixels(initialPt.x)-5+GameRenderer.xOffset,TileMap.tilesToPixels(initialPt.y)-15); //tmpCanvas.drawBitmap(MarioResourceManager.levelComplete, pearls.get(0).x-4+GameRenderer.xOffset,pearls.get(0).y-4+frameBuffer.getHeight()/2, paint); //tmpCanvas.drawBitmap(MarioResourceManager.levelComplete, TileMap.tilesToPixels(initialPt.x)-5+GameRenderer.xOffset,TileMap.tilesToPixels(initialPt.y)+frameBuffer.getHeight()/2-15, paint); Vector2 p=map.bookMarks().get(map.bookMarks().size()-1); batch.draw(MarioResourceManager.instance.creatures.levelComplete, TileMap.tilesToPixels(p.x)+GameRenderer.xOffset-MarioResourceManager.instance.creatures.levelComplete.getRegionWidth()/2,TileMap.tilesToPixels(p.y+1)+GameRenderer.yOffset-MarioResourceManager.instance.creatures.levelComplete.getRegionHeight()); if (Settings.level==3 && lockInputs==false ){ if (blink>=30) GameRenderer.drawBigString(batch,"CONGRATUATIONS!! ",Color.GREEN,game.WIDTH, 2*game.HEIGHT-6*MarioResourceManager.instance.gui.TapToStart.getRegionHeight(),0); GameRenderer.drawNormalString(batch,"You Have Completed World " +Settings.world,Color.ORANGE, game.WIDTH,(int) (2*game.HEIGHT-4.5f*MarioResourceManager.instance.gui.TapToStart.getRegionHeight()-15),0); } } @Override public boolean keyDown(int keycode) { super.keyDown(keycode); if(keycode==Keys.ESCAPE)return true; if(keycode==Keys.SPACE){ touchDown(0,0,0,0); return true; } mario.keyPressed(keycode); return true; } @Override public boolean keyUp(int keycode) { super.keyUp(keycode); return true; } @Override public boolean keyTyped(char character) { //mario.keyReleased(keycode); // TODO Auto-generated method stub return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { if (!lockInputs) { if (Settings.level >= 3) { Settings.level =0; ScreenTransition transition = ScreenTransitionFade.init(1.0f); //ScreenTransition transition =ScreenTransitionSlide.init(2,ScreenTransitionSlide.DOWN,true,Interpolation.fade); game.setScreen(new WorldScreen(game),transition); } else { Settings.level++; //ScreenTransition transition = ScreenTransitionFade.init(1.0f); ScreenTransition transition =ScreenTransitionSlide.init(1,ScreenTransitionSlide.UP,true,Interpolation.sine); game.setScreen(new GameScreen(game),transition); } lockInputs=true; } return true; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { //mario.keyReleased(Keys.LEFT); //mario.keyReleased(Keys.RIGHT); mario.keyReleased(Keys.SPACE); mario.keyReleased(Keys.CONTROL_LEFT); return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { // TODO Auto-generated method stub return false; } @Override public boolean mouseMoved(int screenX, int screenY) { // TODO Auto-generated method stub return false; } @Override public boolean scrolled(int amount) { // TODO Auto-generated method stub return false; } @Override public void pause() { } @Override public boolean onBackPressed() { //pause(); goToMenu(); return true; } private void goToMenu() { if (lockInputs || Settings.level==0)return; MenuScreen mainMenuScreen = new MenuScreen(game); //ScreenTransition transition = ScreenTransitionFade.init(1.0f); ScreenTransition transition =ScreenTransitionSlide.init(2,ScreenTransitionSlide.LEFT,true,Interpolation.swing); game.setScreen(mainMenuScreen,transition); //mario=null; } @Override public void create() { // TODO Auto-generated method stub } @Override public void resize(int width, int height) { camera.setToOrtho(true, 2*game.WIDTH, 2*game.HEIGHT); camera.translate(0,-game.HEIGHT/2); camera.update(); } @Override public void show() { // TODO Auto-generated method stub } @Override public void hide() { // TODO Auto-generated method stub } @Override public InputProcessor getInputProcessor() { // TODO Auto-generated method stub return this; } }
34.122563
313
0.70098
36ad8d739623f75d56140c6cbe0cda0e23447a60
249
public class YeInterger { public String num; public YeInterger(String n) { this.num = n; } public YeInterger plus(YeInterger n) { // 实现加法 System.out.println("n1:" + this.num + " + n2:" + n.num); return new YeInterger("3333"); } }
16.6
58
0.626506