text
stringlengths
7
1.01M
package net.haesleinhuepf.clijx.gui; import ij.IJ; import ij.ImageJ; import ij.ImagePlus; import ij.gui.Toolbar; import ij.plugin.tool.PlugInTool; import net.haesleinhuepf.clijx.gui.panel.CLIJxPanel; import net.haesleinhuepf.clijx.gui.stickyfilters.AbstractStickyFilter; import net.haesleinhuepf.clijx.gui.stickyfilters.StickyImagePlus; import java.awt.event.MouseEvent; public class InteractiveWindowPosition extends PlugInTool { Integer startX = null; Integer startY = null; Integer windowStartX = null; Integer windowStartY = null; @Override public void mousePressed(ImagePlus imp, MouseEvent e) { if(CLIJxPanel.isPanel(imp)) { CLIJxPanel.mouseDown( imp.getWindow().getCanvas().offScreenX(e.getX()), imp.getWindow().getCanvas().offScreenY(e.getY()) ); return; } //super.mousePressed(imp, e); startX = e.getXOnScreen(); startY = e.getYOnScreen(); windowStartX = imp.getWindow().getX(); windowStartY = imp.getWindow().getY(); } @Override public void mouseReleased(ImagePlus imp, MouseEvent e) { if (CLIJxPanel.isPanel(imp)) { CLIJxPanel.mouseUp( imp.getWindow().getCanvas().offScreenX(e.getX()), imp.getWindow().getCanvas().offScreenY(e.getY()) ); return; } else if (imp instanceof StickyImagePlus) { AbstractStickyFilter.handleCoordinates((StickyImagePlus) imp); } else { CLIJxPanel.considerTaking(imp); } //super.mouseReleased(imp, e); startX = null; startY = null; windowStartX = null; windowStartY = null; } @Override public void mouseDragged(ImagePlus imp, MouseEvent e) { if(CLIJxPanel.isPanel(imp)) { CLIJxPanel.mouseMove( imp.getWindow().getCanvas().offScreenX(e.getX()), imp.getWindow().getCanvas().offScreenY(e.getY()) ); return; } //super.mouseDragged(imp, e); if (startX != null && startY != null & windowStartX != null & windowStartY != null) { imp.getWindow().setLocation( windowStartX - startX + e.getXOnScreen(), windowStartY - startY + e.getYOnScreen()); } } public static void main(String[] args) { new ImageJ(); IJ.openImage("src/test/resources/blobs.tif").show(); IJ.openImage("src/test/resources/blobs.tif").show(); Toolbar.addPlugInTool(new InteractiveWindowPosition()); //new InteractiveWindowPosition().run(""); } @Override public String getToolName() { return "Window Position"; } @Override public String getToolIcon() { return Utilities.generateIconCodeString( getToolIconString() ); } public static String getToolIconString() { return // 0123456789ABCDEF /*0*/ " ## " + /*1*/ " #### " + /*2*/ " ###### " + /*3*/ " ## " + /*4*/ " # ## # " + /*5*/ " ## ## ## " + /*6*/ " ### ## ### " + /*7*/ "################" + /*8*/ "################" + /*9*/ " ### ## ### " + /*A*/ " ## ## ## " + /*B*/ " # ## # " + /*C*/ " ## " + /*D*/ " ###### " + /*E*/ " #### " + /*F*/ " ## " ; } }
package packij; import com.sun.speech.freetts.Voice; import com.sun.speech.freetts.VoiceManager; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Arrays; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class KevinChanter implements AutoCloseable { private final Voice kevin = VoiceManager.getInstance().getVoice("kevin"); private final Voice kevin16 = VoiceManager.getInstance().getVoice("kevin16"); private final int MAXIMUM_CONCURRENT_SINGLE_VOICE = 10; private Voice[] voice_array_maker(int how_many, String voiceName){ final Voice[] voices = new Voice[how_many]; final VoiceManager vm = VoiceManager.getInstance(); for (int i = 0; i < how_many; i++) { final Voice v = vm.getVoice(voiceName); v.allocate(); voices[i] = v; } return voices; } private final Voice[] kevins = voice_array_maker(MAXIMUM_CONCURRENT_SINGLE_VOICE, "kevin"); private final Voice[] kevin16s = voice_array_maker(MAXIMUM_CONCURRENT_SINGLE_VOICE, "kevin16"); private final Random rng = new Random(); @Override public void close() throws Exception { kevin.deallocate(); kevin16.deallocate(); for (Voice v: kevins){ v.deallocate(); } for (Voice v: kevin16s){ v.deallocate(); } } private enum KEVIN_SPEECH_TYPE_ENUM{ ONE_LETTER_EACH, SAY_MULTIPLE_TIMES_IN_SERIES, SAY_MULTIPLE_TIMES_ALTERNATING, SAY_MULTIPLE_TIMES_RANDOM, RANDOM_IN_SERIES, SAY_TWICE_AT_ONCE, SAY_DIFFERENT_THINGS_AT_ONCE, KEVIN_SAY_ONCE, KEVIN16_SAY_ONCE, RANDOM_SAY_ONCE } private final KEVIN_SPEECH_TYPE_ENUM[] kevin_speech_types = KEVIN_SPEECH_TYPE_ENUM.values(); private final int kevin_speech_types_len = kevin_speech_types.length; private KEVIN_SPEECH_TYPE_ENUM next_speech_type(){ return kevin_speech_types[rng.nextInt(kevin_speech_types_len)]; } private final String kevString = "Kevin"; private final String[] other_ways_of_saying_kevin = new String[]{ "Kevin","Kevo","Kev in", "Kayvin", "I love Kevin", "Kevin!", "Gimme a K! Gimme an E! Gimme a V! Gimme an I! Gimme an N! What do you get? Kevin!", "Kevin is love, Kevin is life.", "We love Kevin", "Thank you, Kevin.", "Kevin number 1!", "All Hail Kevin!", "Kevin is based.", "Based and Kevinpilled.", "Who needs social credit when you have Kevin?", "All glory to Kevin!", "All praise Kevin!", "Kevin is truly based.", "I love Kevin!", "k e v i n", "K, as in 'Kevin'. E as in 'The second letter of Kevin'. V as in 'The third letter of Kevin'. I as in" + " 'the fourth letter of Kevin'. N as in 'The last letter of Kevin'." + " Put those together, you get Kevin.", "I love Kevin", "Kevin is great", "We all love Kevin", "Kevin is watching you.", "UwU I love Kevin", "Kevin is great", "Kevin is the best!", "Kevin for President!", "Kevin, our glorious benevolent dictator!", "Kevin cares about you!", "Kevin is the greatest!", "I love Kevin!", "Kevin!", "Kevin", "Kevo", "Kevin!", "Kev!", "Kovan? No wait cancel that, I meant 'Kevin'!", "Kevin Kevin Kevin Kevin Kevin!", "Kehvihn", "Kevin!","We love Kevin a lot we truly do he is the best person to ever exist", "I adore Kevin", "everything about Kevin is my favourite thing about Kevin!", "k.e.v.i.n.", "k! e! v! i! n!", "Glorious Dear Leader Kevin!", "Thank you Kevin for allowing us in r/shitposting!", "kevin number 1", "I want Kevin to fuck my dad!", "Kevin is great!", "Kevin!", "k e v i n", "Hooray for Kevin!", "Kevin kevin kevin kevin kevin kevin kevin kevin kevin kevin kevin kevin kevin", "great work, Kevin!", "Kevin is number 1", "Kevin it to win it!", "Kevin great!", "KEVIN.\nTAP TO EDIT TEXT.", "Vote for Kevin!" }; private final int other_len = other_ways_of_saying_kevin.length; /** * Picks which Kevin word to say next. * 50% chance it's just Kevin, 50% chance it'll be something from the other ways of saying kevin * @return next thing to say. */ private String pick_next_kevin_word(){ if (rng.nextBoolean()){ return kevString; } else { return other_ways_of_saying_kevin[rng.nextInt(other_len)]; } } /** * Picks a random way of saying Kevin and (attempts) to say it, returns the count of times that Kevin was said. * @return how many times was Kevin said? */ private int kevin_sayer(){ switch (next_speech_type()){ case KEVIN_SAY_ONCE: kevin.speak(pick_next_kevin_word()); return 1; case KEVIN16_SAY_ONCE: kevin16.speak(pick_next_kevin_word()); return 1; case ONE_LETTER_EACH: if (sayKevinOneLetterEach()){ return 1; } break; case SAY_DIFFERENT_THINGS_AT_ONCE: if (sayDifferentThings(pick_next_kevin_word(), pick_next_kevin_word())){ return 2; } break; case SAY_TWICE_AT_ONCE: if (sayTwice(pick_next_kevin_word())){ return 1; } break; case SAY_MULTIPLE_TIMES_IN_SERIES: final int times_to_say = 3 + rng.nextInt(MAXIMUM_CONCURRENT_SINGLE_VOICE-3); if (sayWordsMultipleTimesInSeries(times_to_say, pick_next_kevin_word())){ return times_to_say/2; } break; case SAY_MULTIPLE_TIMES_ALTERNATING: final int times_to_say_2 = 3 + rng.nextInt(MAXIMUM_CONCURRENT_SINGLE_VOICE-3); if (sayWordsMultipleTimesInSeriesAlternating(times_to_say_2, pick_next_kevin_word(), false)){ return times_to_say_2/2; } break; case SAY_MULTIPLE_TIMES_RANDOM: final int times_to_say_3 = 3 + rng.nextInt(MAXIMUM_CONCURRENT_SINGLE_VOICE-3); if (sayWordsMultipleTimesInSeriesAlternating(times_to_say_3, pick_next_kevin_word(), true)){ return times_to_say_3/2; } break; case RANDOM_SAY_ONCE: default: if (random_say(pick_next_kevin_word())){ return 1; } } return 0; } private long random_long(int max){ return (long)(rng.nextFloat() * max); } private long delay_picker(){ long delay = 10L; for (int i = rng.nextInt(4); i < 4; i++) { delay += random_long(640); } return delay; } /** * Starts saying Kevin the specified number of times. * @param timesToSayKevin how many times does 'Kevin' need to be said? */ public void handle_saying_kevin_x_times(int timesToSayKevin){ int kevin_counter = 0; while (kevin_counter < timesToSayKevin && control.keepGoing()){ kevin_counter += handle_an_iteration_of_kevin_being_said(); control.logInfo( String.format( "%1d of %2d, %3f%% done", kevin_counter, timesToSayKevin, 100*(kevin_counter/(double)timesToSayKevin) ) ); } } private int handle_an_iteration_of_kevin_being_said(){ try{ Thread.sleep(delay_picker()); }catch (InterruptedException ignored){ } return kevin_sayer(); } /** * Call this to say 'Kevin' infinitely many times. */ public void say_kevin_infinitely(){ while (control.keepGoing()){ handle_an_iteration_of_kevin_being_said(); } } private boolean sayKevinOneLetterEach(){ final String[] kevinLetters = new String[]{"k","e","v","i","n"}; boolean kevin16Next = rng.nextBoolean(); for(String s: kevinLetters){ if (kevin16Next){ kevin16.speak(s); } else{ kevin.speak(s); } kevin16Next = !kevin16Next; } return true; } private boolean random_say(String words_to_say){ if (rng.nextBoolean()){ kevin.speak(words_to_say); } else { kevin16.speak(words_to_say); } return true; } private Thread SYNCHRONIZED_VOICE_THREAD_FACTORY(CyclicBarrier cb, Voice voiceToUse, String words, long delay){ return new Thread( () -> { try{ cb.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } try { Thread.sleep(delay); } catch (InterruptedException | IllegalArgumentException e2){ e2.printStackTrace(); } voiceToUse.speak(words); } ); } private boolean sayWordsMultipleTimesInSeries(int timesToSayKevin, String wordsToSay){ try { Thread[] sayThreads = new Thread[timesToSayKevin]; final CyclicBarrier cbm = new CyclicBarrier(timesToSayKevin); final boolean usingKevin16 = rng.nextBoolean(); final long delay = 200L + random_long(100); for (int i = 0; i < timesToSayKevin; i++) { if (usingKevin16) { sayThreads[i] = SYNCHRONIZED_VOICE_THREAD_FACTORY( cbm, kevin16s[i], wordsToSay, i * delay ); } else { sayThreads[i] = SYNCHRONIZED_VOICE_THREAD_FACTORY( cbm, kevins[i], wordsToSay, i * delay ); } } for (Thread t : sayThreads) { t.start(); } for (Thread t : sayThreads) { t.join(); } return true; } catch (InterruptedException e){ e.printStackTrace(); return false; } } private boolean sayWordsMultipleTimesInSeriesAlternating(int times, String words, boolean randomize){ try { Thread[] sayThreads = new Thread[times]; final CyclicBarrier cbm = new CyclicBarrier(times); boolean usingKevin16 = rng.nextBoolean(); final long delay = 200L + random_long(100); for (int i = 0; i < times; i++) { if (usingKevin16) { sayThreads[i] = SYNCHRONIZED_VOICE_THREAD_FACTORY( cbm, kevin16s[i], words, i * delay ); } else { sayThreads[i] = SYNCHRONIZED_VOICE_THREAD_FACTORY( cbm, kevins[i], words, i * delay ); } if (randomize){ usingKevin16 = rng.nextBoolean(); } else { usingKevin16 = !usingKevin16; } } for (Thread t : sayThreads) { t.start(); } for (Thread t : sayThreads) { t.join(); } return true; } catch (InterruptedException e){ e.printStackTrace(); return false; } } private boolean sayDifferentThings(String kevinWords, String kevin16words){ try { CyclicBarrier cb2 = new CyclicBarrier(2); Thread kevThread = SYNCHRONIZED_VOICE_THREAD_FACTORY(cb2, kevin, kevinWords, 0); Thread kev16thread = SYNCHRONIZED_VOICE_THREAD_FACTORY(cb2, kevin16, kevin16words, 0); kevThread.start(); kev16thread.start(); kevThread.join(); kev16thread.join(); return true; } catch (InterruptedException e){ e.printStackTrace(); return false; } } private boolean sayTwice(String sayThis){ return sayDifferentThings(sayThis, sayThis); } private final ChantControlStopperLoggerInterface control; KevinChanter(ChantControlStopperLoggerInterface control){ this.control = control; Voice[] voices = VoiceManager.getInstance().getVoices(); for(Voice v: voices){ System.out.println(v.getName()); } if (kevin != null) { //the Voice class allocate() method allocates this voice kevin.allocate(); } if (kevin16 != null){ kevin16.allocate(); } } public static void main(String[] args) { final ChantControlPanel ccp = new ChantControlPanel(); final JFrame theFrame = ccp.getTheFrame(); theFrame.pack(); theFrame.revalidate(); theFrame.setVisible(true); /* for (String s: args) { System.out.println(s); } int timesToSayKevin = 1000000; boolean infinite_kevins = false; if (args.length > 0){ try{ timesToSayKevin = Integer.parseInt(args[0]); if (timesToSayKevin < 0){ throw new IllegalArgumentException(); } else if (timesToSayKevin == 0){ System.out.println("0 specified in command line; I'm assuming you want infinite kevins."); infinite_kevins = true; } } catch (NumberFormatException e){ System.out.printf("%s is not an integer!",args[0]); System.exit(1); } catch (IllegalArgumentException e2){ System.out.printf("%d must be an integer greater than 0!", timesToSayKevin); System.exit(1); } } else { System.out.println("No command line argument specified!"); } JFrame jf = new JFrame("KevinFrame"); JButton jb = new JButton("STOP"); try (KevinChanter kc = new KevinChanter(new ChantControlStopperLoggerInterface() {})){ if (infinite_kevins){ kc.say_kevin_infinitely(); } else { System.out.printf("Saying Kevin %d times!", timesToSayKevin); System.out.println(); //kc.testSpeaking(); //kc.one_voice_say_twice_at_once("kevin"); //kc.one_voice_say_twice_at_once("kevin", kc.kevin16); kc.handle_saying_kevin_x_times(timesToSayKevin); } } catch (Exception e){ e.printStackTrace(); } */ } } interface ChantControlStopperLoggerInterface{ default boolean keepGoing(){ return true; } default void logInfo(String infoToLog){ System.out.println(infoToLog); } } /** * A totes legit GUI for controlling this stuff */ class ChantControlPanel implements ChantControlStopperLoggerInterface { private boolean keepGoing = true; private final JFrame theFrame = new JFrame("Kevin Chanter Control Window"); private final JTextArea textArea = new JTextArea(20, 60); private boolean canStartTheChanting = true; private final KevinChanter kc; private final String[] infoStrings = new String[20]; private int infoStringsCurrentCursor = -1; private long start_time = 0L; ChantControlPanel(){ Arrays.fill(infoStrings, ""); theFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); final Container contentPane = theFrame.getContentPane(); final BoxLayout boxLayout = new BoxLayout(contentPane, BoxLayout.Y_AXIS); contentPane.setLayout(boxLayout); contentPane.add(new JLabel("Some sort of control panel thing.")); final Border etchedBorder = BorderFactory.createEtchedBorder(); final JPanel startButtonPanel = new JPanel(); startButtonPanel.setLayout(new GridLayout(3,1)); startButtonPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder, "Start it!")); final JButton startMillionButton = new JButton("Start saying Kevin 1 million times"); startMillionButton.addActionListener( e -> this.startSayingKevin(1000000) ); final JButton startInfiniteButton = new JButton("Start saying Kevin infinitely many times"); startInfiniteButton.addActionListener( e -> this.startSayingInfiniteKevins() ); final JButton startChoiceButton = new JButton("Pick how many times to say Kevin"); startChoiceButton.addActionListener( e -> this.startSayingKevinUserInputTimes() ); startButtonPanel.add(startMillionButton); startButtonPanel.add(startInfiniteButton); startButtonPanel.add(startChoiceButton); contentPane.add(startButtonPanel); final JPanel stopButtonPanel = new JPanel(new BorderLayout()); stopButtonPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder, "EMERGENCY STOP")); final JButton stopButton = new JButton("STOP EVERYTHING!"); stopButton.addActionListener( e -> this.stopEverything() ); stopButtonPanel.add(stopButton, BorderLayout.CENTER); contentPane.add(stopButtonPanel); final JPanel logPanel = new JPanel(); logPanel.setLayout(new BorderLayout()); logPanel.setBorder(BorderFactory.createTitledBorder(etchedBorder, "LOGGED INFO")); textArea.setEditable(false); textArea.setLineWrap(true); //textArea.setText(String.join("\n",infoStrings)); final JScrollPane scrollPane = new JScrollPane( textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); logPanel.add(scrollPane); contentPane.add(logPanel); kc = new KevinChanter(this); theFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); theFrame.addWindowListener( new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { stopEverything(); try { kc.close(); } catch (Exception ignored) { } } } ); } public JFrame getTheFrame() { return theFrame; } void stopEverything(){ keepGoing = false; logInfo("WAIT!! [$!?!] THE PRESSES!"); } private void chantingIsOver(){ final long end_time = System.currentTimeMillis(); canStartTheChanting = true; logInfo("Chanting has ended!"); logInfo(String.format("Chanting ended after %f seconds", (end_time-start_time)/1000d)); } private void startSayingInfiniteKevins(){ if (canStartTheChanting) { canStartTheChanting = false; keepGoing = true; Thread kc_runner = new Thread( () -> { Thread kc_thread = new Thread( kc::say_kevin_infinitely ); kc_thread.start(); try { kc_thread.join(); } catch (InterruptedException e){ e.printStackTrace(); } chantingIsOver(); } ); start_time = System.currentTimeMillis(); kc_runner.start(); logInfo("The infinite Kevin chant has started!"); } else { JOptionPane.showMessageDialog( theFrame, "Please stop the current chant before attempting to start a new one.", "Can't chant twice at once!", JOptionPane.WARNING_MESSAGE ); } } private void startSayingKevinUserInputTimes(){ final String input = JOptionPane.showInputDialog( theFrame, "Please enter how many times you want to say Kevin.", "How many Kevins?", JOptionPane.QUESTION_MESSAGE ); try{ final int times = Integer.parseInt(input); startSayingKevin(times); } catch (NumberFormatException e){ JOptionPane.showMessageDialog( theFrame, "Please enter an integer instead.", "Invalid number of Kevins!", JOptionPane.ERROR_MESSAGE ); } } private void startSayingKevin(int times){ if (canStartTheChanting) { if (times < 1){ JOptionPane.showMessageDialog( theFrame, "Please enter a number greater than 0.", "Invalid number of Kevins!", JOptionPane.ERROR_MESSAGE ); return; } canStartTheChanting = false; keepGoing= true; Thread kc_runner = new Thread( () -> { Thread kc_thread = new Thread( () -> kc.handle_saying_kevin_x_times(times) ); kc_thread.start(); try { kc_thread.join(); } catch (InterruptedException e){ e.printStackTrace(); } chantingIsOver(); } ); start_time = System.currentTimeMillis(); kc_runner.start(); logInfo(String.format("Now chanting %d times!",times)); } else { JOptionPane.showMessageDialog( theFrame, "Please stop the current chant before attempting to start a new one.", "Can't chant twice at once!", JOptionPane.WARNING_MESSAGE ); } } @Override public boolean keepGoing() { return keepGoing; } @Override public void logInfo(String infoToLog) { infoStringsCurrentCursor += 1; if (infoStringsCurrentCursor >= infoStrings.length){ infoStringsCurrentCursor = 0; } infoStrings[infoStringsCurrentCursor] = infoToLog + "\n"; StringBuilder infoBuilder = new StringBuilder(infoStrings.length); for (int i = infoStringsCurrentCursor; i >= 0; i--) { infoBuilder.append(infoStrings[i]); } for (int i = infoStrings.length-1; i > infoStringsCurrentCursor; i--){ infoBuilder.append(infoStrings[i]); } textArea.setText(infoBuilder.toString()); } }
package com.cqust.mapper; import com.cqust.pojo.TItemcollocation; import com.cqust.pojo.TItemcollocationExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface TItemcollocationMapper { int countByExample(TItemcollocationExample example); int deleteByExample(TItemcollocationExample example); int deleteByPrimaryKey(Integer id); int insert(TItemcollocation record); int insertSelective(TItemcollocation record); List<TItemcollocation> selectByExample(TItemcollocationExample example); TItemcollocation selectByPrimaryKey(Integer id); int updateByExampleSelective(@Param("record") TItemcollocation record, @Param("example") TItemcollocationExample example); int updateByExample(@Param("record") TItemcollocation record, @Param("example") TItemcollocationExample example); int updateByPrimaryKeySelective(TItemcollocation record); int updateByPrimaryKey(TItemcollocation record); }
/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.map.impl.operation; import com.hazelcast.core.ManagedContext; import com.hazelcast.internal.serialization.SerializationService; import com.hazelcast.map.EntryBackupProcessor; import com.hazelcast.map.EntryProcessor; import com.hazelcast.map.impl.record.Record; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.Data; import com.hazelcast.query.Predicate; import com.hazelcast.query.TruePredicate; import com.hazelcast.query.impl.FalsePredicate; import com.hazelcast.query.impl.QueryableEntry; import com.hazelcast.spi.BackupAwareOperation; import com.hazelcast.spi.Operation; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * GOTCHA : This operation does NOT load missing keys from map-store for now. */ public class PartitionWideEntryOperation extends AbstractMultipleEntryOperation implements BackupAwareOperation { public PartitionWideEntryOperation(String name, EntryProcessor entryProcessor) { super(name, entryProcessor); } public PartitionWideEntryOperation() { } @Override public void innerBeforeRun() throws Exception { super.innerBeforeRun(); final SerializationService serializationService = getNodeEngine().getSerializationService(); final ManagedContext managedContext = serializationService.getManagedContext(); managedContext.initialize(entryProcessor); } @Override public void run() { long now = getNow(); Iterator<Record> iterator = recordStore.iterator(now, false); while (iterator.hasNext()) { Record record = iterator.next(); Data dataKey = record.getKey(); Object oldValue = record.getValue(); if (!applyPredicate(dataKey, oldValue)) { continue; } Map.Entry entry = createMapEntry(dataKey, oldValue); Data response = process(entry); addToResponses(dataKey, response); // first call noOp, other if checks below depends on it. if (noOp(entry, oldValue)) { continue; } if (entryRemoved(entry, dataKey, oldValue, now)) { continue; } entryAddedOrUpdated(entry, dataKey, oldValue, now); evict(); } } @Override public Object getResponse() { return responses; } @Override public boolean shouldBackup() { return entryProcessor.getBackupProcessor() != null; } @Override public int getSyncBackupCount() { return 0; } @Override public int getAsyncBackupCount() { return mapContainer.getTotalBackupCount(); } @Override public Operation getBackupOperation() { EntryBackupProcessor backupProcessor = entryProcessor.getBackupProcessor(); return backupProcessor != null ? new PartitionWideEntryBackupOperation(name, backupProcessor) : null; } private boolean applyPredicate(Data key, Object value) { Predicate predicate = getPredicate(); if (predicate == null || TruePredicate.INSTANCE == predicate) { return true; } if (FalsePredicate.INSTANCE == predicate) { return false; } QueryableEntry queryEntry = mapContainer.newQueryEntry(key, value); return getPredicate().apply(queryEntry); } protected Predicate getPredicate() { return null; } @Override protected void readInternal(ObjectDataInput in) throws IOException { super.readInternal(in); entryProcessor = in.readObject(); } @Override protected void writeInternal(ObjectDataOutput out) throws IOException { super.writeInternal(out); out.writeObject(entryProcessor); } }
package com.codepath.cpw1instagram; import android.text.Html; import android.text.Spanned; /** * Created by qi_zhu on 2/4/16. */ public class Comment { public int createdTime; public String userName; public String text; public String profileUrl; public Spanned shortLine() { return Html.fromHtml("<font color=#ADD8E6>" + this.userName + "</font> " + this.text); } }
package com.stevotvr.aoc2020; import java.util.List; public class Day09 extends Solution { @Override public Object getPart1Solution() { return getKey(getInput()); } @Override public Object getPart2Solution() { final long[] list = getInput(); final long key = getKey(list); for (int i = 0; i < list.length; i++) { long sum = 0; for (int j = i; j < list.length; j++) { sum += list[j]; if (sum > key) { break; } if (sum == key) { long min = Long.MAX_VALUE; long max = Long.MIN_VALUE; for (int k = i; k <= j; k++) { min = Long.min(min, list[k]); max = Long.max(max, list[k]); } return min + max; } } } return null; } private long[] getInput() { final List<String> input = getInputLines(); final long[] list = new long[input.size()]; for (int i = 0; i < list.length; i++) { list[i] = Long.parseLong(input.get(i)); } return list; } private static long getKey(long[] list) { for (int i = 0; i < list.length - 25; i++) { boolean valid = false; for (int j = i; j < i + 25; j++) { for (int k = i; k < i + 25; k++) { if (j == k) { continue; } if (list[j] + list[k] == list[i + 25]) { valid = true; j = i + 25; break; } } } if (!valid) { return list[i + 25]; } } return 0; } }
// -------------------------------------------------------------------------------- // Copyright 2002-2022 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -------------------------------------------------------------------------------- package com.echothree.ui.web.main.action.configuration.securityrolegroup; import com.echothree.ui.web.main.framework.MainBaseDeleteActionForm; import com.echothree.view.client.web.struts.sprout.annotation.SproutForm; @SproutForm(name="SecurityRoleGroupDelete") public class DeleteActionForm extends MainBaseDeleteActionForm { private String securityRoleGroupName; private String parentSecurityRoleGroupName; public void setSecurityRoleGroupName(String securityRoleGroupName) { this.securityRoleGroupName = securityRoleGroupName; } public String getSecurityRoleGroupName() { return securityRoleGroupName; } public String getParentSecurityRoleGroupName() { return parentSecurityRoleGroupName; } public void setParentSecurityRoleGroupName(String parentSecurityRoleGroupName) { this.parentSecurityRoleGroupName = parentSecurityRoleGroupName; } }
package com.cnec5.it.selfservice.provider.domain; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.Date; @Data @Table(name = "admin_user") public class AdminUser implements Serializable { private static final long serialVersionUID = -6963142547079460655L; @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") private Long id; @Column(name = "username") private String username; @Column(name = "`password`") private String password; /** * 头像 */ @Column(name = "icon") private String icon; /** * 邮箱 */ @Column(name = "email") private String email; /** * 昵称 */ @Column(name = "nick_name") private String nickName; /** * 备注信息 */ @Column(name = "note") private String note; /** * 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "create_time") private Date createTime; /** * 最后登录时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Column(name = "login_time") private Date loginTime; /** * 账号启用状态:0->禁用;1->启用 */ @Column(name = "`status`") private Integer status; }
package frame; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyVetoException; import javax.swing.JButton; import javax.swing.JDesktopPane; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import utils.ClassNameTreeCellRenderer; import utils.EditorUtils; import utils.FrameFactory; import utils.ReadLinkmanXMl; import utils.ReceiveMailTable; /** * 主界面 * @author caesar * @version Copyright(C) SCU. 2016 */ public class MainFrame extends JFrame implements ActionListener, MouseListener { private static final long serialVersionUID = 1L; private static JDesktopPane desktopPane = null;// 用于创建多文档界面或虚拟桌面的容器 public static MainFrame MAINFRAME; private JTree tree;// 树形图 private JList jl;// 联系人列表 private JPanel panel, panelframe;// panelframe左半部界面 private JLabel labelbackground; private JScrollPane scrollPane; private JMenuItem exitMI = null, newMailMI = null, sendedMI = null, receiveMI = null, recycleMI = null, refreshMI = null, groupMailMI = null, helpMI = null,aboutMI = null; private JButton addLinkmanButton = null;// 添加联系人按钮 private JMenu fileMenu = null; private JMenu mailMenu = null; private JMenu aboutMenu = null; private ReadLinkmanXMl readLinkman = null; // 初始化界面配置 public void jFrameValidate() { Toolkit tk = getToolkit();// 获得屏幕的宽和高 Dimension dim = tk.getScreenSize(); this.setBounds(dim.width / 2 - 420, dim.height / 2 - 350, 850, 678); validate(); this.setResizable(false); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public MainFrame() { super("SCU邮件客户端"); MAINFRAME = this; this.setIconImage(EditorUtils.createIcon("email.png").getImage()); desktopPane = new JDesktopPane(); jFrameValidate();// 初始化界面 JMenuBar menuBar = new JMenuBar(); this.setJMenuBar(menuBar); fileMenu = new JMenu("文件(F)"); mailMenu = new JMenu("邮件(M)"); aboutMenu = new JMenu("帮助(H)"); menuBar.add(fileMenu); menuBar.add(mailMenu); menuBar.add(aboutMenu); exitMI = addMenuItem(fileMenu, "退出", "exit.gif");// 退出菜单项的初始化 newMailMI = addMenuItem(mailMenu, "新建邮件", "newMail.gif");// 新建邮件菜单项的初始化 groupMailMI = addMenuItem(mailMenu,"新建群邮件","newGroup.jpg"); //发送群邮件菜单项初始化 sendedMI = addMenuItem(mailMenu, "发件箱", "sended.png");// 已发送邮件菜单项的初始化 receiveMI = addMenuItem(mailMenu, "收件箱", "receive.png");// 收件箱邮件菜单项的初始化 recycleMI = addMenuItem(mailMenu, "回收站", "deleted.png");// 已删除邮件菜单项的初始化 refreshMI = addMenuItem(mailMenu, "刷新收件箱", "refresh.jpg");// 已删除邮件菜单项的初始化 helpMI = addMenuItem(aboutMenu,"帮助文档","help.png"); //帮助文档菜单项初始化 aboutMI = addMenuItem(aboutMenu,"关于我们","aboutUs.png"); // 关于我们菜单项的初始化 // 构建树形节点 DefaultMutableTreeNode root = new DefaultMutableTreeNode("SCU邮件客户端"); DefaultMutableTreeNode send = new DefaultMutableTreeNode("新建邮件"); DefaultMutableTreeNode sendGroup = new DefaultMutableTreeNode("新建群邮件"); DefaultMutableTreeNode addressee = new DefaultMutableTreeNode("收件箱"); DefaultMutableTreeNode AlreadySend = new DefaultMutableTreeNode("发件箱"); DefaultMutableTreeNode delete = new DefaultMutableTreeNode("回收站"); root.add(send); root.add(sendGroup); root.add(addressee); root.add(AlreadySend); root.add(delete); tree = new JTree(root); tree.addMouseListener(this);// 为树形节点注册鼠标事件 tree.setPreferredSize(new Dimension(160, 650)); //tree.setBackground(Color.GRAY); // 重新渲染树形节点 ClassNameTreeCellRenderer render = new ClassNameTreeCellRenderer(); tree.setCellRenderer(render); // 联系人面板 panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setPreferredSize(new Dimension(160, 300)); // 界面左半部面板 panelframe = new JPanel(); panelframe.setLayout(new BorderLayout()); panelframe.add(panel, BorderLayout.CENTER); panelframe.add(tree, BorderLayout.NORTH); addLinkmanButton = new JButton(); addLinkmanButton.setText("联系人"); addLinkmanButton.setIcon(EditorUtils.createIcon("linkman.gif")); panel.add(addLinkmanButton, BorderLayout.NORTH); addLinkmanButton.addActionListener(this);// 注册添加联系人事件 readLinkman = new ReadLinkmanXMl(); jl = readLinkman.makeList();// 返回联系人列表 jl.addMouseListener(this);// 添加联系人列表双击事件 scrollPane = new JScrollPane(); panel.add(scrollPane, BorderLayout.CENTER); scrollPane.setViewportView(jl);// 在滚动面板中添加联系人 validate(); labelbackground = new JLabel(); labelbackground.setIcon(null); // 窗体背景 desktopPane.addComponentListener(new ComponentAdapter() { public void componentResized(final ComponentEvent e) { Dimension size = e.getComponent().getSize(); labelbackground.setSize(e.getComponent().getSize()); // 设置窗体背景图 labelbackground.setText("<html><img width=" + size.width + " height=" + size.height + " src='" + this.getClass().getResource("/main.jpg") + "'></html>"); } }); desktopPane.add(labelbackground, new Integer(Integer.MIN_VALUE)); // 添加一个分割窗口 JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panelframe, desktopPane); splitPane.setOneTouchExpandable(true);// 在分隔条上提供一个 UI 小部件来快速展开/折叠分隔条 splitPane.setDividerSize(10);// 设置分隔条的大小 getContentPane().add(splitPane, BorderLayout.CENTER); } // 返回新建菜单项 private JMenuItem addMenuItem(JMenu menu, String name, String icon) { // 新建邮件菜单项的初始化 JMenuItem menuItem = new JMenuItem(name, EditorUtils.createIcon(icon)); menuItem.addActionListener(this);// 监听退出菜单项事件 menu.add(menuItem); return menuItem; } // 添加子窗体的方法 public static void addIFame(JInternalFrame iframe) { JInternalFrame[] frames = desktopPane.getAllFrames(); try { for (JInternalFrame ifm : frames) { if (ifm.getTitle().equals(iframe.getTitle())) { desktopPane.selectFrame(true); ifm.toFront(); ifm.setSelected(true); return; } } desktopPane.add(iframe); iframe.setSelected(true); iframe.toFront(); } catch (PropertyVetoException e) { e.printStackTrace(); } } // action事件的处理 @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == exitMI) { System.exit(0);// 退出系统 } else if (e.getSource() == addLinkmanButton) { addIFame(FrameFactory.getFrameFactory().getAddLinkManFrame());// 联系人列表 } else if (e.getSource() == newMailMI) {// 新建邮件 addIFame(FrameFactory.getFrameFactory().getSendFrame());// 发件夹 } else if (e.getSource() == groupMailMI) { // 新建群邮件 addIFame(FrameFactory.getFrameFactory().getSendGroupMailFrame()); //新建群邮件 } else if (e.getSource() == itemPopupOne || e.getSource() == refreshMI) {// 右键刷新收件列表 ReceiveMailTable.getMail2Table().startReceiveMail();// 右键刷新收件列表 } else if (e.getSource() == sendedMI) {// 已发送 addIFame(FrameFactory.getFrameFactory().getSendedFrame());// 已发送 } else if (e.getSource() == receiveMI) {// 收邮件 addIFame(FrameFactory.getFrameFactory().getReceiveFrame());// 收邮件 } else if (e.getSource() == recycleMI) {// 已删除 addIFame(FrameFactory.getFrameFactory().getRecycleFrame());// 收邮件 } else if (e.getSource() == helpMI) { //帮助文档 addIFame(FrameFactory.getFrameFactory().getHelpContentsFrame()); // 帮助文档 } else if (e.getSource() == aboutMI) { //关于我们 addIFame (FrameFactory.getFrameFactory().getAboutUsFrame()); //关于我们 } } private SendFrame sendFrame = null;// 发送邮件对象 public JMenuItem itemPopupOne = null;// 鼠标右键第一个选项 @Override public void mouseClicked(MouseEvent e) { // 树形节点中的单击事件 DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree .getLastSelectedPathComponent(); if (e.getSource() == tree && e.getButton() != 3 && e.getButton() != 2) { if (selectedNode == null) return; else if (selectedNode.toString().equals("新建邮件")) { sendFrame = FrameFactory.getFrameFactory().getSendFrame(); addIFame(sendFrame);// 发件夹 } else if (selectedNode.toString().equals("新建群邮件")) { addIFame(FrameFactory.getFrameFactory().getSendGroupMailFrame()); //新建群邮件 } else if (selectedNode.toString().equals("收件箱")) { addIFame(FrameFactory.getFrameFactory().getReceiveFrame());// 收件夹 } else if (selectedNode.toString().equals("发件箱")) { addIFame(FrameFactory.getFrameFactory().getSendedFrame());// 已发送邮件 } else if (selectedNode.toString().equals("回收站")) { addIFame(FrameFactory.getFrameFactory().getRecycleFrame());// 已删除邮件 } } else if (e.getSource() == jl && e.getClickCount() == 2) {// 双击联系人事件 int index = jl.getSelectedIndex(); if (sendFrame != null && sendFrame.isSelected()) {// 如果发送邮件界面被初始化并且被激活 sendFrame.addLinkman(readLinkman.findLinkman(index)); } } else if (e.getButton() == MouseEvent.BUTTON3 && e.getSource() == tree) {// 收件箱右键刷新 if (selectedNode == null) return; else if ("收件箱".equals(selectedNode.toString())) { JPopupMenu popup = new JPopupMenu(); itemPopupOne = new JMenuItem("刷新收件箱", EditorUtils.createIcon("refresh.jpg")); itemPopupOne.addActionListener(this); popup.add(itemPopupOne); popup.show(e.getComponent(), e.getX(), e.getY()); } } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony.cdma; import java.util.HashMap; import android.media.ToneGenerator; public class SignalToneUtil { /** A marker that isn't a valid TONE */ public static final int CDMA_INVALID_TONE = -1; // public final int int IS95_CONST_IR_SIGNAL_TYPE_TYPE; static public final int IS95_CONST_IR_SIGNAL_TONE = 0; static public final int IS95_CONST_IR_SIGNAL_ISDN = 1; static public final int IS95_CONST_IR_SIGNAL_IS54B = 2; static public final int IS95_CONST_IR_SIGNAL_USR_DEFD_ALERT = 4; // public final int int IS95_CONST_IR_ALERT_PITCH_TYPE; static public final int IS95_CONST_IR_ALERT_MED = 0; static public final int IS95_CONST_IR_ALERT_HIGH = 1; static public final int IS95_CONST_IR_ALERT_LOW = 2; // Based on 3GPP2 C.S0005-E, section 3.7.5.5 Signal, // set TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN to 0 to avoid // the alert pitch to be involved in hash calculation for // signal type other than IS54B. static public final int TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN = 0; // public final int int IS95_CONST_IR_SIGNAL_TYPE; static public final int IS95_CONST_IR_SIG_ISDN_NORMAL = 0; static public final int IS95_CONST_IR_SIG_ISDN_INTGRP = 1; static public final int IS95_CONST_IR_SIG_ISDN_SP_PRI = 2; static public final int IS95_CONST_IR_SIG_ISDN_PAT_3 = 3; static public final int IS95_CONST_IR_SIG_ISDN_PING = 4; static public final int IS95_CONST_IR_SIG_ISDN_PAT_5 = 5; static public final int IS95_CONST_IR_SIG_ISDN_PAT_6 = 6; static public final int IS95_CONST_IR_SIG_ISDN_PAT_7 = 7; static public final int IS95_CONST_IR_SIG_ISDN_OFF = 15; static public final int IS95_CONST_IR_SIG_TONE_DIAL = 0; static public final int IS95_CONST_IR_SIG_TONE_RING = 1; static public final int IS95_CONST_IR_SIG_TONE_INT = 2; static public final int IS95_CONST_IR_SIG_TONE_ABB_INT = 3; static public final int IS95_CONST_IR_SIG_TONE_REORDER = 4; static public final int IS95_CONST_IR_SIG_TONE_ABB_RE = 5; static public final int IS95_CONST_IR_SIG_TONE_BUSY = 6; static public final int IS95_CONST_IR_SIG_TONE_CONFIRM = 7; static public final int IS95_CONST_IR_SIG_TONE_ANSWER = 8; static public final int IS95_CONST_IR_SIG_TONE_CALL_W = 9; static public final int IS95_CONST_IR_SIG_TONE_PIP = 10; static public final int IS95_CONST_IR_SIG_TONE_NO_TONE = 63; static public final int IS95_CONST_IR_SIG_IS54B_NO_TONE = 0; static public final int IS95_CONST_IR_SIG_IS54B_L = 1; static public final int IS95_CONST_IR_SIG_IS54B_SS = 2; static public final int IS95_CONST_IR_SIG_IS54B_SSL = 3; static public final int IS95_CONST_IR_SIG_IS54B_SS_2 = 4; static public final int IS95_CONST_IR_SIG_IS54B_SLS = 5; static public final int IS95_CONST_IR_SIG_IS54B_S_X4 = 6; static public final int IS95_CONST_IR_SIG_IS54B_PBX_L = 7; static public final int IS95_CONST_IR_SIG_IS54B_PBX_SS = 8; static public final int IS95_CONST_IR_SIG_IS54B_PBX_SSL = 9; static public final int IS95_CONST_IR_SIG_IS54B_PBX_SLS = 10; static public final int IS95_CONST_IR_SIG_IS54B_PBX_S_X4 = 11; static public final int IS95_CONST_IR_SIG_TONE_ABBR_ALRT = 0; // Hashmap to map signalInfo To AudioTone static private HashMap<Integer, Integer> mHm = new HashMap<Integer, Integer>(); private static Integer signalParamHash(int signalType, int alertPitch, int signal) { if ((signalType < 0) || (signalType > 256) || (alertPitch > 256) || (alertPitch < 0) || (signal > 256) || (signal < 0)) { return new Integer(CDMA_INVALID_TONE); } // Based on 3GPP2 C.S0005-E, seciton 3.7.5.5 Signal, // the alert pitch field is ignored by the mobile station unless // SIGNAL_TYPE is '10',IS-54B Alerting. // Set alert pitch to TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN // so the alert pitch is not involved in hash calculation // when signal type is not IS-54B. if (signalType != IS95_CONST_IR_SIGNAL_IS54B) { alertPitch = TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN; } return new Integer(signalType * 256 * 256 + alertPitch * 256 + signal); } public static int getAudioToneFromSignalInfo(int signalType, int alertPitch, int signal) { Integer result = mHm.get(signalParamHash(signalType, alertPitch, signal)); if (result == null) { return CDMA_INVALID_TONE; } return result; } static { /* SIGNAL_TYPE_ISDN */ mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_NORMAL), ToneGenerator.TONE_CDMA_CALL_SIGNAL_ISDN_NORMAL); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_INTGRP), ToneGenerator.TONE_CDMA_CALL_SIGNAL_ISDN_INTERGROUP); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_SP_PRI), ToneGenerator.TONE_CDMA_CALL_SIGNAL_ISDN_SP_PRI); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_PAT_3), ToneGenerator.TONE_CDMA_CALL_SIGNAL_ISDN_PAT3); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_PING), ToneGenerator.TONE_CDMA_CALL_SIGNAL_ISDN_PING_RING); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_PAT_5), ToneGenerator.TONE_CDMA_CALL_SIGNAL_ISDN_PAT5); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_PAT_6), ToneGenerator.TONE_CDMA_CALL_SIGNAL_ISDN_PAT6); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_PAT_7), ToneGenerator.TONE_CDMA_CALL_SIGNAL_ISDN_PAT7); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_ISDN, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_ISDN_OFF), ToneGenerator.TONE_CDMA_SIGNAL_OFF); /* SIGNAL_TYPE_TONE */ mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_DIAL), ToneGenerator.TONE_CDMA_DIAL_TONE_LITE); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_RING), ToneGenerator.TONE_CDMA_NETWORK_USA_RINGBACK); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_INT), ToneGenerator.TONE_SUP_INTERCEPT); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_ABB_INT), ToneGenerator.TONE_SUP_INTERCEPT_ABBREV); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_REORDER), ToneGenerator.TONE_CDMA_REORDER); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_ABB_RE), ToneGenerator.TONE_CDMA_ABBR_REORDER); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_BUSY), ToneGenerator.TONE_CDMA_NETWORK_BUSY); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_CONFIRM), ToneGenerator.TONE_SUP_CONFIRM); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_ANSWER), ToneGenerator.TONE_CDMA_ANSWER); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_CALL_W), ToneGenerator.TONE_CDMA_NETWORK_CALLWAITING); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_PIP), ToneGenerator.TONE_CDMA_PIP); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_TONE, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_NO_TONE), ToneGenerator.TONE_CDMA_SIGNAL_OFF); /* SIGNAL_TYPE_IS54B */ mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_L), ToneGenerator.TONE_CDMA_HIGH_L); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_L), ToneGenerator.TONE_CDMA_MED_L); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_L), ToneGenerator.TONE_CDMA_LOW_L); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_SS), ToneGenerator.TONE_CDMA_HIGH_SS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_SS), ToneGenerator.TONE_CDMA_MED_SS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_SS), ToneGenerator.TONE_CDMA_LOW_SS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_SSL), ToneGenerator.TONE_CDMA_HIGH_SSL); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_SSL), ToneGenerator.TONE_CDMA_MED_SSL); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_SSL), ToneGenerator.TONE_CDMA_LOW_SSL); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_SS_2), ToneGenerator.TONE_CDMA_HIGH_SS_2); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_SS_2), ToneGenerator.TONE_CDMA_MED_SS_2); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_SS_2), ToneGenerator.TONE_CDMA_LOW_SS_2); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_SLS), ToneGenerator.TONE_CDMA_HIGH_SLS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_SLS), ToneGenerator.TONE_CDMA_MED_SLS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_SLS), ToneGenerator.TONE_CDMA_LOW_SLS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_S_X4), ToneGenerator.TONE_CDMA_HIGH_S_X4); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_S_X4), ToneGenerator.TONE_CDMA_MED_S_X4); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_S_X4), ToneGenerator.TONE_CDMA_LOW_S_X4); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_PBX_L), ToneGenerator.TONE_CDMA_HIGH_PBX_L); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_PBX_L), ToneGenerator.TONE_CDMA_MED_PBX_L); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_PBX_L), ToneGenerator.TONE_CDMA_LOW_PBX_L); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_PBX_SS), ToneGenerator.TONE_CDMA_HIGH_PBX_SS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_PBX_SS), ToneGenerator.TONE_CDMA_MED_PBX_SS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_PBX_SS), ToneGenerator.TONE_CDMA_LOW_PBX_SS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_PBX_SSL), ToneGenerator.TONE_CDMA_HIGH_PBX_SSL); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_PBX_SSL), ToneGenerator.TONE_CDMA_MED_PBX_SSL); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_PBX_SSL), ToneGenerator.TONE_CDMA_LOW_PBX_SSL); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_PBX_SLS), ToneGenerator.TONE_CDMA_HIGH_PBX_SLS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_PBX_SLS), ToneGenerator.TONE_CDMA_MED_PBX_SLS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_PBX_SLS), ToneGenerator.TONE_CDMA_LOW_PBX_SLS); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_HIGH, IS95_CONST_IR_SIG_IS54B_PBX_S_X4), ToneGenerator.TONE_CDMA_HIGH_PBX_S_X4); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_MED, IS95_CONST_IR_SIG_IS54B_PBX_S_X4), ToneGenerator.TONE_CDMA_MED_PBX_S_X4); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, IS95_CONST_IR_ALERT_LOW, IS95_CONST_IR_SIG_IS54B_PBX_S_X4), ToneGenerator.TONE_CDMA_LOW_PBX_S_X4); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_IS54B, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_IS54B_NO_TONE), ToneGenerator.TONE_CDMA_SIGNAL_OFF); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_USR_DEFD_ALERT, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_ABBR_ALRT), ToneGenerator.TONE_CDMA_ABBR_ALERT); mHm.put(signalParamHash(IS95_CONST_IR_SIGNAL_USR_DEFD_ALERT, TAPIAMSSCDMA_SIGNAL_PITCH_UNKNOWN, IS95_CONST_IR_SIG_TONE_NO_TONE), ToneGenerator.TONE_CDMA_ABBR_ALERT); } // suppress default constructor for noninstantiability private SignalToneUtil() { } }
package me.gaigeshen.wechat.mp.user; import lombok.Getter; import me.gaigeshen.wechat.mp.AbstractResponse; /** * 获取标签列表结果 * * @author gaigeshen */ @Getter public class TagListResponse extends AbstractResponse { private Tag[] tags; public static class Tag { private Long id; private String name; private Long count; // 此标签下的粉丝数 } }
package com.teamgannon.trips.solarsysmodelling.accrete; import static java.lang.Math.pow; public class SimStar extends SystemObject { /** * Amount by which individual stars might vary from their base type */ public final static double STELLAR_DEVIATION = 0.05; protected String stellarType = ""; protected String name = ""; protected String desig = ""; protected int red = 0; protected int green = 0; protected int blue = 0; protected double luminosity = 0.0; protected double radius = 0.0; protected double temperature = 0.0; protected double absoluteMagnitude = 0.0; protected double lifeTime = 0.0; protected double age = 0.0; protected double radiusEcosphere = 0.0; protected double M2 = 0.0; protected double A = 0.0; protected double E = 0.0; public SimStar(double stellarMass, double stellarLuminosity, double stellarRadius, double temp, double mag) { this.mass = stellarMass; this.luminosity = stellarLuminosity; this.radius = stellarRadius; this.temperature = temp; this.absoluteMagnitude = mag; this.radiusEcosphere = Math.sqrt(luminosity); // is this accurate? Presumably this scales with the inverse square law, so it sounds right. this.lifeTime = 1.0E10 * (mass / luminosity); recalc(); } public void recalc() { // http://hyperphysics.phy-astr.gsu.edu/hbase/Astro/startime.html this.lifeTime = 10E10 * pow(this.mass, 2.5); } public void setAge() { if (lifeTime < 6.0E9) { this.age = Utils.instance().randomNumber(1.0E9, lifeTime); } else { this.age = Utils.instance().randomNumber(1.0E9, 6.0E9); } } /** * set the mass of the sim star * * @param mass the relative mass to the sun */ public void setMass(double mass) { this.mass = mass; } /** * set the radius of the star * * @param radius the relative radius to the sun */ public void setRadius(double radius) { this.radius = radius; } /** * set the luminosity * * @param luminosity the relative luminosity to the sun */ public void setLuminosity(double luminosity) { this.luminosity = luminosity; } /** * set the temperature * * @param temperature the relative temperature to the sun */ public void setTemperature(double temperature) { this.temperature = temperature; } /** * set the absolute magnitude * @param absoluteMagnitude the relative ( :) ) absolute magnitude to the sun */ public void setAbsoluteMagnitude(double absoluteMagnitude) { this.absoluteMagnitude = absoluteMagnitude; } public double stellarDustLimit() { return 200.0 * pow(this.mass, 1.0 / 3.0); } public double innermostPlanet() { return 0.3 * pow(mass, 1.0 / 3.0); // TODO: Check these numbers to ensure accuracy } public double outermostPlanet() { return 50.0 * pow(mass, 1.0 / 3.0); // TODO: Check these numbers to ensure accuracy } /** * @return A copy of this star */ public SimStar copy() { SimStar s = new SimStar(this.mass, this.luminosity, this.radius, this.temperature, this.absoluteMagnitude); s.stellarType = this.stellarType; s.red = this.red; s.green = this.green; s.blue = this.blue; return s; } /** * @return A copy of this star deviated by a random amount */ public SimStar deviate() { SimStar s = this.copy(); double v = Utils.instance().about(STELLAR_DEVIATION, 1); s.mass = s.mass + s.mass * v; s.luminosity = s.luminosity + s.luminosity * v; s.radius = s.radius + s.radius * v; s.temperature = s.temperature + s.temperature * v; s.recalc(); return s; } public String toString() { return stellarType + " (" + String.format("%1$,.2f", mass) + "sm)"; } }
/* * 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.wicket.resource.aggregator; import static org.apache.wicket.markup.head.JavaScriptHeaderItem.forReference; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.wicket.Application; import org.apache.wicket.markup.head.HeaderItem; import org.apache.wicket.markup.head.PriorityHeaderItem; import org.apache.wicket.markup.head.ResourceAggregator; import org.apache.wicket.request.resource.ResourceReference; import org.apache.wicket.resource.CircularDependencyException; import org.apache.wicket.util.tester.WicketTestCase; import org.junit.Before; import org.junit.Test; /** * Tests for the {@link org.apache.wicket.markup.head.ResourceAggregator} class. * * @author Hielke Hoeve */ public class ResourceAggregatorTest extends WicketTestCase { private void assertItems(ResourceReference... references) { List<HeaderItem> items = new ArrayList<HeaderItem>(); for (ResourceReference curReference : references) items.add(forReference(curReference)); assertItems(items); } private void assertItems(HeaderItem... items) { assertItems(Arrays.asList(items)); } private void assertItems(List<HeaderItem> items) { aggregator.close(); assertEquals(items, responseStub.getItems()); } private TestHeaderResponse responseStub; private ResourceAggregator aggregator; /** * Setup the testcase, creating a new header response stub and wrapping it in a resource * aggregator */ @Before public void setup() { responseStub = new TestHeaderResponse(); aggregator = new ResourceAggregator(responseStub); } /** * render [b->a], should render [a,b] */ @Test public void testDependency() { aggregator.render(forReference(new ResourceReferenceB())); assertItems(new ResourceReferenceA(), new ResourceReferenceB()); } /** * render [b->a, c->a], should render [a,b,c] */ @Test public void test2RefsWithDependency() { aggregator.render(forReference(new ResourceReferenceB())); aggregator.render(forReference(new ResourceReferenceC())); assertItems(new ResourceReferenceA(), new ResourceReferenceB(), new ResourceReferenceC()); } /** * render [d->c->a], should render [a, c, d] */ @Test public void testTransitiveDependencies() { aggregator.render(forReference(new ResourceReferenceD())); assertItems(new ResourceReferenceA(), new ResourceReferenceC(), new ResourceReferenceD()); } /** * bundle {a, b->a}, render [a], should render [ab] */ @Test public void testBundle() { HeaderItem bundleAB = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ab.js", new ResourceReferenceA(), new ResourceReferenceB()); aggregator.render(forReference(new ResourceReferenceA())); assertItems(bundleAB); } /** * bundle {a, b->a}, render [b], should render [ab] */ @Test public void testBundleRenderingOther() { HeaderItem bundleAB = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ab.js", new ResourceReferenceA(), new ResourceReferenceB()); aggregator.render(forReference(new ResourceReferenceB())); assertItems(bundleAB); } /** * bundle {a, b->a}, render [a, b], should render [ab] */ @Test public void testBundleRenderingBoth() { HeaderItem bundleAB = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ab.js", new ResourceReferenceA(), new ResourceReferenceB()); aggregator.render(forReference(new ResourceReferenceA())); aggregator.render(forReference(new ResourceReferenceB())); assertItems(bundleAB); } /** * bundle {a, b->a}, render [d->c->a], should render [ab, c, d] */ @Test public void testBundleRenderedAsDependency() { HeaderItem bundleAB = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ab.js", new ResourceReferenceA(), new ResourceReferenceB()); aggregator.render(forReference(new ResourceReferenceD())); assertItems(bundleAB, forReference(new ResourceReferenceC()), forReference(new ResourceReferenceD())); } /** * bundle {c->a, d->c->a}, render [d], should render [a, cd] */ @Test public void testBundleWithDependencies() { HeaderItem bundleCD = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "cd.js", new ResourceReferenceC(), new ResourceReferenceD()); aggregator.render(forReference(new ResourceReferenceD())); assertItems(forReference(new ResourceReferenceA()), bundleCD); } /** * bundle {a, b->a} and {c->a, d->c->a}, render [d], should render [ab, cd] */ @Test public void testTwoBundlesWithDependencies() { HeaderItem bundleAB = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ab.js", new ResourceReferenceA(), new ResourceReferenceB()); HeaderItem bundleCD = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "cd.js", new ResourceReferenceC(), new ResourceReferenceD()); aggregator.render(forReference(new ResourceReferenceD())); assertItems(bundleAB, bundleCD); } /** * bundle {a, b->a} and {c->a, d->c->a}, render [priority(b), d], should render [priority(ab), * cd] */ @Test public void testTwoBundlesWithDependenciesAndPriority() { HeaderItem bundleAB = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ab.js", new ResourceReferenceA(), new ResourceReferenceB()); HeaderItem bundleCD = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "cd.js", new ResourceReferenceC(), new ResourceReferenceD()); aggregator.render(new PriorityHeaderItem(forReference(new ResourceReferenceB()))); aggregator.render(forReference(new ResourceReferenceD())); assertItems(new PriorityHeaderItem(bundleAB), bundleCD); } /** * bundle {a, b->a} and {a, c->a}, should give exception */ @Test(expected = IllegalArgumentException.class) public void testTwoBundlesProvidingSameResource() { Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ab.js", new ResourceReferenceA(), new ResourceReferenceB()); Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ac.js", new ResourceReferenceA(), new ResourceReferenceC()); } /** * render [circ1->circ2->circ1->...], should give exception */ @Test(expected = CircularDependencyException.class) public void testCircularDependency() { aggregator.render(forReference(new ResourceReferenceCirc1())); } /** * bundle {bun1 -> x, bun2 -> y}, render [bun1], should render [x, y, bun12] */ @Test public void testTwoResourcesWithBundleAsDependency() { HeaderItem bundle12 = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "bun12.js", new ResourceReferenceBun1(), new ResourceReferenceBun2()); aggregator.render(forReference(new ResourceReferenceBun1())); assertItems(forReference(new ResourceReferenceX()), forReference(new ResourceReferenceY()), bundle12); } /** * bundle {a, b -> a}, render [x, priority(a)], should render [priority(ab), x] */ @Test public void testBundleWithPriority() { HeaderItem bundleAB = Application.get() .getResourceBundles() .addJavaScriptBundle(Application.class, "ab.js", new ResourceReferenceA(), new ResourceReferenceB()); aggregator.render(forReference(new ResourceReferenceX())); aggregator.render(new PriorityHeaderItem(forReference(new ResourceReferenceA()))); assertItems(new PriorityHeaderItem(bundleAB), forReference(new ResourceReferenceX())); } }
package com.winster.glmall.glmallcoupon.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.winster.glmall.glmallcoupon.entity.CouponEntity; import com.winster.glmall.glmallcoupon.service.CouponService; import com.winster.common.utils.PageUtils; import com.winster.common.utils.R; /** * 优惠券信息 * * @author winster * @email winsterhandsome@gmail.com * @date 2022-02-04 08:04:23 */ @RestController @RequestMapping("glmallcoupon/coupon") public class CouponController { @Autowired private CouponService couponService; /** * 列表 */ @RequestMapping("/list") // @RequiresPermissions("glmallcoupon:coupon:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = couponService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") // @RequiresPermissions("glmallcoupon:coupon:info") public R info(@PathVariable("id") Long id){ CouponEntity coupon = couponService.getById(id); return R.ok().put("coupon", coupon); } /** * 保存 */ @RequestMapping("/save") // @RequiresPermissions("glmallcoupon:coupon:save") public R save(@RequestBody CouponEntity coupon){ couponService.save(coupon); return R.ok(); } /** * 修改 */ @RequestMapping("/update") // @RequiresPermissions("glmallcoupon:coupon:update") public R update(@RequestBody CouponEntity coupon){ couponService.updateById(coupon); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") // @RequiresPermissions("glmallcoupon:coupon:delete") public R delete(@RequestBody Long[] ids){ couponService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
package de.wlsc.management; import static java.util.Locale.GERMANY; import de.wlsc.model.Account; import de.wlsc.model.Customer; import de.wlsc.model.MoneyTransfer; import java.util.Currency; import java.util.UUID; final class AccountTransferCreator { private AccountTransferCreator() { // utility } static Account createJohnsAccount() { Customer john = Customer.builder() .id("cust1") .firstname("first") .lastname("last") .locale(GERMANY) .build(); return Account.builder() .id("acc1") .amount(500) .currency(Currency.getInstance(john.getLocale())) .customer(john) .build(); } static Account createSilversAccount() { Customer silver = Customer.builder() .id("cust2") .firstname("first") .lastname("last") .locale(GERMANY) .build(); return Account.builder() .id("acc2") .amount(2000) .currency(Currency.getInstance(silver.getLocale())) .customer(silver) .build(); } static MoneyTransfer createMoneyTransfer(final Account fromAccount, final Account toAccount, final long amount) { return MoneyTransfer.builder() .id(UUID.randomUUID().toString()) .fromAccountId(fromAccount.getId()) .toAccountId(toAccount.getId()) .amount(amount) .build(); } }
package integrationTest; import io.algobox.microservice.impl.grizzly.GrizzlyMicroService; public class GrizzlyMicroServiceIT extends AbstractMicroServiceIT { public GrizzlyMicroServiceIT() { super(GrizzlyMicroService.class); } }
package com.udn.ntpc.od.common.message.util; import com.udn.ntpc.od.common.message.ErrorCodeEnum; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import java.util.Locale; /** * * error code與訊息轉換的工具類別 * * */ @Slf4j public class MessageUtil { private static ReloadableResourceBundleMessageSource resource ; private static Locale defaultLocale = Locale.getDefault(); /** * Set default locale for message handling * @param locale default locale */ public static void setDefaultLocale(Locale locale) { defaultLocale = locale; } /** * Get default locale for message handling * @return default locale */ public static Locale getDefaultLocale() { return defaultLocale; } /** * 以key取得對應的ResourceBundle Message * * @param key * @return 訊息字串 */ public static String getMessage(ErrorCodeEnum key) { return getMessage(key.toString()); } public static String getMessage(ErrorCodeEnum key, String param) { if (StringUtils.isNotBlank(param)) return getMessage(key.toString(), new Object[]{param}); return getMessage(key.toString()); } public static String getMessage(ErrorCodeEnum key, Object[] params) { if (ArrayUtils.isNotEmpty(params)) return getMessage(key.toString(), params); return getMessage(key.toString()); } /** * 以key, locale取得對應之有參數的ResourceBundle Message * * @param key * @param locale * @param params * @return 訊息字串 */ public static String getMessage(ErrorCodeEnum key, Locale locale, Object[] params) { if (ArrayUtils.isNotEmpty(params)) return getMessage(key.toString(), locale, params); return getMessage(key.toString(), locale); } /** * 以key, locale取得對應的ResourceBundle Message * * @param key * @param locale * @return 訊息字串 */ public static String getMessage(String key, Locale locale) { return getMessage(key, locale, new Object[0]); } /** * 以key取得對應的ResourceBundle Message * * @param key * @return 訊息字串 */ public static String getMessage(String key) { return getMessage(key, getDefaultLocale(), new Object[0]); } /** * 以key取得對應之有參數的ResourceBundle Message * * @param key * @param objs * @return 訊息字串 */ public static String getMessage(String key, Object[] objs) { return getMessage(key, getDefaultLocale(), objs); } /** * 以key, locale取得對應之有參數的ResourceBundle Message * * @param key * @param locale * @param params * @return 訊息字串 */ public static String getMessage(String key, Locale locale, Object[] params) { String message = ""; if (key != null) { try { if (ArrayUtils.isEmpty(params)) { params = ArrayUtils.EMPTY_OBJECT_ARRAY; } locale = (null == locale) ? getDefaultLocale() : locale; message = resource.getMessage(key, params, locale); } catch (NullPointerException | java.util.MissingResourceException e) { log.error("can't find in specified locale resource bundle, key is:" + key); message = key; } } return message; } public ReloadableResourceBundleMessageSource getResource() { return resource; } /** * * @param resource The resouce to set. */ public void setResource(ReloadableResourceBundleMessageSource resource) { MessageUtil.resource = resource; } }
package org.owasp.webgoat; import static org.junit.jupiter.api.DynamicTest.dynamicTest; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import io.restassured.RestAssured; import io.restassured.http.ContentType; import lombok.SneakyThrows; public class IDORTest extends IntegrationTest { @BeforeEach @SneakyThrows public void init() { startLesson("IDOR"); } @TestFactory Iterable<DynamicTest> testIDORLesson() { return Arrays.asList( dynamicTest("login",()-> loginIDOR()), dynamicTest("profile", () -> profile()) ); } @AfterEach public void shutdown() throws IOException { checkResults("/IDOR"); } private void loginIDOR() throws IOException { Map<String, Object> params = new HashMap<>(); params.clear(); params.put("username", "tom"); params.put("password", "cat"); checkAssignment(url("/WebGoat/IDOR/login"), params, true); } private void profile() { Assert.assertThat( RestAssured.given() .when() .relaxedHTTPSValidation() .cookie("JSESSIONID", getWebGoatCookie()) .get(url("/WebGoat/IDOR/profile")) .then() .statusCode(200) .extract().path("userId"), CoreMatchers.is("2342384")); Map<String, Object> params = new HashMap<>(); params.clear(); params.put("attributes", "userId,role"); checkAssignment(url("/WebGoat/IDOR/diff-attributes"), params, true); params.clear(); params.put("url", "WebGoat/IDOR/profile/2342384"); checkAssignment(url("/WebGoat/IDOR/profile/alt-path"), params, true); Assert.assertThat( RestAssured.given() .when() .relaxedHTTPSValidation() .cookie("JSESSIONID", getWebGoatCookie()) .get(url("/WebGoat/IDOR/profile/2342388")) .then() .statusCode(200) .extract().path("lessonCompleted"), CoreMatchers.is(true)); Assert.assertThat( RestAssured.given() .when() .relaxedHTTPSValidation() .cookie("JSESSIONID", getWebGoatCookie()) .contentType(ContentType.JSON) //part of the lesson .body("{\"role\":\"1\", \"color\":\"red\", \"size\":\"large\", \"name\":\"Buffalo Bill\", \"userId\":\"2342388\"}") .put(url("/WebGoat/IDOR/profile/2342388")) .then() .statusCode(200) .extract().path("lessonCompleted"), CoreMatchers.is(true)); } }
package ru.testing.web; import controllers.AllureLogger; import controllers.BaseDesktopTest; import io.qameta.allure.Link; import io.qameta.allure.Owner; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static com.codeborne.selenide.Selenide.open; import static com.codeborne.selenide.Selenide.sleep; @DisplayName("Тест поиска") public class YandexExampleDesktopTest extends BaseDesktopTest { @BeforeEach public void getBase() { setup(); open(BASE_URL); addCookies(); } @Owner(value = "Автор теста") @DisplayName("Пример теста яндекса") @Link(value = "Кейс", url = "https://") @Test public void yandexSearchTest() { String searchQuery = "котики"; yandexSearchPage.yandexSearchField.click(); yandexSearchPage.yandexSearchField.setValue(searchQuery); yandexSearchPage.yandexSearchButton.click(); waitChangeElementProperty(yandexSearchPage.yandexSearchRequest, "value", searchQuery); AllureLogger.info("Инфо лог"); sleep(1000); } @Owner(value = "Автор теста") @DisplayName("Пример теста яндекса") @Link(value = "Кейс", url = "https://") @Test public void yandexSearch2variantTest() { String searchQuery = "котики"; yandexSearchPage.searchByTextInYandexPage(searchQuery); AllureLogger.debug("дебаг лог"); sleep(1000); } }
package io.quarkus.qute; import static io.quarkus.qute.Futures.evaluateParams; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; /** * Basic {@code set} statement. */ public class SetSectionHelper implements SectionHelper { private static final String SET = "set"; private final Map<String, Expression> parameters; SetSectionHelper(Map<String, Expression> parameters) { this.parameters = parameters; } @Override public CompletionStage<ResultNode> resolve(SectionResolutionContext context) { CompletableFuture<ResultNode> result = new CompletableFuture<>(); evaluateParams(parameters, context.resolutionContext()).whenComplete((r, t) -> { if (t != null) { result.completeExceptionally(t); } else { // Execute the main block with the params as the current context object context.execute(context.resolutionContext().createChild(r, null)).whenComplete((r2, t2) -> { if (t2 != null) { result.completeExceptionally(t2); } else { result.complete(r2); } }); } }); return result; } public static class Factory implements SectionHelperFactory<SetSectionHelper> { @Override public List<String> getDefaultAliases() { return ImmutableList.of(SET); } @Override public ParametersInfo getParameters() { return ParametersInfo.EMPTY; } @Override public SetSectionHelper initialize(SectionInitContext context) { Map<String, Expression> params = context.getParameters().entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> context.parseValue(e.getValue()))); return new SetSectionHelper(params); } @Override public Map<String, String> initializeBlock(Map<String, String> outerNameTypeInfos, BlockInfo block) { if (block.getLabel().equals(MAIN_BLOCK_NAME)) { Map<String, String> typeInfos = new HashMap<String, String>(outerNameTypeInfos); for (Entry<String, String> entry : block.getParameters().entrySet()) { Expression expr = block.addExpression(entry.getKey(), entry.getValue()); typeInfos.put(entry.getKey(), expr.typeCheckInfo); } return typeInfos; } else { return Collections.emptyMap(); } } } }
/** * Copyright (c) 2014 SQUARESPACE, 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.squarespace.less.parse; import static com.squarespace.less.core.SyntaxErrorMaker.incompleteParse; import static com.squarespace.less.parse.RecognizerPatterns.DIGITS; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import com.squarespace.less.LessContext; import com.squarespace.less.LessException; import com.squarespace.less.core.Chars; import com.squarespace.less.core.Constants; import com.squarespace.less.exec.ExecEnv; import com.squarespace.less.model.Block; import com.squarespace.less.model.Node; import com.squarespace.compiler.match.Recognizers.Recognizer; /** * Extends the TokenStream with modular parser. */ public class LessStream extends Stream { private final Matcher matcherAttributeKey; private final Matcher matcherAttributeOp; private final Matcher matcherDirective; private final Matcher matcherKeyword; private final Matcher matcherMixinName; private final Matcher matcherOpacity; private final Matcher matcherProperty; private final Matcher matcherRatio; private final Matcher matcherShorthand; private final Matcher matcherUnicodeRange; private final LessParser parser; private final Path path; private final Path rootPath; private final Path fileName; /** * Maintains a list of deferred evaluations during parse. */ private final List<ExecEnv> deferred = new ArrayList<>(); /** * Holds a stack of parse frames, which represent the nested blocks entered * during the parse. This allows us to capture a closure for each import * statement encountered that requires interpolation. We evaluate the * import path against that closure immediately after the parse completes. */ private final ExecEnv parseEnv; private int matchEnd = -1; private Mark tokenPosition = new Mark(); private String token; private boolean inParens; // Special mode for 'font' rules. private boolean requireStrictMath; public LessStream(LessParser parser, String raw) { this(parser, raw, null); } public LessStream(LessParser parser, String raw, Path path) { this(parser, raw, null, null); } public LessStream(LessParser parser, String raw, Path path, ExecEnv env) { super(raw); this.parser = parser; this.path = (path == null) ? Constants.DEFAULT_PATH : path; Path parent = this.path.getParent(); this.rootPath = (parent == null) ? Paths.get(".") : parent; this.fileName = this.path.getFileName(); this.parseEnv = (env == null) ? new ExecEnv(parser.context()) : env; this.matcherAttributeKey = Patterns.ATTRIBUTE_KEY.matcher(raw); this.matcherAttributeOp = Patterns.ATTRIBUTE_OP.matcher(raw); this.matcherDirective = Patterns.DIRECTIVE.matcher(raw); this.matcherKeyword = Patterns.KEYWORD.matcher(raw); this.matcherMixinName = Patterns.MIXIN_NAME.matcher(raw); this.matcherOpacity = Patterns.OPACITY.matcher(raw); this.matcherProperty = Patterns.PROPERTY.matcher(raw); this.matcherRatio = Patterns.RATIO.matcher(raw); this.matcherShorthand = Patterns.SHORTHAND.matcher(raw); this.matcherUnicodeRange = Patterns.UNICODE_DESCRIPTOR.matcher(raw); } public LessException parseError(LessException exc) { return ParseUtils.parseError(exc, fileName, raw, furthest); } public LessParser parser() { return parser; } public LessContext context() { return parser.context(); } public List<ExecEnv> deferreds() { return deferred; } public ExecEnv execEnv() { return parseEnv; } public Path path() { return path; } public Path rootPath() { return rootPath; } public Path fileName() { return fileName; } public boolean inParens() { return inParens; } public void setInParens(boolean flag) { this.inParens = flag; } public boolean requireStrictMath() { return requireStrictMath; } public void setRequireStrictMath(boolean flag) { this.requireStrictMath = flag; } /** * Make sure the stream was fully read; otherwise, throw an exception. */ public void checkComplete() throws LessException { skipWs(); if (peek() != Chars.EOF) { throw parseError(new LessException(incompleteParse())); } } /** * Skips whitespace and tries each parselet in order until one returns a non-null result. */ public Node parse(Parselet[] parselets) throws LessException { skipWs(); Node result = null; Mark pos = mark(); for (Parselet parselet : parselets) { result = parselet.parse(this); if (result != null) { result.setLineOffset(pos.lineOffset); result.setCharOffset(pos.charOffset); break; } } return result; } public String token() { return token; } /** * Defer the current block for evaluation after the parse completes. * To do this we capture the current stack as a closure. */ public void defer() { if (parseEnv != null) { Block block = parseEnv.frames().last(); if (!block.deferred()) { block.markDeferred(); deferred.add(parseEnv.copy()); } } } public boolean matchAnd() { return finish(match(RecognizerPatterns.AND)); } public boolean matchAnonRuleValue() { if (!match(RecognizerPatterns.ANON_RULE_VALUE)) { return false; } matchEnd--; set(index, matchEnd); consume(); return true; } public boolean matchAttributeKey() { return finish(match(matcherAttributeKey)); } public boolean matchAttributeOp() { return finish(match(matcherAttributeOp)); } public boolean matchConditionOp() { return finish(match(RecognizerPatterns.CONDITION_OP)); } public boolean matchCallName() { if (!match(RecognizerPatterns.CALL_NAME)) { return false; } // Back up to before the parenthesis. set(index, matchEnd - 1); consume(); return true; } public boolean matchDigits() { return finish(match(DIGITS)); } public boolean matchDimensionUnit() { return finish(match(RecognizerPatterns.DIMENSION_UNIT)); } public boolean matchDimensionValue() { return finish(match(RecognizerPatterns.DIMENSION_VALUE)); } public boolean matchDirective() { return finish(match(matcherDirective)); } public boolean matchElement0() { return finish(match(RecognizerPatterns.ELEMENT0)); } public boolean matchElement1() { return finish(match(RecognizerPatterns.ELEMENT1)); } public boolean matchElement2() { return finish(match(RecognizerPatterns.ELEMENT2)); } public boolean matchElement3() { return finish(match(RecognizerPatterns.ELEMENT3)); } public boolean matchExtend() { return finish(match(RecognizerPatterns.EXTEND)); } public boolean matchExtendAll() { if (!match(RecognizerPatterns.EXTEND_ALL)) { return false; } // Back up to before the comma or parenthesis. matchEnd--; set(index, matchEnd); consume(); return true; } public boolean matchHexColor() { return finish(match(RecognizerPatterns.HEXCOLOR)); } public boolean matchIdentifier() { return finish(match(RecognizerPatterns.IDENTIFIER)); } public boolean matchImportant() { return finish(match(RecognizerPatterns.IMPORTANT)); } public boolean matchKeyword() { return finish(match(matcherKeyword)); } public boolean matchMixinName() { return finish(match(matcherMixinName)); } public boolean matchNot() { return finish(match(RecognizerPatterns.NOT)); } public boolean matchOpacity() { return finish(match(matcherOpacity)); } public boolean matchProperty() { return finish(match(matcherProperty)); } public boolean matchRatio() { return finish(match(matcherRatio)); } public boolean matchUnicodeRange() { return finish(match(matcherUnicodeRange)); } public boolean matchUrlStart() { return finish(match(RecognizerPatterns.URLSTART)); } public boolean matchWhen() { return finish(match(RecognizerPatterns.WHEN)); } public boolean matchWord() { return finish(match(RecognizerPatterns.WORD)); } public boolean peekShorthand() { return peek(matcherShorthand); } private boolean peek(Matcher matcher) { matcher.region(index, length); return matcher.lookingAt(); } private boolean match(Matcher matcher) { matcher.region(index, length); boolean matched = matcher.lookingAt(); if (matched) { matchEnd = matcher.end(); } return matched; } private boolean match(Recognizer recognizer) { int pos = recognizer.match(raw, index, length); if (pos > index) { matchEnd = pos; return true; } return false; } private boolean finish(boolean result) { if (result) { set(index, matchEnd); consume(); } return result; } private void consume() { seek(matchEnd - index); } private void set(int start, int end) { tokenPosition.index = start; tokenPosition.lineOffset = lineOffset; tokenPosition.charOffset = charOffset; token = raw.substring(start, end); } }
/* * Copyright 2013-2019 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.cloudfoundry.client.v2.environmentvariablegroups; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.cloudfoundry.AllowNulls; import org.cloudfoundry.Nullable; import org.immutables.value.Value; import java.util.Map; /** * The request payload for the update staging environment variable group */ @JsonSerialize @Value.Immutable abstract class _UpdateStagingEnvironmentVariablesRequest { @AllowNulls @JsonValue @Nullable abstract Map<String, Object> getEnvironmentVariables(); }
/* * Copyright 2020 Red Hat, Inc. and/or 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 org.jbpm.runtime.manager.impl.lock; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.jbpm.runtime.manager.spi.RuntimeManagerLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RuntimeManagerLockWatcherSingletonService { private class LockWatchInfo implements Comparable<LockWatchInfo> { RuntimeManagerLock lock; long processInstanceId; long startTime; public LockWatchInfo(long processInstanceId, RuntimeManagerLock lock) { this.processInstanceId = processInstanceId; this.lock = lock; this.startTime = System.currentTimeMillis(); } public long getProcessInstanceId() { return processInstanceId; } public long getCurrentProcessingTime() { return System.currentTimeMillis() - startTime; } @Override public int compareTo(LockWatchInfo o) { return ((Long) startTime).compareTo(o.startTime); } @Override public String toString() { return "[Lock Watch for " + processInstanceId + " locked since " + startTime + "]"; } } protected static final Logger logger = LoggerFactory.getLogger(RuntimeManagerLockWatcherSingletonService.class); private static final RuntimeManagerLockWatcherSingletonService SERVICE = new RuntimeManagerLockWatcherSingletonService(); private Long watchLockPolling; private Long maxLockProcessingTime; private int count; private ExecutorService executorService; private Queue<LockWatchInfo> locksWatched; private RuntimeManagerLockWatcherSingletonService() { this.locksWatched = new PriorityQueue<>(); this.count = 0; } private class RuntimeManagerLockReaper implements Runnable { @Override public void run() { try { while(!Thread.currentThread().isInterrupted()) { long maxTimeToWait = tryForcedUnlock(); Thread.sleep(maxTimeToWait); } } catch(InterruptedException e) { // do nothing. thread has been killed because a shutdown. } } } public long tryForcedUnlock() { synchronized (locksWatched) { while(!locksWatched.isEmpty()) { LockWatchInfo info = locksWatched.peek(); long idleTime = info.getCurrentProcessingTime(); if(maxLockProcessingTime > idleTime) { return maxLockProcessingTime - idleTime; } try { long timeExceeded = idleTime - maxLockProcessingTime; logger.info("Max process time lock exceeded for process instance id {} by {} ms. Trying forceful release lock {}", info.processInstanceId, timeExceeded, info.lock); info.lock.forceUnlock(); } catch(UnsupportedOperationException e) { logger.warn("Runtime manager lock implementation {} does not allow self release for process instance id {}", info.lock.getClass().getName(), info.processInstanceId); } // stop watching this lock. We gave already the information locksWatched.poll(); } } return watchLockPolling; } public void watch(long processInstanceId, RuntimeManagerLock lock) { synchronized (locksWatched) { locksWatched.add(new LockWatchInfo(processInstanceId, lock)); } } public void unwatch(long processInstanceId) { synchronized (locksWatched) { locksWatched.removeIf(e -> e.getProcessInstanceId() == processInstanceId); } } public boolean isWatched(int processInstanceId) { synchronized (locksWatched) { return locksWatched.stream().anyMatch(e -> e.getProcessInstanceId() == processInstanceId); } } private void setWatchLockPolling(Long watchLockPolling) { this.watchLockPolling = watchLockPolling; } private void setMaxLockProcessingTime(Long maxLockProcessingTime) { this.maxLockProcessingTime = maxLockProcessingTime; } private void start() { count++; if(count > 0 && watchLockPolling > 0 && executorService == null) { executorService = Executors.newSingleThreadExecutor(); executorService.submit(new RuntimeManagerLockReaper()); logger.info("Started watching locks"); } } public void unreference () { synchronized (this) { if( executorService != null && --count == 0) { logger.info("Stopped watching locks"); executorService.shutdownNow(); executorService = null; } } } public static RuntimeManagerLockWatcherSingletonService reference() { return reference(Long.getLong("org.kie.jbpm.lock.polling", 0L), Long.getLong("org.kie.jbpm.lock.maxProcessingTime", 60000L)); } public static RuntimeManagerLockWatcherSingletonService reference(Long watchLockPolling, Long maxLockProcessingTime) { synchronized (SERVICE) { SERVICE.setMaxLockProcessingTime(maxLockProcessingTime); SERVICE.setWatchLockPolling(watchLockPolling); SERVICE.start(); return SERVICE; } } public static boolean isActive() { synchronized (SERVICE) { return SERVICE.executorService != null; } } }
/* * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package fromjava.server; //import java.net.InetSocketAddress; //import java.util.concurrent.Executors; //import com.sun.net.httpserver.HttpContext; //import com.sun.net.httpserver.HttpServer; import jakarta.xml.ws.soap.SOAPBinding; import jakarta.xml.ws.Endpoint; public class AddWebservice { public static void main (String[] args) throws Exception { Endpoint.publish ( "http://localhost:8080/jaxws-fromjava/addnumbers", new AddNumbersImpl ()); } // public static void deployMethod2 () throws Exception { // Endpoint endpoint = Endpoint.create( // new URI (SOAPBinding.SOAP11HTTP_BINDING), // new AddNumbersImpl ()); // // HttpServer server = HttpServer.create (new InetSocketAddress (8080), 5); // server.setExecutor (Executors.newFixedThreadPool (5)); // HttpContext context = server.createContext ( // "http", // "/jaxws-fromjava/addnumbers"); // // endpoint.publish (context); // server.start (); // } }
package com.instaclustr.sstabletools; import com.google.common.util.concurrent.RateLimiter; import org.apache.cassandra.db.DecoratedKey; import java.util.Collection; /** * Proxy to column family related functions of Cassandra backend. */ public interface ColumnFamilyProxy extends AutoCloseable { /** * Get readers for SSTable Index.db files for this column family. * * @return Collection of readers for SSTable Index.db files. */ Collection<SSTableReader> getIndexReaders(); /** * Get readers for SSTable Data.db files for this column family. * * @param rateLimiter Rate limiter for readers. * @return Collection of readers for SSTable Data.db files. */ Collection<SSTableReader> getDataReaders(RateLimiter rateLimiter); /** * Get purge statistics reader. * * @param rateLimiter Rater limiter for reading. * @return Reader for purge statistics. */ PurgeStatisticsReader getPurgeStatisticsReader(RateLimiter rateLimiter); /** * Format partition key into human readable format. * * @param key Decorated partition key. * @return Human readable partition key. */ String formatKey(DecoratedKey key); /** * Is the column family using Date Tiered compaction strategy. * * @return True if column family is using Date Tiered compaction strategy. */ boolean isDTCS(); /** * Is the column family using Time Window compaction strategy. * * @return True if column family is using Time Window compaction strategy. */ boolean isTWCS(); @Override void close(); }
/** * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yixi.smartpanda.core.common.constant.state; /** * 数据库排序 * * @author fengshuonan * @Date 2017年5月31日20:48:41 */ public enum Order { ASC("asc"), DESC("desc"); private String des; Order(String des) { this.des = des; } public String getDes() { return des; } public void setDes(String des) { this.des = des; } }
package com.taopao.audio; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
package ontology.effects.binary; import core.vgdl.VGDLRegistry; import core.vgdl.VGDLSprite; import core.content.InteractionContent; import core.game.Game; import core.logging.Logger; import core.logging.Message; import ontology.effects.unary.TransformTo; import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: Diego * Date: 23/10/13 * Time: 15:21 * This is a Java port from Tom Schaul's VGDL - https://github.com/schaul/py-vgdl */ public class TransformIfCount extends TransformTo { //This effect transforms sprite1 into stype if // * num(stypeCount) >= GEQ // * num(stypeCount) <= LEQ public String stypeCount; public int itypeCount; public String estype; public int eitype; public int geq; public int leq; public TransformIfCount(InteractionContent cnt) throws Exception { super(cnt); geq=0; leq=Game.getMaxSprites(); this.parseParameters(cnt); itypeCount = VGDLRegistry.GetInstance().getRegisteredSpriteValue(stypeCount); if(estype != null) eitype = VGDLRegistry.GetInstance().getRegisteredSpriteValue(estype); } @Override public void execute(VGDLSprite sprite1, VGDLSprite sprite2, Game game) { if(sprite1 == null || sprite2 == null){ Logger.getInstance().addMessage(new Message(Message.WARNING, "Neither the 1st nor 2nd sprite can be EOS with TransformIfCount interaction.")); return; } int numSpritesCheck = game.getNumSprites(itypeCount); this.applyScore = false; this.count = false; this.countElse = false; if(numSpritesCheck <= leq && numSpritesCheck >= geq) { VGDLSprite newSprite = game.addSprite(itype, sprite1.getPosition(), true); super.transformTo(newSprite, sprite1, sprite2, game); this.applyScore = true; this.count = true; } else if (estype != null) { VGDLSprite newSprite = game.addSprite(eitype, sprite1.getPosition(), true); super.transformTo(newSprite, sprite1, sprite2, game); this.countElse=true; } } @Override public ArrayList<String> getEffectSprites(){ ArrayList<String> result = new ArrayList<String>(); if(stype!=null) result.add(stype); if(stypeCount!=null) result.add(stypeCount); if(estype!=null) result.add(estype); return result; } }
package jforgame.server.game.database.config.storage; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import jforgame.server.db.DbUtils; import jforgame.server.game.database.config.CommonConfigs; import jforgame.server.game.database.config.Reloadable; import jforgame.server.game.database.config.bean.ConfigConstant; import jforgame.server.logs.LoggerUtils; public class ConfigConstantStorage implements Reloadable { private Map<Integer, ConfigConstant> configs; @Override public void reload() { String sql = "SELECT * FROM ConfigConstant"; try { List<ConfigConstant> datas = DbUtils.queryMany(DbUtils.DB_DATA, sql, ConfigConstant.class); configs = datas.stream().collect(Collectors.toMap(ConfigConstant::getId, Function.identity())); // 把数据转为到枚举对象里 CommonConfigs.initialize(configs); } catch (Exception e) { LoggerUtils.error("", e); } } }
/* * Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.java2d.pipe; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.Transparency; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.DirectColorModel; import java.awt.image.ImageObserver; import java.awt.image.IndexColorModel; import java.awt.image.Raster; import java.awt.image.VolatileImage; import java.awt.image.WritableRaster; import java.awt.image.ImagingOpException; import sun.awt.SunHints; import sun.awt.image.ImageRepresentation; import sun.awt.image.ToolkitImage; import sun.java2d.InvalidPipeException; import sun.java2d.SunGraphics2D; import sun.java2d.SurfaceData; import sun.java2d.loops.Blit; import sun.java2d.loops.BlitBg; import sun.java2d.loops.TransformHelper; import sun.java2d.loops.MaskBlit; import sun.java2d.loops.CompositeType; import sun.java2d.loops.ScaledBlit; import sun.java2d.loops.SurfaceType; public class DrawImage implements DrawImagePipe { public boolean copyImage(SunGraphics2D sg, Image img, int x, int y, Color bgColor) { int imgw = img.getWidth(null); int imgh = img.getHeight(null); if (isSimpleTranslate(sg)) { return renderImageCopy(sg, img, bgColor, x + sg.transX, y + sg.transY, 0, 0, imgw, imgh); } AffineTransform atfm = sg.transform; if ((x | y) != 0) { atfm = new AffineTransform(atfm); atfm.translate(x, y); } transformImage(sg, img, atfm, sg.interpolationType, 0, 0, imgw, imgh, bgColor); return true; } public boolean copyImage(SunGraphics2D sg, Image img, int dx, int dy, int sx, int sy, int w, int h, Color bgColor) { if (isSimpleTranslate(sg)) { return renderImageCopy(sg, img, bgColor, dx + sg.transX, dy + sg.transY, sx, sy, w, h); } scaleImage(sg, img, dx, dy, (dx + w), (dy + h), sx, sy, (sx + w), (sy + h), bgColor); return true; } public boolean scaleImage(SunGraphics2D sg, Image img, int x, int y, int width, int height, Color bgColor) { int imgw = img.getWidth(null); int imgh = img.getHeight(null); // Only accelerate scale if: // - w/h positive values // - sg transform integer translate/identity only // - no bgColor in operation if ((width > 0) && (height > 0) && isSimpleTranslate(sg)) { double dx1 = x + sg.transX; double dy1 = y + sg.transY; double dx2 = dx1 + width; double dy2 = dy1 + height; if (renderImageScale(sg, img, bgColor, sg.interpolationType, 0, 0, imgw, imgh, dx1, dy1, dx2, dy2)) { return true; } } AffineTransform atfm = sg.transform; if ((x | y) != 0 || width != imgw || height != imgh) { atfm = new AffineTransform(atfm); atfm.translate(x, y); atfm.scale(((double)width)/imgw, ((double)height)/imgh); } transformImage(sg, img, atfm, sg.interpolationType, 0, 0, imgw, imgh, bgColor); return true; } /* * This method is only called in those circumstances where the * operation has a non-null secondary transform specfied. Its * role is to check for various optimizations based on the types * of both the secondary and SG2D transforms and to do some * quick calculations to avoid having to combine the transforms * and/or to call a more generalized method. */ protected void transformImage(SunGraphics2D sg, Image img, int x, int y, AffineTransform extraAT, int interpType) { int txtype = extraAT.getType(); int imgw = img.getWidth(null); int imgh = img.getHeight(null); boolean checkfinalxform; if (sg.transformState <= sg.TRANSFORM_ANY_TRANSLATE && (txtype == AffineTransform.TYPE_IDENTITY || txtype == AffineTransform.TYPE_TRANSLATION)) { // First optimization - both are some kind of translate // Combine the translations and check if interpolation is necessary. double tx = extraAT.getTranslateX(); double ty = extraAT.getTranslateY(); tx += sg.transform.getTranslateX(); ty += sg.transform.getTranslateY(); int itx = (int) Math.floor(tx + 0.5); int ity = (int) Math.floor(ty + 0.5); if (interpType == AffineTransformOp.TYPE_NEAREST_NEIGHBOR || (closeToInteger(itx, tx) && closeToInteger(ity, ty))) { renderImageCopy(sg, img, null, x+itx, y+ity, 0, 0, imgw, imgh); return; } checkfinalxform = false; } else if (sg.transformState <= sg.TRANSFORM_TRANSLATESCALE && ((txtype & (AffineTransform.TYPE_FLIP | AffineTransform.TYPE_MASK_ROTATION | AffineTransform.TYPE_GENERAL_TRANSFORM)) == 0)) { // Second optimization - both are some kind of translate or scale // Combine the scales and check if interpolation is necessary. // Transform source bounds by extraAT, // then translate the bounds again by x, y // then transform the bounds again by sg.transform double coords[] = new double[] { 0, 0, imgw, imgh, }; extraAT.transform(coords, 0, coords, 0, 2); coords[0] += x; coords[1] += y; coords[2] += x; coords[3] += y; sg.transform.transform(coords, 0, coords, 0, 2); if (tryCopyOrScale(sg, img, 0, 0, imgw, imgh, null, interpType, coords)) { return; } checkfinalxform = false; } else { checkfinalxform = true; } // Begin Transform AffineTransform tx = new AffineTransform(sg.transform); tx.translate(x, y); tx.concatenate(extraAT); // Do not try any more optimizations if either of the cases // above was tried as we have already verified that the // resulting transform will not simplify. if (checkfinalxform) { // In this case neither of the above simple transform // pairs was found so we will do some final tests on // the final rendering transform which may be the // simple product of two complex transforms. transformImage(sg, img, tx, interpType, 0, 0, imgw, imgh, null); } else { renderImageXform(sg, img, tx, interpType, 0, 0, imgw, imgh, null); } } /* * This method is called with a final rendering transform that * has combined all of the information about the Graphics2D * transform attribute with the transformations specified by * the arguments to the drawImage call. * Its role is to see if the combined transform ends up being * acceleratable by either a renderImageCopy or renderImageScale * once all of the math is done. * * Note: The transform supplied here has an origin that is * already adjusted to point to the device location where * the (sx1, sy1) location of the source image should be placed. */ protected void transformImage(SunGraphics2D sg, Image img, AffineTransform tx, int interpType, int sx1, int sy1, int sx2, int sy2, Color bgColor) { // Transform 3 source corners by tx and analyze them // for simplified operations (Copy or Scale). Using // 3 points lets us analyze any kind of transform, // even transforms that involve very tiny amounts of // rotation or skew to see if they degenerate to a // simple scale or copy operation within the allowable // error bounds. // Note that we use (0,0,w,h) instead of (sx1,sy1,sx2,sy2) // because the transform is already translated such that // the origin is where sx1, sy1 should go. double coords[] = new double[6]; /* index: 0 1 2 3 4 5 */ /* coord: (0, 0), (w, h), (0, h) */ coords[2] = sx2 - sx1; coords[3] = coords[5] = sy2 - sy1; tx.transform(coords, 0, coords, 0, 3); // First test if the X coords of the transformed UL // and LL points match and that the Y coords of the // transformed LR and LL points also match. // If they do then it is a "rectilinear" transform and // tryCopyOrScale will make sure it is upright and // integer-based. if (Math.abs(coords[0] - coords[4]) < MAX_TX_ERROR && Math.abs(coords[3] - coords[5]) < MAX_TX_ERROR && tryCopyOrScale(sg, img, sx1, sy1, sx2, sy2, bgColor, interpType, coords)) { return; } renderImageXform(sg, img, tx, interpType, sx1, sy1, sx2, sy2, bgColor); } /* * Check the bounding coordinates of the transformed source * image to see if they fall on integer coordinates such * that they will cause no interpolation anomalies if we * use our simplified Blit or ScaledBlit operations instead * of a full transform operation. */ protected boolean tryCopyOrScale(SunGraphics2D sg, Image img, int sx1, int sy1, int sx2, int sy2, Color bgColor, int interpType, double coords[]) { double dx = coords[0]; double dy = coords[1]; double dw = coords[2] - dx; double dh = coords[3] - dy; // First check if width and height are very close to img w&h. if (closeToInteger(sx2-sx1, dw) && closeToInteger(sy2-sy1, dh)) { // Round location to nearest pixel and then test // if it will cause interpolation anomalies. int idx = (int) Math.floor(dx + 0.5); int idy = (int) Math.floor(dy + 0.5); if (interpType == AffineTransformOp.TYPE_NEAREST_NEIGHBOR || (closeToInteger(idx, dx) && closeToInteger(idy, dy))) { renderImageCopy(sg, img, bgColor, idx, idy, sx1, sy1, sx2-sx1, sy2-sy1); return true; } } // (For now) We can only use our ScaledBlits if the image // is upright (i.e. dw & dh both > 0) if (dw > 0 && dh > 0) { if (renderImageScale(sg, img, bgColor, interpType, sx1, sy1, sx2, sy2, coords[0], coords[1], coords[2], coords[3])) { return true; } } return false; } /* * Return a BufferedImage of the requested type with the indicated * subimage of the original image located at 0,0 in the new image. * If a bgColor is supplied, composite the original image over that * color with a SrcOver operation, otherwise make a SrcNoEa copy. */ BufferedImage makeBufferedImage(Image img, Color bgColor, int type, int sx1, int sy1, int sx2, int sy2) { BufferedImage bimg = new BufferedImage(sx2-sx1, sy2-sy1, type); Graphics2D g2d = bimg.createGraphics(); g2d.setComposite(AlphaComposite.Src); if (bgColor != null) { g2d.setColor(bgColor); g2d.fillRect(0, 0, sx2-sx1, sy2-sy1); g2d.setComposite(AlphaComposite.SrcOver); } g2d.drawImage(img, -sx1, -sy1, null); g2d.dispose(); return bimg; } protected void renderImageXform(SunGraphics2D sg, Image img, AffineTransform tx, int interpType, int sx1, int sy1, int sx2, int sy2, Color bgColor) { Region clip = sg.getCompClip(); SurfaceData dstData = sg.surfaceData; SurfaceData srcData = dstData.getSourceSurfaceData(img, sg.TRANSFORM_GENERIC, sg.imageComp, bgColor); if (srcData == null) { img = getBufferedImage(img); srcData = dstData.getSourceSurfaceData(img, sg.TRANSFORM_GENERIC, sg.imageComp, bgColor); if (srcData == null) { // REMIND: Is this correct? Can this happen? return; } } if (isBgOperation(srcData, bgColor)) { // We cannot perform bg operations during transform so make // an opaque temp image with the appropriate background // and work from there. img = makeBufferedImage(img, bgColor, BufferedImage.TYPE_INT_RGB, sx1, sy1, sx2, sy2); // Temp image has appropriate subimage at 0,0 now. sx2 -= sx1; sy2 -= sy1; sx1 = sy1 = 0; srcData = dstData.getSourceSurfaceData(img, sg.TRANSFORM_GENERIC, sg.imageComp, bgColor); } SurfaceType srcType = srcData.getSurfaceType(); TransformHelper helper = TransformHelper.getFromCache(srcType); if (helper == null) { /* We have no helper for this source image type. * But we know that we do have helpers for both RGB and ARGB, * so convert to one of those types depending on transparency. * ARGB_PRE might be a better choice if the source image has * alpha, but it may cause some recursion here since we only * tend to have converters that convert to ARGB. */ int type = ((srcData.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB); img = makeBufferedImage(img, null, type, sx1, sy1, sx2, sy2); // Temp image has appropriate subimage at 0,0 now. sx2 -= sx1; sy2 -= sy1; sx1 = sy1 = 0; srcData = dstData.getSourceSurfaceData(img, sg.TRANSFORM_GENERIC, sg.imageComp, null); srcType = srcData.getSurfaceType(); helper = TransformHelper.getFromCache(srcType); // assert(helper != null); } AffineTransform itx; try { itx = tx.createInverse(); } catch (NoninvertibleTransformException e) { // Non-invertible transform means no output return; } /* * Find the maximum bounds on the destination that will be * affected by the transformed source. First, transform all * four corners of the source and then min and max the resulting * destination coordinates of the transformed corners. * Note that tx already has the offset to sx1,sy1 accounted * for so we use the box (0, 0, sx2-sx1, sy2-sy1) as the * source coordinates. */ double coords[] = new double[8]; /* corner: UL UR LL LR */ /* index: 0 1 2 3 4 5 6 7 */ /* coord: (0, 0), (w, 0), (0, h), (w, h) */ coords[2] = coords[6] = sx2 - sx1; coords[5] = coords[7] = sy2 - sy1; tx.transform(coords, 0, coords, 0, 4); double ddx1, ddy1, ddx2, ddy2; ddx1 = ddx2 = coords[0]; ddy1 = ddy2 = coords[1]; for (int i = 2; i < coords.length; i += 2) { double d = coords[i]; if (ddx1 > d) ddx1 = d; else if (ddx2 < d) ddx2 = d; d = coords[i+1]; if (ddy1 > d) ddy1 = d; else if (ddy2 < d) ddy2 = d; } int dx1 = (int) Math.floor(ddx1); int dy1 = (int) Math.floor(ddy1); int dx2 = (int) Math.ceil(ddx2); int dy2 = (int) Math.ceil(ddy2); SurfaceType dstType = dstData.getSurfaceType(); MaskBlit maskblit; Blit blit; if (sg.compositeState <= sg.COMP_ALPHA) { /* NOTE: We either have, or we can make, * a MaskBlit for any alpha composite type */ maskblit = MaskBlit.getFromCache(SurfaceType.IntArgbPre, sg.imageComp, dstType); /* NOTE: We can only use the native TransformHelper * func to go directly to the dest if both the helper * and the MaskBlit are native. * All helpers are native at this point, but some MaskBlit * objects are implemented in Java, so we need to check. */ if (maskblit.getNativePrim() != 0) { // We can render directly. helper.Transform(maskblit, srcData, dstData, sg.composite, clip, itx, interpType, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, null, 0, 0); return; } blit = null; } else { /* NOTE: We either have, or we can make, * a Blit for any composite type, even Custom */ maskblit = null; blit = Blit.getFromCache(SurfaceType.IntArgbPre, sg.imageComp, dstType); } // We need to transform to a temp image and then copy // just the pieces that are valid data to the dest. BufferedImage tmpimg = new BufferedImage(dx2-dx1, dy2-dy1, BufferedImage.TYPE_INT_ARGB); SurfaceData tmpData = SurfaceData.getPrimarySurfaceData(tmpimg); SurfaceType tmpType = tmpData.getSurfaceType(); MaskBlit tmpmaskblit = MaskBlit.getFromCache(SurfaceType.IntArgbPre, CompositeType.SrcNoEa, tmpType); /* * The helper function fills a temporary edges buffer * for us with the bounding coordinates of each scanline * in the following format: * * edges[0, 1] = [top y, bottom y) * edges[2, 3] = [left x, right x) of top row * ... * edges[h*2, h*2+1] = [left x, right x) of bottom row * * all coordinates in the edges array will be relative to dx1, dy1 * * edges thus has to be h*2+2 in length */ int edges[] = new int[(dy2-dy1)*2+2]; // It is important that edges[0]=edges[1]=0 when we call // Transform in case it must return early and we would // not want to render anything on an error condition. helper.Transform(tmpmaskblit, srcData, tmpData, AlphaComposite.Src, null, itx, interpType, sx1, sy1, sx2, sy2, 0, 0, dx2-dx1, dy2-dy1, edges, dx1, dy1); /* * Now copy the results, scanline by scanline, into the dest. * The edges array helps us minimize the work. */ int index = 2; for (int y = edges[0]; y < edges[1]; y++) { int relx1 = edges[index++]; int relx2 = edges[index++]; if (relx1 >= relx2) { continue; } if (maskblit != null) { maskblit.MaskBlit(tmpData, dstData, sg.composite, clip, relx1, y, dx1+relx1, dy1+y, relx2 - relx1, 1, null, 0, 0); } else { blit.Blit(tmpData, dstData, sg.composite, clip, relx1, y, dx1+relx1, dy1+y, relx2 - relx1, 1); } } } // Render an image using only integer translation // (no scale or transform or sub-pixel interpolated translations). protected boolean renderImageCopy(SunGraphics2D sg, Image img, Color bgColor, int dx, int dy, int sx, int sy, int w, int h) { Region clip = sg.getCompClip(); SurfaceData dstData = sg.surfaceData; int attempts = 0; // Loop up to twice through; this gives us a chance to // revalidate the surfaceData objects in case of an exception // and try it once more while (true) { SurfaceData srcData = dstData.getSourceSurfaceData(img, sg.TRANSFORM_ISIDENT, sg.imageComp, bgColor); if (srcData == null) { return false; } try { SurfaceType srcType = srcData.getSurfaceType(); SurfaceType dstType = dstData.getSurfaceType(); blitSurfaceData(sg, clip, srcData, dstData, srcType, dstType, sx, sy, dx, dy, w, h, bgColor); return true; } catch (NullPointerException e) { if (!(SurfaceData.isNull(dstData) || SurfaceData.isNull(srcData))) { // Something else caused the exception, throw it... throw e; } return false; // NOP if we have been disposed } catch (InvalidPipeException e) { // Always catch the exception; try this a couple of times // and fail silently if the system is not yet ready to // revalidate the source or dest surfaceData objects. ++attempts; clip = sg.getCompClip(); // ensures sg.surfaceData is valid dstData = sg.surfaceData; if (SurfaceData.isNull(dstData) || SurfaceData.isNull(srcData) || (attempts > 1)) { return false; } } } } // Render an image using only integer scaling (no transform). protected boolean renderImageScale(SunGraphics2D sg, Image img, Color bgColor, int interpType, int sx1, int sy1, int sx2, int sy2, double dx1, double dy1, double dx2, double dy2) { // Currently only NEAREST_NEIGHBOR interpolation is implemented // for ScaledBlit operations. if (interpType != AffineTransformOp.TYPE_NEAREST_NEIGHBOR) { return false; } Region clip = sg.getCompClip(); SurfaceData dstData = sg.surfaceData; int attempts = 0; // Loop up to twice through; this gives us a chance to // revalidate the surfaceData objects in case of an exception // and try it once more while (true) { SurfaceData srcData = dstData.getSourceSurfaceData(img, sg.TRANSFORM_TRANSLATESCALE, sg.imageComp, bgColor); if (srcData == null || isBgOperation(srcData, bgColor)) { return false; } try { SurfaceType srcType = srcData.getSurfaceType(); SurfaceType dstType = dstData.getSurfaceType(); return scaleSurfaceData(sg, clip, srcData, dstData, srcType, dstType, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2); } catch (NullPointerException e) { if (!SurfaceData.isNull(dstData)) { // Something else caused the exception, throw it... throw e; } return false; // NOP if we have been disposed } catch (InvalidPipeException e) { // Always catch the exception; try this a couple of times // and fail silently if the system is not yet ready to // revalidate the source or dest surfaceData objects. ++attempts; clip = sg.getCompClip(); // ensures sg.surfaceData is valid dstData = sg.surfaceData; if (SurfaceData.isNull(dstData) || SurfaceData.isNull(srcData) || (attempts > 1)) { return false; } } } } public boolean scaleImage(SunGraphics2D sg, Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgColor) { int srcW, srcH, dstW, dstH; int srcX, srcY, dstX, dstY; boolean srcWidthFlip = false; boolean srcHeightFlip = false; boolean dstWidthFlip = false; boolean dstHeightFlip = false; if (sx2 > sx1) { srcW = sx2 - sx1; srcX = sx1; } else { srcWidthFlip = true; srcW = sx1 - sx2; srcX = sx2; } if (sy2 > sy1) { srcH = sy2-sy1; srcY = sy1; } else { srcHeightFlip = true; srcH = sy1-sy2; srcY = sy2; } if (dx2 > dx1) { dstW = dx2 - dx1; dstX = dx1; } else { dstW = dx1 - dx2; dstWidthFlip = true; dstX = dx2; } if (dy2 > dy1) { dstH = dy2 - dy1; dstY = dy1; } else { dstH = dy1 - dy2; dstHeightFlip = true; dstY = dy2; } if (srcW <= 0 || srcH <= 0) { return true; } // Only accelerate scale if it does not involve a flip or transform if ((srcWidthFlip == dstWidthFlip) && (srcHeightFlip == dstHeightFlip) && isSimpleTranslate(sg)) { double ddx1 = dstX + sg.transX; double ddy1 = dstY + sg.transY; double ddx2 = ddx1 + dstW; double ddy2 = ddy1 + dstH; if (renderImageScale(sg, img, bgColor, sg.interpolationType, srcX, srcY, srcX+srcW, srcY+srcH, ddx1, ddy1, ddx2, ddy2)) { return true; } } AffineTransform atfm = new AffineTransform(sg.transform); atfm.translate(dx1, dy1); double m00 = (double)(dx2-dx1)/(sx2-sx1); double m11 = (double)(dy2-dy1)/(sy2-sy1); atfm.scale(m00, m11); atfm.translate(srcX-sx1, srcY-sy1); int imgW = img.getWidth(null); int imgH = img.getHeight(null); srcW += srcX; srcH += srcY; // Make sure we are not out of bounds if (srcW > imgW) { srcW = imgW; } if (srcH > imgH) { srcH = imgH; } if (srcX < 0) { atfm.translate(-srcX, 0); srcX = 0; } if (srcY < 0) { atfm.translate(0, -srcY); srcY = 0; } if (srcX >= srcW || srcY >= srcH) { return true; } // Note: src[WH] are currently the right and bottom coordinates. // The following two lines would adjust src[WH] back to being // dimensions. // srcW -= srcX; // srcH -= srcY; // Since transformImage needs right and bottom coords we will // omit this adjustment. transformImage(sg, img, atfm, sg.interpolationType, srcX, srcY, srcW, srcH, bgColor); return true; } /** ** Utilities ** The following methods are used by the public methods above ** for performing various operations **/ /* * This constant represents a tradeoff between the * need to make sure that image transformations are * "very close" to integer device coordinates before * we decide to use an integer scale or copy operation * as a substitute and the fact that roundoff errors * in AffineTransforms are frequently introduced by * performing multiple sequential operations on them. * * The evaluation of bug 4990624 details the potential * for this error cutoff to result in display anomalies * in different types of image operations and how this * value represents a good compromise here. */ private static final double MAX_TX_ERROR = .0001; public static boolean closeToInteger(int i, double d) { return (Math.abs(d-i) < MAX_TX_ERROR); } public static boolean isSimpleTranslate(SunGraphics2D sg) { int ts = sg.transformState; if (ts <= sg.TRANSFORM_INT_TRANSLATE) { // Integer translates are always "simple" return true; } if (ts >= sg.TRANSFORM_TRANSLATESCALE) { // Scales and beyond are always "not simple" return false; } // non-integer translates are only simple when not interpolating if (sg.interpolationType == AffineTransformOp.TYPE_NEAREST_NEIGHBOR) { return true; } return false; } protected static boolean isBgOperation(SurfaceData srcData, Color bgColor) { // If we cannot get the srcData, then cannot assume anything about // the image return ((srcData == null) || ((bgColor != null) && (srcData.getTransparency() != Transparency.OPAQUE))); } protected BufferedImage getBufferedImage(Image img) { if (img instanceof BufferedImage) { return (BufferedImage)img; } // Must be VolatileImage; get BufferedImage representation return ((VolatileImage)img).getSnapshot(); } /* * Return the color model to be used with this BufferedImage and * transform. */ private ColorModel getTransformColorModel(SunGraphics2D sg, BufferedImage bImg, AffineTransform tx) { ColorModel cm = bImg.getColorModel(); ColorModel dstCM = cm; if (tx.isIdentity()) { return dstCM; } int type = tx.getType(); boolean needTrans = ((type&(tx.TYPE_MASK_ROTATION|tx.TYPE_GENERAL_TRANSFORM)) != 0); if (! needTrans && type != tx.TYPE_TRANSLATION && type != tx.TYPE_IDENTITY) { double[] mtx = new double[4]; tx.getMatrix(mtx); // Check out the matrix. A non-integral scale will force ARGB // since the edge conditions cannot be guaranteed. needTrans = (mtx[0] != (int)mtx[0] || mtx[3] != (int)mtx[3]); } if (sg.renderHint != SunHints.INTVAL_RENDER_QUALITY) { if (cm instanceof IndexColorModel) { Raster raster = bImg.getRaster(); IndexColorModel icm = (IndexColorModel) cm; // Just need to make sure that we have a transparent pixel if (needTrans && cm.getTransparency() == cm.OPAQUE) { // Fix 4221407 if (raster instanceof sun.awt.image.BytePackedRaster) { dstCM = ColorModel.getRGBdefault(); } else { double[] matrix = new double[6]; tx.getMatrix(matrix); if (matrix[1] == 0. && matrix[2] ==0. && matrix[4] == 0. && matrix[5] == 0.) { // Only scaling so do not need to create } else { int mapSize = icm.getMapSize(); if (mapSize < 256) { int[] cmap = new int[mapSize+1]; icm.getRGBs(cmap); cmap[mapSize] = 0x0000; dstCM = new IndexColorModel(icm.getPixelSize(), mapSize+1, cmap, 0, true, mapSize, DataBuffer.TYPE_BYTE); } else { dstCM = ColorModel.getRGBdefault(); } } /* if (matrix[0] < 1.f ...) */ } /* raster instanceof sun.awt.image.BytePackedRaster */ } /* if (cm.getTransparency() == cm.OPAQUE) */ } /* if (cm instanceof IndexColorModel) */ else if (needTrans && cm.getTransparency() == cm.OPAQUE) { // Need a bitmask transparency // REMIND: for now, use full transparency since no loops // for bitmask dstCM = ColorModel.getRGBdefault(); } } /* if (sg.renderHint == RENDER_QUALITY) */ else { if (cm instanceof IndexColorModel || (needTrans && cm.getTransparency() == cm.OPAQUE)) { // Need a bitmask transparency // REMIND: for now, use full transparency since no loops // for bitmask dstCM = ColorModel.getRGBdefault(); } } return dstCM; } protected void blitSurfaceData(SunGraphics2D sg, Region clipRegion, SurfaceData srcData, SurfaceData dstData, SurfaceType srcType, SurfaceType dstType, int sx, int sy, int dx, int dy, int w, int h, Color bgColor) { if (w <= 0 || h <= 0) { /* * Fix for bugid 4783274 - BlitBg throws an exception for * a particular set of anomalous parameters. * REMIND: The native loops do proper clipping and would * detect this situation themselves, but the Java loops * all seem to trust their parameters a little too well * to the point where they will try to process a negative * area of pixels and throw exceptions. The real fix is * to modify the Java loops to do proper clipping so that * they can deal with negative dimensions as well as * improperly large dimensions, but that fix is too risky * to integrate for Mantis at this point. In the meantime * eliminating the negative or zero dimensions here is * "correct" and saves them from some nasty exceptional * conditions, one of which is the test case of 4783274. */ return; } CompositeType comp = sg.imageComp; if (CompositeType.SrcOverNoEa.equals(comp) && (srcData.getTransparency() == Transparency.OPAQUE || (bgColor != null && bgColor.getTransparency() == Transparency.OPAQUE))) { comp = CompositeType.SrcNoEa; } if (!isBgOperation(srcData, bgColor)) { Blit blit = Blit.getFromCache(srcType, comp, dstType); blit.Blit(srcData, dstData, sg.composite, clipRegion, sx, sy, dx, dy, w, h); } else { BlitBg blit = BlitBg.getFromCache(srcType, comp, dstType); blit.BlitBg(srcData, dstData, sg.composite, clipRegion, bgColor.getRGB(), sx, sy, dx, dy, w, h); } } protected boolean scaleSurfaceData(SunGraphics2D sg, Region clipRegion, SurfaceData srcData, SurfaceData dstData, SurfaceType srcType, SurfaceType dstType, int sx1, int sy1, int sx2, int sy2, double dx1, double dy1, double dx2, double dy2) { CompositeType comp = sg.imageComp; if (CompositeType.SrcOverNoEa.equals(comp) && (srcData.getTransparency() == Transparency.OPAQUE)) { comp = CompositeType.SrcNoEa; } ScaledBlit blit = ScaledBlit.getFromCache(srcType, comp, dstType); if (blit != null) { blit.Scale(srcData, dstData, sg.composite, clipRegion, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2); return true; } return false; } protected static boolean imageReady(ToolkitImage sunimg, ImageObserver observer) { if (sunimg.hasError()) { if (observer != null) { observer.imageUpdate(sunimg, ImageObserver.ERROR|ImageObserver.ABORT, -1, -1, -1, -1); } return false; } return true; } public boolean copyImage(SunGraphics2D sg, Image img, int x, int y, Color bgColor, ImageObserver observer) { if (!(img instanceof ToolkitImage)) { return copyImage(sg, img, x, y, bgColor); } else { ToolkitImage sunimg = (ToolkitImage)img; if (!imageReady(sunimg, observer)) { return false; } ImageRepresentation ir = sunimg.getImageRep(); return ir.drawToBufImage(sg, sunimg, x, y, bgColor, observer); } } public boolean copyImage(SunGraphics2D sg, Image img, int dx, int dy, int sx, int sy, int w, int h, Color bgColor, ImageObserver observer) { if (!(img instanceof ToolkitImage)) { return copyImage(sg, img, dx, dy, sx, sy, w, h, bgColor); } else { ToolkitImage sunimg = (ToolkitImage)img; if (!imageReady(sunimg, observer)) { return false; } ImageRepresentation ir = sunimg.getImageRep(); return ir.drawToBufImage(sg, sunimg, dx, dy, (dx + w), (dy + h), sx, sy, (sx + w), (sy + h), bgColor, observer); } } public boolean scaleImage(SunGraphics2D sg, Image img, int x, int y, int width, int height, Color bgColor, ImageObserver observer) { if (!(img instanceof ToolkitImage)) { return scaleImage(sg, img, x, y, width, height, bgColor); } else { ToolkitImage sunimg = (ToolkitImage)img; if (!imageReady(sunimg, observer)) { return false; } ImageRepresentation ir = sunimg.getImageRep(); return ir.drawToBufImage(sg, sunimg, x, y, width, height, bgColor, observer); } } public boolean scaleImage(SunGraphics2D sg, Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgColor, ImageObserver observer) { if (!(img instanceof ToolkitImage)) { return scaleImage(sg, img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgColor); } else { ToolkitImage sunimg = (ToolkitImage)img; if (!imageReady(sunimg, observer)) { return false; } ImageRepresentation ir = sunimg.getImageRep(); return ir.drawToBufImage(sg, sunimg, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgColor, observer); } } public boolean transformImage(SunGraphics2D sg, Image img, AffineTransform atfm, ImageObserver observer) { if (!(img instanceof ToolkitImage)) { transformImage(sg, img, 0, 0, atfm, sg.interpolationType); return true; } else { ToolkitImage sunimg = (ToolkitImage)img; if (!imageReady(sunimg, observer)) { return false; } ImageRepresentation ir = sunimg.getImageRep(); return ir.drawToBufImage(sg, sunimg, atfm, observer); } } public void transformImage(SunGraphics2D sg, BufferedImage img, BufferedImageOp op, int x, int y) { if (op != null) { if (op instanceof AffineTransformOp) { AffineTransformOp atop = (AffineTransformOp) op; transformImage(sg, img, x, y, atop.getTransform(), atop.getInterpolationType()); return; } else { img = op.filter(img, null); } } copyImage(sg, img, x, y, null); } }
package com.chenshun.springdata.commonrepositorymethod; import org.springframework.data.jpa.repository.support.JpaEntityInformation; import org.springframework.data.jpa.repository.support.SimpleJpaRepository; import org.springframework.data.repository.NoRepositoryBean; import javax.persistence.EntityManager; import java.io.Serializable; /** * User: chenshun131 <p /> * Time: 18/2/28 11:06 <p /> * Version: V1.0 <p /> * Description: <p /> */ @NoRepositoryBean public class CommonMethodTestImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements CommonMethodTest<T, ID> { public CommonMethodTestImpl(Class<T> domainClass, EntityManager em) { super(domainClass, em); } public CommonMethodTestImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) { super(entityInformation, entityManager); } @Override public void method() { System.out.println("...METHOD TEST..."); } }
/* * Copyright 2018 Michael Jakubec * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jakubec.view.app; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import net.jakubec.view.app.settings.VSettings; import net.jakubec.view.properties.VProperties; /** * This class is the info dialog for the Program * * @author amunra * */ class AboutDialog extends JDialog { /** * This is the inner class displaying the Information of the Computer * * @author amunra * */ private static class InfoPanel extends JPanel implements MouseMotionListener { Image img; private boolean above = false; private int hpwidth; public InfoPanel() { super(); this.addMouseMotionListener(this); this.setBackground(Color.white); img = null; Thread t = new Thread(() -> { try { img = ImageIO.read(new File(VSettings.rootDir, "Logo2.gif")); } catch (Exception e) { } }); t.start(); } @Override public void mouseDragged(final MouseEvent e) { } @Override public void mouseMoved(final MouseEvent e) { int y = e.getY(); int x = e.getX(); if (y > 85 && y < 103) { if (x > (this.getWidth() - hpwidth) / 2 && x < (this.getWidth() + hpwidth) / 2) { if (!above) { above = true; repaint(); } return; } } if (above) { above = false; repaint(); } } @Override public void paint(final Graphics g) { super.paint(g); if (img != null) { g.drawImage(img, (this.getWidth() - img.getWidth(null)) / 2, (this.getHeight() - img.getHeight(null)) / 2, this); } Font f = new Font("sans", Font.BOLD, 26); g.setFont(f); g.setColor(new Color(0x33, 0x33, 0x99)); FontMetrics fm = getFontMetrics(f); String txt = "ImageView Version " + VSettings.PROG_VERSION; int width = fm.stringWidth(txt); g.drawString(txt, (this.getWidth() - width) / 2, 40); f = new Font("sans", Font.BOLD, 16); g.setFont(f); fm = getFontMetrics(f); g.setColor(new Color(0x00, 0x00, 0)); txt = VProperties.getValue("help.info"); width = fm.stringWidth(txt); g.drawString(txt, (this.getWidth() - width) / 2, 80); g.setColor(Color.blue); txt = VSettings.PROG_HOMEPAGE; width = fm.stringWidth(txt); hpwidth = width; g.drawString(txt, (this.getWidth() - width) / 2, 100); if (above) { g.drawLine((this.getWidth() - width) / 2, 103, (this.getWidth() + width) / 2, 103); } } } Container cp; public AboutDialog() { super(Application.getMainWindow(), VProperties.getValue("menu.help.about"), true); this.setSize(500, 400); JPanel p = new InfoPanel(); cp = this.getContentPane(); cp.setLayout(new BorderLayout()); this.setBackground(Color.white); JPanel btPanel = new JPanel(); JButton b = new JButton(VProperties.getValue("button.ok")); b.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { setVisible(false); dispose(); } }); btPanel.add(b); btPanel.setBackground(Color.WHITE); cp.add(btPanel, BorderLayout.SOUTH); JTabbedPane tabs = new JTabbedPane(); tabs.add("Info", new InfoPanel()); JTextArea license = new JTextArea(); license.setWrapStyleWord(true); license.setLineWrap(true); license.setText(License.getText()); license.setEditable(false); license.setCaretPosition(0); JScrollPane scrollPane = new JScrollPane(license, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setAutoscrolls(false); tabs.add(VProperties.getValue("help.license"), scrollPane); cp.add(tabs, BorderLayout.CENTER); setVisible(true); } }
package g1501_1600.s1600_throne_inheritance; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; import org.junit.jupiter.api.Test; class ThroneInheritanceTest { @Test void throneInheritance() { // order: king ThroneInheritance t = new ThroneInheritance("king"); // order: king > andy t.birth("king", "andy"); // order: king > andy > bob t.birth("king", "bob"); // order: king > andy > bob > catherine t.birth("king", "catherine"); // order: king > andy > matthew > bob > catherine t.birth("andy", "matthew"); // order: king > andy > matthew > bob > alex > catherine t.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > asha > catherine t.birth("bob", "asha"); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"] assertThat( t.getInheritanceOrder(), equalTo( Arrays.asList( "king", "andy", "matthew", "bob", "alex", "asha", "catherine"))); // order: king > andy > matthew > bob > alex > asha > catherine t.death("bob"); // return ["king", "andy", "matthew", "alex", "asha", "catherine"] t.getInheritanceOrder(); assertThat( t.getInheritanceOrder(), equalTo(Arrays.asList("king", "andy", "matthew", "alex", "asha", "catherine"))); } }
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/securitycenter/v1beta1/securitycenter_service.proto package com.google.cloud.securitycenter.v1beta1; public interface UpdateSourceRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.securitycenter.v1beta1.UpdateSourceRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The source resource to update. * </pre> * * <code>.google.cloud.securitycenter.v1beta1.Source source = 1;</code> */ boolean hasSource(); /** * * * <pre> * The source resource to update. * </pre> * * <code>.google.cloud.securitycenter.v1beta1.Source source = 1;</code> */ com.google.cloud.securitycenter.v1beta1.Source getSource(); /** * * * <pre> * The source resource to update. * </pre> * * <code>.google.cloud.securitycenter.v1beta1.Source source = 1;</code> */ com.google.cloud.securitycenter.v1beta1.SourceOrBuilder getSourceOrBuilder(); /** * * * <pre> * The FieldMask to use when updating the source resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ boolean hasUpdateMask(); /** * * * <pre> * The FieldMask to use when updating the source resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ com.google.protobuf.FieldMask getUpdateMask(); /** * * * <pre> * The FieldMask to use when updating the source resource. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder(); }
/* * Copyright 2014-2015 the original author or authors. * * 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, see <https://www.gnu.org/licenses/>. */ package de.schildbach.wallet.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import org.bitcoinj.wallet.WalletProtobufSerializer; import org.junit.Test; /** * @author Andreas Schildbach */ public class CryptoTest { private static final String PLAIN_TEXT = "plain text"; private static final byte[] PLAIN_BYTES = PLAIN_TEXT.getBytes(); private static final char[] PASSWORD = "password".toCharArray(); @Test public void roundtripText() throws Exception { final String plainText = Crypto.decrypt(Crypto.encrypt(PLAIN_TEXT, PASSWORD), PASSWORD); assertEquals(PLAIN_TEXT, plainText); } @Test public void roundtripDifferentTextSizes() throws Exception { final StringBuilder builder = new StringBuilder(); while (builder.length() < 4096) { final String plainText = builder.toString(); final String roundtrippedPlainText = Crypto.decrypt(Crypto.encrypt(plainText, PASSWORD), PASSWORD); assertEquals(plainText, roundtrippedPlainText); builder.append('x'); } } @Test public void roundtripBytes() throws Exception { final byte[] plainBytes = Crypto.decryptBytes(Crypto.encrypt(PLAIN_BYTES, PASSWORD), PASSWORD); assertArrayEquals(PLAIN_BYTES, plainBytes); } @Test public void roundtripDifferentByteSizes() throws Exception { final ByteArrayOutputStream stream = new ByteArrayOutputStream(4096); while (stream.toByteArray().length < 4096) { final byte[] plainBytes = stream.toByteArray(); final byte[] roundtrippedPlainBytes = Crypto.decryptBytes(Crypto.encrypt(plainBytes, PASSWORD), PASSWORD); assertArrayEquals(plainBytes, roundtrippedPlainBytes); stream.write(42); } } @Test public void roundtripDifferentPasswordSizes() throws Exception { final StringBuilder builder = new StringBuilder(); while (builder.length() < 4096) { final char[] password = builder.toString().toCharArray(); final String plainText = Crypto.decrypt(Crypto.encrypt(PLAIN_TEXT, password), password); assertEquals(PLAIN_TEXT, plainText); builder.append('x'); } } @Test public void backups() throws Exception { final byte[] backup = Crypto.decryptBytes(readBackupFromResource("bitcoin-wallet-backup-testnet-3.50"), PASSWORD); assertTrue(WalletProtobufSerializer.isWallet(new ByteArrayInputStream(backup))); final byte[] backupCrLf = Crypto.decryptBytes(readBackupFromResource("bitcoin-wallet-backup-testnet-3.50-crlf"), PASSWORD); assertTrue(WalletProtobufSerializer.isWallet(new ByteArrayInputStream(backupCrLf))); } private String readBackupFromResource(final String filename) throws IOException { final BufferedReader reader = new BufferedReader( new InputStreamReader(getClass().getResourceAsStream(filename), StandardCharsets.UTF_8)); final StringBuilder backup = new StringBuilder(); Io.copy(reader, backup); reader.close(); return backup.toString(); } }
package org.apache.xpath.axes; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ public class AxesWalker extends PredicatedNodeTest implements PathComponent, java.lang.Cloneable, org.apache.xpath.ExpressionOwner { // Fields protected AxesWalker m_nextWalker; protected int m_axis; protected org.apache.xml.dtm.DTMAxisTraverser m_traverser; // Constructors public AxesWalker(LocPathIterator arg1, int arg2){ super((LocPathIterator) null); } // Methods public java.lang.Object clone() throws java.lang.CloneNotSupportedException{ return (java.lang.Object) null; } public void init(org.apache.xpath.compiler.Compiler arg1, int arg2, int arg3) throws javax.xml.transform.TransformerException{ } public boolean deepEquals(org.apache.xpath.Expression arg1){ return false; } public org.apache.xpath.Expression getExpression(){ return (org.apache.xpath.Expression) null; } public void setExpression(org.apache.xpath.Expression arg1){ } public void callVisitors(org.apache.xpath.ExpressionOwner arg1, org.apache.xpath.XPathVisitor arg2){ } public int nextNode(){ return 0; } public void detach(){ } public int getRoot(){ return 0; } public org.apache.xml.dtm.DTM getDTM(int arg1){ return (org.apache.xml.dtm.DTM) null; } public int getLastPos(org.apache.xpath.XPathContext arg1){ return 0; } public final int getCurrentNode(){ return 0; } public int getAnalysisBits(){ return 0; } public void setRoot(int arg1){ } public boolean isDocOrdered(){ return false; } public int getAxis(){ return 0; } protected int getNextNode(){ return 0; } public void setNextWalker(AxesWalker arg1){ } public void setPrevWalker(AxesWalker arg1){ } public final WalkingIterator wi(){ return (WalkingIterator) null; } public AxesWalker getNextWalker(){ return (AxesWalker) null; } public AxesWalker getPrevWalker(){ return (AxesWalker) null; } public void setDefaultDTM(org.apache.xml.dtm.DTM arg1){ } }
/** * Copyright 2010 - 2020 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.tree.btree; import jetbrains.exodus.tree.INode; import jetbrains.exodus.tree.ITreeMutable; import org.junit.Assert; import org.junit.Test; public class BTreeNoDuplicatesExpiredAddressesTest extends BTreeTestBase { @Test public void testAdd() { tm = new BTreeEmpty(log, false, 1).getMutableCopy(); long address = saveTree(); checkExpiredAddress(tm, 0, "Expired: none"); t = new BTree(log, address, false, 1); tm = getTree().getMutableCopy(); getTreeMutable().put(kv(0, "value")); checkExpiredAddress(tm, 1, "Expired: root"); saveTree(); } @Test public void testModify() { tm = new BTreeEmpty(log, false, 1).getMutableCopy(); getTreeMutable().put(kv(0, "value")); getTreeMutable().put(kv(1, "value2")); checkExpiredAddress(tm, 0, "Expired: none"); long address = saveTree(); t = new BTree(log, address, false, 1); tm = getTree().getMutableCopy(); getTreeMutable().put(kv(0, "value2")); checkExpiredAddress(tm, 2, "Expired: root, value"); saveTree(); } @Test public void testDelete() { tm = new BTreeEmpty(log, false, 1).getMutableCopy(); INode leafNode = kv(0, "value"); getTreeMutable().put(leafNode); checkExpiredAddress(tm, 0, "Expired: none"); long address = saveTree(); t = new BTree(log, address, false, 1); tm = getTree().getMutableCopy(); tm.delete(leafNode.getKey()); checkExpiredAddress(tm, 2, "Expired: root, value"); saveTree(); } @Test public void testBulkAdd() { tm = new BTreeEmpty(log, false, 1).getMutableCopy(); long address = saveTree(); checkExpiredAddress(tm, 0, "Expired: none"); t = new BTree(log, address, false, 1); tm = getTree().getMutableCopy(); for (int i = 0; i < 1000; i++) { getTreeMutable().put(kv(i, "value")); } checkExpiredAddress(tm, 1, "Expired: root"); saveTree(); } @Test public void testBulkModify() { tm = new BTreeEmpty(log, createTestSplittingPolicy(), false, 1).getMutableCopy(); for (int i = 0; i < 1000; i++) { getTreeMutable().put(kv(i, "value")); } checkExpiredAddress(tm, 0, "Expired: none"); long address = saveTree(); t = new BTree(log, address, false, 1); tm = getTree().getMutableCopy(); for (int i = 0; i < 1000; i++) { getTreeMutable().put(kv(i, "value2")); } checkExpiredAddress(tm, countNodes(getTreeMutable()), "Expired: root, 1000 values + internal nodes"); saveTree(); } @Test public void testBulkDelete() { tm = new BTreeEmpty(log, createTestSplittingPolicy(), false, 1).getMutableCopy(); INode[] leafNode = new INode[1000]; for (int i = 0; i < 1000; i++) { leafNode[i] = kv(i, "value"); getTreeMutable().put(leafNode[i]); } checkExpiredAddress(tm, 0, "Expired: none"); long address = saveTree(); t = new BTree(log, address, false, 1); tm = getTree().getMutableCopy(); long addresses = countNodes(getTreeMutable()); for (int i = 0; i < 1000; i++) { tm.delete(leafNode[i].getKey()); } checkExpiredAddress(tm, addresses, "Expired: root, 1000 values + internal nodes"); saveTree(); } public void checkExpiredAddress(ITreeMutable tree, long expectedAddresses, String message) { Assert.assertEquals(message, expectedAddresses, tree.getExpiredLoggables().getSize()); } protected long countNodes(BTreeMutable tree) { return countNodes(tree.getRoot()); } private long countNodes(BasePage page) { if (page.isBottom()) { return page.getSize() + 1; } long result = 1; for (int i = 0; i < page.getSize(); i++) { result += countNodes(page.getChild(i)); } return result; } }
/* * @(#)AddNewPoolAction.java * * Copyright 2004 by Oracle Corporation, * 500 Oracle Parkway, Redwood Shores, California, 94065, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information * of Oracle Corporation. */ package org.eclipse.persistence.tools.workbench.scplugin.ui.pool; import javax.swing.JOptionPane; import org.eclipse.persistence.tools.workbench.framework.action.AbstractEnablableFrameworkAction; import org.eclipse.persistence.tools.workbench.framework.app.AbstractApplicationNode; import org.eclipse.persistence.tools.workbench.framework.app.ApplicationNode; import org.eclipse.persistence.tools.workbench.framework.context.WorkbenchContext; import org.eclipse.persistence.tools.workbench.scplugin.model.adapter.ConnectionPoolAdapter; import org.eclipse.persistence.tools.workbench.scplugin.model.adapter.ServerSessionAdapter; public class AddReadPoolAction extends AbstractEnablableFrameworkAction { public AddReadPoolAction( WorkbenchContext context) { super( context); } protected void initialize() { super.initialize(); this.initializeText( "ADD_READ_CONNECTION_POOL"); this.initializeMnemonic( "ADD_READ_CONNECTION_POOL"); // no accelerator this.initializeIcon( "CONNECTION_POOL_READ"); this.initializeToolTipText( "ADD_READ_CONNECTION_POOL.TOOL_TIP"); } protected void execute( ApplicationNode selectedNode) { ServerSessionAdapter session = ( ServerSessionAdapter)selectedNode.getValue(); navigatorSelectionModel().pushExpansionState(); ConnectionPoolAdapter newPool = session.addReadConnectionPool(); navigatorSelectionModel().popAndRestoreExpansionState(); (( AbstractApplicationNode)selectedNode.getProjectRoot()).selectDescendantNodeForValue( newPool, navigatorSelectionModel()); } protected boolean shouldBeEnabled(ApplicationNode selectedNode) { ServerSessionAdapter session = (ServerSessionAdapter) selectedNode.getValue(); return !session.hasReadPool(); } protected String[] enabledPropertyNames() { return new String[] {ServerSessionAdapter.READ_CONNECTION_POOL_PROPERTY}; } private void promptUserToTurnOffExternalConnectionPooling() { JOptionPane.showMessageDialog(getWorkbenchContext().getCurrentWindow(), resourceRepository().getString("EXTERNAL_CONNECTION_POOLING_ENABLED_WARNING_MESSAGE")); } }
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. 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 */ package org.opendaylight.controller.netconf.cli.commands.local; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import io.netty.util.concurrent.GlobalEventExecutor; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Set; import org.opendaylight.controller.netconf.cli.NetconfDeviceConnectionManager; import org.opendaylight.controller.netconf.cli.commands.AbstractCommand; import org.opendaylight.controller.netconf.cli.commands.Command; import org.opendaylight.controller.netconf.cli.commands.input.Input; import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition; import org.opendaylight.controller.netconf.cli.commands.output.Output; import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration; import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder; import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword; import org.opendaylight.protocol.framework.NeverReconnectStrategy; import org.opendaylight.protocol.framework.ReconnectStrategy; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.Node; import org.opendaylight.yangtools.yang.data.api.SimpleNode; import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl; import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl; import org.opendaylight.yangtools.yang.model.api.RpcDefinition; /** * Local command to connect to a remote device */ public class Connect extends AbstractCommand { private final NetconfDeviceConnectionManager connectManager; private final Integer connectionTimeout; private Connect(final QName qName, final InputDefinition args, final OutputDefinition output, final NetconfDeviceConnectionManager connectManager, final String description, final Integer connectionTimeout) { super(qName, args, output, description); this.connectManager = connectManager; this.connectionTimeout = connectionTimeout; } @Override public Output invoke(final Input inputArgs) { final NetconfClientConfigurationBuilder config = getConfig(inputArgs); return invoke(config, getArgument(inputArgs, "address-name", String.class)); } private Output invoke(final NetconfClientConfigurationBuilder config, final String addressName) { final Set<String> remoteCmds = connectManager.connectBlocking(addressName, config); final ArrayList<Node<?>> output = Lists.newArrayList(); output.add(new SimpleNodeTOImpl<>(QName.create(getCommandId(), "status"), null, "Connection initiated")); for (final String cmdId : remoteCmds) { output.add(new SimpleNodeTOImpl<>(QName.create(getCommandId(), "remote-commands"), null, cmdId)); } return new Output(new CompositeNodeTOImpl(getCommandId(), null, output)); } private NetconfClientConfigurationBuilder getConfig(final Input inputArgs) { final ReconnectStrategy strategy = getReconnectStrategy(); final String address = getArgument(inputArgs, "address-name", String.class); final Integer port = getArgument(inputArgs, "address-port", Integer.class); final String username = getArgument(inputArgs, "user-name", String.class); final String passwd = getArgument(inputArgs, "user-password", String.class); final InetSocketAddress inetAddress; try { inetAddress = new InetSocketAddress(InetAddress.getByName(address), port); } catch (final UnknownHostException e) { throw new IllegalArgumentException("Unable to use address: " + address, e); } return NetconfClientConfigurationBuilder.create().withAddress(inetAddress) .withConnectionTimeoutMillis(connectionTimeout) .withReconnectStrategy(strategy) .withAuthHandler(new LoginPassword(username, passwd)) .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH); } private <T> Optional<T> getArgumentOpt(final Input inputArgs, final String argName, final Class<T> type) { final QName argQName = QName.create(getCommandId(), argName); final Node<?> argumentNode = inputArgs.getArg(argName); if (argumentNode == null) { return Optional.absent(); } Preconditions.checkArgument(argumentNode instanceof SimpleNode, "Only simple type argument supported, %s", argQName); final Object value = argumentNode.getValue(); Preconditions.checkArgument(type.isInstance(value), "Unexpected instance type: %s for argument: %s", value.getClass(), argQName); return Optional.of(type.cast(value)); } private <T> T getArgument(final Input inputArgs, final String argName, final Class<T> type) { final Optional<T> argumentOpt = getArgumentOpt(inputArgs, argName, type); Preconditions.checkState(argumentOpt.isPresent(), "Argument: %s is missing but is required", argName); return argumentOpt.get(); } public static ReconnectStrategy getReconnectStrategy() { // FIXME move to args either start-up args or input nodes for connect or both return new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 1000); } public static Command create(final RpcDefinition rpcDefinition, final NetconfDeviceConnectionManager connectManager, final Integer connectionTimeout) { return new Connect(rpcDefinition.getQName(), getInputDefinition(rpcDefinition), getOutputDefinition(rpcDefinition), connectManager, rpcDefinition.getDescription(), connectionTimeout); } }
package de.fu_berlin.inf.ag_se.browser.utils; import de.fu_berlin.inf.ag_se.browser.BrowserUtils; import de.fu_berlin.inf.ag_se.browser.html.IElement; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class BrowserUtilsTest { @Test public void testGetFirstTagName() { assertEquals("body", BrowserUtils.getFirstTagName("<body>")); assertEquals("body", BrowserUtils.getFirstTagName(" <body>")); assertEquals("body", BrowserUtils.getFirstTagName("<body>")); assertEquals("body", BrowserUtils.getFirstTagName(" <body> \n")); assertEquals("bODY", BrowserUtils.getFirstTagName(" abc <bODY a=\"b\"> def")); assertEquals("body", BrowserUtils.getFirstTagName("<body/>")); assertEquals("body", BrowserUtils.getFirstTagName(" <body/>")); assertEquals("body", BrowserUtils.getFirstTagName("<body/>")); assertEquals("body", BrowserUtils.getFirstTagName(" <body /> \n")); assertEquals("bODY", BrowserUtils.getFirstTagName(" abc <bODY a=\'b\' /> def")); assertEquals("body", BrowserUtils.getFirstTagName("<body><div></div></body>")); assertEquals("body", BrowserUtils.getFirstTagName(" <body><div></div></body>")); assertEquals("body", BrowserUtils.getFirstTagName("<body><div></div></body>")); assertEquals( "body", BrowserUtils .getFirstTagName(" <body a=\"b\"><div></div></body> \n")); assertEquals( "bODY", BrowserUtils .getFirstTagName(" abc <bODY a=\'b\' ><div></div></bODY> def")); assertEquals( "a", BrowserUtils .getFirstTagName("<a class=\"link-box\" href=\"//ru.wikipedia.org/\" title=\"Russkiy — Wikipedia — Свободная энциклопедия\"><strong>Русский</strong><br>\n <em>Свободная энциклопедия</em><br>\n <small>1 144 000+ статей</small></a>")); assertEquals( "td", BrowserUtils .getFirstTagName("<td style=\"min-width: 6.5em;\"><div class=\"btn-group\"><a href=\"addcode-apiua://survey/cd/2013-09-19T11:51:16.616+02:00/workStepUnit\" class=\"btn btn-primary btn-xs\">Add Code...</a><a href=\"#\" class=\"btn btn-primary btn-xs\" draggable=\"true\" data-dnd-mime=\"text/plain\" data-dnd-data=\"apiua://survey/cd/2013-09-19T11:51:16.616+02:00/workStepUnit\"><span class=\"glyphicon glyphicon-share-alt no_click\" style=\"height: 1.5em; line-height: 1.4em;\"></span></a></div></td>")); assertEquals(null, BrowserUtils.getFirstTagName("<>")); assertEquals(null, BrowserUtils.getFirstTagName("< >")); assertEquals(null, BrowserUtils.getFirstTagName("<body")); assertEquals(null, BrowserUtils.getFirstTagName("body>")); assertEquals(null, BrowserUtils.getFirstTagName(" <bODY")); assertEquals(null, BrowserUtils.getFirstTagName("<body<div>>")); assertEquals(null, BrowserUtils.getFirstTagName(null)); } @Test public void testExtractElement() { IElement td = BrowserUtils .extractElement("<td style=\"min-width: 6.5em;\"><div class=\"btn-group\"><a href=\"addcode-apiua://survey/cd/2013-09-19T11:51:16.616+02:00/workStepUnit\" class=\"btn btn-primary btn-xs\">Add Code...</a><a href=\"#\" class=\"btn btn-primary btn-xs\" draggable=\"true\" data-dnd-mime=\"text/plain\" data-dnd-data=\"apiua://survey/cd/2013-09-19T11:51:16.616+02:00/workStepUnit\"><span class=\"glyphicon glyphicon-share-alt no_click\" style=\"height: 1.5em; line-height: 1.4em;\"></span></a></div></td>"); assertNotNull(td); assertEquals("td", td.getName()); IElement selfEnclosingTd = BrowserUtils .extractElement("<td style=\"min-width: 6.5em;\"/>"); assertNotNull(selfEnclosingTd); assertEquals("td", selfEnclosingTd.getName()); } }
/** * Given two number, dividend and divisor * Write an algorithm to find remainder if dividend is divided by divisor * * You are not allowed to use % or modulo operator * * Calculate number of left shift * At every left shift divisor is doubled. * * Return the dividend that remained * * Time Complexity: O(logn) */ public class RemainderWithoutUsingModulo { private static int remainderWithoutUsingModulo(int dividend, int divisor) { //If divisor is 0 then remainder is the dividend itself if (divisor == 0) { return dividend; } //The remainder will be zero if (dividend == Integer.MIN_VALUE && divisor == -1) { return 0; } //Get positive values long absDividend = Math.abs((long)dividend); long absDivisor = Math.abs((long)divisor); while(absDividend >= absDivisor) { //Calculate number of left shift //At every left shift, divisor is doubled int numShift = 0; while (absDividend >= (absDivisor << numShift)) { numShift++; } //Dividend minus the largest shift divisor absDividend = absDividend - (absDivisor << (numShift - 1)); } //Finally the absDividend will be the remainder //If dividend is negative the remainder will be negative else it will be positive if (dividend < 0) { return -(int)absDividend; } else { return (int)absDividend; } } public static void main(String[] args) { System.out.println(remainderWithoutUsingModulo(-2147483648, -1)); //0 System.out.println(remainderWithoutUsingModulo(12,0)); //12 System.out.println(remainderWithoutUsingModulo(12,5)); //2 System.out.println(remainderWithoutUsingModulo(10,4)); //2 } }
package com.metkal.taskit.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.metkal.taskit.dao.TaskDao; import com.metkal.taskit.model.Task; import com.metkal.taskit.model.User; @Service public class TaskService { @Autowired private TaskDao taskDao; @Transactional public List<Task> getTasks(long userId){ return taskDao.getTasks(userId); } @Transactional public Task getTask(long id) { return taskDao.getTask(id); } @Transactional public Task addTask(Task task) { return taskDao.addTask(task); } @Transactional public Task updateTask(Task task) { return taskDao.updateTask(task); } @Transactional public boolean deleteTask(long id) { return taskDao.deleteTask(id); } @Transactional public boolean deleteTasks(long userId) { return taskDao.deleteTasks(userId); } @Transactional public boolean shareTask(String email, Task task) { return taskDao.shareTask(email, task); } }
package com.sfxcode.sapphire.javafx.skin; import com.sfxcode.sapphire.javafx.control.SFXDataListView; import com.sfxcode.sapphire.javafx.control.SFXDualDataListView; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.layout.*; import java.util.ArrayList; import java.util.List; public class SFXDualDataListViewSkin<S> extends SkinBase<SFXDualDataListView<S>>{ public SFXDataListView<S> leftDataListView = new SFXDataListView<S>(); public SFXDataListView<S> rightDataListView = new SFXDataListView<S>(); public GridPane gridPane = new GridPane(); public Button buttonMoveToTarget = new Button("->"); public Button buttonMoveToTargetAll = new Button("=>"); public Button buttonMoveToSource = new Button("<-"); public Button buttonMoveToSourceAll = new Button("<="); public VBox buttonBox = new VBox(5); private List<String> list = new ArrayList<String>(); private ObservableList<String> observableList = FXCollections.observableList(list); public ListView<String> listView = new ListView<String>(observableList); /** * Constructor for all SkinBase instances. * * @param control The control for which this Skin should attach to. */ public SFXDualDataListViewSkin(SFXDualDataListView<S> control) { super(control); observableList.add("Item 1"); observableList.add("Item 2"); observableList.add("Item 3"); updateView(); } public void updateView() { RowConstraints row = new RowConstraints(); row.setFillHeight(true); row.setVgrow(Priority.NEVER); gridPane.getRowConstraints().add(row); ColumnConstraints col1 = new ColumnConstraints(); col1.setFillWidth(true); col1.setHgrow(Priority.ALWAYS); col1.setMaxWidth(Double.MAX_VALUE); col1.setPrefWidth(200); ColumnConstraints col2 = new ColumnConstraints(); col2.setFillWidth(true); col2.setHgrow(Priority.NEVER); col2.setMaxWidth(50); col2.setMinWidth(50); ColumnConstraints col3 = new ColumnConstraints(); col3.setFillWidth(true); col3.setHgrow(Priority.ALWAYS); col3.setMaxWidth(Double.MAX_VALUE); col3.setPrefWidth(200); gridPane.getColumnConstraints().addAll(col1, col2, col3); buttonBox.setAlignment(Pos.CENTER); buttonBox.setFillWidth(true); buttonBox.getChildren().addAll(buttonMoveToTarget, buttonMoveToTargetAll, buttonMoveToSource, buttonMoveToSourceAll); buttonBox.setMinHeight(100); gridPane.add(leftDataListView, 0, 0); gridPane.add(buttonBox, 1, 0); gridPane.add(rightDataListView, 2, 0); getChildren().add(gridPane); } }
package parser.visitor; import cc.kave.commons.model.naming.codeelements.IMethodName; import cc.kave.commons.model.ssts.expressions.assignable.ICastExpression; import cc.kave.commons.model.ssts.expressions.assignable.IInvocationExpression; import cc.kave.commons.model.ssts.impl.visitor.AbstractTraversingNodeVisitor; import cc.kave.commons.model.ssts.references.IPropertyReference; import parser.addition.CastAdder; import parser.addition.MethodAdder; import parser.addition.PropertyAdder; import parser.addition.SimpleMethodAdder; public class ContextVisitor extends AbstractTraversingNodeVisitor<Void, Void> { MethodAdder adder; String path; public ContextVisitor(String path) { this.path = path; } @Override public Void visit(IInvocationExpression expr, Void context) { adder = new SimpleMethodAdder(path); IMethodName method = expr.getMethodName(); if (!method.getName().contains("?") && !method.getDeclaringType().getAssembly().isLocalProject()) { adder.addMethod(method); } return null; } @Override public Void visit(ICastExpression expr, Void context) { if (!expr.getTargetType().getName().contains("?") && !expr.getTargetType().getAssembly().isLocalProject()) { adder = new CastAdder(path); adder.addMethod(expr.getTargetType()); } return null; } @Override public Void visit(IPropertyReference expr, Void context) { if (!expr.getPropertyName().getDeclaringType().getAssembly().isLocalProject()) { adder = new PropertyAdder(path); adder.addMethod(expr.getPropertyName()); } return null; } }
package com.chen.ad; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
/* * 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. */ /* * $Id: SerializerMessages_pl.java 471981 2006-11-07 04:28:00Z minchau $ */ package org.apache.xml.serializer.utils; import java.util.ListResourceBundle; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * An instance of this class is a ListResourceBundle that * has the required getContents() method that returns * an array of message-key/message associations. * <p> * The message keys are defined in {@link MsgKey}. The * messages that those keys map to are defined here. * <p> * The messages in the English version are intended to be * translated. * * This class is not a public API, it is only public because it is * used in org.apache.xml.serializer. * * @xsl.usage internal */ public class SerializerMessages_pl extends ListResourceBundle { /* * This file contains error and warning messages related to * Serializer Error Handling. * * General notes to translators: * 1) A stylesheet is a description of how to transform an input XML document * into a resultant XML document (or HTML document or text). The * stylesheet itself is described in the form of an XML document. * * 2) An element is a mark-up tag in an XML document; an attribute is a * modifier on the tag. For example, in <elem attr='val' attr2='val2'> * "elem" is an element name, "attr" and "attr2" are attribute names with * the values "val" and "val2", respectively. * * 3) A namespace declaration is a special attribute that is used to associate * a prefix with a URI (the namespace). The meanings of element names and * attribute names that use that prefix are defined with respect to that * namespace. * * */ /** The lookup table for error messages. */ public Object[][] getContents() { Object[][] contents = new Object[][] { { MsgKey.BAD_MSGKEY, "Klucz komunikatu ''{0}'' nie znajduje si\u0119 w klasie komunikat\u00f3w ''{1}''" }, { MsgKey.BAD_MSGFORMAT, "Nie powiod\u0142o si\u0119 sformatowanie komunikatu ''{0}'' w klasie komunikat\u00f3w ''{1}''." }, { MsgKey.ER_SERIALIZER_NOT_CONTENTHANDLER, "Klasa szereguj\u0105ca ''{0}'' nie implementuje org.xml.sax.ContentHandler." }, { MsgKey.ER_RESOURCE_COULD_NOT_FIND, "Nie mo\u017cna znale\u017a\u0107 zasobu [ {0} ].\n {1}" }, { MsgKey.ER_RESOURCE_COULD_NOT_LOAD, "Zas\u00f3b [ {0} ] nie m\u00f3g\u0142 za\u0142adowa\u0107: {1} \n {2} \t {3}" }, { MsgKey.ER_BUFFER_SIZE_LESSTHAN_ZERO, "Wielko\u015b\u0107 buforu <=0" }, { MsgKey.ER_INVALID_UTF16_SURROGATE, "Wykryto niepoprawny odpowiednik UTF-16: {0} ?" }, { MsgKey.ER_OIERROR, "B\u0142\u0105d we/wy" }, { MsgKey.ER_ILLEGAL_ATTRIBUTE_POSITION, "Nie mo\u017cna doda\u0107 atrybutu {0} po bezpo\u015brednich w\u0119z\u0142ach potomnych ani przed wyprodukowaniem elementu. Atrybut zostanie zignorowany." }, /* * Note to translators: The stylesheet contained a reference to a * namespace prefix that was undefined. The value of the substitution * text is the name of the prefix. */ { MsgKey.ER_NAMESPACE_PREFIX, "Nie zadeklarowano przestrzeni nazw dla przedrostka ''{0}''." }, /* * Note to translators: This message is reported if the stylesheet * being processed attempted to construct an XML document with an * attribute in a place other than on an element. The substitution text * specifies the name of the attribute. */ { MsgKey.ER_STRAY_ATTRIBUTE, "Atrybut ''{0}'' znajduje si\u0119 poza elementem." }, /* * Note to translators: As with the preceding message, a namespace * declaration has the form of an attribute and is only permitted to * appear on an element. The substitution text {0} is the namespace * prefix and {1} is the URI that was being used in the erroneous * namespace declaration. */ { MsgKey.ER_STRAY_NAMESPACE, "Deklaracja przestrzeni nazw ''{0}''=''{1}'' znajduje si\u0119 poza elementem." }, { MsgKey.ER_COULD_NOT_LOAD_RESOURCE, "Nie mo\u017cna za\u0142adowa\u0107 ''{0}'' (sprawd\u017a CLASSPATH) - u\u017cywane s\u0105 teraz warto\u015bci domy\u015blne" }, { MsgKey.ER_ILLEGAL_CHARACTER, "Pr\u00f3ba wyprowadzenia znaku warto\u015bci ca\u0142kowitej {0}, kt\u00f3ry nie jest reprezentowany w podanym kodowaniu wyj\u015bciowym {1}." }, { MsgKey.ER_COULD_NOT_LOAD_METHOD_PROPERTY, "Nie mo\u017cna za\u0142adowa\u0107 pliku w\u0142a\u015bciwo\u015bci ''{0}'' dla metody wyj\u015bciowej ''{1}'' (sprawd\u017a CLASSPATH)" }, { MsgKey.ER_INVALID_PORT, "Niepoprawny numer portu" }, { MsgKey.ER_PORT_WHEN_HOST_NULL, "Nie mo\u017cna ustawi\u0107 portu, kiedy host jest pusty" }, { MsgKey.ER_HOST_ADDRESS_NOT_WELLFORMED, "Host nie jest poprawnie skonstruowanym adresem" }, { MsgKey.ER_SCHEME_NOT_CONFORMANT, "Schemat nie jest zgodny." }, { MsgKey.ER_SCHEME_FROM_NULL_STRING, "Nie mo\u017cna ustawi\u0107 schematu z pustego ci\u0105gu znak\u00f3w" }, { MsgKey.ER_PATH_CONTAINS_INVALID_ESCAPE_SEQUENCE, "\u015acie\u017cka zawiera nieznan\u0105 sekwencj\u0119 o zmienionym znaczeniu" }, { MsgKey.ER_PATH_INVALID_CHAR, "\u015acie\u017cka zawiera niepoprawny znak {0}" }, { MsgKey.ER_FRAG_INVALID_CHAR, "Fragment zawiera niepoprawny znak" }, { MsgKey.ER_FRAG_WHEN_PATH_NULL, "Nie mo\u017cna ustawi\u0107 fragmentu, kiedy \u015bcie\u017cka jest pusta" }, { MsgKey.ER_FRAG_FOR_GENERIC_URI, "Fragment mo\u017cna ustawi\u0107 tylko dla og\u00f3lnego URI" }, { MsgKey.ER_NO_SCHEME_IN_URI, "Nie znaleziono schematu w URI" }, { MsgKey.ER_CANNOT_INIT_URI_EMPTY_PARMS, "Nie mo\u017cna zainicjowa\u0107 URI z pustymi parametrami" }, { MsgKey.ER_NO_FRAGMENT_STRING_IN_PATH, "Nie mo\u017cna poda\u0107 fragmentu jednocze\u015bnie w \u015bcie\u017cce i fragmencie" }, { MsgKey.ER_NO_QUERY_STRING_IN_PATH, "Tekstu zapytania nie mo\u017cna poda\u0107 w tek\u015bcie \u015bcie\u017cki i zapytania" }, { MsgKey.ER_NO_PORT_IF_NO_HOST, "Nie mo\u017cna poda\u0107 portu, je\u015bli nie podano hosta" }, { MsgKey.ER_NO_USERINFO_IF_NO_HOST, "Nie mo\u017cna poda\u0107 informacji o u\u017cytkowniku, je\u015bli nie podano hosta" }, { MsgKey.ER_XML_VERSION_NOT_SUPPORTED, "Ostrze\u017cenie: Wymagan\u0105 wersj\u0105 dokumentu wyj\u015bciowego jest ''{0}''. Ta wersja XML nie jest obs\u0142ugiwana. Wersj\u0105 dokumentu wyj\u015bciowego b\u0119dzie ''1.0''." }, { MsgKey.ER_SCHEME_REQUIRED, "Schemat jest wymagany!" }, /* * Note to translators: The words 'Properties' and * 'SerializerFactory' in this message are Java class names * and should not be translated. */ { MsgKey.ER_FACTORY_PROPERTY_MISSING, "Obiekt klasy Properties przekazany do klasy SerializerFactory nie ma w\u0142a\u015bciwo\u015bci ''{0}''." }, { MsgKey.ER_ENCODING_NOT_SUPPORTED, "Ostrze\u017cenie: dekodowany ''{0}'' nie jest obs\u0142ugiwany przez \u015brodowisko wykonawcze Java." }, {MsgKey.ER_FEATURE_NOT_FOUND, "Parametr ''{0}'' nie zosta\u0142 rozpoznany."}, {MsgKey.ER_FEATURE_NOT_SUPPORTED, "Parametr ''{0}'' zosta\u0142 rozpoznany, ale nie mo\u017cna ustawi\u0107 \u017c\u0105danej warto\u015bci."}, {MsgKey.ER_STRING_TOO_LONG, "Wynikowy \u0142a\u0144cuch jest zbyt d\u0142ugi, aby si\u0119 zmie\u015bci\u0107 w obiekcie DOMString: ''{0}''."}, {MsgKey.ER_TYPE_MISMATCH_ERR, "Typ warto\u015bci parametru o tej nazwie jest niezgodny z oczekiwanym typem warto\u015bci. "}, {MsgKey.ER_NO_OUTPUT_SPECIFIED, "Docelowe miejsce zapisu danych wyj\u015bciowych by\u0142o puste (null)."}, {MsgKey.ER_UNSUPPORTED_ENCODING, "Napotkano nieobs\u0142ugiwane kodowanie."}, {MsgKey.ER_UNABLE_TO_SERIALIZE_NODE, "Nie mo\u017cna przekszta\u0142ci\u0107 w\u0119z\u0142a do postaci szeregowej."}, {MsgKey.ER_CDATA_SECTIONS_SPLIT, "Sekcja CDATA zawiera jeden lub kilka znacznik\u00f3w zako\u0144czenia ']]>'."}, {MsgKey.ER_WARNING_WF_NOT_CHECKED, "Nie mo\u017cna utworzy\u0107 instancji obiektu sprawdzaj\u0105cego Well-Formedness. Parametr well-formed ustawiono na warto\u015b\u0107 true, ale nie mo\u017cna by\u0142o dokona\u0107 sprawdzenia poprawno\u015bci konstrukcji." }, {MsgKey.ER_WF_INVALID_CHARACTER, "W\u0119ze\u0142 ''{0}'' zawiera niepoprawne znaki XML." }, { MsgKey.ER_WF_INVALID_CHARACTER_IN_COMMENT, "W komentarzu znaleziono niepoprawny znak XML (Unicode: 0x{0})." }, { MsgKey.ER_WF_INVALID_CHARACTER_IN_PI, "W danych instrukcji przetwarzania znaleziono niepoprawny znak XML (Unicode: 0x{0})." }, { MsgKey.ER_WF_INVALID_CHARACTER_IN_CDATA, "W sekcji CDATA znaleziono niepoprawny znak XML (Unicode: 0x{0})." }, { MsgKey.ER_WF_INVALID_CHARACTER_IN_TEXT, "W tre\u015bci danych znakowych w\u0119z\u0142a znaleziono niepoprawny znak XML (Unicode: 0x{0})." }, { MsgKey.ER_WF_INVALID_CHARACTER_IN_NODE_NAME, "W {0} o nazwie ''{1}'' znaleziono niepoprawne znaki XML." }, { MsgKey.ER_WF_DASH_IN_COMMENT, "Ci\u0105g znak\u00f3w \"--\" jest niedozwolony w komentarzu." }, {MsgKey.ER_WF_LT_IN_ATTVAL, "Warto\u015b\u0107 atrybutu \"{1}\" zwi\u0105zanego z typem elementu \"{0}\" nie mo\u017ce zawiera\u0107 znaku ''<''." }, {MsgKey.ER_WF_REF_TO_UNPARSED_ENT, "Odwo\u0142anie do encji nieprzetwarzanej \"&{0};\" jest niedozwolone." }, {MsgKey.ER_WF_REF_TO_EXTERNAL_ENT, "Odwo\u0142anie do zewn\u0119trznej encji \"&{0};\" jest niedozwolone w warto\u015bci atrybutu." }, {MsgKey.ER_NS_PREFIX_CANNOT_BE_BOUND, "Nie mo\u017cna zwi\u0105za\u0107 przedrostka \"{0}\" z przestrzeni\u0105 nazw \"{1}\"." }, {MsgKey.ER_NULL_LOCAL_ELEMENT_NAME, "Nazwa lokalna elementu \"{0}\" jest pusta (null)." }, {MsgKey.ER_NULL_LOCAL_ATTR_NAME, "Nazwa lokalna atrybutu \"{0}\" jest pusta (null)." }, { MsgKey.ER_ELEM_UNBOUND_PREFIX_IN_ENTREF, "Tekst zast\u0119puj\u0105cy w\u0119z\u0142a encji \"{0}\" zawiera w\u0119ze\u0142 elementu \"{1}\" o niezwi\u0105zanym przedrostku \"{2}\"." }, { MsgKey.ER_ATTR_UNBOUND_PREFIX_IN_ENTREF, "Tekst zast\u0119puj\u0105cy w\u0119z\u0142a encji \"{0}\" zawiera w\u0119ze\u0142 atrybutu \"{1}\" o niezwi\u0105zanym przedrostku \"{2}\"." }, }; return contents; } }
package com.example.gbelton.flixter; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.example.gbelton.flixter.adapters.MovieArrayAdapter; import com.example.gbelton.flixter.models.Movie; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import cz.msebera.android.httpclient.Header; public class MoviesActivity extends AppCompatActivity { ArrayList<Movie> movies; MovieArrayAdapter movieAdapter; ListView lvItems; private SwipeRefreshLayout swipeContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movies); //TextView title = (TextView) findViewById(R.id.tvOverview); //Typeface titleFont = Typeface.createFromAsset(getAssets(), "fonts/Wisdom Script AJ.ttf"); //title.setTypeface(titleFont); fetchTimelineAsync(0); // Lookup the swipe container view swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Your code to refresh the list here. // Make sure you call swipeContainer.setRefreshing(false) // once the network request has completed successfully. fetchTimelineAsync(0); } }); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); lvItems = (ListView) findViewById(R.id.lvMovies); movies = new ArrayList<>(); movieAdapter = new MovieArrayAdapter(this, movies); lvItems.setAdapter(movieAdapter); lvItems = (ListView) findViewById(R.id.lvMovies); lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // first parameter is the context, second is the class of the activity to launch Intent i = new Intent(MoviesActivity.this, MoreInfoActivity.class); i.putExtra("title", movies.get(position).getTitle()); i.putExtra("overview", movies.get(position).getOverview()); i.putExtra("release", movies.get(position).getReleaseDate()); i.putExtra("posterURL", movies.get(position).getBackdropPath()); startActivity(i); // brings up the second activity } }); } public void fetchTimelineAsync(int page) { // Send the network request to fetch the updated data // `client` here is an instance of Android Async HTTP String url= "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed"; AsyncHttpClient client = new AsyncHttpClient(); client.get(url, new JsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { //super.onSuccess(statusCode, headers, response); JSONArray movieJsonResults = null; try { movieJsonResults = response.getJSONArray("results"); movies.clear(); movies.addAll(Movie.fromJSONArray(movieJsonResults)); movieAdapter.notifyDataSetChanged(); Log.d("DEBUG",movies.toString()); } catch (JSONException e) { e.printStackTrace(); } swipeContainer.setRefreshing(false); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { super.onFailure(statusCode, headers, responseString, throwable); } }); } }
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.hasModifier; import static com.google.errorprone.matchers.Matchers.isArrayType; import static com.google.errorprone.matchers.Matchers.methodReturns; import static com.google.errorprone.suppliers.Suppliers.typeFromString; import com.google.common.collect.ImmutableListMultimap; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import java.util.Map; import javax.lang.model.element.Modifier; /** * Flags mutable collections in AutoValue. * * @author bhagwani@google.com (Sumit Bhagwani) */ @BugPattern( name = "AutoValueImmutableFields", altNames = "mutable", summary = "AutoValue recommends using immutable collections", severity = WARNING, documentSuppression = false) public class AutoValueImmutableFields extends BugChecker implements ClassTreeMatcher { private static final ImmutableListMultimap<String, Matcher<MethodTree>> REPLACEMENT_TO_MATCHERS = ImmutableListMultimap.<String, Matcher<MethodTree>>builder() .put("ImmutableCollection", returning("java.util.Collection")) .putAll( "ImmutableList", methodReturns(isArrayType()), returning("java.util.List"), returning("java.util.ArrayList"), returning("java.util.LinkedList"), returning("com.google.common.collect.ImmutableList.Builder")) .putAll( "ImmutableMap", returning("java.util.Map"), returning("java.util.HashMap"), returning("java.util.LinkedHashMap"), returning("com.google.common.collect.ImmutableMap.Builder")) .putAll( "ImmutableSortedMap", returning("java.util.SortedMap"), returning("java.util.TreeMap"), returning("com.google.common.collect.ImmutableSortedMap.Builder")) .putAll( "ImmutableBiMap", returning("com.google.common.collect.BiMap"), returning("com.google.common.collect.ImmutableBiMap.Builder")) .putAll( "ImmutableSet", returning("java.util.Set"), returning("java.util.HashSet"), returning("java.util.LinkedHashSet"), returning("com.google.common.collect.ImmutableSet.Builder")) .putAll( "ImmutableSortedSet", returning("java.util.SortedSet"), returning("java.util.TreeSet"), returning("com.google.common.collect.ImmutableSortedSet.Builder")) .putAll( "ImmutableMultimap", returning("com.google.common.collect.Multimap"), returning("com.google.common.collect.ImmutableMultimap.Builder")) .putAll( "ImmutableListMultimap", returning("com.google.common.collect.ListMultimap"), returning("com.google.common.collect.ImmutableListMultimap.Builder")) .putAll( "ImmutableSetMultimap", returning("com.google.common.collect.SetMultimap"), returning("com.google.common.collect.ImmutableSetMultimap.Builder")) .putAll( "ImmutableMultiset", returning("com.google.common.collect.Multiset"), returning("com.google.common.collect.ImmutableMultiset.Builder")) .putAll( "ImmutableSortedMultiset", returning("com.google.common.collect.SortedMultiset"), returning("com.google.common.collect.ImmutableSortedMultiset.Builder")) .putAll( "ImmutableTable", returning("com.google.common.collect.Table"), returning("com.google.common.collect.ImmutableTable.Builder")) .putAll( "ImmutableRangeMap", returning("com.google.common.collect.RangeMap"), returning("com.google.common.collect.ImmutableRangeMap.Builder")) .putAll( "ImmutableRangeSet", returning("com.google.common.collect.RangeSet"), returning("com.google.common.collect.ImmutableRangeSet.Builder")) .putAll( "ImmutablePrefixTrie", returning("com.google.common.collect.PrefixTrie"), returning("com.google.common.collect.ImmutablePrefixTrie.Builder")) .build(); private static Matcher<MethodTree> returning(String type) { return methodReturns(typeFromString(type)); } private static final Matcher<MethodTree> ABSTRACT_MATCHER = hasModifier(Modifier.ABSTRACT); @Override public Description matchClass(ClassTree tree, VisitorState state) { if (ASTHelpers.hasAnnotation(tree, "com.google.auto.value.AutoValue", state)) { for (Tree memberTree : tree.getMembers()) { if (memberTree instanceof MethodTree && !isSuppressed(memberTree)) { MethodTree methodTree = (MethodTree) memberTree; if (ABSTRACT_MATCHER.matches(methodTree, state)) { for (Map.Entry<String, Matcher<MethodTree>> entry : REPLACEMENT_TO_MATCHERS.entries()) { if (entry.getValue().matches(methodTree, state)) { state.reportMatch( buildDescription(methodTree) .setMessage( String.format( "AutoValue instances should be deeply immutable. Therefore, we" + " recommend returning %s instead.", entry.getKey())) .build()); } } } } } } return NO_MATCH; } }
/* * $Id: KeyExchangeToken.java,v 1.3 2008-02-26 06:33:19 ofung Exp $ */ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.xml.ws.security.trust.elements; import java.util.List; /** * TODO: Not clear how this gets used * @author WS-Trust Implementation Team. */ public interface KeyExchangeToken { /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } * * */ List<Object> getAny(); }
/* * Copyright © 2015 Cask Data, 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 io.cdap.cdap.cli.util.table; import org.junit.Ignore; /** * */ @Ignore public class CsvTableRendererTest extends TableRendererTest { @Override public TableRenderer getRenderer() { return new CsvTableRenderer(); } }
/* * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.argumentselectiondefects; import com.google.errorprone.CompilationTestHelper; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for {@code NamedParameterChecker} */ @RunWith(JUnit4.class) public class NamedParameterCheckerTest { private CompilationTestHelper compilationHelper; @Before public void setUp() { compilationHelper = CompilationTestHelper.newInstance(NamedParameterChecker.class, getClass()); } @Test public void namedParametersChecker_ignoresCall_withNoComments() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " target(arg1, arg2);", " }", "}") .doTest(); } @Test public void namedParametersChecker_findsError_withOneBadComment() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " // BUG: Diagnostic contains: target(arg2, /* param2= */arg1)", " target(/* param2= */arg1, arg2);", " }", "}") .doTest(); } @Test public void namedParametersChecker_suggestsSwap_withSwappedArgs() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " // BUG: Diagnostic contains: target(/* param1= */arg1, /* param2= */arg2)", " target(/* param2= */arg2, /* param1= */arg1);", " }", "}") .doTest(); } @Test public void namedParametersChecker_suggestsSwap_withOneCommentedSwappedArgs() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " // BUG: Diagnostic contains: target(arg1, /* param2= */arg2)", " target(/* param2= */arg2, arg1);", " }", "}") .doTest(); } @Test public void namedParametersChecker_toleratesApproximateComment_onRequiredNamesMethod() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(/*note param = */arg);", " }", "}") .doTest(); } @Test public void namedParametersChecker_tolerateComment_withNoEquals() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(/*param*/arg);", " }", "}") .doTest(); } @Test public void namedParametersChecker_toleratesMatchingComment_blockAfter() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(arg/*param*/);", " }", "}") .doTest(); } @Test public void namedParametersChecker_toleratesApproximateComment_blockAfter() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(arg/*imprecise match for param*/);", " }", "}") .doTest(); } @Test public void namedParametersChecker_toleratesMatchingComment_lineAfter() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(arg); //param", " }", "}") .doTest(); } @Test public void namedParametersChecker_ignoresComment_nonMatchinglineAfter() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(arg); // some_other_comment", " }", "}") .doTest(); } @Test public void namedParametersChecker_ignoresComment_markedUpDelimiter() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " target(arg1,", " /* ---- param1 <-> param2 ---- */", " arg2);", " }", "}") .doTest(); } @Test public void namedParametersChecker_ignoresComment_wrongNameWithNoEquals() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param);", " void test(Object arg) {", " target(/* some_other_comment */arg);", " }", "}") .doTest(); } @Test public void namedParametersChecker_matchesComment_withChainedMethod() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract Test getTest(Object param);", " abstract void target(Object param2);", " void test(Object arg, Object arg2) {", " getTest(/* param= */arg).target(arg2);", " }", "}") .doTest(); } @Test public void namedParametersChecker_suggestsChangeComment_whenNoMatchingNames() { compilationHelper .addSourceLines( "Test.java", "abstract class Test {", " abstract void target(Object param1, Object param2);", " void test(Object arg1, Object arg2) {", " // BUG: Diagnostic contains:", " // target(/* param1= */arg1, arg2)", " // `/* notMatching= */` does not match formal parameter name `param1`", " target(/* notMatching= */arg1, arg2);", " }", "}") .doTest(); } /** A test for inner class constructor parameter names across compilation boundaries. */ public static class InnerClassTest { /** An inner class. */ public class Inner { public Inner(int foo, int bar) {} // this is a (non-static) inner class on purpose { System.err.println(InnerClassTest.this); } } } @Test public void innerClassNegative() { compilationHelper .addSourceLines( "Test.java", "import " + InnerClassTest.class.getCanonicalName() + ";", "class Test {", " {", " new InnerClassTest().new Inner(/* foo= */ 1, /* bar= */ 2);", " }", "}") .doTest(); } @Ignore // see b/64954766 @Test public void innerClassPositive() { compilationHelper .addSourceLines( "Test.java", "import " + InnerClassTest.class.getCanonicalName() + ";", "class Test {", " {", " // BUG: Diagnostic contains:", " new InnerClassTest().new Inner(/* bar= */ 1, /* foo= */ 2);", " }", "}") .doTest(); } /** A test for anonymous class constructors across compilation boundaries. */ public static class Foo { public Foo(int foo, int bar) {} } @Test public void anonymousClassConstructorNegative() { compilationHelper .addSourceLines( "Test.java", "import " + Foo.class.getCanonicalName() + ";", "class Test {", " {", " new Foo(/* foo= */ 1, /* bar= */ 2) {", " };", " }", "}") .doTest(); } @Ignore // see b/65065109 @Test public void anonymousClassConstructor() { compilationHelper .addSourceLines( "Test.java", "import " + Foo.class.getCanonicalName() + ";", "class Test {", " {", " // BUG: Diagnostic contains:", " new Foo(/* bar= */ 1, /* foo= */ 2) {", " };", " }", "}") .doTest(); } }
/** * Copyright (c) 2013-2020 Nikita Koksharov * * 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.redisson.reactive; import java.util.concurrent.Callable; import org.redisson.api.BatchOptions; import org.redisson.api.BatchResult; import org.redisson.api.RFuture; import org.redisson.api.RedissonReactiveClient; import org.redisson.client.codec.Codec; import org.redisson.client.protocol.RedisCommand; import org.redisson.command.CommandAsyncExecutor; import org.redisson.command.CommandBatchService; import org.redisson.connection.ConnectionManager; import org.redisson.connection.NodeSource; import org.redisson.misc.RPromise; import reactor.core.publisher.Mono; /** * * @author Nikita Koksharov * */ public class CommandReactiveBatchService extends CommandReactiveService { private final CommandBatchService batchService; public CommandReactiveBatchService(ConnectionManager connectionManager, BatchOptions options) { super(connectionManager); batchService = new CommandBatchService(connectionManager, options); } @Override public <R> Mono<R> reactive(Callable<RFuture<R>> supplier) { Mono<R> mono = super.reactive(new Callable<RFuture<R>>() { volatile RFuture<R> future; @Override public RFuture<R> call() throws Exception { if (future == null) { synchronized (this) { if (future == null) { future = supplier.call(); } } } return future; } }); mono.subscribe(); return mono; } @Override protected <R> RPromise<R> createPromise() { return batchService.createPromise(); } @Override public <V, R> void async(boolean readOnlyMode, NodeSource nodeSource, Codec codec, RedisCommand<V> command, Object[] params, RPromise<R> mainPromise, boolean ignoreRedirect) { batchService.async(readOnlyMode, nodeSource, codec, command, params, mainPromise, ignoreRedirect); } public RFuture<BatchResult<?>> executeAsync() { return batchService.executeAsync(); } @Override public CommandAsyncExecutor enableRedissonReferenceSupport(RedissonReactiveClient redissonReactive) { batchService.enableRedissonReferenceSupport(redissonReactive); return super.enableRedissonReferenceSupport(redissonReactive); } }
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.identitymanagement.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.identitymanagement.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * PolicyVersion StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PolicyVersionStaxUnmarshaller implements Unmarshaller<PolicyVersion, StaxUnmarshallerContext> { public PolicyVersion unmarshall(StaxUnmarshallerContext context) throws Exception { PolicyVersion policyVersion = new PolicyVersion(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return policyVersion; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("Document", targetDepth)) { policyVersion.setDocument(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("VersionId", targetDepth)) { policyVersion.setVersionId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("IsDefaultVersion", targetDepth)) { policyVersion.setIsDefaultVersion(BooleanStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("CreateDate", targetDepth)) { policyVersion.setCreateDate(DateStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return policyVersion; } } } } private static PolicyVersionStaxUnmarshaller instance; public static PolicyVersionStaxUnmarshaller getInstance() { if (instance == null) instance = new PolicyVersionStaxUnmarshaller(); return instance; } }
/** * Copyright 2020 ArcSoft Corporation Limited. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package com.arcsoft.arcfacesingle.data.event; public class ReOpenCameraEvent { public boolean needReOpenCamera; public boolean needInitFaceEngine; public boolean useIrFaceLive; public boolean showIrPreview; public ReOpenCameraEvent(boolean needInitEngine, boolean needOpenCamera, boolean useIrFaceLive, boolean showIrPreview) { this.needInitFaceEngine = needInitEngine; this.needReOpenCamera = needOpenCamera; this.useIrFaceLive = useIrFaceLive; this.showIrPreview = showIrPreview; } }
package org.camunda.bpm.scenario.act; import org.camunda.bpm.scenario.delegate.EventSubscriptionDelegate; /** * @author Martin Schimak <martin.schimak@plexiti.com> */ public interface MessageIntermediateCatchEventAction extends Action<EventSubscriptionDelegate> { /** * Implement this action with custom code to be executed when the * process instance arrives at a message intermediate catch event. * * @param message the event subscription waiting for a message. * * @throws Exception in case your custom code throws checked exceptions. * Such exceptions will be wrapped into RuntimeExceptions and rethrown. */ @Override void execute(final EventSubscriptionDelegate message) throws Exception; }
/** * Copyright 2018 ADLINK Technology Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.zeligsoft.domain.zml.ui.viewcustomizers; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.diagram.core.preferences.PreferencesHint; import org.eclipse.gmf.runtime.diagram.core.services.ViewService; import org.eclipse.gmf.runtime.notation.Diagram; import org.eclipse.gmf.runtime.notation.View; import com.ibm.xtools.umlnotation.UMLComponentStyle; import com.ibm.xtools.umlnotation.UMLListStereotypeDisplay; import com.ibm.xtools.umlnotation.UmlnotationFactory; import com.ibm.xtools.umlnotation.UmlnotationPackage; import com.zeligsoft.base.ui.viewcustomizers.BaseViewCustomizer; import com.zeligsoft.base.zdl.util.ZDLUtil; import com.zeligsoft.domain.zml.util.ZMLMMNames; public class ZMLComponentViewCustomizer extends BaseViewCustomizer { public static final String PORT_OPERATIONS_VIEW_TYPE = "PortOperationsListCompartment";//$NON-NLS-1$ /** * The only instance of <code>ComponentViewCustomizer</code> */ public static ZMLComponentViewCustomizer INSTANCE = new ZMLComponentViewCustomizer(); protected ZMLComponentViewCustomizer() { // do not instantiate } /** * Sets the Component View style so that the External View is shown when * visualized. The list compartments are not visible. * * @param view * the <code>Node</code> view for a <code>Component</code>. */ @SuppressWarnings("unchecked") public void customizeView(View view) { // Do not customize the view if the context of the Component is RSMs // Struture diagram, the defaults are sufficient. if (view.eContainer() instanceof Diagram && "Structure".equals(((Diagram) view.eContainer()).getType())) {//$NON-NLS-1$ return; } super.customizeView(view); //component style UMLComponentStyle componentStyle = (UMLComponentStyle) view .getStyle(UmlnotationPackage.Literals.UML_COMPONENT_STYLE); if (componentStyle == null) { componentStyle = UmlnotationFactory.eINSTANCE .createUMLComponentStyle(); view.getStyles().add(componentStyle); } componentStyle.setShowWhiteBox(true); // For structural realization and implementations add the // PortOperations list compartment if (hasPortOperations(view.getElement())) { ViewService.createNode(view, view.getElement(), PORT_OPERATIONS_VIEW_TYPE, PreferencesHint.USE_DEFAULTS); // To hide the <<workerfunction>> stereotype on operations componentStyle .setShowListStereotype(UMLListStereotypeDisplay.NONE_LITERAL); } // Hide the Provided and Required Interface list compartments. EList<View> children = view.getChildren(); for (View childView : children) { String childViewType = childView.getType(); if (REQUIRES_LIST_VIEW_NAME.equals(childViewType) || PROVIDES_LIST_VIEW_NAME.equals(childViewType)) { childView.setVisible(false); } if ((STRUCTURE_COMPARTMENT_VIEW_NAME.equals(childViewType) || PORT_OPERATIONS_VIEW_TYPE .equals(childViewType)) && ZDLUtil.isZDLConcept(childView.getElement(), ZMLMMNames.STRUCTURAL_REALIZATION)) { childView.setVisible(true); } } } /** * StructuralRealization and Implementations support Port Operations. * * @param element * @return */ private boolean hasPortOperations(EObject element) { return element != null && ZDLUtil.isZDLConcept(element, ZMLMMNames.STRUCTURAL_REALIZATION); // TODO: Add PortOperations on Implementations. } }
/* * /* * Informational Notice: * This software was developed under contract funded by the National Library of Medicine, which is part of the National Institutes of Health, * an agency of the Department of Health and Human Services, United States Government. * * The license of this software is an open-source BSD license. It allows use in both commercial and non-commercial products. * * The license does not supersede any applicable United States law. * * The license does not indemnify you from any claims brought by third parties whose proprietary rights may be infringed by your usage of this software. * * Government usage rights for this software are established by Federal law, which includes, but may not be limited to, Federal Acquisition Regulation * (FAR) 48 C.F.R. Part52.227-14, Rights in Data�General. * The license for this software is intended to be expansive, rather than restrictive, in encouraging the use of this software in both commercial and * non-commercial products. * * LICENSE: * * Government Usage Rights Notice: The U.S. Government retains unlimited, royalty-free usage rights to this software, but not ownership, * as provided by Federal law. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above Government Usage Rights Notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above Government Usage Rights Notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the distribution. * * - The names,trademarks, and service marks of the National Library of Medicine, the National Cancer Institute, the National Institutes * of Health, and the names of any of the software developers shall not be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE U.S. GOVERNMENT AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE U.S. GOVERNMENT * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package fmservice.server.result; import java.io.Serializable; import java.util.HashMap; /** * * */ public class FMServiceResponse implements Serializable { public int statusCode; public String statusMsg; public String returnContent; // Output data as a JSON String public HashMap returnHeader; public float serviceTime; // total round-trp time for service completion public FMServiceResponse() {}; /********************************************************************************************************************/ // Build a response message with header parameteres (to be set in the response message to the server // public FMServiceResponse (int status, String retMessage) { statusCode = status; statusMsg = retMessage; } }
package com.tinkerpop.blueprints.impls.orient; import com.tinkerpop.blueprints.Vertex; import java.util.Iterator; public class OrientClassVertexIterable extends OrientElementIterable<Vertex> { private String klass; public OrientClassVertexIterable(OrientBaseGraph graph, Iterable<?> iterable, String klass) { super(graph, iterable); this.klass = klass; } @Override public Iterator<Vertex> iterator() { return new OrientClassVertexIterator(super.graph, super.iterator(), klass); } }
package com.alibaba.druid.pool; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.sql.*; import java.sql.Date; import java.util.*; import java.util.concurrent.Executor; /** * Created by allwefantasy on 8/30/16. */ public class ElasticSearchConnection implements Connection { private Client client; public ElasticSearchConnection(String jdbcUrl) { Settings settings = Settings.builder().put("client.transport.ignore_cluster_name", true).build(); try { TransportClient transportClient = new PreBuiltTransportClient(settings); String hostAndPortArrayStr = jdbcUrl.split("/")[2]; String[] hostAndPortArray = hostAndPortArrayStr.split(","); for (String hostAndPort : hostAndPortArray) { String host = hostAndPort.split(":")[0]; String port = hostAndPort.split(":")[1]; transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName(host), Integer.parseInt(port))); } client = transportClient; } catch (UnknownHostException e) { e.printStackTrace(); } } public Client getClient() { return client; } @Override public Statement createStatement() throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return new PreparedStatement() { @Override public ResultSet executeQuery() throws SQLException { return null; } @Override public int executeUpdate() throws SQLException { return 0; } @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { } @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { } @Override public void setByte(int parameterIndex, byte x) throws SQLException { } @Override public void setShort(int parameterIndex, short x) throws SQLException { } @Override public void setInt(int parameterIndex, int x) throws SQLException { } @Override public void setLong(int parameterIndex, long x) throws SQLException { } @Override public void setFloat(int parameterIndex, float x) throws SQLException { } @Override public void setDouble(int parameterIndex, double x) throws SQLException { } @Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { } @Override public void setString(int parameterIndex, String x) throws SQLException { } @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { } @Override public void setDate(int parameterIndex, Date x) throws SQLException { } @Override public void setTime(int parameterIndex, Time x) throws SQLException { } @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { } @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { } @Override public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { } @Override public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { } @Override public void clearParameters() throws SQLException { } @Override public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { } @Override public void setObject(int parameterIndex, Object x) throws SQLException { } @Override public boolean execute() throws SQLException { return false; } @Override public void addBatch() throws SQLException { } @Override public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { } @Override public void setRef(int parameterIndex, Ref x) throws SQLException { } @Override public void setBlob(int parameterIndex, Blob x) throws SQLException { } @Override public void setClob(int parameterIndex, Clob x) throws SQLException { } @Override public void setArray(int parameterIndex, Array x) throws SQLException { } @Override public ResultSetMetaData getMetaData() throws SQLException { return null; } @Override public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { } @Override public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { } @Override public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { } @Override public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { } @Override public void setURL(int parameterIndex, URL x) throws SQLException { } @Override public ParameterMetaData getParameterMetaData() throws SQLException { return null; } @Override public void setRowId(int parameterIndex, RowId x) throws SQLException { } @Override public void setNString(int parameterIndex, String value) throws SQLException { } @Override public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { } @Override public void setNClob(int parameterIndex, NClob value) throws SQLException { } @Override public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { } @Override public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { } @Override public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { } @Override public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { } @Override public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { } @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { } @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { } @Override public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { } @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { } @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { } @Override public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { } @Override public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { } @Override public void setClob(int parameterIndex, Reader reader) throws SQLException { } @Override public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { } @Override public void setNClob(int parameterIndex, Reader reader) throws SQLException { } @Override public ResultSet executeQuery(String sql) throws SQLException { return null; } @Override public int executeUpdate(String sql) throws SQLException { return 0; } @Override public void close() throws SQLException { } @Override public int getMaxFieldSize() throws SQLException { return 0; } @Override public void setMaxFieldSize(int max) throws SQLException { } @Override public int getMaxRows() throws SQLException { return 0; } @Override public void setMaxRows(int max) throws SQLException { } @Override public void setEscapeProcessing(boolean enable) throws SQLException { } @Override public int getQueryTimeout() throws SQLException { return 0; } @Override public void setQueryTimeout(int seconds) throws SQLException { } @Override public void cancel() throws SQLException { } @Override public SQLWarning getWarnings() throws SQLException { return null; } @Override public void clearWarnings() throws SQLException { } @Override public void setCursorName(String name) throws SQLException { } @Override public boolean execute(String sql) throws SQLException { return false; } @Override public ResultSet getResultSet() throws SQLException { return null; } @Override public int getUpdateCount() throws SQLException { return 0; } @Override public boolean getMoreResults() throws SQLException { return false; } @Override public void setFetchDirection(int direction) throws SQLException { } @Override public int getFetchDirection() throws SQLException { return 0; } @Override public void setFetchSize(int rows) throws SQLException { } @Override public int getFetchSize() throws SQLException { return 0; } @Override public int getResultSetConcurrency() throws SQLException { return 0; } @Override public int getResultSetType() throws SQLException { return 0; } @Override public void addBatch(String sql) throws SQLException { } @Override public void clearBatch() throws SQLException { } @Override public int[] executeBatch() throws SQLException { return new int[0]; } @Override public Connection getConnection() throws SQLException { return null; } @Override public boolean getMoreResults(int current) throws SQLException { return false; } @Override public ResultSet getGeneratedKeys() throws SQLException { return null; } @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { return 0; } @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { return 0; } @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { return 0; } @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { return false; } @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { return false; } @Override public boolean execute(String sql, String[] columnNames) throws SQLException { return false; } @Override public int getResultSetHoldability() throws SQLException { return 0; } @Override public boolean isClosed() throws SQLException { return false; } @Override public void setPoolable(boolean poolable) throws SQLException { } @Override public boolean isPoolable() throws SQLException { return false; } @Override public void closeOnCompletion() throws SQLException { } @Override public boolean isCloseOnCompletion() throws SQLException { return false; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } }; } @Override public CallableStatement prepareCall(String sql) throws SQLException { return null; } @Override public String nativeSQL(String sql) throws SQLException { return null; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { } @Override public boolean getAutoCommit() throws SQLException { return false; } @Override public void commit() throws SQLException { } @Override public void rollback() throws SQLException { } @Override public void close() throws SQLException { } @Override public boolean isClosed() throws SQLException { return false; } @Override public DatabaseMetaData getMetaData() throws SQLException { return null; } @Override public void setReadOnly(boolean readOnly) throws SQLException { } @Override public boolean isReadOnly() throws SQLException { return false; } @Override public void setCatalog(String catalog) throws SQLException { } @Override public String getCatalog() throws SQLException { return null; } @Override public void setTransactionIsolation(int level) throws SQLException { } @Override public int getTransactionIsolation() throws SQLException { return 0; } @Override public SQLWarning getWarnings() throws SQLException { return null; } @Override public void clearWarnings() throws SQLException { } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null; } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { return null; } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { } @Override public void setHoldability(int holdability) throws SQLException { } @Override public int getHoldability() throws SQLException { return 0; } @Override public Savepoint setSavepoint() throws SQLException { return null; } @Override public Savepoint setSavepoint(String name) throws SQLException { return null; } @Override public void rollback(Savepoint savepoint) throws SQLException { } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return null; } @Override public Clob createClob() throws SQLException { return null; } @Override public Blob createBlob() throws SQLException { return null; } @Override public NClob createNClob() throws SQLException { return null; } @Override public SQLXML createSQLXML() throws SQLException { return null; } @Override public boolean isValid(int timeout) throws SQLException { return false; } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { } @Override public String getClientInfo(String name) throws SQLException { return null; } @Override public Properties getClientInfo() throws SQLException { return null; } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return null; } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return null; } @Override public void setSchema(String schema) throws SQLException { } @Override public String getSchema() throws SQLException { return null; } @Override public void abort(Executor executor) throws SQLException { } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { } @Override public int getNetworkTimeout() throws SQLException { return 0; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } }
package com.zm.zmregister; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class ZmRegisterApplication { public static void main(String[] args) { SpringApplication.run(ZmRegisterApplication.class, args); } }
@MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault package dev.socketmods.socketperms.values; import javax.annotation.ParametersAreNonnullByDefault; import mcp.MethodsReturnNonnullByDefault;
/* * * 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 flex2.compiler.mxml.builder; import flash.util.StringJoiner; import flex2.compiler.CompilationUnit; import flex2.compiler.util.CompilerMessage.CompilerError; import flex2.compiler.mxml.Attribute; import flex2.compiler.mxml.MXMLNamespaces; import flex2.compiler.mxml.MxmlConfiguration; import flex2.compiler.mxml.dom.*; import flex2.compiler.mxml.gen.TextGen; import flex2.compiler.mxml.lang.BindingHandler; import flex2.compiler.mxml.lang.StandardDefs; import flex2.compiler.mxml.lang.TextParser; import flex2.compiler.mxml.lang.TypeCompatibility; import flex2.compiler.mxml.lang.ValueNodeHandler; import flex2.compiler.mxml.reflect.Assignable; import flex2.compiler.mxml.reflect.Property; import flex2.compiler.mxml.reflect.Type; import flex2.compiler.mxml.reflect.TypeTable; import flex2.compiler.mxml.rep.*; import flex2.compiler.util.MimeMappings; import flex2.compiler.util.MxmlCommentUtil; import flex2.compiler.util.NameFormatter; import flex2.compiler.util.QName; import flex2.compiler.util.QNameSet; import java.util.*; /* * TODO the overriding of ComponentBuilder.ComponentChildNodeHandler * callouts is starting to get complicated, due to differences * between processing the root and the children. Should probably * bite the bullet and create a DocumentChildNodeHandler in * mxml.lang */ /** * This builder handles building a Model instance from the root node * of an MXML document. This isn't just an &lt;Application/&gt;. * * @author Clement Wong */ public class DocumentBuilder extends ComponentBuilder implements MXMLNamespaces { /** * Note: kind of a messy overlap here. There is a set of "special" root * attributes (attributes that may appear on the root, that aren't * properties/effects/styles/events). These are skipped by the normal * compilation process, which uses isSpecialAttribute() to detect them. * These all have meaning downstream, and are collected by * parseRootAttributes(). * * Then there are also a handful of "ordinary" attributes that *also* have * downstream meaning, when they appear on the root. They are *both* * processed by parseRootAttributes(), and by the normal compilation * process. These are listed below by the rootAttr* constants. */ protected static final String rootAttrBackgroundColor = "backgroundColor"; protected static final String rootAttrHeight = "height"; protected static final String rootAttrStyleName = "styleName"; protected static final String rootAttrWidth = "width"; protected static final String specialAttrExclude = "excludeFrom"; protected static final String specialAttrFrameRate = "frameRate"; protected static final String specialAttrImplements = "implements"; protected static final String specialAttrInclude = "includeIn"; protected static final String specialAttrItemCPolicy = "itemCreationPolicy"; protected static final String specialAttrItemDPolicy = "itemDestructionPolicy"; protected static final String specialAttrLib = "lib"; protected static final String specialAttrPageTitle = "pageTitle"; protected static final String specialAttrPreloader = "preloader"; protected static final String specialAttrRsl = "rsl"; protected static final String specialAttrRuntimeDPIProvider = "runtimeDPIProvider"; protected static final String specialAttrScriptRecursionLimit = "scriptRecursionLimit"; protected static final String specialAttrScriptTimeLimit = "scriptTimeLimit"; protected static final String specialAttrTheme = "theme"; protected static final String specialAttrUsePreloader = "usePreloader"; protected static final String specialAttrVersion = "version"; protected static final String specialAttrSplashScreenImage = "splashScreenImage"; protected static final String specialAttrUseGPU = "useGPU"; protected static final String specialAttrUseDirectBlit = "useDirectBlit"; // MXML 2006 Special Attributes private static final String DEFAULT_NAMESPACE = QName.DEFAULT_NAMESPACE; private static QNameSet specialAttributes2006 = new QNameSet(16); static { specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrFrameRate); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrImplements); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrLib); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrPageTitle); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrPreloader); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrRsl); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrScriptRecursionLimit); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrScriptTimeLimit); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrTheme); specialAttributes2006.add(DEFAULT_NAMESPACE, specialAttrUsePreloader); } // MXML 2009 Special Attributes (qualified in language namespace) private static QNameSet specialAttributes2009 = new QNameSet(16); static { specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrFrameRate); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrImplements); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrLib); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrPageTitle); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrPreloader); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrRsl); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrRuntimeDPIProvider); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrScriptRecursionLimit); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrScriptTimeLimit); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrTheme); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrUsePreloader); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrSplashScreenImage); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrUseGPU); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrUseDirectBlit); // Though considered special attributes we end up disallowing the following // on the root. We ensure they are in the special attributes list so that we // don't end up in the default attribute handling code (and end up issuing // and extraneous 'unknown attribute' error). specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrExclude); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrInclude); specialAttributes2009.add(MXML_2009_NAMESPACE, specialAttrItemCPolicy); } public DocumentBuilder(CompilationUnit unit, TypeTable typeTable, MxmlConfiguration mxmlConfiguration, MxmlDocument document) { super(unit, typeTable, mxmlConfiguration, document, null, null, null, false, null); // NOTE: override already-initialized childNodeHandler this.childNodeHandler = new DocumentChildNodeHandler(typeTable); this.rootAttributeParser = new RootAttributeParser(typeTable); this.nestedDeclarationNodeHandler = new NestedDeclarationNodeHandler(); this.componentDeclarationBindingHandler = new ComponentDeclarationBindingHandler(); this.primitiveDeclarationBindingHandler = new PrimitiveDeclarationBindingHandler(); } protected RootAttributeParser rootAttributeParser; protected NestedDeclarationNodeHandler nestedDeclarationNodeHandler; protected ComponentDeclarationBindingHandler componentDeclarationBindingHandler; protected PrimitiveDeclarationBindingHandler primitiveDeclarationBindingHandler; private boolean generateLoader = true; private boolean inDeclaration = false; public void analyze(Node node) { checkInvalidRootAttributes(node); if(mxmlConfiguration.getGenerateAbstractSyntaxTree()) { if(node.comment != null) { document.setComment( MxmlCommentUtil.commentToXmlComment(node.comment) ); } } else { document.setComment( node.comment ); } Type type = nodeTypeResolver.resolveType(node, document); constructComponent(type, node.beginLine); // TODO eliminate horrible confusion by renaming one or the other "root" below, // NOTE: "document.root" means the root component, i.e. the component represented by the root node document.setRoot(component); processAttributes(node, type); processChildren(node, type); // post-processing grab bag document.resolveTwoWayBindings(); document.postProcessStates(); postProcessDesignLayers(); // post-processing on *application component only* - that's what unit.isRoot() means if (unit.isRoot()) { rootPostProcess(node); // at the moment, binding destinations aren't set up until some arbitrary time after construction, so we have // to do this import fixup late. // // TODO add BindingExpression factory functions which set destination stuff up // immediately, then shift this addImport() into MxmlDocument.addBindingExpression(). // for (Iterator iter = document.getBindingExpressions().iterator(); iter.hasNext(); ) { BindingExpression bexpr = (BindingExpression)iter.next(); document.addImport(bexpr.getDestinationTypeName(), bexpr.getXmlLineNumber()); } } } public void analyze(LayeredNode node) { analyze((Node) node); } public void analyze(MetaDataNode node) { CDATANode cdata = (CDATANode)node.getChildAt(0); if (cdata != null && cdata.image != null) { // metadata scripts are added to document info in InterfaceCompiler // If the document sets Frame metadata, then we must not overwrite it. // Is there a better way to do this? This seems really hacky and brittle. if (node.getText().toString().indexOf( "[Frame" ) != -1) { assert unit.isRoot(); generateLoader = false; } } } public void analyze(StyleNode node) { if (node.getStyleSheet() != null) { try { document.getStylesContainer().extractStyles(node.getStyleSheet(), true); } catch (Exception exception) { String message = exception.getLocalizedMessage(); if (message == null) { message = exception.getClass().getName(); } logError(node, message); } } } public void analyze(WebServiceNode node) { WebServiceBuilder builder = new WebServiceBuilder(unit, typeTable, mxmlConfiguration, document); node.analyze(builder); } public void analyze(HTTPServiceNode node) { HTTPServiceBuilder builder = new HTTPServiceBuilder(unit, typeTable, mxmlConfiguration, document); node.analyze(builder); } public void analyze(RemoteObjectNode node) { RemoteObjectBuilder builder = new RemoteObjectBuilder(unit, typeTable, mxmlConfiguration, document); node.analyze(builder); } /** * */ public void analyze(BindingNode node) { boolean isTwoWayBind = false; String source = (String) node.getAttributeValue("source"); if (source == null) { log(node, new MissingAttribute("source")); return; } String destination = (String) node.getAttributeValue("destination"); if (destination == null) { log(node, new MissingAttribute("destination")); return; } String twoWay = (String) node.getAttributeValue("twoWay"); if (twoWay != null) { Object value = rootAttributeParser.parseBoolean(twoWay, node.beginLine, "twoWay"); if (value != null) { // If twoWay, both the source and the destination have to be // bindable properties or property chains. The ConstantEvaluator // will error if the destination isn't a reference value. isTwoWayBind = ((Boolean)value); } } Object value = textParser.parseValue(source, typeTable.stringType, 0, node.beginLine, "source"); // Note: allow source="expr". // Don't allow source = "@{expr}" and if two-way bind, source = "{expr}", BindingExpression bindingExpression; if (value instanceof BindingExpression) { bindingExpression = (BindingExpression) value; if (bindingExpression.isTwoWayPrimary()) { log(node, new TwoWayBindingNotAllowedInitializer("source", source)); } else if (isTwoWayBind) { log(node, new BindingNotAllowedInitializer("source", source)); } } else { bindingExpression = new BindingExpression((String)value, node.beginLine, document); } bindingExpression.setDestinationProperty(destination); bindingExpression.setDestinationLValue(destination); bindingExpression.setFromBindingNode(true); value = textParser.parseValue(destination, typeTable.stringType, 0, node.beginLine, "destination"); // Don't allow destination="{expr}" or destination="@{expr}" if (value instanceof BindingExpression) { bindingExpression = (BindingExpression) value; if (bindingExpression.isTwoWayPrimary()) { log(node, new TwoWayBindingNotAllowedInitializer("destination", destination)); } else { log(node, new BindingNotAllowedInitializer("destination", destination)); } } // If a two-way binding, create another one, with the source and destination // reversed. They will be hooked together when all the two-way bindings // are resolved. if (isTwoWayBind) { BindingExpression bindingExpression2 = new BindingExpression(destination, node.beginLine, document); source = TextGen.stripParens(bindingExpression.getSourceExpression()); bindingExpression2.setDestinationProperty(source); bindingExpression2.setDestinationLValue(source); bindingExpression2.setFromBindingNode(true); } } /** * Overrides AbstractBuilder.checkTypeCompatibility() to provide * more document specific error messages. */ protected int checkTypeCompatibility(Node node, Type lvalueType, Type lvalueArrayElementType, String lvalueDescription, boolean rvalueIsSingleton, boolean isDefaultProperty) { Type rtype = nodeTypeResolver.resolveType(node, document); // Determine type compatibility. We account for the possibility of // incorrectly nested language or service tags. String rvalueTypeName = (rtype != null) ? rtype.getName() : node.getLocalPart(); int compat = TypeCompatibility.check(lvalueType, lvalueArrayElementType, rtype, rvalueIsSingleton, standardDefs); compat = coerceStatefulNodes(node, lvalueType, compat); switch (compat) { case TypeCompatibility.Ok: case TypeCompatibility.OkCoerceToArray: case TypeCompatibility.OkCoerceToVector: { return compat; } case TypeCompatibility.ErrRTypeNotAssignableToLType: { if (isDefaultProperty) { log(node.beginLine, new TypeNotAssignableToDefaultProperty(lvalueDescription, NameFormatter.toDot(rvalueTypeName), NameFormatter.toDot(lvalueType.getName()))); } else { log(node.beginLine, new TypeNotAssignableToLType(lvalueDescription, NameFormatter.toDot(rvalueTypeName), NameFormatter.toDot(lvalueType.getName()))); } return compat; } case TypeCompatibility.ErrLTypeNotMultiple: { if (isDefaultProperty) { log(node.beginLine, new DefaultPropertyNotMultiple(lvalueDescription, NameFormatter.toDot(lvalueType.getName()))); } else { log(node.beginLine, new TypeNotMultiple(lvalueDescription, NameFormatter.toDot(lvalueType.getName()))); } return compat; } case TypeCompatibility.ErrSingleRValueNotArrayOrArrayElem: { if (isDefaultProperty) { log(node.beginLine, new SingleRValueNestedDeclaration(node.getLocalPart(), NameFormatter.toDot(lvalueType.getName()), NameFormatter.toDot(lvalueArrayElementType.getName()))); } else { log(node.beginLine, new SingleRValueNotTargetTypeOrTargetElementType(lvalueDescription, NameFormatter.toDot(rvalueTypeName), NameFormatter.toDot(lvalueType.getName()), NameFormatter.toDot(lvalueArrayElementType.getName()))); } return compat; } case TypeCompatibility.ErrMultiRValueNotArrayElem: { if (isDefaultProperty) { log(node.beginLine, new MultiRValueNestedDeclaration(node.getLocalPart(), NameFormatter.toDot(lvalueType.getName()), NameFormatter.toDot(lvalueArrayElementType.getName()))); } else { log(node.beginLine, new MultiRValueNotElementType(lvalueDescription, NameFormatter.toDot(rvalueTypeName), NameFormatter.toDot(lvalueType.getName()), NameFormatter.toDot(lvalueArrayElementType.getName()))); } return compat; } default: { assert false; return compat; } } } /** * */ protected boolean isLegalLanguageNode(Node node) { Class<? extends Node> nodeClass = node.getClass(); return super.isLegalLanguageNode(node) || nodeClass == MetaDataNode.class || nodeClass == StyleNode.class || nodeClass == BindingNode.class || isServiceNode(node); } /** * RemoteObject, HTTPService and WebService tags represent services * that require special handling and so are considered language tags. * * @param node * @return true if the node represents a service */ protected boolean isServiceNode(Node node) { Class<? extends Node> nodeClass = node.getClass(); return nodeClass == RemoteObjectNode.class || nodeClass == HTTPServiceNode.class || nodeClass == WebServiceNode.class; } /** * Override ComponentBuilder's isProhibitedProperty. */ protected boolean isAllowedProperty(Property property) { return true; } /** * Override ComponentBuilder.isSpecialAttribute(). The root node doesn't * allow "id", but it allows for special attributes (e.g. frameRate, * usePreloader, etc...). * @param namespace - the qualified attribute namespace * @param localPart - the qualified attribute local name * @return true if the given attribute requires special handling. */ protected boolean isSpecialAttribute(String namespace, String localPart) { if (document.getVersion() < 4) { return specialAttributes2006.contains(namespace, localPart); } else { if (namespace.length() == 0) namespace = MXML_2009_NAMESPACE; return specialAttributes2009.contains(namespace, localPart); } } /** * Searches for a special (language) attribute on a given node. * * Prior to Flex 4, attributes were never qualified and were in the default * (empty string) namespace. * * From Flex 4 onwards, language attributes could be qualified if a * non-default prefix was used for the language namespace. For usability * sake, even though unprefixed attributes are in the default (empty * string) namespace (regardless of whether the language namespace was * the default namespace for the document), we continue to see them as * special attributes. * * @param node The node to search for the attribute. * @param localPart The unqualified attribute name * @return attribute value as a String, or null if the attribute was not found */ protected Attribute getSpecialAttribute(Node node, String localPart) { Attribute attr = null; if (document.getVersion() < 4) { attr = node.getAttribute(DEFAULT_NAMESPACE, localPart); } else { // We check the default namespace first as it is the most common // use case... attr = node.getAttribute(DEFAULT_NAMESPACE, localPart); if (attr == null) attr = node.getAttribute(document.getLanguageNamespace(), localPart); } return attr; } /** * Walk all 'orphan' DesignLayer instances in the document * (those with id's but no layer children) and ensure we process them * as top level declarations. */ public void postProcessDesignLayers() { List<DesignLayerNode> layers = document.getLayerDeclarationNodes(); for (Iterator<DesignLayerNode> i = layers.iterator(); i.hasNext();) { DesignLayerNode node = i.next(); if (document.getLayerModel(node) == null) { ComponentBuilder builder = new ComponentBuilder(unit, typeTable, mxmlConfiguration, document, component, null, null, true, null); node.analyze(builder); } } } /** * override ComponentBuilder.ComponentAttributeHandler for root-node special handling */ protected class DocumentAttributeHandler extends ComponentBuilder.ComponentAttributeHandler { /** * even if our supertype is dynamic, we (an MXML document) never define a dynamic class. */ protected void dynamicProperty(String name, String state) { unknownAttributeError("", name, line); } } /** * override ComponentBuilder.ChildNodeHandler for root-node special handling */ protected class DocumentChildNodeHandler extends ComponentBuilder.ComponentChildNodeHandler { DocumentChildNodeHandler(TypeTable typeTable) { super(typeTable); } /** * In MXML 2009 (and later), RemoteObject, HTTPService and WebService need to * be declared under the Declarations section. */ protected void languageNode() { if (document.getVersion() >= 4 && isServiceNode(child)) { log(child, new NestedDeclaration(child.getLocalPart(), NameFormatter.toDot(standardDefs.INTERFACE_IUICOMPONENT))); } else { super.languageNode(); } } /** * even if our supertype is dynamic, we (an MXML document) never define a dynamic class. If the dynamic * property handler has been called, it means that no statically defined entity by this name could be found on * our backing type, so here we just route it to the handler it would've gone to had our backing class been static. */ protected void dynamicProperty(String name, String state) { nestedDeclaration(false); } /** * Default properties are suppressed on the root - they step on the syntactic territory used by top-level * declarations. So here we're routing to the handler that would have been called had our backing class had no DP. * <p> * But note that we come through here on the root of an inline component as well. It would be consistent to * treat them identically, but since a) nested declarations are used 0% of the time within inline components, * and b) the misunderstanding would be silent, we're going to choose usability over consistency here. */ protected void defaultPropertyElement(boolean locError) { String mimeType = document.getCompilationUnit().getSource().getMimeType(); if (DocumentBuilder.this.document.getIsInlineComponent() || (mimeType.equals(MimeMappings.MXML) && (document.getVersion() >= 4)) || mimeType.equals(MimeMappings.FXG)) { // In an inline component, process default property elements as usual. Note that this // suppresses nested declarations inside inline components, as intended (see header comment). super.defaultPropertyElement(locError); } else { // NOTE: we can *not* simply report an error here. If we did, MXML components based on classes with // default properties would no longer be able to declare things FC-style at the top level. super.nestedDeclaration(false); } } protected void nestedDeclaration() { String mimeType = document.getCompilationUnit().getSource().getMimeType(); if (mimeType.equals(MimeMappings.MXML) && document.getVersion() < 4) { super.nestedDeclaration(); } else { Type childType = nodeTypeResolver.resolveType(child, document); assert childType != null : "nested declaration node type == null, node = " + child.image; if (standardDefs.isContainer(parentType) && standardDefs.isIUIComponent(childType) && ((mimeType.equals(MimeMappings.MXML) && (document.getVersion() < 4)) || (parentType.getDefaultProperty() == null))) { processVisualChild(child); } else if (child instanceof ReparentNode) { ComponentBuilder builder = new ComponentBuilder(unit, typeTable, mxmlConfiguration, document, component, null, null, true, null); child.analyze(builder); } else if ((standardDefs.isContainer(parentType) && (childType.isAssignableTo(standardDefs.CLASS_RADIOBUTTONGROUP) || childType.isAssignableTo(standardDefs.CLASS_SPARK_RADIOBUTTONGROUP)))) { // Special cases to allow non-visual children in visual containers. ComponentBuilder builder = new ComponentBuilder(unit, typeTable, mxmlConfiguration, document, component, null, null, true, null); child.analyze(builder); } else { if (standardDefs.isSparkGraphic(childType)) { log(child, new SparkPrimitiveInHalo(child.getLocalPart(), parent.getLocalPart())); } else { log(child, new NestedDeclaration(child.getLocalPart(), NameFormatter.toDot(standardDefs.INTERFACE_IUICOMPONENT))); } } } } /** * in our case, nested declarations are top-level declarations. However, note that here we're subclassing the * sub-handler that runs *after* the visual-child and repeater special cases have been checked. * Note that we'll only be called for "value nodes" - nodes that represent values that can be translated into AS * values everywhere. (See NodeTypeResolver.isValueNode() and ChildNodeHandler.invoke()) for details). Other top-level * tags are considered "language tags" and result in a call to langaugeNode() rather than nestedDeclaration() in the handler. */ protected void processNestedDeclaration(Type childType) { nestedDeclarationNodeHandler.invoke(null, child, document); } /** * Scans for any invalid attributes on nested declarations. */ protected boolean validateNestedDeclarationAttrs(Node node) { // Ensure we disallow state-specific children of the <Declarations> tag. String include = (String) getLanguageAttributeValue(node, specialAttrInclude); String exclude = (String) getLanguageAttributeValue(node, specialAttrExclude); String icpolicy = (String) getLanguageAttributeValue(node, specialAttrItemCPolicy); String idpolicy = (String) getLanguageAttributeValue(node, specialAttrItemDPolicy); if (include != null || exclude != null) { log(node, new StateAttrsNotAllowedOnDecls()); return false; } if (icpolicy != null || idpolicy != null) { log(node, new ItemPolicyNotAllowedOnDecls()); return false; } return true; } protected void invoke(Node parent, Type parentType, Node child) { if (child.getClass() == DeclarationsNode.class) { this.parent = parent; this.parentType = parentType; inDeclaration = true; for (Iterator iter = child.getChildIterator(); iter.hasNext(); ) { this.child = (Node) iter.next(); if (validateNestedDeclarationAttrs(this.child)) { if (isServiceNode(this.child)) super.languageNode(); else if (isLegalLanguageNode(this.child)) log(this.child, new LanguageNodeInDeclarationError(this.child.image)); else super.nestedDeclaration(false); } } inDeclaration = false; } else if (child.getClass() == LibraryNode.class) { // Skip Library while building Application } else if (child.getClass() == PrivateNode.class) { // Skip Private tag } else { super.invoke(parent, parentType, child); } } } /** * */ protected class NestedDeclarationNodeHandler extends ValueNodeHandler { protected void componentNode(Assignable property, Node node, MxmlDocument document) { ComponentBuilder builder = new ComponentBuilder(unit, typeTable, mxmlConfiguration, document, component, null, null, true, componentDeclarationBindingHandler); node.analyze(builder); } protected void arrayNode(Assignable property, ArrayNode node) { ArrayBuilder builder = new ArrayBuilder(unit, typeTable, mxmlConfiguration, document); node.analyze(builder); } protected void vectorNode(Assignable property, VectorNode node) { String typeAttributeValue = (String) node.getAttribute(StandardDefs.PROP_TYPE).getValue(); Type elementType = typeTable.getType(NameFormatter.toColon(typeAttributeValue)); VectorBuilder builder = new VectorBuilder(unit, typeTable, mxmlConfiguration, document, null, null, elementType, true); node.analyze(builder); } protected void primitiveNode(Assignable property, PrimitiveNode node) { PrimitiveBuilder builder = new PrimitiveBuilder(unit, typeTable, mxmlConfiguration, document, component, true, null, primitiveDeclarationBindingHandler); node.analyze(builder); } protected void xmlNode(Assignable property, XMLNode node) { XMLBuilder builder = new XMLBuilder(unit, typeTable, mxmlConfiguration, document); node.analyze(builder); registerModel(node, builder.xml, true); } protected void xmlListNode(Assignable property, XMLListNode node) { XMLListBuilder builder = new XMLListBuilder(unit, typeTable, mxmlConfiguration, document); node.analyze(builder); registerModel(node, builder.xmlList, true); } protected void modelNode(Assignable property, ModelNode node) { ModelBuilder builder = new ModelBuilder(unit, typeTable, mxmlConfiguration, document, null); node.analyze(builder); } protected void inlineComponentNode(Assignable property, InlineComponentNode node) { InlineComponentBuilder builder = new InlineComponentBuilder(unit, typeTable, mxmlConfiguration, document, true); node.analyze(builder); } protected void reparentNode(Assignable property, ReparentNode node) { ComponentBuilder builder = new ComponentBuilder(unit, typeTable, mxmlConfiguration, document, component, null, null, true, null); node.analyze(builder); } protected void stateNode(Assignable property, StateNode node) { ComponentBuilder builder = new ComponentBuilder(unit, typeTable, mxmlConfiguration, document, component, null, null, true, null); node.analyze(builder); } protected void cdataNode(Assignable property, CDATANode node) { PrimitiveBuilder builder = new PrimitiveBuilder(unit, typeTable, mxmlConfiguration, document, component, true, null, primitiveDeclarationBindingHandler); node.analyze(builder); } protected void unknown(Assignable property, Node node) { assert false : "Unexpected node class in processNestedDeclaration: " + node.getClass(); } } /** * Primitive specific binding handler. */ protected static class PrimitiveDeclarationBindingHandler implements BindingHandler { public BindingExpression invoke(BindingExpression bindingExpression, Model dest) { bindingExpression.setDestination(dest); ((Primitive)dest).setValue(null); return bindingExpression; } } /** * Override ComponentBuilder.processSpecialAttributes()... */ protected void processSpecialAttributes(Node node) { if (unit.getSource().isRoot()) { parseRootAttributes(node); } } /** * Override ComponentBuilder.processVisualChild to avoid deferred * instantiation of any visual children declared inside a Declarations * tag. These should be treated as "top level" definitions which are * initialized in the documents constructor. */ protected void processVisualChild(Node node) { if (inDeclaration) { ComponentBuilder builder = new ComponentBuilder(unit, typeTable, mxmlConfiguration, document, component, null, null, true, null); node.analyze(builder); } else { super.processVisualChild(node); } } private static String buildSwfMetadata( Map<String, Object> varmap ) { if ((varmap == null) || (varmap.size() == 0)) return null; StringBuffer buf = new StringBuffer( 50 ); buf.append( "[SWF( " ); boolean more = false; for (Iterator<String> it = varmap.keySet().iterator(); it.hasNext(); ) { String var = it.next(); Object val = varmap.get( var ); if (more) buf.append( ", " ); else more = true; buf.append( var ); buf.append( "='" ); buf.append( val ); buf.append( "'" ); } buf.append( ")]" ); return buf.toString(); } // C: Most of these root attributes are linker properties. They should be // saved to the CompilationUnit object or to a per-compile Context object... private void parseRootAttributes(Node node) { // NOTE: only put variables relevant to SWF production into the SWF // metadata! MXML-specific bootstrap info should be saved into the // unit's context and incorporated into the generated IFlexBootstrap // derivative. Map<String, Object> swfvarmap = new TreeMap<String, Object>(); Attribute frameRate = getSpecialAttribute(node, specialAttrFrameRate); if (frameRate != null) { Object value = rootAttributeParser.parseUInt((String)frameRate.getValue(), frameRate.getLine(), specialAttrFrameRate); if (value != null) { swfvarmap.put(specialAttrFrameRate, value.toString()); } } Attribute scriptRecursionLimit = getSpecialAttribute(node, specialAttrScriptRecursionLimit); if (scriptRecursionLimit != null) { Object value = rootAttributeParser.parseUInt((String)scriptRecursionLimit.getValue(), scriptRecursionLimit.getLine(), specialAttrScriptRecursionLimit); if (value != null) { swfvarmap.put(specialAttrScriptRecursionLimit, value.toString()); } } Attribute scriptTimeLimit = getSpecialAttribute(node, specialAttrScriptTimeLimit); if (scriptTimeLimit != null) { Object value = rootAttributeParser.parseUInt((String)scriptTimeLimit.getValue(), scriptTimeLimit.getLine(), specialAttrScriptTimeLimit); if (value != null) { swfvarmap.put(specialAttrScriptTimeLimit, value.toString()); } } Attribute bgcolor = node.getAttribute(DEFAULT_NAMESPACE, rootAttrBackgroundColor); if (bgcolor != null) { Object value = rootAttributeParser.parseColor((String)bgcolor.getValue(), bgcolor.getLine(), rootAttrBackgroundColor); if (value != null) { swfvarmap.put(rootAttrBackgroundColor, value.toString()); } } // useDirectBlit="true|false" Attribute useDirectBlit = node.getAttribute(DEFAULT_NAMESPACE, specialAttrUseDirectBlit); if(useDirectBlit != null) { Object value = rootAttributeParser.parseBoolean( (String) useDirectBlit.getValue(), useDirectBlit.getLine(), specialAttrUseDirectBlit); if (value != null) { swfvarmap.put(specialAttrUseDirectBlit, value.toString()); } } // useGPU="true|false" Attribute useGPU = node.getAttribute(DEFAULT_NAMESPACE, specialAttrUseGPU); if(useGPU != null) { Object value = rootAttributeParser.parseBoolean( (String) useGPU.getValue(), useGPU.getLine(), specialAttrUseGPU); if (value != null) { swfvarmap.put(specialAttrUseGPU, value.toString()); } } Attribute styleName = node.getAttribute(DEFAULT_NAMESPACE, rootAttrStyleName); if (styleName != null) { document.getCompilationUnit().styleName = (String) styleName.getValue(); } Attribute title = getSpecialAttribute(node, specialAttrPageTitle); if (title != null) { swfvarmap.put(specialAttrPageTitle, title.getValue()); } // Only do the "percent" logic for Application nodes, not modules. There is no // html wrapper for a module and the logic keeps modules from sizing // to the ModuleLoader component, SDK-9527. Type nodeType = nodeTypeResolver.resolveType(node, document); boolean isApplication = StandardDefs.isApplication(nodeType); Attribute width = node.getAttribute(DEFAULT_NAMESPACE, rootAttrWidth); if (width != null && isApplication) { String widthString = width.getValue().toString(); Object value = rootAttributeParser.parseNumberOrPercentage(widthString, width.getLine(), rootAttrWidth); if (value != null) { if (rootAttributeParser.wasPercentage()) { if (widthString.endsWith("%")) { swfvarmap.put("widthPercent", widthString); } else { swfvarmap.put("widthPercent", widthString + '%'); } // HACK for 174078: width="n%" at the root of an MXML app is a specification of the ratio of // player to browser width, not app to player width. So we pass it through to the SWF, but strip // it from the MXML DOM, preventing it from showing up in the property settings for the root UIC. node.removeAttribute(new QName(width.getNamespace(), rootAttrWidth)); } else { if (value instanceof Double) { value = new Integer(((Double) value).intValue()); } swfvarmap.put(rootAttrWidth, value); } } } Attribute height = node.getAttribute(DEFAULT_NAMESPACE, rootAttrHeight); if (height != null && isApplication) { String heightString = height.getValue().toString(); Object value = rootAttributeParser.parseNumberOrPercentage(heightString, height.getLine(), rootAttrHeight); if (value != null) { if (rootAttributeParser.wasPercentage()) { if (heightString.endsWith("%")) { swfvarmap.put("heightPercent", heightString); } else { swfvarmap.put("heightPercent", heightString + '%'); } // HACK for 174078: as above for width node.removeAttribute(new QName(height.getNamespace(), rootAttrHeight)); } else { if (value instanceof Double) { value = new Integer(((Double) value).intValue()); } swfvarmap.put(rootAttrHeight, value); } } } Attribute usePreloader = getSpecialAttribute(node, specialAttrUsePreloader); if (usePreloader != null) { Object value = rootAttributeParser.parseBoolean((String)usePreloader.getValue(), usePreloader.getLine(), specialAttrUsePreloader); if (value != null) { document.setUsePreloader(((Boolean)value).booleanValue()); } } Attribute preloader = getSpecialAttribute(node, specialAttrPreloader); if (preloader != null) { String preloaderString = (String)preloader.getValue(); String preloaderClassName = TextParser.parseClassName(preloaderString); if (preloaderClassName != null) { document.setPreloader(preloaderString); } else { log(node, new InvalidPreLoaderClassName(preloaderString)); } } Attribute runtimeDPIProvider = getSpecialAttribute(node, specialAttrRuntimeDPIProvider); if (runtimeDPIProvider != null) { String runtimeDPIProviderString = (String)runtimeDPIProvider.getValue(); String runtimeDPIProviderClassName = TextParser.parseClassName(runtimeDPIProviderString); if (runtimeDPIProviderClassName == null) { log(node, new InvalidRuntimeDPIProviderClassName(runtimeDPIProviderString)); } } if (swfvarmap.size() > 0) { String metadata = buildSwfMetadata( swfvarmap ); Script script = new Script( metadata ); document.addMetadata( script ); } Attribute theme = getSpecialAttribute(node, specialAttrTheme); if (theme != null) { log(new ThemeAttributeError()); } Attribute rsl = getSpecialAttribute(node, specialAttrRsl); if (rsl != null) { log(new RslAttributeError()); } Attribute lib = getSpecialAttribute(node, specialAttrLib); if (lib != null) { log(new LibAttributeError()); } } /** * */ protected class RootAttributeParser extends TextValueParser { protected RootAttributeParser(TypeTable typeTable) { super(typeTable); } public Object parseUInt(String text, int line, String name) { return parseValue(text, typeTable.uintType, 0, line, name); } public Object parseColor(String text, int line, String name) { return parseValue(text, typeTable.uintType, FlagConvertColorNames, line, name); } public Object parseNumberOrPercentage(String text, int line, String name) { return parseValue(text, typeTable.numberType, FlagAllowPercentages, line, name); } public Object parseBoolean(String text, int line, String name) { return parseValue(text, typeTable.booleanType, 0, line, name); } // TextParser impl public Object embed(String text, Type type) { log(line, new EmbedNotAllowed()); return null; } public Object clear() { log(line, new ClearNotAllowed()); return null; } public Object bindingExpression(String converted) { log(line, new BindingNotAllowed()); return null; } } /** * */ private void rootPostProcess(Node node) { if (generateLoader) { generateLoaderInfo(node); } else { document.addMetadata( new Script( "[Frame(extraClass=\"FlexInit\")]\n" ) ); } } /** * */ private void generateLoaderInfo(Node node) { String baseLoaderClass = document.getSuperClass().getLoaderClass(); if (baseLoaderClass == null) return; unit.auxGenerateInfo = new HashMap<String, Object>(); String generateInitClass = "_" + document.getClassName() + "_FlexInit"; generateInitClass = generateInitClass.replaceAll( "[^A-Za-z0-9]", "_" ); document.addMetadata( new Script( "[Frame(extraClass=\"" + generateInitClass + "\")]\n" ) ); // fixme - the lingo of the classes specified are in package:name syntax // in order to be able to find them in unit.topLevelDefs. baseLoaderClass = baseLoaderClass.replace( ':', '.' ); String generateLoaderClass = "_" + document.getClassName() + "_" + baseLoaderClass; generateLoaderClass = generateLoaderClass.replaceAll( "[^A-Za-z0-9]", "_" ); document.addMetadata( new Script( "[Frame(factoryClass=\"" + generateLoaderClass + "\")]\n" ) ); Map<String, Object> rootAttributeMap = new HashMap<String, Object>(); Map<String, Object> rootAttributeEmbedVarsMap = new HashMap<String, Object>(); Map<String, Object> rootAttributeEmbedNamesMap = new HashMap<String, Object>(); // Type type = typeTable.getType(node.getNamespace(), node.getLocalPart()); for (Iterator it = node.getAttributeNames(); it != null && it.hasNext();) { QName qname = (QName) it.next(); // String namespace = qname.getNamespace(); String localPart = qname.getLocalPart(); /* if ((type.getProperty( localPart ) != null) || (type.hasEffect( localPart )) || (type.getStyle( localPart ) != null) || (type.getEvent( localPart ) != null)) continue; */ String value = (String) node.getAttributeValue( qname ); value = value.replaceAll( "\"", "\\\"" ); if (!TextParser.isScopedName(localPart)) { rootAttributeMap.put( localPart, value ); // The splashScreenImage attribute is used by the SplashScreen preloader and // it could be @Embed or a class. We need to handle the @Embed here, but don't // want to do it for all of the attributes since it will change some error messages // for example for the legacy backgroundImage style on mx:Application. Sorry. if (localPart.equals("splashScreenImage")) { // Do we have "@Embed" function? If so, we need to process it here // and generate code pieces that will be used during the generation of the loader Class. String atFunctionName = TextParser.getAtFunctionName(value); if (atFunctionName != null && "Embed".equals(atFunctionName)) { AtEmbed atEmbed = AtEmbed.create(this.typeTable.getPerCompileData(), this.unit.getSource(), value, node.getLineNumber(qname)); if (atEmbed != null) { String embedVar = atEmbed.codegenEmbedVar(); String embedName = atEmbed.getPropName(); rootAttributeEmbedVarsMap.put(localPart, embedVar); rootAttributeEmbedNamesMap.put(localPart, embedName); } } else // Must be Class { String className = TextParser.parseClassName(value); if (className == null) log(node, new InvalidSplashScreenImageClassName(value)); } } } } String windowClass = document.getClassName(); if ((document.getPackageName() != null) && (document.getPackageName().length() != 0)) { windowClass = document.getPackageName() + "." + document.getClassName(); } unit.auxGenerateInfo.put( "baseLoaderClass", baseLoaderClass ); unit.auxGenerateInfo.put( "generateLoaderClass", generateLoaderClass ); unit.auxGenerateInfo.put( "windowClass", windowClass ); unit.auxGenerateInfo.put( "preloaderClass", document.getPreloader() ); unit.auxGenerateInfo.put( specialAttrUsePreloader, new Boolean( document.getUsePreloader() ) ); unit.auxGenerateInfo.put( "rootAttributes", rootAttributeMap ); unit.auxGenerateInfo.put( "rootAttributeEmbedVars", rootAttributeEmbedVarsMap ); unit.auxGenerateInfo.put( "rootAttributeEmbedNames", rootAttributeEmbedNamesMap ); } /** * */ private void checkInvalidRootAttributes(Node node) { Attribute idAttr = getLanguageAttribute(node, StandardDefs.PROP_ID); if (idAttr != null) { log(node, idAttr.getLine(), new IdNotAllowedOnRoot()); } if (getLanguageAttribute(node, specialAttrInclude) != null || getLanguageAttribute(node, specialAttrExclude) != null) { log(new StateAttrsNotAllowedOnRoot()); } if (getLanguageAttribute(node, specialAttrItemCPolicy) != null || getLanguageAttribute(node, specialAttrItemDPolicy) != null ) { log(new ItemPolicyNotAllowedOnRoot()); } } public static class DefaultPropertyError extends CompilerError { private static final long serialVersionUID = 4064574335519417302L; } public static class IdNotAllowedOnRoot extends CompilerError { private static final long serialVersionUID = -2319051120793286922L; } public static class StateAttrsNotAllowedOnRoot extends CompilerError { private static final long serialVersionUID = -5448289747847880603L; } public static class StateAttrsNotAllowedOnDecls extends CompilerError { private static final long serialVersionUID = -5448289747843880603L; } public static class ItemPolicyNotAllowedOnRoot extends CompilerError { private static final long serialVersionUID = -5448389747847880603L; } public static class ItemPolicyNotAllowedOnDecls extends CompilerError { private static final long serialVersionUID = -5448889747843880603L; } public static class MissingAttribute extends CompilerError { private static final long serialVersionUID = -3356986862852847108L; public String attribute; public MissingAttribute(String attribute) { this.attribute = attribute; } } public static class LanguageNodeInDeclarationError extends CompilerError { private static final long serialVersionUID = 2738031782626560481L; public String image; public LanguageNodeInDeclarationError(String image) { this.image = image; } } public static class NestedDeclaration extends CompilerError { private static final long serialVersionUID = -2341988816922122620L; public String declaration; public String targetType; public NestedDeclaration(String declaration, String targetType) { this.declaration = declaration; this.targetType = targetType; } } public static class SingleRValueNestedDeclaration extends NestedDeclaration { private static final long serialVersionUID = -2341988816922122621L; public String targetElementType; public SingleRValueNestedDeclaration(String declaration, String targetType, String targetElementType) { super(declaration, targetType); this.targetElementType = targetElementType; } } public static class MultiRValueNestedDeclaration extends NestedDeclaration { private static final long serialVersionUID = -2341988816922122622L; public String targetType; public String targetElementType; public MultiRValueNestedDeclaration(String declaration, String targetType, String targetElementType) { super(declaration, targetType); this.targetElementType = targetElementType; } } public static class ThemeAttributeError extends CompilerError { private static final long serialVersionUID = 3082224489629723459L; } public static class RslAttributeError extends CompilerError { private static final long serialVersionUID = 606263107981414356L; } public static class LibAttributeError extends CompilerError { private static final long serialVersionUID = 6302777794984339496L; } public static class EmbedNotAllowed extends CompilerError { private static final long serialVersionUID = -6247692654987565435L; } public static class ClearNotAllowed extends CompilerError { private static final long serialVersionUID = -307322186643423229L; } public static class InvalidPreLoaderClassName extends CompilerError { private static final long serialVersionUID = -1419336460920873288L; public String className; public InvalidPreLoaderClassName(String className) { this.className = className; } } public static class InvalidSplashScreenImageClassName extends CompilerError { private static final long serialVersionUID = -4647232290960588369L; public String className; public InvalidSplashScreenImageClassName(String className) { this.className = className; } } public static class InvalidRuntimeDPIProviderClassName extends CompilerError { private static final long serialVersionUID = -2342232946832901971L; public String className; public InvalidRuntimeDPIProviderClassName(String className) { this.className = className; } } }
/* Copyright (C) 2012 by CapCaval.org 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 org.capcaval.c3.component; public interface ComponentService { }
/* * Copyright (c) 2011-2020, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.demonstrations.sfm.d3; import boofcv.abst.feature.associate.AssociateDescTo2D; import boofcv.abst.feature.associate.AssociateDescription2D; import boofcv.abst.feature.associate.ScoreAssociateHamming_B; import boofcv.abst.feature.describe.DescribeRegionPoint; import boofcv.abst.feature.detdesc.DetectDescribeMulti; import boofcv.abst.feature.detdesc.DetectDescribeMultiFusion; import boofcv.abst.feature.detect.extract.ConfigExtract; import boofcv.abst.feature.detect.extract.NonMaxSuppression; import boofcv.abst.feature.detect.intensity.GeneralFeatureIntensity; import boofcv.abst.feature.detect.interest.ConfigGeneralDetector; import boofcv.abst.feature.detect.interest.DetectorInterestPointMulti; import boofcv.abst.feature.detect.interest.GeneralToInterestMulti; import boofcv.abst.feature.disparity.StereoDisparitySparse; import boofcv.abst.sfm.AccessPointTracks3D; import boofcv.abst.sfm.d3.StereoVisualOdometry; import boofcv.abst.tracker.PointTracker; import boofcv.abst.tracker.PointTrackerToTwoPass; import boofcv.abst.tracker.PointTrackerTwoPass; import boofcv.alg.feature.detect.interest.GeneralFeatureDetector; import boofcv.alg.filter.derivative.GImageDerivativeOps; import boofcv.alg.tracker.klt.ConfigPKlt; import boofcv.factory.feature.associate.FactoryAssociation; import boofcv.factory.feature.describe.FactoryDescribeRegionPoint; import boofcv.factory.feature.detect.extract.FactoryFeatureExtractor; import boofcv.factory.feature.detect.intensity.FactoryIntensityPoint; import boofcv.factory.feature.disparity.ConfigDisparityBM; import boofcv.factory.feature.disparity.FactoryStereoDisparity; import boofcv.factory.sfm.FactoryVisualOdometry; import boofcv.factory.tracker.FactoryPointTracker; import boofcv.gui.StereoVideoAppBase; import boofcv.gui.VisualizeApp; import boofcv.gui.d3.Polygon3DSequenceViewer; import boofcv.gui.feature.VisualizeFeatures; import boofcv.gui.image.ImagePanel; import boofcv.gui.image.ShowImages; import boofcv.io.PathLabel; import boofcv.io.UtilIO; import boofcv.io.image.SimpleImageSequence; import boofcv.struct.calib.CameraPinholeBrown; import boofcv.struct.feature.TupleDesc_B; import boofcv.struct.image.GrayF32; import boofcv.struct.image.ImageGray; import boofcv.struct.pyramid.ConfigDiscreteLevels; import georegression.struct.point.Point2D_F64; import georegression.struct.point.Point3D_F64; import georegression.struct.se.Se3_F64; import georegression.transform.se.SePointOps_F64; import org.ddogleg.struct.GrowQueue_F64; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; /** * @author Peter Abeles */ public class VisualizeStereoVisualOdometryApp <I extends ImageGray<I>> extends StereoVideoAppBase<I> implements VisualizeApp, VisualOdometryPanel.Listener { VisualOdometryPanel guiInfo; ImagePanel guiLeft; ImagePanel guiRight; Polygon3DSequenceViewer guiCam3D; StereoVisualOdometry<I> alg; boolean hasProcessedImage = false; boolean noFault; boolean showTracks; boolean showInliers; int numFaults; int numTracks; int numInliers; int whichAlg; public VisualizeStereoVisualOdometryApp( Class<I> imageType ) { super(1, imageType); addAlgorithm(0, "Single Depth : KLT", 0); addAlgorithm(0, "Single Depth : ST-BRIEF", 1); addAlgorithm(0, "Single Depth : ST-SURF-KLT", 2); addAlgorithm(0, "Dual Track : KLT + SURF", 3); addAlgorithm(0, "Quad Match : ST-BRIEF", 4); guiInfo = new VisualOdometryPanel(VisualOdometryPanel.Type.STEREO); guiLeft = new ImagePanel(); guiRight = new ImagePanel(); guiCam3D = new Polygon3DSequenceViewer(); add(guiInfo, BorderLayout.WEST); add(guiRight, BorderLayout.EAST); setMainGUI(guiLeft); guiLeft.addMouseListener(this); guiInfo.setListener(this); } private void drawFeatures( AccessPointTracks3D tracker , BufferedImage image ) { Graphics2D g2 = image.createGraphics(); numInliers=0; int N = numTracks = tracker.getTotalTracks(); if( N == 0 ) return; var ranges = new GrowQueue_F64(N); var world = new Point3D_F64(); for( int i = 0; i < N; i++ ) { tracker.getTrackWorld3D(i, world); ranges.add(world.z); } ranges.sort(); double maxRange = ranges.getFraction(0.8); var pixel = new Point2D_F64(); for( int i = 0; i < N; i++ ) { tracker.getTrackPixel(i,pixel); if( tracker.isTrackInlier(i) ) { if( showInliers ) VisualizeFeatures.drawPoint(g2,(int)pixel.x,(int)pixel.y,7,Color.BLUE,false); numInliers++; } if( showTracks && tracker.isTrackNew(i) ) { VisualizeFeatures.drawPoint(g2,(int)pixel.x,(int)pixel.y,3,Color.GREEN); continue; } if( !showTracks ) continue; tracker.getTrackWorld3D(i,world); double r = world.z/maxRange; if( r < 0 ) r = 0; else if( r > 1 ) r = 1; int color = (255 << 16) | ((int)(255*r) << 8); VisualizeFeatures.drawPoint(g2,(int)pixel.x,(int)pixel.y,3,new Color(color)); } } @Override protected void process(SimpleImageSequence<I> sequence1, SimpleImageSequence<I> sequence2 ) { // stop the image processing code stopWorker(); sequence1.setLoop(false); sequence2.setLoop(false); this.sequence1 = sequence1; this.sequence2 = sequence2; // start everything up and resume processing doRefreshAll(); } @Override protected void updateAlg(I frame1, BufferedImage buffImage1, I frame2, BufferedImage buffImage2) { if( config.left.width != frame1.width || config.left.height != frame1.height ) throw new IllegalArgumentException("Miss match between calibration and actual image size"); noFault = alg.process(frame1,frame2); } @Override protected void updateAlgGUI(I frame1, final BufferedImage buffImage1, I frame2, final BufferedImage buffImage2, final double fps) { if( !noFault) numFaults++; showTracks = guiInfo.isShowAll(); showInliers = guiInfo.isShowInliers(); drawFeatures((AccessPointTracks3D)alg,buffImage1); final Se3_F64 leftToWorld = alg.getCameraToWorld().copy(); SwingUtilities.invokeLater(new Runnable() { public void run() { guiLeft.setImage(buffImage1); guiRight.setImage(buffImage2); guiLeft.autoSetPreferredSize(); guiRight.autoSetPreferredSize(); guiLeft.repaint(); guiRight.repaint(); guiInfo.setCameraToWorld(leftToWorld); guiInfo.setNumFaults(numFaults); guiInfo.setNumTracks(numTracks); guiInfo.setNumInliers(numInliers); guiInfo.setFps(fps); } }); double r = config.getBaseline(); Point3D_F64 p1 = new Point3D_F64(-r,-r,0); Point3D_F64 p2 = new Point3D_F64(r,-r,0); Point3D_F64 p3 = new Point3D_F64(r,r,0); Point3D_F64 p4 = new Point3D_F64(-r,r,0); SePointOps_F64.transform(leftToWorld,p1,p1); SePointOps_F64.transform(leftToWorld,p2,p2); SePointOps_F64.transform(leftToWorld,p3,p3); SePointOps_F64.transform(leftToWorld,p4,p4); guiCam3D.add(p1,p2,p3,p4); guiCam3D.repaint(); hasProcessedImage = true; } @Override public void refreshAll(Object[] cookies) { numFaults = 0; if( cookies != null ) whichAlg = (Integer)cookies[0]; alg = createStereoDepth(whichAlg); alg.setCalibration(config); alg.reset(); guiInfo.reset(); handleRunningStatus(2); CameraPinholeBrown right = config.right; guiCam3D.init(); guiCam3D.setFocalLength(300); guiCam3D.setStepSize(config.getBaseline()); guiCam3D.setPreferredSize(new Dimension(right.width, right.height)); guiCam3D.setMaximumSize(guiCam3D.getPreferredSize()); startWorkerThread(); } private StereoVisualOdometry<I> createStereoDepth( int whichAlg ) { Class derivType = GImageDerivativeOps.getDerivativeType(imageType); var configBM = new ConfigDisparityBM(); configBM.disparityMin = 2; configBM.disparityRange = 150; configBM.regionRadiusX = 3; configBM.regionRadiusY = 3; configBM.maxPerPixelError = 30; configBM.texture = -1; configBM.subpixel = true; StereoDisparitySparse<I> disparity = FactoryStereoDisparity.sparseRectifiedBM(configBM,imageType); ConfigPKlt kltConfig = new ConfigPKlt(); kltConfig.toleranceFB = 3; kltConfig.pruneClose = true; kltConfig.templateRadius = 3; kltConfig.pyramidLevels = ConfigDiscreteLevels.levels(4); if( whichAlg == 0 ) { ConfigGeneralDetector configDetector = new ConfigGeneralDetector(1000,4,0.1f); PointTracker<I> tracker = FactoryPointTracker.klt(kltConfig, configDetector,imageType,derivType); return FactoryVisualOdometry.stereoDepth(1.5,120,2,200,50, false, disparity, tracker, imageType); } else if( whichAlg == 1 ) { ConfigGeneralDetector configExtract = new ConfigGeneralDetector(1000,4,0.1f); GeneralFeatureDetector detector = FactoryPointTracker.createShiTomasi(configExtract, derivType); DescribeRegionPoint describe = FactoryDescribeRegionPoint.brief(null,imageType); ScoreAssociateHamming_B score = new ScoreAssociateHamming_B(); AssociateDescription2D<TupleDesc_B> associate = new AssociateDescTo2D<>(FactoryAssociation.greedy(score, 150, true)); PointTracker<I> tracker = FactoryPointTracker.dda(detector, describe, associate, 1, imageType); return FactoryVisualOdometry.stereoDepth(1.5,80,3,200,50, false, disparity, tracker, imageType); } else if( whichAlg == 2 ) { PointTracker<I> tracker = FactoryPointTracker. combined_ST_SURF_KLT(new ConfigGeneralDetector(600, 3, 0), kltConfig, 50, null, null, imageType, derivType); PointTrackerTwoPass<I> twopass = new PointTrackerToTwoPass<>(tracker); return FactoryVisualOdometry.stereoDepth(1.5,80,3,200,50, false, disparity, twopass, imageType); } else if( whichAlg == 3 ) { ConfigGeneralDetector configDetector = new ConfigGeneralDetector(600,3,1); PointTracker<I> trackerLeft = FactoryPointTracker.klt(kltConfig, configDetector,imageType,derivType); PointTracker<I> trackerRight = FactoryPointTracker.klt(kltConfig, configDetector,imageType,derivType); DescribeRegionPoint describe = FactoryDescribeRegionPoint.surfFast(null, imageType); return FactoryVisualOdometry.stereoDualTrackerPnP(90, 2, 1.5, 1.5, 200, 50, trackerLeft, trackerRight,describe,11.0, imageType); } else if( whichAlg == 4 ) { // TODO Fix this. Totally broken and needs to be re-done. Plus name doesn't match what it is // GeneralFeatureIntensity intensity = // FactoryIntensityPoint.hessian(HessianBlobIntensity.Type.TRACE,defaultType); GeneralFeatureIntensity intensity = FactoryIntensityPoint.shiTomasi(2,false,imageType); NonMaxSuppression nonmax = FactoryFeatureExtractor.nonmax(new ConfigExtract(2,50,0,true,false,true)); GeneralFeatureDetector general = new GeneralFeatureDetector(intensity,nonmax); general.setMaxFeatures(1000); DetectorInterestPointMulti detector = new GeneralToInterestMulti(general,11.0,imageType,derivType); // DescribeRegionPoint describe = FactoryDescribeRegionPoint.brief(new ConfigBrief(true),defaultType); // DescribeRegionPoint describe = FactoryDescribeRegionPoint.pixelNCC(5,5,defaultType); DescribeRegionPoint describe = FactoryDescribeRegionPoint.surfFast(null, imageType); DetectDescribeMulti detDescMulti = new DetectDescribeMultiFusion(detector,null,describe); return FactoryVisualOdometry.stereoQuadPnP(1.5, 0.5 ,75, Double.MAX_VALUE, 600, 50, detDescMulti, imageType); } else { throw new RuntimeException("Unknown selection"); } } @Override public void setActiveAlgorithm(int indexFamily, String name, Object cookie) { stopWorker(); whichAlg = (Integer)cookie; sequence1.reset(); sequence2.reset(); refreshAll(null); } @Override public void loadConfigurationFile(String fileName) {} @Override public boolean getHasProcessedImage() { return hasProcessedImage; } @Override protected void handleRunningStatus(int status) { final String text; final Color color; switch( status ) { case 0: text = "RUNNING"; color = Color.BLACK; break; case 1: text = "PAUSED"; color = Color.RED; break; case 2: text = "FINISHED"; color = Color.RED; break; default: text = "UNKNOWN"; color = Color.BLUE; } SwingUtilities.invokeLater(new Runnable() { public void run() { guiInfo.setStatus(text,color); }}); } @Override public void eventVoPanel(final int view) { SwingUtilities.invokeLater(new Runnable() { public void run() { if( view == 0 ) { remove(guiCam3D); add(guiRight, BorderLayout.EAST); } else { remove(guiRight); add(guiCam3D,BorderLayout.EAST); } revalidate(); repaint(); }}); } public static void main( String args[] ) throws FileNotFoundException { Class type = GrayF32.class; // Class type = GrayU8.class; VisualizeStereoVisualOdometryApp app = new VisualizeStereoVisualOdometryApp(type); // app.setMediaManager(new XugglerMediaManager()); List<PathLabel> inputs = new ArrayList<>(); inputs.add(new PathLabel("Inside", UtilIO.pathExample("vo/library/config.txt"))); inputs.add(new PathLabel("Outside", UtilIO.pathExample("vo/backyard/config.txt"))); inputs.add(new PathLabel("Urban", UtilIO.pathExample("vo/rockville/config.txt"))); app.setInputList(inputs); // wait for it to process one image so that the size isn't all screwed up while( !app.getHasProcessedImage() ) { Thread.yield(); } ShowImages.showWindow(app, "Stereo Visual Odometry",true); } }
/* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.discovery.html; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.openid4java.discovery.DiscoveryException; import java.io.IOException; /** * @author Sutra Zhou * */ public class CyberNekoDOMHtmlParserTest extends TestCase { private CyberNekoDOMHtmlParser parser; /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); parser = new CyberNekoDOMHtmlParser(); } /** * Test method for * {@link org.openid4java.discovery.html.CyberNekoDOMHtmlParser#parseHtml(java.lang.String, org.openid4java.discovery.html.HtmlResult)} * . * * @throws IOException * @throws DiscoveryException */ public void testParseHtml() throws IOException, DiscoveryException { String htmlData = IOUtils.toString(this.getClass().getResourceAsStream( "identityPage.html")); HtmlResult result = new HtmlResult(); parser.parseHtml(htmlData, result); assertEquals("http://www.example.com:8080/openidserver/users/myusername", result .getDelegate1()); System.out.println(result.getOP1Endpoint()); assertEquals("http://www.example.com:8080/openidserver/openid.server", result .getOP1Endpoint().toExternalForm()); } /** * Test method for * {@link org.openid4java.discovery.html.CyberNekoDOMHtmlParser#parseHtml(java.lang.String, org.openid4java.discovery.html.HtmlResult)} * . * * @throws IOException * @throws DiscoveryException */ public void testParseHtmlWithXmlNamespace() throws IOException, DiscoveryException { String htmlData = IOUtils.toString(this.getClass().getResourceAsStream( "identityPage-with-xml-namespace.html")); HtmlResult result = new HtmlResult(); parser.parseHtml(htmlData, result); assertEquals("http://www.example.com:8080/openidserver/users/myusername", result .getDelegate1()); assertEquals("http://www.example.com:8080/openidserver/openid.server", result .getOP1Endpoint().toExternalForm()); } public void testParseHtmlXXE() throws Exception { String htmlData = IOUtils.toString(this.getClass().getResourceAsStream( "identityPageWithExternalEntityReference.html")); parser.parseHtml(htmlData, new HtmlResult()); // don't fail trying to read "/path/to/some/file" from the input data } }
package com.revengemission.commons.ratelimiter; import java.security.AccessControlException; /** * @author wzhang */ public class RateLimiterException extends AccessControlException { private String ip; public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public RateLimiterException(String message) { super(message); } public RateLimiterException(String message, String ip) { super(message); this.ip = ip; } }
package com.geekq.guns.rest.modular.auth.filter; import com.geekq.guns.core.base.tips.ErrorTip; import com.geekq.guns.core.util.RenderUtil; import com.geekq.guns.rest.common.CurrentUser; import com.geekq.guns.rest.common.exception.BizExceptionEnum; import com.geekq.guns.rest.config.properties.JwtProperties; import com.geekq.guns.rest.modular.auth.util.JwtTokenUtil; import io.jsonwebtoken.JwtException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 对客户端请求的jwt token验证过滤器 * * @author fengshuonan * @Date 2017/8/24 14:04 */ public class AuthFilter extends OncePerRequestFilter { private final Log logger = LogFactory.getLog(this.getClass()); @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private JwtProperties jwtProperties; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getServletPath().equals("/" + jwtProperties.getAuthPath())) { chain.doFilter(request, response); return; } // 配置忽略列表 String ignoreUrl = jwtProperties.getIgnoreUrl(); String[] ignoreUrls = ignoreUrl.split(","); for(int i=0;i<ignoreUrls.length;i++){ if(request.getServletPath().startsWith(ignoreUrls[i])){ chain.doFilter(request, response); return; } } final String requestHeader = request.getHeader(jwtProperties.getHeader()); String authToken = null; if (requestHeader != null && requestHeader.startsWith("Bearer ")) { authToken = requestHeader.substring(7); // 通过Token获取userID,并且将之存入Threadlocal,以便后续业务调用 String userId = jwtTokenUtil.getUsernameFromToken(authToken); if(userId == null){ return; } else { CurrentUser.saveUserId(userId); } //验证token是否过期,包含了验证jwt是否正确 try { boolean flag = jwtTokenUtil.isTokenExpired(authToken); if (flag) { RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage())); return; } } catch (JwtException e) { //有异常就是token解析失败 RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage())); return; } } else { //header没有带Bearer字段 RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage())); return; } chain.doFilter(request, response); } }
/* * Copyright (c) 2013 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing.server.jetty; import net.jadler.stubbing.StubResponse; import net.jadler.RequestManager; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.Iterator; import java.util.Map.Entry; import org.apache.commons.collections.MultiMap; import org.apache.commons.lang.Validate; /** * Jetty Handler which handles all http communication by returning an http response according to a stub response * obtained from a {@link RequestManager} instance. */ class JadlerHandler extends AbstractHandler { private final RequestManager requestManager; /** * @param requestManager request manager instance to retrieve stub responses */ JadlerHandler(final RequestManager requestManager) { Validate.notNull(requestManager, "requestManager cannot be null"); this.requestManager = requestManager; } @Override public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final net.jadler.Request req = RequestUtils.convert(request); final StubResponse stubResponse = this.requestManager.provideStubResponseFor(req); response.setStatus(stubResponse.getStatus()); this.insertResponseHeaders(stubResponse.getHeaders(), response); baseRequest.setHandled(true); this.processDelay(stubResponse.getDelay()); this.insertResponseBody(stubResponse.getBody(), response); } private void insertResponseBody(final byte[] body, final HttpServletResponse response) throws IOException { if (body.length > 0) { final OutputStream os = response.getOutputStream(); os.write(body); } } private void insertResponseHeaders(final MultiMap headers, final HttpServletResponse response) { for (@SuppressWarnings("unchecked") final Iterator<Entry<String, Collection<String>>> it = headers.entrySet().iterator(); it.hasNext(); ) { final Entry<String, Collection<String>> e = it.next(); for (final String value: e.getValue()) { response.addHeader(e.getKey(), value); } } } private void processDelay(final long delay) { if (delay > 0) { try { Thread.sleep(delay); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } } } }
/** * Copyright 2017 The jetcd 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 io.etcd.jetcd.internal.impl; import com.google.common.base.Charsets; import io.etcd.jetcd.data.ByteSequence; import java.io.IOException; import java.net.ServerSocket; public class TestUtil { public static String randomString() { return java.util.UUID.randomUUID().toString(); } public static ByteSequence randomByteSequence() { return ByteSequence.from(randomString(), Charsets.UTF_8); } public static int findNextAvailablePort() throws IOException { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } } }
package com.qa.ims.persistence.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public interface Dao<T> { List<T> readAll(); T read(Long id); T create(T t); T update(T t); int delete(long id); T modelFromResultSet(ResultSet resultSet) throws SQLException; }
package de.crunc.jackson.datatype.vertx.parser; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import org.junit.Test; import java.io.IOException; import static com.fasterxml.jackson.core.JsonToken.*; import static de.crunc.jackson.datatype.vertx.JsonArrayBuilder.array; import static de.crunc.jackson.datatype.vertx.JsonObjectBuilder.object; import static de.crunc.jackson.datatype.vertx.matcher.JsonParserMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.nullValue; /** * Unit test for {@link JsonElementParser}. * * @author Hauke Jaeger, hauke.jaeger@googlemail.com */ public class JsonElementParserArrayContextTest extends JsonElementParserBaseTest { private JsonParser jp; @Test public void shouldBeInRootAfterCreation() { jp = createParser(array()); assertThat(jp, context(inRoot())); } @Test public void shouldBeInRootAfterFullIteration() { jp = createParser(array() .add(object()) .add(array())); assertThat(jp, nextToken(START_ARRAY)); { assertThat(jp, nextToken(startToken())); assertThat(jp, nextToken(endToken())); assertThat(jp, nextToken(startToken())); assertThat(jp, nextToken(endToken())); } assertThat(jp, nextToken(END_ARRAY)); assertThat(jp, nextToken(nullValue())); assertThat(jp, context(inRoot())); } @Test public void shouldBeInArrayWhenAtEmptyArrayStart() { jp = createParser(array()); assertThat(jp, nextToken(JsonToken.START_ARRAY)); assertThat(jp, context(inArray())); } @Test public void shouldBeInArrayWhenAtEmptyArrayEnd() { jp = createParser(array()); assertThat(jp, nextToken(JsonToken.START_ARRAY)); assertThat(jp, nextToken(JsonToken.END_ARRAY)); assertThat(jp, context(inArray())); } @Test public void shouldBeInArrayWhenAtArrayStart() { jp = createParser(array() .add(1) .add("B") .add(3.141) .add(true) .add(false) .addNull()); assertThat(jp, nextToken(JsonToken.START_ARRAY)); assertThat(jp, context(inArray())); } @Test public void shouldBeInArrayWhenWithinArrayAndAtArrayEnd() { jp = createParser(array() .add(1) .add("B") .add(3.141) .add(true) .add(false) .addNull()); assertThat(jp, nextToken(JsonToken.START_ARRAY)); { assertThat(jp, nextToken(valueToken())); assertThat(jp, context(inArray())); assertThat(jp, nextToken(valueToken())); assertThat(jp, context(inArray())); assertThat(jp, nextToken(valueToken())); assertThat(jp, context(inArray())); assertThat(jp, nextToken(valueToken())); assertThat(jp, context(inArray())); assertThat(jp, nextToken(valueToken())); assertThat(jp, context(inArray())); assertThat(jp, nextToken(valueToken())); assertThat(jp, context(inArray())); } assertThat(jp, nextToken(JsonToken.END_ARRAY)); assertThat(jp, context(inArray())); } @Test public void shouldBeInObjectWhenAtEmptyObjectItem() { jp = createParser(array() .add(object())); assertThat(jp, nextToken(JsonToken.START_ARRAY)); assertThat(jp, context(inArray())); { assertThat(jp, nextToken(START_OBJECT)); assertThat(jp, context(inObject())); assertThat(jp, nextToken(END_OBJECT)); assertThat(jp, context(inObject())); } assertThat(jp, nextToken(JsonToken.END_ARRAY)); assertThat(jp, context(inArray())); } @Test public void shouldBeInObjectWhenAtObjectItem() { jp = createParser(array() .add(object() .put("Foo", "Bar"))); assertThat(jp, nextToken(JsonToken.START_ARRAY)); assertThat(jp, context(inArray())); { assertThat(jp, nextToken(START_OBJECT)); assertThat(jp, context(inObject())); { assertThat(jp, nextToken(FIELD_NAME)); assertThat(jp, context(inObject())); assertThat(jp, nextToken(valueToken())); assertThat(jp, context(inObject())); } assertThat(jp, nextToken(END_OBJECT)); assertThat(jp, context(inObject())); } assertThat(jp, nextToken(JsonToken.END_ARRAY)); assertThat(jp, context(inArray())); } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package cacheperf.comparisons.gemfirexd.useCase5.poc; import cacheperf.comparisons.gemfirexd.QueryPerfException; import com.gemstone.gemfire.StatisticDescriptor; import com.gemstone.gemfire.StatisticsType; import com.gemstone.gemfire.internal.NanoTimer; import perffmwk.HistogramStats; import perffmwk.PerformanceStatistics; /** * Implements statistics related to UseCase5. */ public class UseCase5Stats extends PerformanceStatistics { public static enum Stmt { insTerminal, insSource, insSourceMessageLog, insSingleTicket, insTicketHistory, insSourceMessageResult, insTicketsToPool, selTerminalStatus, insTerminalBalanceTransactionLog, selectTicketByTSN, updTicketForPay; } /** <code>UseCase5Stats</code> are maintained on a per-thread basis */ private static final int SCOPE = THREAD_SCOPE; public static final String VM_COUNT = "vmCount"; protected static final String COMMITS_COMPLETED = "commitsCompleted"; protected static final String COMMIT_TIME = "commitTime"; protected static final String CB_SELLS_COMPLETED = "cbSellsCompleted"; protected static final String CB_SELL_TIME = "cbSellTime"; protected static final String CB_PAYS_COMPLETED = "cbPaysCompleted"; protected static final String CB_PAY_TIME = "cbPayTime"; protected static final String insTerminalStmt = "insTerminalStmtsExecuted"; protected static final String insSourceStmt = "insSourceStmtsExecuted"; protected static final String insSourceMessageLogStmt = "insSourceMessageLogStmtsExecuted"; protected static final String insSingleTicketStmt = "insSingleTicketStmtsExecuted"; protected static final String insTicketHistoryStmt = "insTicketHistoryStmtsExecuted"; protected static final String insSourceMessageResultStmt = "insSourceMessageResultStmtsExecuted"; protected static final String insTicketsToPoolStmt = "insTicketsToPoolStmtsExecuted"; protected static final String selTerminalStatusStmt = "selTerminalStatusStmtsExecuted"; protected static final String insTerminalBalanceTransactionLogStmt = "insTerminalBalanceTransactionLogStmtsExecuted"; protected static final String selectTicketByTSNStmt = "selectTicketByTSNStmtsExecuted"; protected static final String updTicketForPayStmt = "updTicketForPayStmtsExecuted"; protected static final String insTerminalStmtTime = "insTerminalStmtTime"; protected static final String insSourceStmtTime = "insSourceStmtTime"; protected static final String insSourceMessageLogStmtTime = "insSourceMessageLogStmtTime"; protected static final String insSingleTicketStmtTime = "insSingleTicketStmtTime"; protected static final String insTicketHistoryStmtTime = "insTicketHistoryStmtTime"; protected static final String insSourceMessageResultStmtTime = "insSourceMessageResultStmtTime"; protected static final String insTicketsToPoolStmtTime = "insTicketsToPoolStmtTime"; protected static final String selTerminalStatusStmtTime = "selTerminalStatusStmtTime"; protected static final String insTerminalBalanceTransactionLogStmtTime = "insTerminalBalanceTransactionLogStmtTime"; protected static final String selectTicketByTSNStmtTime = "selectTicketByTSNStmtTime"; protected static final String updTicketForPayStmtTime = "updTicketForPayStmtTime"; //////////////////////// Static Methods //////////////////////// /** * Returns the statistic descriptors for <code>UseCase5Stats</code>. */ public static StatisticDescriptor[] getStatisticDescriptors() { boolean largerIsBetter = true; return new StatisticDescriptor[] { factory().createIntGauge ( VM_COUNT, "When aggregated, the number of VMs using this statistics object.", "VMs" ), factory().createIntCounter ( COMMITS_COMPLETED, "Number of commits completed.", "operations", largerIsBetter ), factory().createLongCounter ( COMMIT_TIME, "Total time spent on commits (minus DML time).", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( CB_SELLS_COMPLETED, "Number of cash sells completed.", "operations", largerIsBetter ), factory().createLongCounter ( CB_SELL_TIME, "Total time spent on cash sells that were completed (minus commit time).", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( CB_PAYS_COMPLETED, "Number of cash pays completed.", "operations", largerIsBetter ), factory().createLongCounter ( CB_PAY_TIME, "Total time spent on cash pays that were completed (minus commit time).", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( insTerminalStmt, "Number of insTerminalStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( insTerminalStmtTime, "Total time spent executing insTerminalStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( insSourceStmt, "Number of insSourceStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( insSourceStmtTime, "Total time spent executing insSourceStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( insSourceMessageLogStmt, "Number of insSourceMessageLogStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( insSourceMessageLogStmtTime, "Total time spent executing insSourceMessageLogStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( insSingleTicketStmt, "Number of insSingleTicketStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( insSingleTicketStmtTime, "Total time spent executing insSingleTicketStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( insTicketHistoryStmt, "Number of insTicketHistoryStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( insTicketHistoryStmtTime, "Total time spent executing insTicketHistoryStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( insSourceMessageResultStmt, "Number of insSourceMessageResultStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( insSourceMessageResultStmtTime, "Total time spent executing insSourceMessageResultStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( insTicketsToPoolStmt, "Number of insTicketsToPoolStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( insTicketsToPoolStmtTime, "Total time spent executing insTicketsToPoolStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( selTerminalStatusStmt, "Number of selTerminalStatusStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( selTerminalStatusStmtTime, "Total time spent executing selTerminalStatusStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( insTerminalBalanceTransactionLogStmt, "Number of insTerminalBalanceTransactionLogStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( insTerminalBalanceTransactionLogStmtTime, "Total time spent executing insTerminalBalanceTransactionLogStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( selectTicketByTSNStmt, "Number of selectTicketByTSNStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( selectTicketByTSNStmtTime, "Total time spent executing selectTicketByTSNStmt.", "nanoseconds", !largerIsBetter ), factory().createIntCounter ( updTicketForPayStmt, "Number of updTicketForPayStmt executed.", "executions", largerIsBetter ), factory().createLongCounter ( updTicketForPayStmtTime, "Total time spent executing updTicketForPayStmt.", "nanoseconds", !largerIsBetter ) }; } public static UseCase5Stats getInstance() { UseCase5Stats tps = (UseCase5Stats)getInstance(UseCase5Stats.class, SCOPE); tps.incVMCount(); return tps; } public static UseCase5Stats getInstance(String name) { UseCase5Stats tps = (UseCase5Stats)getInstance(UseCase5Stats.class, SCOPE, name); tps.incVMCount(); return tps; } public static UseCase5Stats getInstance( String name, String trimspecName ) { UseCase5Stats tps = (UseCase5Stats)getInstance(UseCase5Stats.class, SCOPE, name, trimspecName); tps.incVMCount(); return tps; } /////////////////// Construction / initialization //////////////// public UseCase5Stats( Class cls, StatisticsType type, int scope, String instanceName, String trimspecName ) { super( cls, type, scope, instanceName, trimspecName ); } /////////////////// Updating stats ///////////////////////// // vm count -------------------------------------------------------------------- /** * increase the count on the vmCount */ private synchronized void incVMCount() { if (!VMCounted) { statistics().incInt(VM_COUNT, 1); VMCounted = true; } } private static boolean VMCounted = false; // histogram ------------------------------------------------------------------- /** * increase the time on the optional histogram by the supplied amount */ public void incHistogram(HistogramStats histogram, long amount) { if (histogram != null) { histogram.incBin(amount); } } // transactions ---------------------------------------------------------------- public long startCommit() { return NanoTimer.getTime(); } public void endCommit(long start) { statistics().incInt(COMMITS_COMPLETED, 1); statistics().incLong(COMMIT_TIME, NanoTimer.getTime() - start); } public long startCBSell() { return NanoTimer.getTime(); } public void endCBSell(long start) { statistics().incInt(CB_SELLS_COMPLETED, 1); statistics().incLong(CB_SELL_TIME, NanoTimer.getTime() - start); } public long startCBPay() { return NanoTimer.getTime(); } public void endCBPay(long start) { statistics().incInt(CB_PAYS_COMPLETED, 1); statistics().incLong(CB_PAY_TIME, NanoTimer.getTime() - start); } // statements ------------------------------------------------------------------ public long startStmt(Stmt stmt) { return NanoTimer.getTime(); } public void endStmt(Stmt stmt, long start) { endStmt(stmt, start, 1, null); } public void endStmt(Stmt stmt, long start, HistogramStats histogram) { endStmt(stmt, start, 1, histogram); } public void endStmt(Stmt stmt, long start, int amount, HistogramStats histogram) { long elapsed = NanoTimer.getTime() - start; switch (stmt) { case insTerminal: statistics().incInt(insTerminalStmt, amount); statistics().incLong(insTerminalStmtTime, elapsed); break; case insSource: statistics().incInt(insSourceStmt, amount); statistics().incLong(insSourceStmtTime, elapsed); break; case insSourceMessageLog: statistics().incInt(insSourceMessageLogStmt, amount); statistics().incLong(insSourceMessageLogStmtTime, elapsed); break; case insSingleTicket: statistics().incInt(insSingleTicketStmt, amount); statistics().incLong(insSingleTicketStmtTime, elapsed); break; case insTicketHistory: statistics().incInt(insTicketHistoryStmt, amount); statistics().incLong(insTicketHistoryStmtTime, elapsed); break; case insSourceMessageResult: statistics().incInt(insSourceMessageResultStmt, amount); statistics().incLong(insSourceMessageResultStmtTime, elapsed); break; case insTicketsToPool: statistics().incInt(insTicketsToPoolStmt, amount); statistics().incLong(insTicketsToPoolStmtTime, elapsed); break; case selTerminalStatus: statistics().incInt(selTerminalStatusStmt, amount); statistics().incLong(selTerminalStatusStmtTime, elapsed); break; case insTerminalBalanceTransactionLog: statistics().incInt(insTerminalBalanceTransactionLogStmt, amount); statistics().incLong(insTerminalBalanceTransactionLogStmtTime, elapsed); break; case selectTicketByTSN: statistics().incInt(selectTicketByTSNStmt, amount); statistics().incLong(selectTicketByTSNStmtTime, elapsed); break; case updTicketForPay: statistics().incInt(updTicketForPayStmt, amount); statistics().incLong(updTicketForPayStmtTime, elapsed); break; default: String s = "Should not happen"; throw new QueryPerfException(s); } if (histogram != null) { incHistogram(histogram, elapsed); } } }
package com.echopen.asso.echopen.model.EchoImage; import android.graphics.Bitmap; /** * Created by mehdibenchoufi on 21/10/15. */ public class EchoCharImage extends AbstractEchoImage { private char[] pixelsArray; private Bitmap bitmap; public char[] getPixelsArray() { return pixelsArray; } public void setPixelsArray(char[] pixelsArray) { this.pixelsArray = pixelsArray; } public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public EchoCharImage(char[] pixelsArray) { bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_8888); this.pixelsArray = pixelsArray; } protected Bitmap accept(Bitmap bitmap){ Bitmap echoImageToBitmap = new EchoImageToBitmap().visit(this); return echoImageToBitmap; } }
/* * Copyright (c) 2010-2015, b3log.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.b3log.solo.repository.impl; import org.b3log.latke.repository.Transaction; import org.b3log.solo.AbstractTestCase; import org.b3log.solo.model.Link; import org.b3log.solo.repository.LinkRepository; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.Test; /** * {@link LinkRepositoryImpl} test case. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.0.0.0, Dec 29, 2011 */ @Test(suiteName = "repository") public final class LinkRepositoryImplTestCase extends AbstractTestCase { /** * Tests. * * @throws Exception exception */ @Test public void test() throws Exception { final LinkRepository linkRepository = getLinkRepository(); final int link1Order = 1, link2Order = 2, link3Order = 3; JSONObject link1 = new JSONObject(); link1.put(Link.LINK_TITLE, "link title"); link1.put(Link.LINK_DESCRIPTION, "link description"); link1.put(Link.LINK_ADDRESS, "link address"); link1.put(Link.LINK_ORDER, link1Order); Transaction transaction = linkRepository.beginTransaction(); linkRepository.add(link1); transaction.commit(); Assert.assertNull(linkRepository.getByAddress("test")); Assert.assertNotNull(linkRepository.getByAddress("link address")); Assert.assertNull(linkRepository.getByOrder(0)); Assert.assertNotNull(linkRepository.getByOrder(link1Order)); final JSONObject link2 = new JSONObject(); link2.put(Link.LINK_TITLE, "link title"); link2.put(Link.LINK_DESCRIPTION, "link description"); link2.put(Link.LINK_ADDRESS, "link address"); link2.put(Link.LINK_ORDER, link2Order); transaction = linkRepository.beginTransaction(); final String link2Id = linkRepository.add(link2); transaction.commit(); Assert.assertEquals(linkRepository.getMaxOrder(), link2Order); JSONObject link3 = new JSONObject(); link3.put(Link.LINK_TITLE, "link title"); link3.put(Link.LINK_DESCRIPTION, "link description"); link3.put(Link.LINK_ADDRESS, "link address"); link3.put(Link.LINK_ORDER, link3Order); transaction = linkRepository.beginTransaction(); linkRepository.add(link3); transaction.commit(); final int total = 3; Assert.assertEquals(linkRepository.count(), total); link1 = linkRepository.getUpper(link2Id); Assert.assertNotNull(link1); Assert.assertEquals(link1.getInt(Link.LINK_ORDER), link1Order); link3 = linkRepository.getUnder(link2Id); Assert.assertNotNull(link3); Assert.assertEquals(link3.getInt(Link.LINK_ORDER), link3Order); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.appservice.implementation; import com.azure.resourcemanager.appservice.AppServiceManager; import com.azure.resourcemanager.appservice.models.AppServiceCertificateKeyVaultBinding; import com.azure.resourcemanager.appservice.models.AppServiceCertificateOrder; import com.azure.resourcemanager.appservice.models.AppServicePlan; import com.azure.resourcemanager.appservice.models.KeyVaultSecretStatus; import com.azure.resourcemanager.appservice.fluent.inner.AppServiceCertificateResourceInner; import com.azure.resourcemanager.resources.fluentcore.arm.models.implementation.IndependentChildResourceImpl; import reactor.core.publisher.Mono; /** The implementation for {@link AppServicePlan}. */ class AppServiceCertificateKeyVaultBindingImpl extends IndependentChildResourceImpl< AppServiceCertificateKeyVaultBinding, AppServiceCertificateOrder, AppServiceCertificateResourceInner, AppServiceCertificateKeyVaultBindingImpl, AppServiceManager> implements AppServiceCertificateKeyVaultBinding { private final AppServiceCertificateOrderImpl parent; AppServiceCertificateKeyVaultBindingImpl( AppServiceCertificateResourceInner innerObject, AppServiceCertificateOrderImpl parent) { super(innerObject.name(), innerObject, (parent != null) ? parent.manager() : null); this.parent = parent; } @Override public String id() { return innerModel().id(); } @Override public Mono<AppServiceCertificateKeyVaultBinding> createChildResourceAsync() { final AppServiceCertificateKeyVaultBinding self = this; return parent .manager() .serviceClient() .getAppServiceCertificateOrders() .createOrUpdateCertificateAsync(parent.resourceGroupName(), parent.name(), name(), innerModel()) .map( appServiceCertificateInner -> { setInner(appServiceCertificateInner); return self; }); } @Override public String keyVaultId() { return innerModel().keyVaultId(); } @Override public String keyVaultSecretName() { return innerModel().keyVaultSecretName(); } @Override public KeyVaultSecretStatus provisioningState() { return innerModel().provisioningState(); } @Override protected Mono<AppServiceCertificateResourceInner> getInnerAsync() { return parent .manager() .serviceClient() .getAppServiceCertificateOrders() .getCertificateAsync(parent.resourceGroupName(), parent.name(), name()); } }
package tech.quantit.northstar.strategy.api.model; import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import tech.quantit.northstar.strategy.api.constant.ModuleType; @Builder @NoArgsConstructor @AllArgsConstructor @Document @Data public class ModuleInfo { /** * 信号策略 */ private ComponentAndParamsPair signalPolicy; /** * 风控规则 */ private List<ComponentAndParamsPair> riskControlRules; /** * 交易策略 */ private ComponentAndParamsPair dealer; /** * 账户ID */ private String accountGatewayId; /** * 模组名称 */ @Id private String moduleName; /** * 是否启用 */ private boolean enabled; /** * 策略类型 */ private ModuleType type; }
package collection; import java.util.HashMap; import java.util.Map; /** * @author ze.liu * @since 2014/6/9 */ public class FinalMap { /** * 因为在hashmap中存储的entry,所以最后是entry改变了,并没有改变map,final不影响 */ static final Map map = new HashMap(); public static void main(String[] args) { for (int i = 0; i < 1000; i++) { map.put(i, "hello " + i); } } }
package mock.plugin.private_and_static; import com.intellij.openapi.components.PersistentStateComponent; /*expected(PROBLEM) Abstract method com.intellij.openapi.components.PersistentStateComponent.getState() : T is not implemented Concrete class mock.plugin.private_and_static.StaticOverridingNotImplemented inherits from com.intellij.openapi.components.PersistentStateComponent but doesn't implement the abstract method getState() : T. This can lead to **AbstractMethodError** exception at runtime. */ public class StaticOverridingNotImplemented implements PersistentStateComponent<String> { //in PSC there are 2 methods //should be error , because static overriding public static String getState() { return null; } }
/** * Copyright (c) 2004-2011 Wang Jinbao(Julian Wong), http://www.ralasafe.com * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php */ package org.ralasafe.db; import org.ralasafe.EntityExistException; import java.sql.Connection; /** * Update entity operations to database. * * @author back * */ public interface TableUpdator { /** * Table definition. * * @param mapping */ public void setTable( Table mapping ); /** * Update an entity. * If it doesn't exist, throw no exception; * If update operation would violate some constraints, throw EntityExistException * * @param newValue * @throws EntityExistException */ public void updateByIdColumns( Object newValue ) throws EntityExistException; public void updateByIdColumns( Connection conn, Object newValue ) throws EntityExistException; }
package com.revature.dungeonsite.controllers; import com.revature.dungeonsite.exceptions.ResourceNotFoundException; import com.revature.dungeonsite.models.*; import com.revature.dungeonsite.repositories.*; import com.revature.dungeonsite.utils.KeyUtils; import com.revature.dungeonsite.utils.PasswordUtils; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.*; @RestController @CrossOrigin @RequestMapping("/api/games") public class GameController { private AddressRepository ar; private BehaviorRepository br; private GameRepository games; private GameAddressRepository gar; private GameBehaviorRepository gbr; private GameLanguageRepository glgr; private GameLinkRepository glnr; private GameScheduleRepository gsr; private LanguageRepository lgr; private LinkRepository lnr; private RulesRepository rr; private ScheduleRepository sr; private UserGameRepository ug; private UserRepository ur; public GameController( AddressRepository nar, BehaviorRepository nbr, GameRepository games, GameAddressRepository ngar, GameBehaviorRepository ngb, GameLanguageRepository nglg, GameLinkRepository ngln, GameScheduleRepository gameSched, LanguageRepository nlr, LinkRepository nln, RulesRepository nrr, ScheduleRepository schedule, UserGameRepository userGames, UserRepository userRep) { this.ar = nar; this.br = nbr; this.gsr = gameSched; this.gar = ngar; this.gbr = ngb; this.glgr =nglg; this.glnr = ngln; this.lgr = nlr; this.lnr = nln; this.rr = nrr; this.sr = schedule; this.ug = userGames; this.ur = userRep; this.games = games; } public Game getGameByGameID(Long gameID) throws ResourceNotFoundException { return games.findById(gameID) .orElseThrow( () -> new ResourceNotFoundException("Game not found for ID: " + gameID) ); } @GetMapping public ResponseEntity<List<Game>> findAll() { return ResponseEntity.ok(this.games.findAll()); } @GetMapping("/{id}") public ResponseEntity<Game> getGameByID(@PathVariable(value="id") Long gameID) throws ResourceNotFoundException { Game game = getGameByGameID(gameID); return ResponseEntity.ok().body(game); } @GetMapping("/address/{id}") public ResponseEntity<List<Optional<Address>>> getGameAddressesByID(@PathVariable(value="id") Long gameID) { List<GameAddress> listGA = gar.findByGameID(gameID); List<Optional<Address>> list = new ArrayList<>(); for (GameAddress item: listGA) { list.add(ar.findById(item.getAddressID()) ); } return ResponseEntity.ok(list); } @GetMapping("/full/{id}") public ResponseEntity<GameFull> gameFullByID(@PathVariable(value="id") Long gameID) throws ResourceNotFoundException { GameFull returnThis = new GameFull(); returnThis.setGame(this.getGameByGameID(gameID) ); List<GameAddress> listGA = this.gar.findByGameID(gameID); List<GameBehavior> listGB = this.gbr.findByGameID(gameID); List<GameLanguage> listGLG = this.glgr.findByGameID(gameID); List<GameLink> listGLN = this.glnr.findByGameID(gameID); List<GameSchedule> listGS = this.gsr.findByGameID(gameID); List<UserGame> listUG = this.ug.findByGameID(gameID); List<Optional<Address>> listA = new ArrayList<>(); List<Optional<Behavior>> listB = new ArrayList<>(); List<Optional<Language>> listLG = new ArrayList<>(); List<Optional<Link>> listLN = new ArrayList<>(); List<Optional<Schedule>> listS = new ArrayList<>(); List<SiteUser> listU = new ArrayList<>(); for (GameAddress item: listGA) { listA.add(ar.findById(item.getAddressID()) ); } for (GameBehavior item: listGB) { listB.add(br.findById(item.getBehaviorID()) ); } for (GameLanguage item: listGLG) { listLG.add(lgr.findById(item.getLanguageID()) ); } for (GameLink item: listGLN) { listLN.add(lnr.findById(item.getLinkID()) ); } for (GameSchedule item: listGS) { listS.add(sr.findById(item.getScheduleID()) ); } for (UserGame item: listUG) { listU.add(ur.findById(item.getUserID()).get() ); } returnThis.setAddress(listA); returnThis.setBehavior(listB); returnThis.setLanguage(listLG); returnThis.setLink(listLN); returnThis.setSchedule(listS); returnThis.setGMName(ur.findById(returnThis.getGame().getGameMasterID()).get().getUsername() ); returnThis.setUsers(listU); returnThis.setRulesName(rr.findById(games.findById(gameID).get().getRulesID()).get().getRulesName() ); return ResponseEntity.ok(returnThis); } @GetMapping("/master/{id}") public ResponseEntity<List<Game>> getGamesByMasterID(@PathVariable(value="id") Long masterID){ List<Game> gamesFound = games.findByGameMasterID(masterID); return ResponseEntity.ok().body(gamesFound); } @GetMapping("/mastername/{namae}") public ResponseEntity<List<Game>> findGamesByMasterName(@PathVariable(value="namae") String masterName) { SiteUser master = ur.findByUsername(masterName); List<Game> list = games.findByGameMasterID(master.getUserID()); return ResponseEntity.ok().body(list); } @GetMapping("/name/{namae}") public ResponseEntity<Game> getGameByGameName(@PathVariable(value="namae") String name) throws ResourceNotFoundException { Game game = games.findByGameName(name); return ResponseEntity.ok().body(game); } @GetMapping("/user/{id}") public ResponseEntity<List<Game>> getGamesByUserID(@PathVariable(value="id") Long ID) throws ResourceNotFoundException { List<UserGame> listUG = ug.findByUserID(ID); List<Game> list = new ArrayList<>(); for (UserGame ug: listUG) { list.add(getGameByGameID(ug.getGameID()) ); } return ResponseEntity.ok(list); } @PutMapping("/{id}") public ResponseEntity<Game> updateGame(@PathVariable(value = "id") Long gameID, @RequestBody Game game) throws ResourceNotFoundException { Game neoGame = getGameByGameID(gameID); if (game.getGameName() != null && !game.getGameName().equals("")) neoGame.setGameName(game.getGameName()); if (game.getGamePassword() != null && !game.getGamePassword().equals("") && neoGame.getGamePassword()!=null && !game.getGamePassword().equals(neoGame.getGamePassword())) neoGame.setGamePassword(game.getGamePassword()); if (game.getRulesID() != null) neoGame.setRulesID(game.getRulesID()); if (game.getDescription() != null && !game.getDescription().equals("")) neoGame.setDescription(game.getDescription()); return ResponseEntity.ok(this.games.save(neoGame)); } @PostMapping public Game makeGame(@RequestBody Game neoGame) { neoGame.setGameID(KeyUtils.nextKey()); if(neoGame.getGamePassword()!=null && !neoGame.getGamePassword().equals("")) neoGame.setGamePassword(PasswordUtils.encrypt(neoGame.getGamePassword())); UserGame neoUG = new UserGame(); neoUG.setGameID(KeyUtils.nextKey()); neoUG.setUserID(neoGame.getGameMasterID()); neoUG.setGameID(neoGame.getGameID()); this.ug.save(neoUG); return this.games.save(neoGame); } @PostMapping("/full") public ResponseEntity<GameFull> postGameFull(@RequestBody GameFull data) { System.out.println("In GameFull"); Game tGame = data.getGame(); if (tGame.getRulesID() == 0) tGame.setRulesID(1L); System.out.println("Game data retrieved"); List<Address> tAddress = data.getAddresses(); System.out.println("GameAddress data retrieved"); List<Behavior> tBehavior = data.getBehaviors(); System.out.println("GameBehave data retrieved"); List<Language> tLanguage = data.getLanguages(); System.out.println("GameLang data retrieved"); List<Link> tLink = data.getLinks(); System.out.println("GameLink data retrieved"); List<Schedule> tSchedule = data.getSchedules(); System.out.println("GameSched data retrieved"); List<SiteUser> users = data.getUsers(); System.out.println("GameUser data retrieved"); GameFull response = new GameFull(); response.setGame(makeGameIfNotExist(tGame)); System.out.println("Game data retrieved or created"); response.setAddresses(new ArrayList<>()); response.setBehaviors(new ArrayList<>()); response.setLanguages(new ArrayList<>()); response.setLinks(new ArrayList<>()); response.setSchedules(new ArrayList<>()); Long gameID = tGame.getGameID(); System.out.println("Game ID: " + gameID); for (Address item : tAddress) { response.getAddresses().add(createAddressWithLink(item, gameID)); } System.out.println("Addresses set"); for (Behavior item : tBehavior) { response.getBehaviors().add(createBehaviorWithLink(item, gameID.longValue())); } System.out.println("Behaviors set"); for (Language item : tLanguage) { response.getLanguages().add(createLanguageWithLink(item, gameID.longValue())); } System.out.println("Languages set"); for (Link item : tLink) { response.getLinks().add(createLinkWithLink(item, gameID.longValue())); } System.out.println("Links set"); for (Schedule item : tSchedule) { response.getSchedules().add(createScheduleWithLink(item, gameID.longValue())); } System.out.println("Schedules set"); response.setGMName(ur.findById(response.getGame().getGameMasterID()).get().getUsername() ); response.setRulesName(rr.findById(games.findById(gameID).get().getRulesID()).get().getRulesName() ); System.out.println("sending response"); return ResponseEntity.ok(response); } @PostMapping("/schedule/{id}") public Schedule makeGameSchedule( @PathVariable(value="id") Long gameID, @RequestBody Schedule gs) { gs.setScheduleID(KeyUtils.nextKey()); Schedule linkThis = sr.save(gs); GameSchedule tempGS = new GameSchedule(); tempGS.setID(KeyUtils.nextKey()); tempGS.setScheduleID(linkThis.getScheduleID()); tempGS.setGameID(gameID); this.gsr.save(tempGS); return linkThis; } @DeleteMapping("/{id}") public Map<String, Boolean> deleteGame(@PathVariable(value = "id") Long gameID) throws ResourceNotFoundException { Game oldGame = getGameByGameID(gameID); deleteGAByGameID(gameID); deleteGBByGameID(gameID); deleteGLGByGameID(gameID); deleteGLNByGameID(gameID); deleteGSByGameID(gameID); this.games.delete(oldGame); Map<String,Boolean> response = new HashMap<>(); response.put("deleted", Boolean.TRUE); return response; } public Boolean containsGA(Long gameID, Long addressID) { List<GameAddress> list = this.gar.findByAddressID(addressID); for (GameAddress ga : list) { if (ga.getGameID() == gameID.longValue()) return true; } return false; } public Boolean containsGB(Long gameID, Long behaviorID) { List<GameBehavior> list = this.gbr.findByBehaviorID(behaviorID); for (GameBehavior item : list) { if (item.getGameID().longValue() == gameID.longValue()) return true; } return false; } public Boolean containsGLG(Long gameID, Long langID) { List<GameLanguage> list = this.glgr.findByLanguageID(langID); for (GameLanguage item : list) { if (item.getGameID().longValue() == gameID.longValue()) return true; } return false; } public Boolean containsGLN(Long gameID, Long linkID) { List<GameLink> list = this.glnr.findByLinkID(linkID); for (GameLink item : list) { if (item.getGameID().longValue() == gameID.longValue()) return true; } return false; } public Boolean containsGS(Long gameID, Long scheduleID) { List<GameSchedule> list = this.gsr.findByScheduleID(scheduleID); for (GameSchedule item : list) { if (item.getGameID().longValue() == gameID.longValue()) return true; } return false; } private Address createAddressWithLink(Address add, Long gameID) { Address returnThis = add; try { if (!ar.findById(add.getAddressID()).isPresent()) { add.setAddressID(KeyUtils.nextKey()); returnThis = ar.save(add); } else { returnThis = add; } } catch (Exception e) { //e.printStackTrace(); } try { if (!containsGA(gameID, returnThis.getAddressID())) { gar.save(createGameAddress(gameID, add.getAddressID())); } } catch (Exception e) { //e.printStackTrace(); } return (returnThis != null)?returnThis:add; } private Behavior createBehaviorWithLink(Behavior behave, Long gameID) { Behavior returnThis = null; try { if (behave.getBehaviorID() == 0) { Behavior temp = br.findByBehavior(behave.getBehavior()); if (temp.getBehaviorID() != 0) { returnThis = temp; } else { returnThis = br.save(behave); } } if (!br.findById(behave.getBehaviorID()).isPresent()) returnThis = br.save(behave); } catch (Exception e) { //e.printStackTrace(); } try { if (!containsGB(gameID, behave.getBehaviorID())) gbr.save(createGameBehavior(gameID, behave.getBehaviorID())); } catch (Exception e) { //e.printStackTrace(); } return (returnThis != null)?returnThis:behave; } private GameAddress createGameAddress(Long gi, Long ai) { GameAddress returnThis = new GameAddress(KeyUtils.nextKey(), gi, ai); return returnThis; } private GameBehavior createGameBehavior(Long gi, Long bi) { GameBehavior returnThis = new GameBehavior(KeyUtils.nextKey(), gi, bi); return returnThis; } private GameLanguage createGameLanguage(Long gi, Long lgi) { GameLanguage returnThis = new GameLanguage(KeyUtils.nextKey(), gi, lgi); return returnThis; } private GameLink createGameLink(Long gi, Long lni) { GameLink returnThis = new GameLink(KeyUtils.nextKey(), gi, lni); return returnThis; } private GameSchedule createGameSchedule(Long gi, Long si) { GameSchedule returnThis = new GameSchedule(KeyUtils.nextKey(), gi, si); return returnThis; } private void deleteGAByGameID(Long gameID) { List<GameAddress> list = gar.findByGameID(gameID); for (GameAddress remove : list) { gar.delete(remove); } } private void deleteGBByGameID(Long gameID) { List<GameBehavior> list = gbr.findByGameID(gameID); for (GameBehavior remove : list) { gbr.delete(remove); } } private void deleteGLGByGameID(Long gameID) { List<GameLanguage> list = glgr.findByGameID(gameID); for (GameLanguage remove : list) { glgr.delete(remove); } } private void deleteGLNByGameID(Long gameID) { List<GameLink> list = glnr.findByGameID(gameID); for (GameLink remove : list) { glnr.delete(remove); } } private void deleteGSByGameID(Long gameID) { List<GameSchedule> list = gsr.findByGameID(gameID); for (GameSchedule remove : list) { gsr.delete(remove); } } private Game makeGameIfNotExist(Game tGame) { try { if (!this.games.findById(tGame.getGameID()).isPresent() ) { tGame.setGameID(KeyUtils.nextKey()); if (this.games.findByGameName(tGame.getGameName()) != null) { tGame.setGameName(tGame.getGameName() + "_" + KeyUtils.nextKey()); } return this.games.save(tGame); } } catch (Exception e) { //e.printStackTrace(); } return tGame; } private Language createLanguageWithLink(Language lang, Long gameID) { Language returnThis = null; try { if (lang.getLanguageid() == 0) { returnThis = lgr.getByLanguage(lang.getLanguage()); } else if (!lgr.findById(lang.getLanguageid()).isPresent()) { returnThis = lgr.save(lang); } } catch (Exception e) { //e.printStackTrace(); } try { if(lang != null) if (!containsGLG(gameID, lang.getLanguageid())) glgr.save(createGameLanguage(gameID, lang.getLanguageid())); } catch (Exception e) { //e.printStackTrace(); } return (returnThis != null)?returnThis:lang; } private Link createLinkWithLink(Link link, Long gameID) { Link returnThis = null; try { if (link.getLinkid() == 0) { returnThis = lnr.getByUrl(link.getUrl()); } else if (!lnr.findById(link.getLinkid()).isPresent()) { returnThis = lnr.save(link); } } catch (Exception e) { //e.printStackTrace(); } try { if (link != null) if (!containsGLN(gameID, link.getLinkid()) ) glnr.save(createGameLink(gameID, link.getLinkid()) ); } catch (Exception e) { //e.printStackTrace(); } return (returnThis != null)?returnThis:link; } private Schedule createScheduleWithLink(Schedule schedule, Long gameID) { Schedule returnThis = null; try { if (schedule.getScheduleID() == 0) { schedule.setScheduleID(KeyUtils.nextKey()); returnThis = sr.save(schedule); } } catch (Exception e) { //e.printStackTrace(); } try { if (schedule != null) if (!containsGS(gameID, schedule.getScheduleID())) gsr.save(createGameSchedule(gameID, schedule.getScheduleID())); } catch (Exception e) { //e.printStackTrace(); } return (returnThis != null)?returnThis:schedule; } }
package se.kth.ansjobmarcular; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Random; public class Bot { /** * The database interface */ protected ActionsStorage db = new FileActionsStorage(); protected static List<Integer> results = new LinkedList<Integer>(); /** * The dice currently at hand */ protected byte[] dice = new byte[5]; /** * Runs a bot that plays args[0] number of games, and prints the results to * stdout. * * @param args */ public static void main(String[] args) { int numGames = 20000; Bot bot = new Bot(); for (int i = 0; i < numGames; i++) { bot.playGame(); } double avg = 0; for (Integer res : results) { avg += res; } avg /= results.size(); System.out.printf("Played %d games, at average score %.2f\n", numGames, avg); } private void playGame() { ScoreCard sc = new ScoreCard(); int totalScore = 0; for (int round = 0; round < 15; round++) { /* * Start by rolling all dice */ randomize(dice, 0x0); for (int roll = 1; roll <= 2; roll++) { int holdMask = db.suggestRoll(new Hand(dice[0], dice[1], dice[2], dice[3], dice[4]), sc, roll); randomize(dice, holdMask); } /* * Now we need to to the marking */ Hand h = new Hand(dice[0], dice[1], dice[2], dice[3], dice[4]); if (round < 14) { int cat = db.suggestMarking(h, sc); Category c = Category.fromInt(cat); totalScore += sc.value(h, c); sc.fillScore(c); if (c.isUpper()) { int value = ScoreCard.count(h, cat+1) * (cat+1); sc.addScore(value); } } else { for (Category cat : Category.values) { if (!sc.isFilled(cat)) { totalScore += sc.value(h, cat); } } } } results.add(totalScore); System.out.printf("%d\n", totalScore); } static Random r = new Random(); private static void randomize(byte[] dice, int mask) { for (int i = 0; i < dice.length; i++) { if (((1 << (dice.length - (i + 1))) & mask) == 0) { dice[i] = (byte) (1 + r.nextInt(6)); } } Arrays.sort(dice); } }
package soot.jimple.spark.geom.heapinsE; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2011 Richard Xiao * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.Iterator; import soot.jimple.spark.geom.dataRep.CgEdge; import soot.jimple.spark.geom.dataRep.PlainConstraint; import soot.jimple.spark.geom.geomE.GeometricManager; import soot.jimple.spark.geom.geomPA.Constants; import soot.jimple.spark.geom.geomPA.DummyNode; import soot.jimple.spark.geom.geomPA.GeomPointsTo; import soot.jimple.spark.geom.geomPA.IEncodingBroker; import soot.jimple.spark.geom.geomPA.IVarAbstraction; import soot.jimple.spark.pag.AllocNode; import soot.jimple.spark.pag.FieldRefNode; import soot.jimple.spark.pag.Node; import soot.jimple.toolkits.callgraph.Edge; /** * Build the initial pointer assignment graph with the HeapIns encoding. * * @author xiao * */ public class HeapInsNodeGenerator extends IEncodingBroker { private static final int full_convertor[] = { GeometricManager.ONE_TO_ONE, GeometricManager.MANY_TO_MANY, GeometricManager.MANY_TO_MANY, GeometricManager.MANY_TO_MANY }; @Override public void initFlowGraph(GeomPointsTo ptAnalyzer) { int k; int n_legal_cons; int nf1, nf2; int code; IVarAbstraction my_lhs, my_rhs; // Visit all the simple constraints n_legal_cons = 0; for (PlainConstraint cons : ptAnalyzer.constraints) { if (!cons.isActive) { continue; } my_lhs = cons.getLHS().getRepresentative(); my_rhs = cons.getRHS().getRepresentative(); nf1 = ptAnalyzer.getMethodIDFromPtr(my_lhs); nf2 = ptAnalyzer.getMethodIDFromPtr(my_rhs); // Test how many globals are in this constraint code = ((nf1 == Constants.SUPER_MAIN ? 1 : 0) << 1) | (nf2 == Constants.SUPER_MAIN ? 1 : 0); switch (cons.type) { case Constants.NEW_CONS: // We directly add the objects to the points-to set my_rhs.add_points_to_3((AllocNode) my_lhs.getWrappedNode(), (code & 1) == 1 ? 0 : 1, // to decide if the receiver // is a global or not (code >> 1) == 1 ? 0 : 1, // if the object is a global or not (code & 1) == 1 ? ptAnalyzer.context_size[nf1] : ptAnalyzer.context_size[nf2]); // Enqueue to the worklist ptAnalyzer.getWorklist().push(my_rhs); break; case Constants.ASSIGN_CONS: // The core part of any context sensitive algorithms if (cons.interCallEdges != null) { // Inter-procedural assignment for (Iterator<Edge> it = cons.interCallEdges.iterator(); it.hasNext();) { Edge sEdge = it.next(); CgEdge q = ptAnalyzer.getInternalEdgeFromSootEdge(sEdge); if (q.is_obsoleted == true) { continue; } // Parameter passing if (nf2 == q.t) { /* * The receiver must be a local, while the sender is perhaps not (e.g. for handling reflection, see class * PAG) In that case, nf1 is 0. */ if (nf1 == Constants.SUPER_MAIN) { my_lhs.add_simple_constraint_3(my_rhs, 0, q.map_offset, ptAnalyzer.max_context_size_block[q.s]); } else { // nf1 == q.s // We should treat the self recursive calls specially if (q.s == q.t) { my_lhs.add_simple_constraint_3(my_rhs, 1, 1, ptAnalyzer.context_size[nf1]); } else { for (k = 0; k < ptAnalyzer.block_num[nf1]; ++k) { my_lhs.add_simple_constraint_3(my_rhs, k * ptAnalyzer.max_context_size_block[nf1] + 1, q.map_offset, ptAnalyzer.max_context_size_block[nf1]); } } } } else { // nf2 == q.s // Return value // Both are locals if (q.s == q.t) { my_lhs.add_simple_constraint_3(my_rhs, 1, 1, ptAnalyzer.context_size[nf2]); } else { for (k = 0; k < ptAnalyzer.block_num[nf2]; ++k) { my_lhs.add_simple_constraint_3(my_rhs, q.map_offset, k * ptAnalyzer.max_context_size_block[nf2] + 1, ptAnalyzer.max_context_size_block[nf2]); } } } } } else { // Intraprocedural // And, assignment involves global variable goes here. By // definition, global variables belong to SUPER_MAIN. // By the Jimple IR, not both sides are global variables my_lhs.add_simple_constraint_3(my_rhs, nf1 == Constants.SUPER_MAIN ? 0 : 1, nf2 == Constants.SUPER_MAIN ? 0 : 1, nf1 == Constants.SUPER_MAIN ? ptAnalyzer.context_size[nf2] : ptAnalyzer.context_size[nf1]); } break; case Constants.LOAD_CONS: // lhs is always a local // rhs = lhs.f cons.code = full_convertor[code]; cons.otherSide = my_rhs; my_lhs.put_complex_constraint(cons); break; case Constants.STORE_CONS: // rhs is always a local // rhs.f = lhs cons.code = full_convertor[code]; cons.otherSide = my_lhs; my_rhs.put_complex_constraint(cons); break; default: throw new RuntimeException("Invalid node type"); } ++n_legal_cons; } ptAnalyzer.ps.printf("Only %d (%.1f%%) constraints are needed for this run.\n", n_legal_cons, ((double) n_legal_cons / ptAnalyzer.n_init_constraints) * 100); } @Override public IVarAbstraction generateNode(Node vNode) { IVarAbstraction ret = null; if (vNode instanceof AllocNode || vNode instanceof FieldRefNode) { ret = new DummyNode(vNode); } else { ret = new HeapInsNode(vNode); } return ret; } @Override public String getSignature() { return Constants.heapinsE; } }
package com.mtx.androidcommonutil.ui.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; /** * Created by lishaoming on 17-7-31. */ public class CustomProgress extends View { private Paint mPaint; /** * 圆的宽度 */ private int mCircleWidth = 3; public CustomProgress(Context context) { this(context, null); } public CustomProgress(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomProgress(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mPaint = new Paint(); mPaint.setAntiAlias(true);//取消锯齿 mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(mCircleWidth); mPaint.setColor(Color.CYAN); } @Override protected void onDraw(Canvas canvas) { /** * 这是一个居中的圆 */ float x = (getWidth() - getHeight() / 2) / 2; float y = getHeight() / 4; RectF rectF = new RectF(x, y, getWidth() - x, getHeight() - y); canvas.drawArc(rectF, -90, 160, true, mPaint); } }
package com.buyout.sale.buyout.controllers; import com.buyout.sale.buyout.models.Product; import com.buyout.sale.buyout.repository.BuyoutUserRepository; import com.buyout.sale.buyout.repository.ProductRepository; import com.buyout.sale.buyout.repository.ProfileRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.servlet.view.RedirectView; import java.security.Principal; @Controller public class ProductController { @Autowired BuyoutUserRepository buyoutUserRepository; @Autowired ProductRepository productRepository; @Autowired ProfileRepository profileRepository; }
/*Generics Intro*/ public class Pairs<X, Y, Z> { X x; Y y; public Pairs(X x, Y y) { this.x = x; this.y = y; } public void getDescription() { System.out.println(x + " and " + y); } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.alexaforbusiness.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The data of a room profile. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/alexaforbusiness-2017-11-09/ProfileData" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ProfileData implements Serializable, Cloneable, StructuredPojo { /** * <p> * The ARN of a room profile. * </p> */ private String profileArn; /** * <p> * The name of a room profile. * </p> */ private String profileName; /** * <p> * Retrieves if the profile data is default or not. * </p> */ private Boolean isDefault; /** * <p> * The address of a room profile. * </p> */ private String address; /** * <p> * The time zone of a room profile. * </p> */ private String timezone; /** * <p> * The distance unit of a room profile. * </p> */ private String distanceUnit; /** * <p> * The temperature unit of a room profile. * </p> */ private String temperatureUnit; /** * <p> * The wake word of a room profile. * </p> */ private String wakeWord; /** * <p> * The locale of a room profile. (This is currently available only to a limited preview audience.) * </p> */ private String locale; /** * <p> * The ARN of a room profile. * </p> * * @param profileArn * The ARN of a room profile. */ public void setProfileArn(String profileArn) { this.profileArn = profileArn; } /** * <p> * The ARN of a room profile. * </p> * * @return The ARN of a room profile. */ public String getProfileArn() { return this.profileArn; } /** * <p> * The ARN of a room profile. * </p> * * @param profileArn * The ARN of a room profile. * @return Returns a reference to this object so that method calls can be chained together. */ public ProfileData withProfileArn(String profileArn) { setProfileArn(profileArn); return this; } /** * <p> * The name of a room profile. * </p> * * @param profileName * The name of a room profile. */ public void setProfileName(String profileName) { this.profileName = profileName; } /** * <p> * The name of a room profile. * </p> * * @return The name of a room profile. */ public String getProfileName() { return this.profileName; } /** * <p> * The name of a room profile. * </p> * * @param profileName * The name of a room profile. * @return Returns a reference to this object so that method calls can be chained together. */ public ProfileData withProfileName(String profileName) { setProfileName(profileName); return this; } /** * <p> * Retrieves if the profile data is default or not. * </p> * * @param isDefault * Retrieves if the profile data is default or not. */ public void setIsDefault(Boolean isDefault) { this.isDefault = isDefault; } /** * <p> * Retrieves if the profile data is default or not. * </p> * * @return Retrieves if the profile data is default or not. */ public Boolean getIsDefault() { return this.isDefault; } /** * <p> * Retrieves if the profile data is default or not. * </p> * * @param isDefault * Retrieves if the profile data is default or not. * @return Returns a reference to this object so that method calls can be chained together. */ public ProfileData withIsDefault(Boolean isDefault) { setIsDefault(isDefault); return this; } /** * <p> * Retrieves if the profile data is default or not. * </p> * * @return Retrieves if the profile data is default or not. */ public Boolean isDefault() { return this.isDefault; } /** * <p> * The address of a room profile. * </p> * * @param address * The address of a room profile. */ public void setAddress(String address) { this.address = address; } /** * <p> * The address of a room profile. * </p> * * @return The address of a room profile. */ public String getAddress() { return this.address; } /** * <p> * The address of a room profile. * </p> * * @param address * The address of a room profile. * @return Returns a reference to this object so that method calls can be chained together. */ public ProfileData withAddress(String address) { setAddress(address); return this; } /** * <p> * The time zone of a room profile. * </p> * * @param timezone * The time zone of a room profile. */ public void setTimezone(String timezone) { this.timezone = timezone; } /** * <p> * The time zone of a room profile. * </p> * * @return The time zone of a room profile. */ public String getTimezone() { return this.timezone; } /** * <p> * The time zone of a room profile. * </p> * * @param timezone * The time zone of a room profile. * @return Returns a reference to this object so that method calls can be chained together. */ public ProfileData withTimezone(String timezone) { setTimezone(timezone); return this; } /** * <p> * The distance unit of a room profile. * </p> * * @param distanceUnit * The distance unit of a room profile. * @see DistanceUnit */ public void setDistanceUnit(String distanceUnit) { this.distanceUnit = distanceUnit; } /** * <p> * The distance unit of a room profile. * </p> * * @return The distance unit of a room profile. * @see DistanceUnit */ public String getDistanceUnit() { return this.distanceUnit; } /** * <p> * The distance unit of a room profile. * </p> * * @param distanceUnit * The distance unit of a room profile. * @return Returns a reference to this object so that method calls can be chained together. * @see DistanceUnit */ public ProfileData withDistanceUnit(String distanceUnit) { setDistanceUnit(distanceUnit); return this; } /** * <p> * The distance unit of a room profile. * </p> * * @param distanceUnit * The distance unit of a room profile. * @return Returns a reference to this object so that method calls can be chained together. * @see DistanceUnit */ public ProfileData withDistanceUnit(DistanceUnit distanceUnit) { this.distanceUnit = distanceUnit.toString(); return this; } /** * <p> * The temperature unit of a room profile. * </p> * * @param temperatureUnit * The temperature unit of a room profile. * @see TemperatureUnit */ public void setTemperatureUnit(String temperatureUnit) { this.temperatureUnit = temperatureUnit; } /** * <p> * The temperature unit of a room profile. * </p> * * @return The temperature unit of a room profile. * @see TemperatureUnit */ public String getTemperatureUnit() { return this.temperatureUnit; } /** * <p> * The temperature unit of a room profile. * </p> * * @param temperatureUnit * The temperature unit of a room profile. * @return Returns a reference to this object so that method calls can be chained together. * @see TemperatureUnit */ public ProfileData withTemperatureUnit(String temperatureUnit) { setTemperatureUnit(temperatureUnit); return this; } /** * <p> * The temperature unit of a room profile. * </p> * * @param temperatureUnit * The temperature unit of a room profile. * @return Returns a reference to this object so that method calls can be chained together. * @see TemperatureUnit */ public ProfileData withTemperatureUnit(TemperatureUnit temperatureUnit) { this.temperatureUnit = temperatureUnit.toString(); return this; } /** * <p> * The wake word of a room profile. * </p> * * @param wakeWord * The wake word of a room profile. * @see WakeWord */ public void setWakeWord(String wakeWord) { this.wakeWord = wakeWord; } /** * <p> * The wake word of a room profile. * </p> * * @return The wake word of a room profile. * @see WakeWord */ public String getWakeWord() { return this.wakeWord; } /** * <p> * The wake word of a room profile. * </p> * * @param wakeWord * The wake word of a room profile. * @return Returns a reference to this object so that method calls can be chained together. * @see WakeWord */ public ProfileData withWakeWord(String wakeWord) { setWakeWord(wakeWord); return this; } /** * <p> * The wake word of a room profile. * </p> * * @param wakeWord * The wake word of a room profile. * @return Returns a reference to this object so that method calls can be chained together. * @see WakeWord */ public ProfileData withWakeWord(WakeWord wakeWord) { this.wakeWord = wakeWord.toString(); return this; } /** * <p> * The locale of a room profile. (This is currently available only to a limited preview audience.) * </p> * * @param locale * The locale of a room profile. (This is currently available only to a limited preview audience.) */ public void setLocale(String locale) { this.locale = locale; } /** * <p> * The locale of a room profile. (This is currently available only to a limited preview audience.) * </p> * * @return The locale of a room profile. (This is currently available only to a limited preview audience.) */ public String getLocale() { return this.locale; } /** * <p> * The locale of a room profile. (This is currently available only to a limited preview audience.) * </p> * * @param locale * The locale of a room profile. (This is currently available only to a limited preview audience.) * @return Returns a reference to this object so that method calls can be chained together. */ public ProfileData withLocale(String locale) { setLocale(locale); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getProfileArn() != null) sb.append("ProfileArn: ").append(getProfileArn()).append(","); if (getProfileName() != null) sb.append("ProfileName: ").append(getProfileName()).append(","); if (getIsDefault() != null) sb.append("IsDefault: ").append(getIsDefault()).append(","); if (getAddress() != null) sb.append("Address: ").append(getAddress()).append(","); if (getTimezone() != null) sb.append("Timezone: ").append(getTimezone()).append(","); if (getDistanceUnit() != null) sb.append("DistanceUnit: ").append(getDistanceUnit()).append(","); if (getTemperatureUnit() != null) sb.append("TemperatureUnit: ").append(getTemperatureUnit()).append(","); if (getWakeWord() != null) sb.append("WakeWord: ").append(getWakeWord()).append(","); if (getLocale() != null) sb.append("Locale: ").append(getLocale()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ProfileData == false) return false; ProfileData other = (ProfileData) obj; if (other.getProfileArn() == null ^ this.getProfileArn() == null) return false; if (other.getProfileArn() != null && other.getProfileArn().equals(this.getProfileArn()) == false) return false; if (other.getProfileName() == null ^ this.getProfileName() == null) return false; if (other.getProfileName() != null && other.getProfileName().equals(this.getProfileName()) == false) return false; if (other.getIsDefault() == null ^ this.getIsDefault() == null) return false; if (other.getIsDefault() != null && other.getIsDefault().equals(this.getIsDefault()) == false) return false; if (other.getAddress() == null ^ this.getAddress() == null) return false; if (other.getAddress() != null && other.getAddress().equals(this.getAddress()) == false) return false; if (other.getTimezone() == null ^ this.getTimezone() == null) return false; if (other.getTimezone() != null && other.getTimezone().equals(this.getTimezone()) == false) return false; if (other.getDistanceUnit() == null ^ this.getDistanceUnit() == null) return false; if (other.getDistanceUnit() != null && other.getDistanceUnit().equals(this.getDistanceUnit()) == false) return false; if (other.getTemperatureUnit() == null ^ this.getTemperatureUnit() == null) return false; if (other.getTemperatureUnit() != null && other.getTemperatureUnit().equals(this.getTemperatureUnit()) == false) return false; if (other.getWakeWord() == null ^ this.getWakeWord() == null) return false; if (other.getWakeWord() != null && other.getWakeWord().equals(this.getWakeWord()) == false) return false; if (other.getLocale() == null ^ this.getLocale() == null) return false; if (other.getLocale() != null && other.getLocale().equals(this.getLocale()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getProfileArn() == null) ? 0 : getProfileArn().hashCode()); hashCode = prime * hashCode + ((getProfileName() == null) ? 0 : getProfileName().hashCode()); hashCode = prime * hashCode + ((getIsDefault() == null) ? 0 : getIsDefault().hashCode()); hashCode = prime * hashCode + ((getAddress() == null) ? 0 : getAddress().hashCode()); hashCode = prime * hashCode + ((getTimezone() == null) ? 0 : getTimezone().hashCode()); hashCode = prime * hashCode + ((getDistanceUnit() == null) ? 0 : getDistanceUnit().hashCode()); hashCode = prime * hashCode + ((getTemperatureUnit() == null) ? 0 : getTemperatureUnit().hashCode()); hashCode = prime * hashCode + ((getWakeWord() == null) ? 0 : getWakeWord().hashCode()); hashCode = prime * hashCode + ((getLocale() == null) ? 0 : getLocale().hashCode()); return hashCode; } @Override public ProfileData clone() { try { return (ProfileData) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.alexaforbusiness.model.transform.ProfileDataMarshaller.getInstance().marshall(this, protocolMarshaller); } }
import java.util.ArrayList; import java.util.List; import java.util.Random; import org.opencv.core.*; import org.opencv.calib3d.Calib3d; import org.opencv.highgui.HighGui; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; class PerspectiveCorrectionRun { void perspectiveCorrection (String[] args) { String img1Path = args[0], img2Path = args[1]; Mat img1 = Imgcodecs.imread(img1Path); Mat img2 = Imgcodecs.imread(img2Path); //! [find-corners] MatOfPoint2f corners1 = new MatOfPoint2f(), corners2 = new MatOfPoint2f(); boolean found1 = Calib3d.findChessboardCorners(img1, new Size(9, 6), corners1 ); boolean found2 = Calib3d.findChessboardCorners(img2, new Size(9, 6), corners2 ); //! [find-corners] if (!found1 || !found2) { System.out.println("Error, cannot find the chessboard corners in both images."); System.exit(-1); } //! [estimate-homography] Mat H = new Mat(); H = Calib3d.findHomography(corners1, corners2); System.out.println(H.dump()); //! [estimate-homography] //! [warp-chessboard] Mat img1_warp = new Mat(); Imgproc.warpPerspective(img1, img1_warp, H, img1.size()); //! [warp-chessboard] Mat img_draw_warp = new Mat(); List<Mat> list1 = new ArrayList<>(), list2 = new ArrayList<>() ; list1.add(img2); list1.add(img1_warp); Core.hconcat(list1, img_draw_warp); HighGui.imshow("Desired chessboard view / Warped source chessboard view", img_draw_warp); //! [compute-transformed-corners] Mat img_draw_matches = new Mat(); list2.add(img1); list2.add(img2); Core.hconcat(list2, img_draw_matches); Point []corners1Arr = corners1.toArray(); for (int i = 0 ; i < corners1Arr.length; i++) { Mat pt1 = new Mat(3, 1, CvType.CV_64FC1), pt2 = new Mat(); pt1.put(0, 0, corners1Arr[i].x, corners1Arr[i].y, 1 ); Core.gemm(H, pt1, 1, new Mat(), 0, pt2); double[] data = pt2.get(2, 0); Core.divide(pt2, new Scalar(data[0]), pt2); double[] data1 =pt2.get(0, 0); double[] data2 = pt2.get(1, 0); Point end = new Point((int)(img1.cols()+ data1[0]), (int)data2[0]); Imgproc.line(img_draw_matches, corners1Arr[i], end, RandomColor(), 2); } HighGui.imshow("Draw matches", img_draw_matches); HighGui.waitKey(0); //! [compute-transformed-corners] System.exit(0); } Scalar RandomColor () { Random rng = new Random(); int r = rng.nextInt(256); int g = rng.nextInt(256); int b = rng.nextInt(256); return new Scalar(r, g, b); } } public class PerspectiveCorrection { public static void main (String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); new PerspectiveCorrectionRun().perspectiveCorrection(args); } }
/* * Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved. */ package com.maxifier.mxcache.impl.caches.storage.elementlocked; import com.maxifier.mxcache.impl.MutableStatistics; import com.maxifier.mxcache.impl.caches.storage.StorageHolder; import com.maxifier.mxcache.impl.caches.abs.elementlocked.*; import com.maxifier.mxcache.caches.*; import com.maxifier.mxcache.storage.elementlocked.*; import com.maxifier.mxcache.interfaces.Statistics; import com.maxifier.mxcache.interfaces.StatisticsHolder; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.concurrent.locks.Lock; /** * THIS IS GENERATED CLASS! DON'T EDIT IT MANUALLY! * * GENERATED FROM StorageP2PCache.template * * @author Andrey Yakoushin (andrey.yakoushin@maxifier.com) * @author Alexander Kochurov (alexander.kochurov@maxifier.com) */ public class StorageByteByteCacheImpl extends AbstractByteByteCache implements StorageHolder<ByteObjectElementLockedStorage> { private ByteObjectElementLockedStorage storage; public StorageByteByteCacheImpl(Object owner, ByteByteCalculatable calculatable, @Nonnull MutableStatistics statistics) { super(owner, calculatable, statistics); } @Override public void setStorage(@Nonnull ByteObjectElementLockedStorage storage) { if (this.storage != null) { throw new UnsupportedOperationException("Storage already set"); } this.storage = storage; } @Override public Object load(byte key) { return storage.load(key); } @Override public void save(byte key, Object value) { storage.save(key, value); } @Override public void lock(byte key) { storage.lock(key); } @Override public void unlock(byte key) { storage.unlock(key); } @Override public Lock getLock() { return storage.getLock(); } @Override public void clear() { storage.clear(); } @Override public int size() { return storage.size(); } @Nullable @Override public Statistics getStatistics() { if (storage instanceof StatisticsHolder) { return ((StatisticsHolder)storage).getStatistics(); } return super.getStatistics(); } }
/* * Copyright (c) 2017 Jan Berkel <jan.berkel@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.catherine.classloader; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.util.Log; import com.firebase.jobdispatcher.Driver; import com.firebase.jobdispatcher.Job; import com.firebase.jobdispatcher.JobParameters; import com.firebase.jobdispatcher.JobTrigger; import com.firebase.jobdispatcher.JobValidator; import com.firebase.jobdispatcher.RetryStrategy; import java.util.List; import static android.app.AlarmManager.RTC_WAKEUP; import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; import static com.firebase.jobdispatcher.FirebaseJobDispatcher.CANCEL_RESULT_SUCCESS; import static com.firebase.jobdispatcher.FirebaseJobDispatcher.SCHEDULE_RESULT_SUCCESS; import static com.firebase.jobdispatcher.FirebaseJobDispatcher.SCHEDULE_RESULT_UNSUPPORTED_TRIGGER; /** * Simple driver to emulate old AlarmManager backup scheduling behaviour. */ class AlarmManagerDriver implements Driver, JobValidator { private final AlarmManager alarmManager; private final Context context; AlarmManagerDriver(Context context) { this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); this.context = context.getApplicationContext(); } @Override public int schedule(@NonNull Job job) { final JobTrigger trigger = job.getTrigger(); final long atTime = scheduleTime(trigger); if (atTime > 0) { alarmManager.set(RTC_WAKEUP, atTime, createPendingIntent(context)); return SCHEDULE_RESULT_SUCCESS; } else { return SCHEDULE_RESULT_UNSUPPORTED_TRIGGER; } } @Override public int cancel(@NonNull String tag) { // Matching intents based on Intent#filterEquals(): // That is, if their action, data, type, class, and categories are the same. alarmManager.cancel(createPendingIntent(context)); return CANCEL_RESULT_SUCCESS; } @Override public int cancelAll() { cancel("TagPaylo"); return CANCEL_RESULT_SUCCESS; } @Override public @NonNull JobValidator getValidator() { return this; } @Override public boolean isAvailable() { return true; } @Override public List<String> validate(JobParameters jobParameters) { return null; } /** * @return a List of error messages, or null if the Trigger is valid. */ @Override public List<String> validate(JobTrigger jobTrigger) { return null; } /** * @return a List of error messages, or null if the Trigger is valid. */ @Override public List<String> validate(RetryStrategy retryStrategy) { return null; } private static PendingIntent createPendingIntent(Context ctx) { final Intent intent = (new Intent(ctx, Payload.class)) .setAction("TagPaylo"); return PendingIntent.getService(ctx, 0, intent, FLAG_UPDATE_CURRENT); } private static long scheduleTime(JobTrigger trigger) { if (trigger instanceof JobTrigger.ImmediateTrigger) { return System.currentTimeMillis(); } else if (trigger instanceof JobTrigger.ExecutionWindowTrigger) { JobTrigger.ExecutionWindowTrigger executionWindowTrigger = (JobTrigger.ExecutionWindowTrigger) trigger; return System.currentTimeMillis() + (executionWindowTrigger.getWindowStart() * 1000L); } else { return -1; } } }
package DAO; import java.util.List; import java.util.Optional; import models.User; public interface UserService { public User save(User product); public void remove(User product); public Optional<User> find(Long id); public List<User> findAll(); }
/* * $Id$ * * $State$ * * $Log$ * Revision 1.1 2008/04/04 18:21:10 cvs * Added legacy code to repository * * Revision 1.4 2004/08/30 14:50:33 mjmaloney * Javadocs * * Revision 1.3 2002/03/14 21:07:55 mike * Bug fixes. * * Revision 1.2 2001/09/18 00:46:50 mike * Working implementation of DateDelegate * * Revision 1.1 2001/09/14 21:20:17 mike * created. * */ package ilex.var; import java.util.Date; import java.util.TimeZone; import java.util.Calendar; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import ilex.var.DelegateVariable; import ilex.var.NoConversionException; import ilex.var.IVariable; import ilex.var.BadArgumentException; /** * Class DateDelegate holds a Date/Time stamp. */ public class DateDelegate extends DelegateVariable { Date value; private static DateFormat dateFormat; static { dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); TimeZone jtz=java.util.TimeZone.getTimeZone("UTC"); dateFormat.setCalendar(Calendar.getInstance(jtz)); } /** * Sets the static DateFormat used when a String value is requested. * @param df */ public static void setDateFormat( DateFormat df ) { dateFormat = df; } /** * Parses a date using the set DateFormat. * @param s String * @return Date * @throws NoConversionException if bad date format */ public static Date parseDate( String s ) throws NoConversionException { try { return dateFormat.parse(s); } catch(ParseException e) { throw new NoConversionException("Invalid date format '" + s + "': " + e.toString()); } } /** Default constructor */ public DateDelegate( ) { super(); value = new Date(); } /** * Constructor. * @param v the value. */ public DateDelegate( Date v ) { this(); value = v; } /** * @return clone of this object. */ public Object clone( ) { return new DateDelegate(value); } /** * @return constant from VariableType class indicating this type of value. */ public char getNativeType( ) { return VariableType.DATE; } //========== Type Specific Get Methods Overridden by Subclasses ======= /** * @throws NoConversionException always */ public byte getByteValue( ) throws NoConversionException { throw new NoConversionException("Cannot convert Date to byte."); } /** * @return msec value of Date as a double. */ public double getDoubleValue( ) { return (double)value.getTime(); } /** * @return msec value of Date as a float. */ public float getFloatValue( ) { return (float)value.getTime(); } /** * @return msec value of Date as an int (probably out of range!). */ public int getIntValue( ) { return (int)value.getTime(); } /** * @return msec value of Date as an long. */ public long getLongValue( ) { return value.getTime(); } /** * @throws NoConversionException always */ public char getCharValue( ) throws NoConversionException { throw new NoConversionException("Cannot convert Date to char."); } /** * @return Date formatted into a String. */ public String getStringValue( ) { return dateFormat.format(value); } /** * @return value as a date * @throws NoConversionException */ public Date getDateValue( ) { return value; } //======== Arithmetic Operation on Variable ========================= /** * Divide this variable by another * @param v the other variable * @return a delegate holding the result * @throws BadArgumentException always */ public DelegateVariable divideBy( IVariable v ) throws NoConversionException, BadArgumentException { throw new BadArgumentException("Cannot divide Date values."); } /** * Subtract a variable from this variable. * @param v the other variable * @return Delegate holding result * @throws NoConversionException * @throws BadArgumentException */ public DelegateVariable minus( IVariable v ) throws NoConversionException, BadArgumentException { int vt = v.getNativeType(); if (vt == VariableType.BYTE || vt == VariableType.INT || vt == VariableType.LONG || vt == VariableType.DOUBLE || vt == VariableType.FLOAT) { // Subtract number (milliseconds) from date, result is a date. long delta = v.getLongValue(); return new DateDelegate(new Date(value.getTime() - delta)); } else if (vt == VariableType.DATE) { // Subtracting two dates yields a long # of seconds. long rv = value.getTime() - v.getLongValue(); return new LongDelegate(rv); } throw new BadArgumentException( "Cannot subtract non-numeric variable"); } /** * Multiply a variable by this variable. * @param v the other variable * @return Delegate holding result * @throws NoConversionException * @throws BadArgumentException */ public DelegateVariable multiplyBy( IVariable v ) throws NoConversionException, BadArgumentException { throw new BadArgumentException( "Cannot multiply Date variable"); } /** * Add a variable to this variable. * @param v the other variable * @return Delegate holding result * @throws NoConversionException * @throws BadArgumentException */ public DelegateVariable plus( IVariable v ) throws NoConversionException, BadArgumentException { int vt = v.getNativeType(); if (vt == VariableType.BYTE || vt == VariableType.INT || vt == VariableType.LONG || vt == VariableType.DOUBLE || vt == VariableType.FLOAT) { // Integer addition long rv = value.getTime() + v.getLongValue(); return new DateDelegate(new Date(rv)); } else throw new NoConversionException("cannot add dates."); } }
/* * Copyright 2012 The Netty Project * * The Netty 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 io.netty.bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelPromise; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.ReflectiveChannelFactory; import io.netty.util.AttributeKey; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.internal.ObjectUtil; import io.netty.util.internal.SocketUtils; import io.netty.util.internal.StringUtil; import io.netty.util.internal.logging.InternalLogger; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * {@link AbstractBootstrap} is a helper class that makes it easy to bootstrap a {@link Channel}. It support * method-chaining to provide an easy way to configure the {@link AbstractBootstrap}. * <p> * <p>When not used in a {@link ServerBootstrap} context, the {@link #bind()} methods are useful for connectionless * transports such as datagram (UDP).</p> */ public abstract class AbstractBootstrap<B extends AbstractBootstrap<B, C>, C extends Channel> implements Cloneable { volatile EventLoopGroup group; /** * Channel 工厂,用于创建 Channel 对象。 * NioServerSocketChannel.class,正常来说,只用到这个 * OioServerSocketChannel 废弃掉了, */ @SuppressWarnings("deprecation") private volatile ChannelFactory<? extends C> channelFactory; /** * 本地地址 */ private volatile SocketAddress localAddress; // 可选项集合, ChannelOption private final Map<ChannelOption<?>, Object> options = new LinkedHashMap<ChannelOption<?>, Object>(); // 自定义属性 private final Map<AttributeKey<?>, Object> attrs = new LinkedHashMap<AttributeKey<?>, Object>(); private volatile ChannelHandler handler; AbstractBootstrap() { // Disallow extending from a different package. } AbstractBootstrap(AbstractBootstrap<B, C> bootstrap) { group = bootstrap.group; channelFactory = bootstrap.channelFactory; handler = bootstrap.handler; localAddress = bootstrap.localAddress; synchronized (bootstrap.options) { options.putAll(bootstrap.options); } synchronized (bootstrap.attrs) { attrs.putAll(bootstrap.attrs); } } /** * The {@link EventLoopGroup} which is used to handle all the events for the to-be-created {@link Channel} */ public B group(EventLoopGroup group) { ObjectUtil.checkNotNull(group, "group"); if (this.group != null) { throw new IllegalStateException("group set already"); } this.group = group; return self(); } @SuppressWarnings("unchecked") private B self() { return (B) this; } /** * The {@link Class} which is used to create {@link Channel} instances from. You either use this or {@link * #channelFactory(io.netty.channel.ChannelFactory)} if your {@link Channel} implementation has no no-args * constructor. */ public B channel(Class<? extends C> channelClass) { return channelFactory(new ReflectiveChannelFactory<C>( ObjectUtil.checkNotNull(channelClass, "channelClass") )); } /** * @deprecated Use {@link #channelFactory(io.netty.channel.ChannelFactory)} instead. */ @Deprecated public B channelFactory(ChannelFactory<? extends C> channelFactory) { ObjectUtil.checkNotNull(channelFactory, "channelFactory"); if (this.channelFactory != null) { throw new IllegalStateException("channelFactory set already"); } this.channelFactory = channelFactory; return self(); } /** * {@link io.netty.channel.ChannelFactory} which is used to create {@link Channel} instances from when calling * {@link #bind()}. This method is usually only used if {@link #channel(Class)} is not working for you because of * some more complex needs. If your {@link Channel} implementation has a no-args constructor, its highly recommend * to just use {@link #channel(Class)} to simplify your code. */ @SuppressWarnings({"unchecked", "deprecation"}) public B channelFactory(io.netty.channel.ChannelFactory<? extends C> channelFactory) { return channelFactory((ChannelFactory<C>) channelFactory); } /** * The {@link SocketAddress} which is used to bind the local "end" to. */ public B localAddress(SocketAddress localAddress) { this.localAddress = localAddress; return self(); } /** * @see #localAddress(SocketAddress) */ public B localAddress(int inetPort) { return localAddress(new InetSocketAddress(inetPort)); } /** * @see #localAddress(SocketAddress) */ public B localAddress(String inetHost, int inetPort) { return localAddress(SocketUtils.socketAddress(inetHost, inetPort)); } /** * @see #localAddress(SocketAddress) */ public B localAddress(InetAddress inetHost, int inetPort) { return localAddress(new InetSocketAddress(inetHost, inetPort)); } /** * Allow to specify a {@link ChannelOption} which is used for the {@link Channel} instances once they got created. * Use a value of {@code null} to remove a previous set {@link ChannelOption}. */ public <T> B option(ChannelOption<T> option, T value) { ObjectUtil.checkNotNull(option, "option"); if (value == null) { synchronized (options) { options.remove(option); } } else { synchronized (options) { options.put(option, value); } } return self(); } /** * Allow to specify an initial attribute of the newly created {@link Channel}. If the {@code value} is {@code * null}, the attribute of the specified {@code key} is removed. */ public <T> B attr(AttributeKey<T> key, T value) { ObjectUtil.checkNotNull(key, "key"); if (value == null) { synchronized (attrs) { attrs.remove(key); } } else { synchronized (attrs) { attrs.put(key, value); } } return self(); } /** * Validate all the parameters. Sub-classes may override this, but should call the super method in that case. */ public B validate() { if (group == null) { throw new IllegalStateException("group not set"); } if (channelFactory == null) { throw new IllegalStateException("channel or channelFactory not set"); } return self(); } /** * Returns a deep clone of this bootstrap which has the identical configuration. This method is useful when making * multiple {@link Channel}s with similar settings. Please note that this method does not clone the {@link * EventLoopGroup} deeply but shallowly, making the group a shared resource. */ @Override @SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException") public abstract B clone(); /** * Create a new {@link Channel} and register it with an {@link EventLoop}. */ public ChannelFuture register() { validate(); return initAndRegister(); } /** * Create a new {@link Channel} and bind it. */ public ChannelFuture bind() { validate(); SocketAddress localAddress = this.localAddress; if (localAddress == null) { throw new IllegalStateException("localAddress not set"); } return doBind(localAddress); } /** * Create a new {@link Channel} and bind it. */ public ChannelFuture bind(int inetPort) { return bind(new InetSocketAddress(inetPort)); } /** * Create a new {@link Channel} and bind it. */ public ChannelFuture bind(String inetHost, int inetPort) { return bind(SocketUtils.socketAddress(inetHost, inetPort)); } /** * Create a new {@link Channel} and bind it. */ public ChannelFuture bind(InetAddress inetHost, int inetPort) { return bind(new InetSocketAddress(inetHost, inetPort)); } /** * Create a new {@link Channel} and bind it. */ public ChannelFuture bind(SocketAddress localAddress) { validate(); return doBind(ObjectUtil.checkNotNull(localAddress, "localAddress")); } // 端口绑定操作 private ChannelFuture doBind(final SocketAddress localAddress) { final ChannelFuture regFuture = initAndRegister(); final Channel channel = regFuture.channel(); if (regFuture.cause() != null) { return regFuture; } // 如果注册完毕 if (regFuture.isDone()) { // At this point we know that the registration was complete and successful. ChannelPromise promise = channel.newPromise(); doBind0(regFuture, channel, localAddress, promise); return promise; } else { // Registration future is almost always fulfilled already, but just in case it's not. final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel); regFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Throwable cause = future.cause(); if (cause != null) { // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an // IllegalStateException once we try to access the EventLoop of the Channel. promise.setFailure(cause); } else { // Registration was successful, so set the correct executor to use. // See https://github.com/netty/netty/issues/2586 promise.registered(); doBind0(regFuture, channel, localAddress, promise); } } }); return promise; } } /** * 初始化并注册channel * * @return */ final ChannelFuture initAndRegister() { Channel channel = null; try { // 根据channel方法传入的socketchannel创建一个新的channel // EchoServer中channel(NioServerSocketChannel.class)指定channel类型 channel = channelFactory.newChannel(); // 初始化channel init(channel); } catch (Throwable t) { if (channel != null) { // channel can be null if newChannel crashed (eg SocketException("too many open files")) channel.unsafe().closeForcibly(); // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t); } // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor return new DefaultChannelPromise(new FailedChannel(), GlobalEventExecutor.INSTANCE).setFailure(t); } // 注册channel 到 eventloop ChannelFuture regFuture = config().group().register(channel); if (regFuture.cause() != null) { if (channel.isRegistered()) { channel.close(); } else { channel.unsafe().closeForcibly(); } } // If we are here and the promise is not failed, it's one of the following cases: // 1) If we attempted registration from the event loop, the registration has been completed at this point. // i.e. It's safe to attempt bind() or connect() now because the channel has been registered. // 2) If we attempted registration from the other thread, the registration request has been successfully // added to the event loop's task queue for later execution. // i.e. It's safe to attempt bind() or connect() now: // because bind() or connect() will be executed *after* the scheduled registration task is executed // because register(), bind(), and connect() are all bound to the same thread. return regFuture; } abstract void init(Channel channel) throws Exception; private static void doBind0( final ChannelFuture regFuture, final Channel channel, final SocketAddress localAddress, final ChannelPromise promise) { // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up // the pipeline in its channelRegistered() implementation. channel.eventLoop().execute(new Runnable() { @Override public void run() { if (regFuture.isSuccess()) { channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } else { promise.setFailure(regFuture.cause()); } } }); } /** * the {@link ChannelHandler} to use for serving the requests. */ public B handler(ChannelHandler handler) { this.handler = ObjectUtil.checkNotNull(handler, "handler"); return self(); } /** * Returns the configured {@link EventLoopGroup} or {@code null} if non is configured yet. * * @deprecated Use {@link #config()} instead. */ @Deprecated public final EventLoopGroup group() { return group; } /** * Returns the {@link AbstractBootstrapConfig} object that can be used to obtain the current config of the * bootstrap. */ public abstract AbstractBootstrapConfig<B, C> config(); static <K, V> Map<K, V> copiedMap(Map<K, V> map) { final Map<K, V> copied; synchronized (map) { if (map.isEmpty()) { return Collections.emptyMap(); } copied = new LinkedHashMap<K, V>(map); } return Collections.unmodifiableMap(copied); } final Map<ChannelOption<?>, Object> options0() { return options; } final Map<AttributeKey<?>, Object> attrs0() { return attrs; } final SocketAddress localAddress() { return localAddress; } @SuppressWarnings("deprecation") final ChannelFactory<? extends C> channelFactory() { return channelFactory; } final ChannelHandler handler() { return handler; } final Map<ChannelOption<?>, Object> options() { return copiedMap(options); } final Map<AttributeKey<?>, Object> attrs() { return copiedMap(attrs); } /** * 该方法针对channel Options * * @param channel * @param options * @param logger */ static void setChannelOptions( Channel channel, Map<ChannelOption<?>, Object> options, InternalLogger logger) { for (Map.Entry<ChannelOption<?>, Object> e : options.entrySet()) { setChannelOption(channel, e.getKey(), e.getValue(), logger); } } /** * 这个方法主要针对childChannel Options * * @param channel * @param options * @param logger */ static void setChannelOptions( Channel channel, Map.Entry<ChannelOption<?>, Object>[] options, InternalLogger logger) { for (Map.Entry<ChannelOption<?>, Object> e : options) { setChannelOption(channel, e.getKey(), e.getValue(), logger); } } /** * 设置已经创建的channel的可选项, options设置可选项 options方法设置的可选性最终会被依然会通过该方法放到已经创建的channel的config中。 */ @SuppressWarnings("unchecked") private static void setChannelOption( Channel channel, ChannelOption<?> option, Object value, InternalLogger logger) { try { if (!channel.config().setOption((ChannelOption<Object>) option, value)) { logger.warn("Unknown channel option '{}' for channel '{}'", option, channel); } } catch (Throwable t) { logger.warn( "Failed to set channel option '{}' with value '{}' for channel '{}'", option, value, channel, t); } } @Override public String toString() { StringBuilder buf = new StringBuilder() .append(StringUtil.simpleClassName(this)) .append('(').append(config()).append(')'); return buf.toString(); } static final class PendingRegistrationPromise extends DefaultChannelPromise { // Is set to the correct EventExecutor once the registration was successful. Otherwise it will // stay null and so the GlobalEventExecutor.INSTANCE will be used for notifications. private volatile boolean registered; PendingRegistrationPromise(Channel channel) { super(channel); } void registered() { registered = true; } @Override protected EventExecutor executor() { if (registered) { // If the registration was a success executor is set. // // See https://github.com/netty/netty/issues/2586 return super.executor(); } // The registration failed so we can only use the GlobalEventExecutor as last resort to notify. return GlobalEventExecutor.INSTANCE; } } }
/* * Copyright 2017-present Open Networking Laboratory * * 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.onosproject.routing.fpm.protocol; import org.onlab.packet.DeserializationException; /** * Decoder for a route attribute. */ @FunctionalInterface public interface RouteAttributeDecoder<A extends RouteAttribute> { /** * Decodes the a route attribute from the input buffer. * * @param length length of the attribute * @param type type of the attribute * @param value input buffer * @return route attribute * @throws DeserializationException if a route attribute could not be * decoded from the input buffer */ A decodeAttribute(int length, int type, byte[] value) throws DeserializationException; }
package com.hhl.rebound; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.GridLayout; import android.widget.ImageView; import com.facebook.rebound.SimpleSpringListener; import com.facebook.rebound.Spring; import com.facebook.rebound.SpringConfig; import com.facebook.rebound.SpringSystem; import java.util.ArrayList; import java.util.List; /** * 弹出菜单 * Created by HanHailong on 16/2/17. */ public class PopMenu { /** * 默认的列数为4个 */ private static final int DEFAULT_COLUMN_COUNT = 3; /** * 动画时间 */ private static final int DEFAULT_DURATION = 300; /** * 拉力系数 */ private static final int DEFAULT_TENSION = 40; /** * 摩擦力系数 */ private static final int DEFAULT_FRICTION = 5; /** * item水平之间的间距 */ private static final int DEFAULT_HORIZONTAL_PADDING = 40; /** * item竖直之间的间距 */ private static final int DEFAULT_VERTICAL_PADDING = 15; private Activity mActivity; private int mColumnCount; private List<PopMenuItem> mMenuItems = new ArrayList<>(); private FrameLayout mAnimateLayout; private GridLayout mGridLayout; private ImageView mCloseIv; private int mDuration; private double mTension; private double mFriction; private int mHorizontalPadding; private int mVerticalPadding; private PopMenuItemListener mPopMenuItemListener; private int mScreenWidth; private int mScreenHeight; private boolean isShowing = false; private SpringSystem mSpringSystem; { mSpringSystem = SpringSystem.create(); } private PopMenu(Builder builder) { this.mActivity = builder.activity; this.mMenuItems.clear(); this.mMenuItems.addAll(builder.itemList); this.mColumnCount = builder.columnCount; this.mDuration = builder.duration; this.mTension = builder.tension; this.mFriction = builder.friction; this.mHorizontalPadding = builder.horizontalPadding; this.mVerticalPadding = builder.verticalPadding; this.mPopMenuItemListener = builder.popMenuItemListener; mScreenWidth = mActivity.getResources().getDisplayMetrics().widthPixels; mScreenHeight = mActivity.getResources().getDisplayMetrics().heightPixels; } /** * 显示菜单 */ public void show() { buildAnimateGridLayout(); if (mAnimateLayout.getParent() != null) { ViewGroup viewGroup = (ViewGroup) mAnimateLayout.getParent(); viewGroup.removeView(mAnimateLayout); } ViewGroup decorView = (ViewGroup) mActivity.getWindow().getDecorView(); ViewGroup contentView = (ViewGroup) decorView.findViewById(android.R.id.content); contentView.addView(mAnimateLayout); //执行显示动画 showSubMenus(mGridLayout); isShowing = true; } /** * 隐藏菜单 */ public void hide() { //先执行消失的动画 if (isShowing && mGridLayout != null) { hideSubMenus(mGridLayout, new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { ViewGroup decorView = (ViewGroup) mActivity.getWindow().getDecorView(); ViewGroup contentView = (ViewGroup) decorView.findViewById(android.R.id.content); contentView.removeView(mAnimateLayout); } }); isShowing = false; } } public boolean isShowing() { return isShowing; } /** * 构建动画布局 */ private void buildAnimateGridLayout() { mAnimateLayout = new FrameLayout(mActivity); mGridLayout = new GridLayout(mActivity); mGridLayout.setColumnCount(mColumnCount); mGridLayout.setBackgroundColor(Color.parseColor("#f0ffffff")); int hPadding = dp2px(mActivity, mHorizontalPadding); int vPadding = dp2px(mActivity, mVerticalPadding); int itemWidth = (mScreenWidth - (mColumnCount + 1) * hPadding) / mColumnCount; int rowCount = mMenuItems.size() % mColumnCount == 0 ? mMenuItems.size() / mColumnCount : mMenuItems.size() / mColumnCount + 1; int topMargin = (mScreenHeight - (itemWidth + vPadding) * rowCount + vPadding) / 2; for (int i = 0; i < mMenuItems.size(); i++) { final int position = i; PopSubView subView = new PopSubView(mActivity); PopMenuItem menuItem = mMenuItems.get(i); subView.setPopMenuItem(menuItem); subView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mPopMenuItemListener != null) { mPopMenuItemListener.onItemClick(PopMenu.this, position); } hide(); } }); GridLayout.LayoutParams lp = new GridLayout.LayoutParams(); lp.width = itemWidth; lp.leftMargin = hPadding; if (i / mColumnCount == 0) { lp.topMargin = topMargin; } else { lp.topMargin = vPadding; } mGridLayout.addView(subView, lp); } mAnimateLayout.addView(mGridLayout); mCloseIv = new ImageView(mActivity); mCloseIv.setScaleType(ImageView.ScaleType.CENTER_INSIDE); mCloseIv.setImageResource(R.drawable.tabbar_compose_background_icon_close); mCloseIv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hide(); } }); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); layoutParams.bottomMargin = dp2px(mActivity, 25); mAnimateLayout.addView(mCloseIv, layoutParams); } /** * show sub menus with animates * * @param viewGroup */ private void showSubMenus(ViewGroup viewGroup) { if (viewGroup == null) return; int childCount = viewGroup.getChildCount(); for (int i = 0; i < childCount; i++) { View view = viewGroup.getChildAt(i); animateViewDirection(view, mScreenHeight, 0, mTension, mFriction); } } /** * hide sub menus with animates * * @param viewGroup * @param listener */ private void hideSubMenus(ViewGroup viewGroup, final AnimatorListenerAdapter listener) { if (viewGroup == null) return; int childCount = viewGroup.getChildCount(); for (int i = 0; i < childCount; i++) { View view = viewGroup.getChildAt(i); view.animate().translationY(mScreenHeight).setDuration(mDuration).setListener(listener).start(); } } /** * 弹簧动画 * * @param v 动画View * @param from * @param to * @param tension 拉力系数 * @param friction 摩擦力系数 */ private void animateViewDirection(final View v, float from, float to, double tension, double friction) { Spring spring = mSpringSystem.createSpring(); spring.setCurrentValue(from); spring.setSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(tension, friction)); spring.addListener(new SimpleSpringListener() { @Override public void onSpringUpdate(Spring spring) { v.setTranslationY((float) spring.getCurrentValue()); } }); spring.setEndValue(to); } public static class Builder { private Activity activity; private int columnCount = DEFAULT_COLUMN_COUNT; private List<PopMenuItem> itemList = new ArrayList<>(); private int duration = DEFAULT_DURATION; private double tension = DEFAULT_TENSION; private double friction = DEFAULT_FRICTION; private int horizontalPadding = DEFAULT_HORIZONTAL_PADDING; private int verticalPadding = DEFAULT_VERTICAL_PADDING; private PopMenuItemListener popMenuItemListener; public Builder attachToActivity(Activity activity) { this.activity = activity; return this; } public Builder columnCount(int count) { this.columnCount = count; return this; } public Builder addMenuItem(PopMenuItem menuItem) { this.itemList.add(menuItem); return this; } public Builder duration(int duration) { this.duration = duration; return this; } public Builder tension(double tension) { this.tension = tension; return this; } public Builder friction(double friction) { this.friction = friction; return this; } public Builder horizontalPadding(int padding) { this.horizontalPadding = padding; return this; } public Builder verticalPadding(int padding) { this.verticalPadding = padding; return this; } public Builder setOnItemClickListener(PopMenuItemListener listener) { this.popMenuItemListener = listener; return this; } public PopMenu build() { final PopMenu popMenu = new PopMenu(this); return popMenu; } } /** * dp 2 px * * @param context * @param dpVal * @return */ protected int dp2px(Context context, int dpVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources().getDisplayMetrics()); } }
/* * 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.saga.omega.transaction; import org.apache.servicecomb.saga.common.EventType; public class TxEndedEvent extends TxEvent { public TxEndedEvent(String globalTxId, String localTxId, String parentTxId, String compensationMethod) { super(EventType.TxEndedEvent, globalTxId, localTxId, parentTxId, compensationMethod, 0, "", 0); } }
/* * @(#)Layouter.java 5.2 * */ package CH.ifa.draw.contrib; import CH.ifa.draw.util.Storable; import java.io.Serializable; import java.awt.*; /** * A Layouter encapsulates a algorithm to layout * a figure. It is passed on to a figure which delegates the * layout task to the Layouter's layout method. * The Layouter might need access to some information * specific to a certain figure in order to layout it out properly. * * Note: Currently, only the GraphicalCompositeFigure uses * such a Layouter to layout its child components. * * @see GraphicalCompositeFigure * @author Wolfram Kaiser */ public interface Layouter extends Serializable, Storable { /* * Calculate the layout for the figure and all its subelements. The * layout is not actually performed but just its dimensions are calculated. * * @param origin start point for the layout * @param corner minimum corner point for the layout */ public Rectangle calculateLayout(Point origin, Point corner); /** * Method which lays out a figure. It is called by the figure * if a layout task is to be performed. Implementing classes * specify a certain layout algorithm in this method. * * @param origin start point for the layout * @param corner minimum corner point for the layout */ public Rectangle layout(Point origin, Point corner); /** * Set the insets for spacing between the figure and its subfigures * * @param newInsets new spacing dimensions */ public void setInsets(Insets newInsets); /** * Get the insets for spacing between the figure and its subfigures * * @return spacing dimensions */ public Insets getInsets(); }
package com.zensar.currency.conversion; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class CurrencyConversionServiceApplicationTests { @Test void contextLoads() { } }
package com.stylefeng.guns.api.film.vo; import lombok.Data; import java.io.Serializable; @Data public class InfoRequestVo implements Serializable { private String biography; private ActorRequestVo actors; private ImgVo imgVo; private String filmId; }
package blueprintlabs.zulu; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
/* * Copyright 2004,2005 The Apache Software Foundation. * * 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.apache.rampart.util; import com.sun.org.apache.xerces.internal.impl.Constants; import org.apache.axiom.om.*; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.axiom.om.impl.dom.DOOMAbstractFactory; import org.apache.axiom.soap.*; import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.rampart.handler.WSSHandlerConstants; import org.apache.ws.security.WSSecurityException; import org.apache.xml.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.apache.xerces.util.SecurityManager; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Iterator; /** * Utility class for the Axis2-WSS4J Module */ public class Axis2Util { private static ThreadLocal doomTacker = new ThreadLocal(); private static final int ENTITY_EXPANSION_LIMIT = 0; private static final Log logger = LogFactory.getLog(Axis2Util.class); public static boolean isUseDOOM() { Object value = doomTacker.get(); return (value != null); } public static void useDOOM(boolean isDOOMRequired) { //TODO Enable this when we have DOOM fixed to be able to flow in and out of Axis2 // if(isDOOMRequired) { // if(!isUseDOOM()) { // System.setProperty(OMAbstractFactory.SOAP11_FACTORY_NAME_PROPERTY, SOAP11Factory.class.getName()); // System.setProperty(OMAbstractFactory.SOAP12_FACTORY_NAME_PROPERTY, SOAP12Factory.class.getName()); // System.setProperty(OMAbstractFactory.OM_FACTORY_NAME_PROPERTY, OMDOMFactory.class.getName()); // doomTacker.set(new Object()); // } // } else { // System.getProperties().remove(OMAbstractFactory.SOAP11_FACTORY_NAME_PROPERTY); // System.getProperties().remove(OMAbstractFactory.SOAP12_FACTORY_NAME_PROPERTY); // System.getProperties().remove(OMAbstractFactory.OM_FACTORY_NAME_PROPERTY); // doomTacker.set(null); // } } /** * Creates a DOM Document using the SOAP Envelope. * @param env An org.apache.axiom.soap.SOAPEnvelope instance * @return Returns the DOM Document of the given SOAP Envelope. * @throws Exception */ public static Document getDocumentFromSOAPEnvelope(SOAPEnvelope env, boolean useDoom) throws WSSecurityException { try { if(env instanceof Element) { return ((Element)env).getOwnerDocument(); } if (useDoom) { env.build(); // Workaround to prevent a bug in AXIOM where // there can be an incomplete OMElement as the first child body OMElement firstElement = env.getBody().getFirstElement(); if (firstElement != null) { firstElement.build(); } //Get processed headers SOAPHeader soapHeader = env.getHeader(); ArrayList processedHeaderQNames = new ArrayList(); if(soapHeader != null) { Iterator headerBlocs = soapHeader.getChildElements(); while (headerBlocs.hasNext()) { SOAPHeaderBlock element = (SOAPHeaderBlock) headerBlocs.next(); if(element.isProcessed()) { processedHeaderQNames.add(element.getQName()); } } } // Check the namespace and find SOAP version and factory String nsURI = null; SOAPFactory factory; if (env.getNamespace().getNamespaceURI().equals( SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)) { nsURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI; factory = DOOMAbstractFactory.getSOAP11Factory(); } else { nsURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI; factory = DOOMAbstractFactory.getSOAP12Factory(); } StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder( env.getXMLStreamReader(), factory, nsURI); SOAPEnvelope envelope = (stAXSOAPModelBuilder) .getSOAPEnvelope(); ((OMNode) envelope.getParent()).build(); //Set the processed flag of the processed headers SOAPHeader header = envelope.getHeader(); for (Iterator iter = processedHeaderQNames.iterator(); iter .hasNext();) { QName name = (QName) iter.next(); Iterator omKids = header.getChildrenWithName(name); if(omKids.hasNext()) { ((SOAPHeaderBlock)omKids.next()).setProcessed(); } } Element envElem = (Element) envelope; return envElem.getOwnerDocument(); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); env.build(); env.serialize(baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos .toByteArray()); DocumentBuilderFactory factory = getSecuredDocumentBuilderFactory(); factory.setNamespaceAware(true); return factory.newDocumentBuilder().parse(bais); } } catch (Exception e) { throw new WSSecurityException( "Error in converting SOAP Envelope to Document", e); } } /** * Builds a SOAPEnvelope from DOM Document. * @param doc - The dom document that contains a SOAP message * @param useDoom * @return * @throws WSSecurityException */ public static SOAPEnvelope getSOAPEnvelopeFromDOMDocument(Document doc, boolean useDoom) throws WSSecurityException { if(useDoom) { try { //Get processed headers SOAPEnvelope env = (SOAPEnvelope)doc.getDocumentElement(); ArrayList processedHeaderQNames = new ArrayList(); SOAPHeader soapHeader = env.getHeader(); if(soapHeader != null) { Iterator headerBlocs = soapHeader.getChildElements(); while (headerBlocs.hasNext()) { OMElement element = (OMElement)headerBlocs.next(); SOAPHeaderBlock header = null; if (element instanceof SOAPHeaderBlock) { header = (SOAPHeaderBlock) element; // If a header block is not an instance of SOAPHeaderBlock, it means that // it is a header we have added in rampart eg. EncryptedHeader and should // be converted to SOAPHeaderBlock for processing } else { header = soapHeader.addHeaderBlock(element.getLocalName(), element.getNamespace()); Iterator attrIter = element.getAllAttributes(); while (attrIter.hasNext()) { OMAttribute attr = (OMAttribute)attrIter.next(); header.addAttribute(attr.getLocalName(), attr.getAttributeValue(), attr.getNamespace()); } Iterator nsIter = element.getAllDeclaredNamespaces(); while (nsIter.hasNext()) { OMNamespace ns = (OMNamespace) nsIter.next(); header.declareNamespace(ns); } // retrieve all child nodes (including any text nodes) // and re-attach to header block Iterator children = element.getChildren(); while (children.hasNext()) { OMNode child = (OMNode)children.next(); child.detach(); header.addChild(child); } element.detach(); soapHeader.build(); header.setProcessed(); } if(header.isProcessed()) { processedHeaderQNames.add(element.getQName()); } } } XMLStreamReader reader = ((OMElement) doc.getDocumentElement()) .getXMLStreamReader(); StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder( reader, null); SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope(); //Set the processed flag of the processed headers SOAPHeader header = envelope.getHeader(); for (Iterator iter = processedHeaderQNames.iterator(); iter .hasNext();) { QName name = (QName) iter.next(); Iterator omKids = header.getChildrenWithName(name); if(omKids.hasNext()) { ((SOAPHeaderBlock)omKids.next()).setProcessed(); } } envelope.build(); return envelope; } catch (FactoryConfigurationError e) { throw new WSSecurityException(e.getMessage()); } } else { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); XMLUtils.outputDOM(doc.getDocumentElement(), os, true); ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray()); StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder(XMLInputFactory.newInstance().createXMLStreamReader(bais), null); return stAXSOAPModelBuilder.getSOAPEnvelope(); } catch (Exception e) { throw new WSSecurityException(e.getMessage()); } } } /** * Provides the appropriate key to pickup config params from the message context. * This is acutally used when the outflow handler (WSDoAllSender) * is repeated n number of times. * @param originalKey The default key * @param inHandler Whether the handler is the inflow handler or not * @param repetition The current repetition number * @return Returns the key to be used internally in the security module to pick * up the config params. */ public static String getKey(String originalKey, boolean inHandler, int repetition) { if(repetition > 0 && !inHandler && !originalKey.equals(WSSHandlerConstants.OUTFLOW_SECURITY)&& !originalKey.equals(WSSHandlerConstants.SENDER_REPEAT_COUNT)) { return originalKey + repetition; } return originalKey; } /** * This will build a DOOM Element that is of the same <code>Document</code> * @param factory * @param element * @return */ public static OMElement toDOOM(OMFactory factory, OMElement element){ StAXOMBuilder builder = new StAXOMBuilder(factory, element.getXMLStreamReader()); OMElement elem = builder.getDocumentElement(); elem.build(); return elem; } /** * Create DocumentBuilderFactory with the XXE prevention measurements * * @return DocumentBuilderFactory instance */ public static DocumentBuilderFactory getSecuredDocumentBuilderFactory() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); try { dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE, false); dbf.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); dbf.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (ParserConfigurationException e) { logger.error( "Failed to load XML Processor Feature " + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE + " or " + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE + " or " + Constants.LOAD_EXTERNAL_DTD_FEATURE); } SecurityManager securityManager = new SecurityManager(); securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); dbf.setAttribute(Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY, securityManager); return dbf; } }