text
stringlengths
7
1.01M
// Copyright 2018 The Cockroach 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.cockroachlabs.teamcity.github; import jetbrains.buildServer.controllers.BuildDataExtensionUtil; import jetbrains.buildServer.serverSide.Branch; import jetbrains.buildServer.serverSide.SBuild; import jetbrains.buildServer.serverSide.SBuildServer; import jetbrains.buildServer.vcs.VcsRootInstance; import jetbrains.buildServer.vcs.VcsRootInstanceEntry; import jetbrains.buildServer.web.openapi.PlaceId; import jetbrains.buildServer.web.openapi.PluginDescriptor; import jetbrains.buildServer.web.openapi.SimplePageExtension; import jetbrains.buildServer.web.openapi.WebControllerManager; import org.jetbrains.annotations.NotNull; import javax.servlet.http.HttpServletRequest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Map; public class GitHubLinkExtension extends SimplePageExtension { @NotNull private final SBuildServer server; @NotNull private final Pattern urlPattern = Pattern.compile("github.com[:/](?<org>[^/.]+)/(?<repo>[^/.]+)"); public GitHubLinkExtension(@NotNull final WebControllerManager manager, @NotNull final PluginDescriptor pluginDescriptor, @NotNull final SBuildServer serverIn) { super(manager, PlaceId.BUILD_SUMMARY, pluginDescriptor.getPluginName(), pluginDescriptor.getPluginResourcesPath("githubLink.jsp")); server = serverIn; register(); } @Override public void fillModel(@NotNull final Map<String, Object> model, @NotNull final HttpServletRequest request) { final SBuild build = BuildDataExtensionUtil.retrieveBuild(request, server); if (build == null) { return; } Branch branch = build.getBranch(); if (branch == null) { return; } java.util.List<VcsRootInstanceEntry> vcsRoots = build.getVcsRootEntries(); if (vcsRoots.isEmpty()) { return; } String vcsRootUrl = vcsRoots.get(0).getVcsRoot().getProperty("url"); if (vcsRootUrl == null) { return; } Matcher urlMatcher = urlPattern.matcher(vcsRootUrl); if (!urlMatcher.find()) { return; } model.put("github_pr_url", String.format("https://github.com/%s/%s/pull/%s", urlMatcher.group("org"), urlMatcher.group("repo"), branch.getName())); model.put("github_pr_number", branch.getName()); super.fillModel(model, request); } @Override public boolean isAvailable(@NotNull final HttpServletRequest request) { final SBuild build = BuildDataExtensionUtil.retrieveBuild(request, server); if (build == null) { return false; } Branch branch = build.getBranch(); if (branch == null) { return false; } if (!branch.getName().matches("\\d+")) { return false; } java.util.List<VcsRootInstanceEntry> vcsRoots = build.getVcsRootEntries(); if (vcsRoots.isEmpty()) { return false; } String vcsRootUrl = vcsRoots.get(0).getVcsRoot().getProperty("url"); if (vcsRootUrl == null) { return false; } return urlPattern.matcher(vcsRootUrl).find(); } }
/* * Copyright (c) 2012 Soar Technology Inc. * * Created on July 10, 2012 */ package org.jsoar.kernel.io.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.jsoar.kernel.io.InputOutput; import org.jsoar.kernel.memory.WmeBuilder; import org.jsoar.kernel.memory.WmeFactory; import org.jsoar.kernel.symbols.Identifier; import org.jsoar.kernel.symbols.SymbolFactory; import org.jsoar.kernel.symbols.Symbols; import org.jsoar.kernel.tracing.Printer; import org.jsoar.util.adaptables.Adaptables; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Abstract class which contains functions to load XML from file and add a * parsed XML document to JSoar working memory. * * @author chris.kawatsu * */ abstract class AbstractXmlFileToWme implements XmlFileToWme, XmlToWme { private WmeBuilder<?> builder = null; private WmeFactory<?> factory = null; /** * Overloaded {@link #AbstractXmlFileToWme(WmeFactory)}. * * @param io */ public AbstractXmlFileToWme(InputOutput io) { factory = io.asWmeFactory(); } /** * Create an xmlToWme object which adds WMEs to an arbitrary location. The * root WME is returned by {@link #fromXml(Element)}.<br> * <br> * * Note: {@link #xmlToWme(File, InputOutput) xmlToWme} adds WMEs directly to * the input link instead of returning a reference to a WME. * * @param wmeFactory */ public AbstractXmlFileToWme(WmeFactory<?> wmeFactory) { factory = wmeFactory; } @Override public void xmlToWme(File file, InputOutput io) { final Element root = getRootElement(file); final Identifier ret = fromXml(root); final SymbolFactory sf = io.getSymbols(); io.addInputWme(io.getInputLink(), Symbols.create(sf, root.getNodeName()), ret); } @Override public Identifier fromXml(Element element) { builder = WmeBuilder.create(factory, element.getNodeName()); // builder = builder.push(element.getNodeName()); addAttributes(element.getAttributes(), builder); getXmlTree(element.getChildNodes(), builder); return builder.topId(); } /** * Add all of the nodes in the list to the builder. If the nodes contain * children, make a recursive call to add them. Attributes of XML tags are * also added to the builder.<br> * <br> * * Leaf tags containing text are added to the builder. Empty leaf tags are * added to the builder as an empty string, provided the tag contains no * attributes. * * @param nodeList - the list of nodes * @param builder - the JSoar builder */ abstract void getXmlTree(NodeList nodeList, WmeBuilder<?> builder); /** * Add the attributes contained in the <code>NamedNodeMap</code> to the * builder. * * @param nnm * - a collection of attribute nodes * @param builder * - the JSoar builder */ abstract void addAttributes(NamedNodeMap nnm, WmeBuilder<?> builder); /** * Parse an XML file and get its root {@link Element}. * * @param f * - the XML file to parse * @return The root <code>Element</code> of the XML file. Returns * <code>null</code> if the file cannot be read or an error occurs * during parsing. */ protected Element getRootElement(File f) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(f); return dom.getDocumentElement(); } catch (ParserConfigurationException | SAXException | IOException ex) { Printer p = Adaptables.adapt(this.factory.getSymbols(), Printer.class); if(p == null) { ex.printStackTrace(); } else { ex.printStackTrace(p.asPrintWriter()); p.flush(); } } return null; } }
package org.example.controller; import com.github.sarxos.webcam.Webcam; import com.github.sarxos.webcam.WebcamPanel; import com.github.sarxos.webcam.ds.ipcam.IpCamDevice; import com.github.sarxos.webcam.ds.ipcam.IpCamDeviceRegistry; import com.github.sarxos.webcam.ds.ipcam.IpCamDriver; import com.github.sarxos.webcam.ds.ipcam.IpCamMode; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import org.example.model.Camera; import org.example.model.CameraP; import javax.swing.*; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.ResourceBundle; public class CameraViewController implements Initializable { @FXML private TextField txt_libelle; @FXML private Label lbl1; @FXML private TextField txt_url; @FXML private Button btn_camera; @FXML private TableView<Camera> tablev_cameras; private ArrayList<Camera> cameras; private Camera selectedCamera; @FXML void onClickCamera(ActionEvent event) { if(this.selectedCamera == null){ return; } dispCam(selectedCamera.getEquipementStr(), selectedCamera.getUrl()); } @FXML void onClickSauvgarder(ActionEvent event) { if(selectedCamera!=null){ //update String libelle = txt_libelle.getText(); String url = txt_url.getText(); selectedCamera.setUrl(url); if(selectedCamera.update(libelle)){ loadTableviewCamerasData(); clearInputs(); } } else{ if(txt_url.getText().isEmpty()||txt_libelle.getText().isEmpty()) { Alert alert=new Alert(Alert.AlertType.ERROR); alert.setHeaderText(null); alert.setContentText("entrer tous les champs "); alert.showAndWait(); return; } else { //create Camera camera = new Camera(); String libelle = txt_libelle.getText(); String url = txt_url.getText(); camera.setUrl(url); if (camera.create(libelle)) { cameras.add(camera); loadTableviewCamerasData(); clearInputs(); } } } } @FXML void onClickSupprimer(ActionEvent event) { int action = JOptionPane.showConfirmDialog(null, "Confirmer votre suppession?"); if (action == 0) { if(selectedCamera!=null){ if(selectedCamera.delete()){ cameras.remove(selectedCamera); loadTableviewCamerasData(); selectedCamera = null; this.clearInputs(); } } else {JOptionPane.showMessageDialog(null,"Selectionne une element que vous vouler supprimer");} } } @FXML void onMouseClickTableView(MouseEvent event) { Object obj = tablev_cameras.getSelectionModel().getSelectedItem(); if (event.getClickCount() == 2 && obj != null) { if (cameras.indexOf(obj) >= 0) { selectedCamera = (Camera) obj; txt_libelle.setText(selectedCamera.getEquipementStr()); txt_url.setText(selectedCamera.getUrl()); } } } @Override public void initialize(URL url, ResourceBundle resourceBundle) { loadCamerasData(); loadTableviewCameraColumns(); loadTableviewCamerasData(); } public void loadCamerasData() { cameras = new ArrayList<>(); List<Map<String, Object>> all = (new Camera()).getAll(true); for (Map<String, Object> row : all) { Camera c = new Camera(); c.readRow(row); cameras.add(c); } } public void loadTableviewCamerasData() { tablev_cameras.getColumns().get(0).setVisible(false); tablev_cameras.getColumns().get(0).setVisible(true); ObservableList<Camera> camperaObservableList = FXCollections.observableList(cameras); tablev_cameras.setItems(camperaObservableList); } public void loadTableviewCameraColumns() { TableColumn column = new TableColumn("id"); column.setCellValueFactory(new PropertyValueFactory<>("id")); tablev_cameras.getColumns().add(column); for (Map.Entry<String, Object> entry : (new Camera()).toRow().entrySet()) { if (entry.getKey() == "id_equipement") { column = new TableColumn("equipement"); column.setCellValueFactory(new PropertyValueFactory<>("equipementStr")); tablev_cameras.getColumns().add(column); continue; } column = new TableColumn(entry.getKey()); column.setCellValueFactory(new PropertyValueFactory<>(entry.getKey())); tablev_cameras.getColumns().add(column); } } private void clearInputs() { txt_libelle.clear(); txt_url.clear(); } static { Webcam.setDriver(new IpCamDriver()); } public void dispCam(String name, String url) { try { if(!IpCamDeviceRegistry.isRegistered(name)){ IpCamDeviceRegistry.register(name, url, IpCamMode.PUSH); } int index = 0; for (IpCamDevice ip:IpCamDeviceRegistry.getIpCameras()) { System.out.println(ip.getName()+" "+name); if(ip.getName().equals(name)){ break; } index++; } if(index>=IpCamDeviceRegistry.getIpCameras().size()) return; WebcamPanel panel = new WebcamPanel(Webcam.getWebcams().get(index)); panel.setFPSDisplayed(true); panel.setDisplayDebugInfo(true); panel.setImageSizeDisplayed(true); panel.setMirrored(true); JFrame window = new JFrame("Test webcam panel"); window.add(panel); window.setResizable(true); //window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.pack(); window.setVisible(true); } catch (MalformedURLException e) { e.printStackTrace(); } } }
package ${package}; /** * Hello world! */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); } }
// // ======================================================================== // Copyright (c) 1995-2017 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.websocket.jsr356.server; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.startsWith; import static org.junit.Assert.assertThat; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Executor; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.websocket.ContainerProvider; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import javax.websocket.server.ServerEndpoint; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.util.IO; import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.eclipse.jetty.websocket.api.util.WSURI; import org.eclipse.jetty.websocket.jsr356.ClientContainer; import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer; import org.junit.Test; public class DelayedStartClientOnServerTest { @ServerEndpoint("/echo") public static class EchoSocket { @OnMessage public String echo(String msg) { return msg; } } /** * Using the Client specific techniques of JSR356, connect to the echo socket * and perform an echo request. */ public static class ClientConnectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Client specific technique WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { URI wsURI = WSURI.toWebsocket(req.getRequestURL()).resolve("/echo"); Session session = container.connectToServer(new Endpoint() { @Override public void onOpen(Session session, EndpointConfig config) { /* do nothing */ } }, wsURI); // don't care about the data sent, just the connect itself. session.getBasicRemote().sendText("Hello"); session.close(); resp.setContentType("text/plain"); resp.getWriter().println("Connected to " + wsURI); } catch (Throwable t) { throw new ServletException(t); } } } /** * Using the Server specific techniques of JSR356, connect to the echo socket * and perform an echo request. */ public static class ServerConnectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Server specific technique javax.websocket.server.ServerContainer container = (javax.websocket.server.ServerContainer) req.getServletContext().getAttribute("javax.websocket.server.ServerContainer"); try { URI wsURI = WSURI.toWebsocket(req.getRequestURL()).resolve("/echo"); Session session = container.connectToServer(new Endpoint() { @Override public void onOpen(Session session, EndpointConfig config) { /* do nothing */ } }, wsURI); // don't care about the data sent, just the connect itself. session.getBasicRemote().sendText("Hello"); session.close(); resp.setContentType("text/plain"); resp.getWriter().println("Connected to " + wsURI); } catch (Throwable t) { throw new ServletException(t); } } } /** * Using the Client specific techniques of JSR356, configure the WebSocketContainer. */ public static class ClientConfigureServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Client specific technique WebSocketContainer container = ContainerProvider.getWebSocketContainer(); try { container.setAsyncSendTimeout(5000); container.setDefaultMaxTextMessageBufferSize(1000); resp.setContentType("text/plain"); resp.getWriter().printf("Configured %s - %s%n", container.getClass().getName(), container); } catch (Throwable t) { throw new ServletException(t); } } } private void assertNoHttpClientPoolThreads(List<String> threadNames) { for (String threadName : threadNames) { if (threadName.startsWith("HttpClient@") && !threadName.endsWith("-scheduler")) { throw new AssertionError("Found non-scheduler HttpClient thread in <" + threadNames.stream().collect(Collectors.joining("[", ", ", "]")) + ">"); } } } /** * Using the Server specific techniques of JSR356, configure the WebSocketContainer. */ public static class ServerConfigureServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Server specific technique javax.websocket.server.ServerContainer container = (javax.websocket.server.ServerContainer) req.getServletContext().getAttribute("javax.websocket.server.ServerContainer"); try { container.setAsyncSendTimeout(5000); container.setDefaultMaxTextMessageBufferSize(1000); resp.setContentType("text/plain"); resp.getWriter().printf("Configured %s - %s%n", container.getClass().getName(), container); } catch (Throwable t) { throw new ServletException(t); } } } @Test public void testNoExtraHttpClientThreads() throws Exception { Server server = new Server(0); ServletContextHandler contextHandler = new ServletContextHandler(); server.setHandler(contextHandler); try { server.start(); List<String> threadNames = getThreadNames(server); assertNoHttpClientPoolThreads(threadNames); assertThat("Threads", threadNames, not(hasItem(containsString("WebSocketContainer@")))); assertThat("Threads", threadNames, not(hasItem(containsString("WebSocketClient@")))); } finally { server.stop(); } } @Test public void testHttpClientThreads_AfterClientConnectTo() throws Exception { Server server = new Server(0); ServletContextHandler contextHandler = new ServletContextHandler(); server.setHandler(contextHandler); // Using JSR356 Client Techniques to connectToServer() contextHandler.addServlet(ClientConnectServlet.class, "/connect"); javax.websocket.server.ServerContainer container = WebSocketServerContainerInitializer.configureContext(contextHandler); container.addEndpoint(EchoSocket.class); try { server.start(); String response = GET(server.getURI().resolve("/connect")); assertThat("Response", response, startsWith("Connected to ws://")); List<String> threadNames = getThreadNames(server); assertNoHttpClientPoolThreads(threadNames); assertThat("Threads", threadNames, hasItem(containsString("WebSocketContainer@"))); } finally { server.stop(); } } @Test public void testHttpClientThreads_AfterServerConnectTo() throws Exception { Server server = new Server(0); ServletContextHandler contextHandler = new ServletContextHandler(); server.setHandler(contextHandler); // Using JSR356 Server Techniques to connectToServer() contextHandler.addServlet(ServerConnectServlet.class, "/connect"); javax.websocket.server.ServerContainer container = WebSocketServerContainerInitializer.configureContext(contextHandler); container.addEndpoint(EchoSocket.class); try { server.start(); String response = GET(server.getURI().resolve("/connect")); assertThat("Response", response, startsWith("Connected to ws://")); List<String> threadNames = getThreadNames((ContainerLifeCycle)container, server); assertNoHttpClientPoolThreads(threadNames); assertThat("Threads", threadNames, hasItem(containsString("WebSocketClient@"))); } finally { server.stop(); } } @Test public void testHttpClientThreads_AfterClientConfigure() throws Exception { Server server = new Server(0); ServletContextHandler contextHandler = new ServletContextHandler(); server.setHandler(contextHandler); // Using JSR356 Client Techniques to configure WebSocketContainer contextHandler.addServlet(ClientConfigureServlet.class, "/configure"); javax.websocket.server.ServerContainer container = WebSocketServerContainerInitializer.configureContext(contextHandler); container.addEndpoint(EchoSocket.class); try { server.start(); String response = GET(server.getURI().resolve("/configure")); assertThat("Response", response, startsWith("Configured " + ClientContainer.class.getName())); List<String> threadNames = getThreadNames((ContainerLifeCycle)container, server); assertNoHttpClientPoolThreads(threadNames); assertThat("Threads", threadNames, not(hasItem(containsString("WebSocketContainer@")))); assertThat("Threads", threadNames, not(hasItem(containsString("WebSocketClient@")))); } finally { server.stop(); } } @Test public void testHttpClientThreads_AfterServerConfigure() throws Exception { Server server = new Server(0); ServletContextHandler contextHandler = new ServletContextHandler(); server.setHandler(contextHandler); // Using JSR356 Server Techniques to configure WebSocketContainer contextHandler.addServlet(ServerConfigureServlet.class, "/configure"); javax.websocket.server.ServerContainer container = WebSocketServerContainerInitializer.configureContext(contextHandler); container.addEndpoint(EchoSocket.class); try { server.start(); String response = GET(server.getURI().resolve("/configure")); assertThat("Response", response, startsWith("Configured " + ServerContainer.class.getName())); List<String> threadNames = getThreadNames((ContainerLifeCycle)container, server); assertNoHttpClientPoolThreads(threadNames); assertThat("Threads", threadNames, not(hasItem(containsString("WebSocketContainer@")))); } finally { server.stop(); } } private String GET(URI destURI) throws IOException { HttpURLConnection http = (HttpURLConnection) destURI.toURL().openConnection(); assertThat("HTTP GET (" + destURI + ") Response Code", http.getResponseCode(), is(200)); try (InputStream in = http.getInputStream(); InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8); StringWriter writer = new StringWriter()) { IO.copy(reader, writer); return writer.toString(); } } public static List<String> getThreadNames(ContainerLifeCycle... containers) { List<String> threadNames = new ArrayList<>(); Set<Object> seen = new HashSet<>(); for (ContainerLifeCycle container : containers) { if (container == null) { continue; } findConfiguredThreadNames(seen, threadNames, container); } seen.clear(); // System.out.println("Threads: " + threadNames.stream().collect(Collectors.joining(", ", "[", "]"))); return threadNames; } private static void findConfiguredThreadNames(Set<Object> seen, List<String> threadNames, ContainerLifeCycle container) { if (seen.contains(container)) { // skip return; } seen.add(container); Collection<Executor> executors = container.getBeans(Executor.class); for (Executor executor : executors) { if (executor instanceof QueuedThreadPool) { QueuedThreadPool qtp = (QueuedThreadPool) executor; threadNames.add(qtp.getName()); } } for (ContainerLifeCycle child : container.getBeans(ContainerLifeCycle.class)) { findConfiguredThreadNames(seen, threadNames, child); } } }
/* * 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. */ /** * @author Dmitry A. Durnev * @version $Revision$ */ package java.awt; import java.awt.List.AccessibleAWTList; import java.beans.PropertyChangeEvent; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.accessibility.AccessibleSelection; import javax.accessibility.AccessibleState; import junit.framework.TestCase; /** * AccessibleAWTListTest */ public class AccessibleAWTListTest extends TestCase { List list; AccessibleContext ac; protected PropertyChangeEvent lastPropEvent; @Override protected void setUp() throws Exception { super.setUp(); list = new List(); ac = list.getAccessibleContext(); assertNotNull(ac); } public final void testGetAccessibleChildrenCount() { assertEquals(0, ac.getAccessibleChildrenCount()); list.add("item1"); list.add("item2"); assertEquals(2, ac.getAccessibleChildrenCount()); } public final void testGetAccessibleChild() { assertNull(ac.getAccessibleChild(0)); list.add("item"); Accessible aChild = ac.getAccessibleChild(0); assertNotNull(aChild); assertTrue(aChild instanceof AccessibleAWTList.AccessibleAWTListChild); assertNotNull(aChild = ac.getAccessibleChild(-2)); assertTrue(aChild instanceof AccessibleAWTList.AccessibleAWTListChild); assertNull(ac.getAccessibleChild(1)); } public final void testGetAccessibleRole() { assertSame(AccessibleRole.LIST, ac.getAccessibleRole()); } public final void testGetAccessibleStateSet() { final AccessibleState STATE = AccessibleState.MULTISELECTABLE; assertFalse(ac.getAccessibleStateSet().contains(STATE)); list.setMultipleMode(true); assertTrue(ac.getAccessibleStateSet().contains(STATE)); list.setMultipleMode(false); assertFalse(ac.getAccessibleStateSet().contains(STATE)); } public final void testGetAccessibleAt() { list.add("item1"); Point p = new Point(); assertNull(ac.getAccessibleComponent().getAccessibleAt(p)); } public final void testAccessibleAWTList() { AccessibleAWTList aList = list.new AccessibleAWTList(); assertNotNull(aList); // constructor has side-effect: listeners are added: assertSame(aList, list.getItemListeners()[1]); assertSame(aList, list.getActionListeners()[1]); } public final void testGetAccessibleSelectionCount() { list.add("item1"); list.add("item2"); AccessibleSelection as = ac.getAccessibleSelection(); assertEquals(0, as.getAccessibleSelectionCount()); list.select(0); assertEquals(1, as.getAccessibleSelectionCount()); list.select(1); assertEquals(1, as.getAccessibleSelectionCount()); list.setMultipleMode(true); list.select(0); assertEquals(2, as.getAccessibleSelectionCount()); } public final void testClearAccessibleSelection() { list.add("item1"); list.add("item2"); list.setMultipleMode(true); AccessibleSelection as = ac.getAccessibleSelection(); list.select(0); list.select(1); assertEquals(2, list.getSelectedItems().length); as.clearAccessibleSelection(); assertEquals(0, list.getSelectedItems().length); assertEquals(0, as.getAccessibleSelectionCount()); } public final void testSelectAllAccessibleSelection() { AccessibleSelection as = ac.getAccessibleSelection(); list.add("item1"); list.add("item2"); assertEquals(0, list.getSelectedItems().length); as.selectAllAccessibleSelection(); assertEquals(1, list.getSelectedItems().length); assertEquals("item1", list.getSelectedItem()); as.selectAllAccessibleSelection(); assertEquals(1, list.getSelectedItems().length); assertEquals("item1", list.getSelectedItem()); list.setMultipleMode(true); as.selectAllAccessibleSelection(); assertEquals(2, list.getSelectedItems().length); } public final void testAddAccessibleSelection() { AccessibleSelection as = ac.getAccessibleSelection(); list.add("item1"); list.add("item2"); assertEquals(0, list.getSelectedItems().length); as.addAccessibleSelection(1); assertEquals(1, list.getSelectedItems().length); assertEquals("item2", list.getSelectedItem()); as.addAccessibleSelection(0); assertEquals(1, list.getSelectedItems().length); assertEquals("item1", list.getSelectedItem()); list.setMultipleMode(true); as.addAccessibleSelection(1); assertEquals(2, list.getSelectedItems().length); } public final void testRemoveAccessibleSelection() { AccessibleSelection as = ac.getAccessibleSelection(); list.add("item1"); list.add("item2"); assertEquals(0, list.getSelectedItems().length); as.removeAccessibleSelection(0); as.removeAccessibleSelection(1); assertEquals(0, list.getSelectedItems().length); list.select(0); assertEquals(1, list.getSelectedItems().length); as.removeAccessibleSelection(1); assertEquals(1, list.getSelectedItems().length); as.removeAccessibleSelection(0); assertEquals(0, list.getSelectedItems().length); } public final void testIsAccessibleChildSelected() { AccessibleSelection as = ac.getAccessibleSelection(); list.add("item1"); list.add("item2"); assertFalse(as.isAccessibleChildSelected(0)); assertFalse(as.isAccessibleChildSelected(1)); list.select(1); assertFalse(as.isAccessibleChildSelected(0)); assertTrue(as.isAccessibleChildSelected(1)); list.select(0); assertFalse(as.isAccessibleChildSelected(1)); assertTrue(as.isAccessibleChildSelected(0)); } /* * Class under test for javax.accessibility.Accessible getAccessibleSelection(int) */ public final void testGetAccessibleSelectionint() { AccessibleSelection as = ac.getAccessibleSelection(); list.add("item1"); list.add("item2"); assertNull(as.getAccessibleSelection(-1)); assertNull(as.getAccessibleSelection(0)); assertNull(as.getAccessibleSelection(1)); list.select(1); assertNull(as.getAccessibleSelection(-1)); assertTrue(as.getAccessibleSelection(0) instanceof AccessibleAWTList.AccessibleAWTListChild); assertNull(as.getAccessibleSelection(1)); } public final void testGetAccessibleSelection() { assertSame(ac, ac.getAccessibleSelection()); } public final void testItemStateChanged() { // not implemented } public final void testActionPerformed() { // not implemented } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.camel.example package|package name|org operator|. name|apache operator|. name|camel operator|. name|example package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|AggregationStrategy import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|Exchange import|; end_import begin_comment comment|/** * Aggregate two numbers */ end_comment begin_comment comment|// START SNIPPET: e1 end_comment begin_class DECL|class|NumberAggregationStrategy specifier|public class|class name|NumberAggregationStrategy implements|implements name|AggregationStrategy block|{ annotation|@ name|Override DECL|method|aggregate (Exchange oldExchange, Exchange newExchange) specifier|public name|Exchange name|aggregate parameter_list|( name|Exchange name|oldExchange parameter_list|, name|Exchange name|newExchange parameter_list|) block|{ if|if condition|( name|oldExchange operator|== literal|null condition|) block|{ return|return name|newExchange return|; block|} comment|// check for stop command name|String name|input init|= name|newExchange operator|. name|getIn argument_list|() operator|. name|getBody argument_list|( name|String operator|. name|class argument_list|) decl_stmt|; if|if condition|( literal|"STOP" operator|. name|equalsIgnoreCase argument_list|( name|input argument_list|) condition|) block|{ return|return name|oldExchange return|; block|} name|Integer name|num1 init|= name|oldExchange operator|. name|getIn argument_list|() operator|. name|getBody argument_list|( name|Integer operator|. name|class argument_list|) decl_stmt|; name|Integer name|num2 init|= name|newExchange operator|. name|getIn argument_list|() operator|. name|getBody argument_list|( name|Integer operator|. name|class argument_list|) decl_stmt|; comment|// just avoid bad inputs by assuming its a 0 value name|Integer name|num3 init|= operator|( name|num1 operator|!= literal|null condition|? name|num1 else|: literal|0 operator|) operator|+ operator|( name|num2 operator|!= literal|null condition|? name|num2 else|: literal|0 operator|) decl_stmt|; name|oldExchange operator|. name|getIn argument_list|() operator|. name|setBody argument_list|( name|num3 argument_list|) expr_stmt|; return|return name|oldExchange return|; block|} block|} end_class begin_comment comment|// END SNIPPET: e1 end_comment end_unit
package com.xyc.security.helper; import com.xyc.security.annotation.Module; import com.xyc.security.annotation.Permission; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by xyc on 2017/8/9 0009. */ public class SecurityHelper { private final static Logger logger = LoggerFactory.getLogger(SecurityHelper.class); /** * 解析源码 * * @param mpMap * @param className * @throws ClassNotFoundException */ public static void analyseClassPathCode(Map<Module, List<Permission>> mpMap, String className) throws ClassNotFoundException { Class cls = Class.forName(className); if (!cls.isAnnotationPresent(Controller.class) && !cls.isAnnotationPresent(RestController.class)) { return; } if (!cls.isAnnotationPresent(Module.class)) { //没有权限模块配置 return; } Module module = (Module) cls.getAnnotation(Module.class); if (mpMap.get(module) != null) { return; } List<Permission> permissionList = new ArrayList<>(); Method[] methods = cls.getDeclaredMethods(); if (methods == null || methods.length == 0) { //没有权限项配置 mpMap.put(module, permissionList); return; } for (Method method : methods) { if (!method.isAnnotationPresent(Permission.class)) { continue; } permissionList.add(method.getAnnotation(Permission.class)); } mpMap.put(module, permissionList); } /** * 扫描源码 * * @param mpMap * @throws URISyntaxException * @throws IOException */ public static void scanSecurity(Map<Module, List<Permission>> mpMap) throws URISyntaxException, IOException { ClassLoader classLoader = MethodHandles.lookup().lookupClass().getClassLoader(); //获取类加载器 URL[] urls = ((URLClassLoader) classLoader).getURLs(); //获取项目的所有文件路径URL if (urls == null || urls.length == 0) { //如果项目下文件路径为空则返回 return; } for (URL url : urls) { final Path path = Paths.get(url.toURI()); if (!path.toFile().isDirectory()) { continue; } //如果是目录则代表是我们自己写的代码,进行解析 Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { //正在访问一个文件时要干啥 String fileName = file.getFileName().toString(); if (!fileName.endsWith(".class") || fileName.contains("$")) { //$后面跟数字是匿名类编译出来的/$后面跟文字是内部类编译出来的 return FileVisitResult.CONTINUE; //继续遍历 } String classPathName = file.toUri().toString().split(path.toUri().toString())[1]; //class path name com/xyc/permission/web/AController.class String className = classPathName.substring(0, classPathName.lastIndexOf(".")).replace('/', '.'); //class name com.xyc.permission.web.AController try { SecurityHelper.analyseClassPathCode(mpMap, className); } catch (ClassNotFoundException e) { logger.error("解析权限异常", e); } return FileVisitResult.CONTINUE; //继续遍历 } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { //访问一个文件失败时要干啥 return FileVisitResult.CONTINUE; //继续遍历 } }); } } }
package com.gulimail.gulimail.coupon.service.impl; import org.springframework.stereotype.Service; import java.util.Map; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.gulimail.common.utils.PageUtils; import com.gulimail.common.utils.Query; import com.gulimail.gulimail.coupon.dao.MemberPriceDao; import com.gulimail.gulimail.coupon.entity.MemberPriceEntity; import com.gulimail.gulimail.coupon.service.MemberPriceService; @Service("memberPriceService") public class MemberPriceServiceImpl extends ServiceImpl<MemberPriceDao, MemberPriceEntity> implements MemberPriceService { @Override public PageUtils queryPage(Map<String, Object> params) { IPage<MemberPriceEntity> page = this.page( new Query<MemberPriceEntity>().getPage(params), new QueryWrapper<MemberPriceEntity>() ); return new PageUtils(page); } }
/* * 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.hive.serde2; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hive.serde2.AbstractSerDe; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.SerDeStats; import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.io.ByteBufWritable; import org.apache.hadoop.io.Writable; import org.apache.hive.serde2.objectinspector.ImmutableBinaryObjectInspector; import org.apache.util.TlvUtils; /** * 基于 Tlv 编码的 Hive 序列化器 */ public class TlvByteSerDe extends AbstractSerDe { public static final String TLV_COLUMNS = "tlvColumn.lengths"; private static final int LV_MARK = -1; private static final byte[] EMPTY_BYTES = new byte[0]; private List<Integer> vAndLvColumnLengths; private Map<Integer, Integer> tag2IndexMap; /** * 反序列化后,返回的值 */ private ImmutableBytesWritable[] rows; /** * 反序列化对象检查器 */ private StructObjectInspector soi; /** * 根据传入的参数,为Hive表的每个字段创建(反)序列化器 */ @Override public void initialize(Configuration configuration, Properties properties) throws SerDeException { String columnItermsStr = properties.getProperty(TLV_COLUMNS); vAndLvColumnLengths = new ArrayList<>(); tag2IndexMap = new HashMap<>(); final String[] columnIterms = columnItermsStr.split(","); for (int i = 0; i < columnIterms.length; i++) { String item = columnIterms[i]; if (item.startsWith("v")) { final int vLength = Integer.parseInt(item.substring(1)); vAndLvColumnLengths.add(vLength); } else if (item.equals("lv")) { vAndLvColumnLengths.add(LV_MARK); } else if (item.startsWith("tlv")) { final int tag = Integer.parseInt(item.substring(3)); tag2IndexMap.put(tag, i); } else if (item.equals("tail")) { // ignored } else { throw new IllegalArgumentException("" + "输入的参数只能是 v, lv, tlv 中的一个,而且 v 和 tlv 后面必须加一个数字:" + "对于 v,后面加的数字表示字节长度,对于 tlv,后面加的数字表示 tag 值。"); } } LazySimpleSerDe.SerDeParameters serDeParameters = LazySimpleSerDe.initSerdeParams( configuration, properties, this.getClass().getName()); final int totalLength = columnIterms.length; rows = new ImmutableBytesWritable[totalLength]; for (int i = 0; i < rows.length; i++) { rows[i] = new ImmutableBytesWritable(EMPTY_BYTES, 0, 0, false); } ObjectInspector[] ois = new ObjectInspector[totalLength]; // 这里所有字段都是可变数组类型 Arrays.fill(ois, ImmutableBinaryObjectInspector.ImmutableOI); soi = ObjectInspectorFactory.getStandardStructObjectInspector( serDeParameters.getColumnNames(), Arrays.asList(ois)); } @Override public Class<? extends Writable> getSerializedClass() { throw new IllegalStateException("Serialization is not supported at present"); } @Override public Writable serialize(Object o, ObjectInspector objectInspector) throws SerDeException { throw new SerDeException("Serialization is not supported at present"); } @Override public SerDeStats getSerDeStats() { return new SerDeStats(); } @Override public Object deserialize(Writable writable) { ByteBufWritable input = (ByteBufWritable) writable; byte[] bytes = input.getBuffer(); resetRows(); int pos; for (int i = 0; i < vAndLvColumnLengths.size(); i++) { pos = input.getReaderIndex(); ImmutableBytesWritable row = rows[i]; final Integer colLength = vAndLvColumnLengths.get(i); if (colLength.equals(LV_MARK)) { // 处理 LV final int valueOffset = TlvUtils.getLVValueOffset(bytes, pos); final int valueLength = TlvUtils.getLVValueLength(bytes, pos); row.set(bytes, valueOffset, valueLength); input.addReaderIndex(valueOffset - pos + valueLength); } else { // 处理 V row.set(bytes, pos, colLength); input.addReaderIndex(colLength); } } // 处理 tlv 字段 while (!input.isEnd()) { pos = input.getReaderIndex(); final int tag = TlvUtils.getTLVTag(bytes, pos); final int valueOffset = TlvUtils.getTLVValueOffset(bytes, pos); final int valueLength = TlvUtils.getTLVValueLength(bytes, pos); final Integer idx = tag2IndexMap.get(tag); if (idx != null) { rows[idx].set(bytes, valueOffset, valueLength); } input.addReaderIndex(valueOffset - pos + valueLength); } return rows; } @Override public ObjectInspector getObjectInspector() { return soi; } private void resetRows() { for (ImmutableBytesWritable row : rows) { row.set(EMPTY_BYTES, 0, 0); } } }
package com.ldb.dao; /** * @ProjectName: spring * @Package: com.ldb.dao * @ClassName: LdbDao * @Author: LJP * @Description: * @Date: 2019/8/15 22:28 * @Version: 1.0 */ public interface LdbDao { public void query(); }
package org.knowm.xchange.binance.dto.account; import com.fasterxml.jackson.annotation.JsonProperty; public class FutureTransferResponse { public final long tranId; public FutureTransferResponse(@JsonProperty("tranId") long tranId) { this.tranId = tranId; } public long getTranId() { return tranId; } }
package com.wangyizhuo.rfidindoorlocation; 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() throws Exception { assertEquals(4, 2 + 2); } }
package cn.enilu.flash.api.interceptor; import cn.enilu.flash.bean.entity.system.User; import cn.enilu.flash.bean.vo.SpringContextHolder; import cn.enilu.flash.security.JwtToken; import cn.enilu.flash.security.JwtUtil; import cn.enilu.flash.service.system.UserService; import cn.enilu.flash.utils.HttpUtil; import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author :enilu * @date :Created in 2019/7/30 23:07 */ public class JwtFilter extends BasicHttpAuthenticationFilter { private Logger logger = LoggerFactory.getLogger(getClass()); /** * 判断用户是否想要登入。 * 检测header里面是否包含Authorization字段即可 */ @Override protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) { HttpServletRequest req = (HttpServletRequest) request; String authorization = req.getHeader("Authorization"); return authorization != null; } /** * 登录验证 */ @Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String authorization = httpServletRequest.getHeader("Authorization"); JwtToken token = new JwtToken(authorization); // 提交给realm进行登入,如果错误他会抛出异常并被捕获 getSubject(request, response).login(token); // 如果没有抛出异常则代表登入成功,返回true return true; } @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { if (isLoginAttempt(request, response)) { try { return executeLogin(request, response); } catch (Exception e) { logger.info(e.getMessage()); //判断如果抛出token失效,则执行刷新token逻辑 if (e.getMessage().contains("expired")) { //获取用户信息 String oldToken = HttpUtil.getToken(); Long userId = JwtUtil.getUserId(oldToken); UserService userService = SpringContextHolder.getBean(UserService.class); User user = userService.get(userId); //验证refreshToken是否有效 if (userService.refreshTokenIsValid(oldToken)) { //生成新token 返回界面 String newToken = userService.loginForToken(user); JwtToken jwtToken = new JwtToken(newToken); this.getSubject(request, response).login(jwtToken); HttpUtil.getResponse().setHeader("token", newToken); return true; } } response401(request, response); return false; } } return false; } /** * 对跨域提供支持 */ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")); // 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态 if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) { httpServletResponse.setStatus(HttpStatus.OK.value()); return false; } return super.preHandle(request, response); } /** * 将非法请求返回httpcode:401 */ private void response401(ServletRequest req, ServletResponse resp) { try { HttpServletResponse httpServletResponse = (HttpServletResponse) resp; httpServletResponse.setStatus(401); // httpServletResponse.getWriter().println("401"); } catch (Exception e) { logger.error(e.getMessage(), e); } } /** * 重新该方法直接返回false,因为走到这个方法的请求都是因为401过来的,所以拒绝继续访问 * 如果不重写该方法,父类的方法回返回WWW-Authenticate 头信息导致浏览器自身弹出验证框,影响用户使用体验。本项目的业务要求前端自行判断401的话往登录页面跳转,不需要浏览器自己弹框。 * * @param request * @param response * @param mappedValue * @return * @throws Exception */ @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { return false; } }
/* * 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.asterix.translator; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.core.algebra.prettyprint.AlgebricksAppendable; public class SessionOutput { private final SessionConfig config; // Output path for primary execution. private final PrintWriter out; private StringWriter buffer; private PrintWriter bufferedOut; private final SessionOutput.ResultDecorator preResultDecorator; private final SessionOutput.ResultDecorator postResultDecorator; private final SessionOutput.ResultAppender handleAppender; private final SessionOutput.ResultAppender statusAppender; public SessionOutput(SessionConfig config, PrintWriter out) { this(config, out, null, null, null, null); } public SessionOutput(SessionConfig config, PrintWriter out, ResultDecorator preResultDecorator, ResultDecorator postResultDecorator, ResultAppender handleAppender, ResultAppender statusAppender) { this.config = config; this.out = out; this.preResultDecorator = preResultDecorator; this.postResultDecorator = postResultDecorator; this.handleAppender = handleAppender; this.statusAppender = statusAppender; } /** * Retrieve the PrintWriter to produce output to. */ public PrintWriter out() { return this.bufferedOut != null ? this.bufferedOut : this.out; } /** * buffer the data provided to the PrintWriter returned by out() to be able to set the status of the response * message when it can be determined. This is a no-op, if data is already buffered. */ public void hold() { if (this.bufferedOut == null) { this.buffer = new StringWriter(); this.bufferedOut = new PrintWriter(this.buffer); } } /** * release the data that was buffered by calling hold() and remove the buffer from the pipeline. * This is a no-op, if data is not buffered. */ public void release() { if (this.bufferedOut != null) { this.bufferedOut.flush(); this.out.write(buffer.toString()); this.bufferedOut = null; this.buffer = null; } } public AlgebricksAppendable resultPrefix(AlgebricksAppendable app) throws AlgebricksException { return this.preResultDecorator != null ? this.preResultDecorator.append(app) : app; } public AlgebricksAppendable resultPostfix(AlgebricksAppendable app) throws AlgebricksException { return this.postResultDecorator != null ? this.postResultDecorator.append(app) : app; } public AlgebricksAppendable appendHandle(AlgebricksAppendable app, String handle) throws AlgebricksException { return this.handleAppender != null ? this.handleAppender.append(app, handle) : app; } public AlgebricksAppendable appendStatus(AlgebricksAppendable app, String status) throws AlgebricksException { return this.statusAppender != null ? this.statusAppender.append(app, status) : app; } public SessionConfig config() { return config; } @FunctionalInterface public interface ResultDecorator { AlgebricksAppendable append(AlgebricksAppendable app) throws AlgebricksException; } @FunctionalInterface public interface ResultAppender { AlgebricksAppendable append(AlgebricksAppendable app, String str) throws AlgebricksException; } }
// PROGRAM-NAME : Multiply two Numbers // By Spenser Daniel // PROGRAM-CODE : class multitwo { public void main() { int a=5; int b=13; int prod=a*b; System.out.println("Product of two numbers="+prod); } }
/** * 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.heron.spi.utils; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.fail; public class UploaderUtilsTest { @Test public void testGenerateFilename() throws Exception { int expectedUniqueFilename = 10000; String topologyName = "topologyName"; String role = "role"; String tag = ""; int version = -1; Set<String> filenames = new HashSet<>(); for (int i = 0; i < expectedUniqueFilename; i++) { filenames.add(UploaderUtils.generateFilename( topologyName, role, tag, version, "")); } // All filenames should be unique Assert.assertEquals(expectedUniqueFilename, filenames.size()); } @Test public void testFilenameFormat() throws Exception { String topologyName = "topologyName"; String role = "role"; String filename = UploaderUtils.generateFilename(topologyName, role); Assert.assertTrue(filename.endsWith(UploaderUtils.DEFAULT_FILENAME_EXTENSION)); String tag = ""; int version = -1; String extension = ".extension"; String customizedFilename = UploaderUtils.generateFilename(topologyName, role, tag, version, extension); Assert.assertTrue(customizedFilename.endsWith(extension)); } @Test public void testCopyToOutputStream() throws Exception { String fileContent = "temp file test content"; String prefix = "myTestFile"; String suffix = ".tmp"; File tempFile = null; try { // create temp file tempFile = File.createTempFile(prefix, suffix); // write content to temp file writeContentToFile(tempFile.getAbsolutePath(), fileContent); // copy file content to output stream ByteArrayOutputStream out = new ByteArrayOutputStream(); UploaderUtils.copyToOutputStream(tempFile.getAbsolutePath(), out); Assert.assertEquals(fileContent, new String(out.toByteArray())); } finally { if (tempFile != null) { tempFile.deleteOnExit(); } } } @Test(expected = FileNotFoundException.class) public void testCopyToOutputStreamWithInvalidFile() throws Exception { UploaderUtils.copyToOutputStream("invalid_file_name", new ByteArrayOutputStream()); } private void writeContentToFile(String fileName, String content) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) { bw.write(content); } catch (IOException e) { fail("Unexpected IOException has been thrown so unit test fails. Error message: " + e.getMessage()); } } }
package com.ryanst.app.activity.launchMode; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.widget.Button; import com.ryanst.app.R; import com.ryanst.app.core.BaseActivity; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by zhengjuntong on 1/4/17. */ public class LaunchModeActivity extends BaseActivity { @BindView(R.id.btn_simple) Button btnSimple; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_button); ButterKnife.bind(this); btnSimple.setText("前往B"); toast("A"); } public void onClick(View view) { startActivity(new Intent(this, LaunchModeActivity2.class)); } }
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package blood0cean.com.github.office.schedule.service; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.jsonwebservice.JSONWebService; import com.liferay.portal.kernel.security.access.control.AccessControlled; import com.liferay.portal.kernel.service.BaseService; import com.liferay.portal.kernel.transaction.Isolation; import com.liferay.portal.kernel.transaction.Transactional; import org.osgi.annotation.versioning.ProviderType; /** * Provides the remote service interface for OfficeSchedule. Methods of this * service are expected to have security checks based on the propagated JAAS * credentials because this service can be accessed remotely. * * @author Blood 0cean * @see OfficeScheduleServiceUtil * @generated */ @AccessControlled @JSONWebService @ProviderType @Transactional( isolation = Isolation.PORTAL, rollbackFor = {PortalException.class, SystemException.class} ) public interface OfficeScheduleService extends BaseService { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this interface directly. Always use {@link OfficeScheduleServiceUtil} to access the office schedule remote service. Add custom service methods to <code>blood0cean.com.github.office.schedule.service.impl.OfficeScheduleServiceImpl</code> and rerun ServiceBuilder to automatically copy the method declarations to this interface. */ /** * Returns the OSGi service identifier. * * @return the OSGi service identifier */ public String getOSGiServiceIdentifier(); }
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.deployer.admin.server.config.security.support; import java.net.URI; import javax.validation.constraints.NotNull; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties for the Ldap security aspects of an application. * * @author Gunnar Hillert * @since 1.1.0 */ @ConfigurationProperties(prefix = "dataflow.security.authentication.ldap") @LdapSecurityPropertiesValid public class LdapSecurityProperties { @NotNull(message="Provide a valid url to your Ldap server") private URI url; private String userDnPattern; private String managerDn; private String managerPassword; private String userSearchBase = ""; private String userSearchFilter; private String groupSearchFilter = ""; private String groupSearchBase = ""; private String groupRoleAttribute = "cn"; public URI getUrl() { return url; } public void setUrl(URI url) { this.url = url; } public String getUserDnPattern() { return userDnPattern; } public void setUserDnPattern(String userDnPattern) { this.userDnPattern = userDnPattern; } public String getManagerDn() { return managerDn; } public void setManagerDn(String managerDn) { this.managerDn = managerDn; } public String getManagerPassword() { return managerPassword; } public void setManagerPassword(String managerPassword) { this.managerPassword = managerPassword; } public String getUserSearchBase() { return userSearchBase; } public void setUserSearchBase(String userSearchBase) { this.userSearchBase = userSearchBase; } public String getUserSearchFilter() { return userSearchFilter; } public void setUserSearchFilter(String userSearchFilter) { this.userSearchFilter = userSearchFilter; } public String getGroupSearchFilter() { return groupSearchFilter; } public void setGroupSearchFilter(String groupSearchFilter) { this.groupSearchFilter = groupSearchFilter; } public String getGroupSearchBase() { return groupSearchBase; } public void setGroupSearchBase(String groupSearchBase) { this.groupSearchBase = groupSearchBase; } public String getGroupRoleAttribute() { return groupRoleAttribute; } public void setGroupRoleAttribute(String groupRoleAttribute) { this.groupRoleAttribute = groupRoleAttribute; } }
package io.fabric8.certmanager.api.model.v1alpha3; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.ContainerPort; import io.fabric8.kubernetes.api.model.EnvVar; import io.fabric8.kubernetes.api.model.IntOrString; import io.fabric8.kubernetes.api.model.KubernetesResource; import io.fabric8.kubernetes.api.model.LabelSelector; import io.fabric8.kubernetes.api.model.LocalObjectReference; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.ObjectReference; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.PodTemplateSpec; import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.fabric8.kubernetes.api.model.Volume; import io.fabric8.kubernetes.api.model.VolumeMount; import io.sundr.builder.annotations.Buildable; import io.sundr.builder.annotations.BuildableReference; import lombok.EqualsAndHashCode; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; @JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "apiVersion", "kind", "metadata", "jks", "pkcs12" }) @ToString @EqualsAndHashCode @Setter @Accessors(prefix = { "_", "" }) @Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = { @BuildableReference(ObjectMeta.class), @BuildableReference(LabelSelector.class), @BuildableReference(Container.class), @BuildableReference(PodTemplateSpec.class), @BuildableReference(ResourceRequirements.class), @BuildableReference(IntOrString.class), @BuildableReference(ObjectReference.class), @BuildableReference(LocalObjectReference.class), @BuildableReference(PersistentVolumeClaim.class), @BuildableReference(EnvVar.class), @BuildableReference(ContainerPort.class), @BuildableReference(Volume.class), @BuildableReference(VolumeMount.class) }) public class CertificateKeystores implements KubernetesResource { @JsonProperty("jks") private JKSKeystore jks; @JsonProperty("pkcs12") private PKCS12Keystore pkcs12; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * No args constructor for use in serialization * */ public CertificateKeystores() { } /** * * @param jks * @param pkcs12 */ public CertificateKeystores(JKSKeystore jks, PKCS12Keystore pkcs12) { super(); this.jks = jks; this.pkcs12 = pkcs12; } @JsonProperty("jks") public JKSKeystore getJks() { return jks; } @JsonProperty("jks") public void setJks(JKSKeystore jks) { this.jks = jks; } @JsonProperty("pkcs12") public PKCS12Keystore getPkcs12() { return pkcs12; } @JsonProperty("pkcs12") public void setPkcs12(PKCS12Keystore pkcs12) { this.pkcs12 = pkcs12; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
/** * 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 net.java.html.json.sub; import net.java.html.json.Model; import net.java.html.json.Property; @Model(className = "Street", properties = { @Property(name = "name", type = String.class), @Property(name = "id", type = int.class), }) class StreetCntrl { }
package org.cache2k.core; /* * #%L * cache2k initialization tests * %% * Copyright (C) 2000 - 2019 headissue GmbH, Munich * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.cache2k.Cache; import org.cache2k.Cache2kBuilder; import org.cache2k.CacheManager; import static org.junit.Assert.*; import org.junit.Test; /** * @author Jens Wilke */ public class CacheManagerInitTest { public static final String OTHER_DEFAULT_CACHE_MANAGER_NAME = "main"; static { CacheManager.setDefaultName(OTHER_DEFAULT_CACHE_MANAGER_NAME); } @Test public void differentCacheManagerName() { assertEquals(CacheManager.getInstance().getName(), OTHER_DEFAULT_CACHE_MANAGER_NAME); assertNotEquals(OTHER_DEFAULT_CACHE_MANAGER_NAME, CacheManager.STANDARD_DEFAULT_MANAGER_NAME); } /** * After the cache manager is closed, creating a cache, will create a new cache manager. */ @Test public void closeAll() { CacheManager cm1 = CacheManager.getInstance(); CacheManager.closeAll(); Cache c = Cache2kBuilder.forUnknownTypes().name("xy").build(); assertNotSame(cm1, c.getCacheManager()); c.close(); } }
package com.kbd.cockfit; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecipePostFragment extends Fragment { private FirebaseAuth mAuth; private DatabaseReference mDatabase; private String forumType; private String postId; private String recipeId; private String writerUid; private HashMap<String, String> likeUidMap; private String title; private ImageView imageView_picture; private TextView textView_recipeName; private TextView textView_tags; private TextView textView_proof; private TextView textView_base; private TextView textView_ingredient; private TextView textView_equipment; private TextView textView_description; private Button button_like; private Button button_bookmark; private Drawable drawable_alreadyLike; private Drawable drawable_waitLike; private Drawable drawable_alreadyBookmark; private Drawable drawable_waitBookmark; private ProgressBar progressBar; private LinearLayout linearLayout; private RecyclerView recycler_comments; private CommentAdapter commentAdapter; private ArrayList<Comment> commentArrayList; private Post post; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_recipe_post, container, false); //firebase initialize mAuth = FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance("https://cock-fit-ebaa7-default-rtdb.asia-southeast1.firebasedatabase.app").getReference(); //getBundle Bundle bundle = getArguments(); forumType = bundle.getString("forumType"); postId = bundle.getString("postId"); recipeId = bundle.getString("recipeId"); writerUid = bundle.getString("writerUid"); post = bundle.getParcelable("post"); //view initialize imageView_picture = v.findViewById(R.id.share_imageView_picture); textView_recipeName = v.findViewById(R.id.share_textView_recipeName); textView_tags = v.findViewById(R.id.share_textView_tag); textView_proof = v.findViewById(R.id.share_textView_proof); textView_base = v.findViewById(R.id.share_textView_base); textView_ingredient = v.findViewById(R.id.share_textView_ingredient); textView_equipment = v.findViewById(R.id.share_textView_equipment); textView_description = v.findViewById(R.id.share_textView_description); button_like = v.findViewById(R.id.share_button_like); button_bookmark = v.findViewById(R.id.share_button_bookmark); progressBar = v.findViewById(R.id.share_progressBar); linearLayout = v.findViewById(R.id.share_linearLayout); drawable_alreadyLike = getResources().getDrawable(R.drawable.ic_baseline_thumb_up_24, getActivity().getTheme()); drawable_waitLike = getResources().getDrawable(R.drawable.ic_outline_thumb_up_24, getActivity().getTheme()); drawable_alreadyBookmark = getResources().getDrawable(R.drawable.ic_baseline_bookmark_true_24, getActivity().getTheme()); drawable_waitBookmark = getResources().getDrawable(R.drawable.ic_baseline_bookmark_false_24, getActivity().getTheme()); // recycler_comments = v.findViewById(R.id.share_recyclerView_comments); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getContext(), LinearLayoutManager.VERTICAL, false) { @Override public boolean canScrollVertically() { return false; } }; recycler_comments.setLayoutManager(linearLayoutManager); commentArrayList = new ArrayList<>(); commentAdapter = new CommentAdapter(commentArrayList); recycler_comments.setAdapter(commentAdapter); mDatabase.child("forum").child(forumType).child(postId).child("likeUidMap").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { likeUidMap = (HashMap<String, String>) snapshot.getValue(); int likeCount = (int) snapshot.getChildrenCount(); if(likeUidMap != null) { button_like.setText(String.valueOf(likeCount)); if(likeUidMap.containsKey(mAuth.getUid())) { button_like.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable_alreadyLike, null, null, null); button_like.setOnClickListener(new UnLikeListener()); } else { button_like.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable_waitLike, null, null, null); button_like.setOnClickListener(new LikeListener()); } } else { button_like.setText("0"); button_like.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable_waitLike, null, null, null); button_like.setOnClickListener(new LikeListener()); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); mDatabase.child("user").child(mAuth.getUid()).child("bookmarkedPost").child(postId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String checkText = snapshot.getValue(String.class); if(checkText != null) { button_bookmark.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable_alreadyBookmark, null, null, null); button_bookmark.setOnClickListener(new UnBookmarkListener()); } else { button_bookmark.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable_waitBookmark, null, null, null); button_bookmark.setOnClickListener(new BookmarkListener()); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); mDatabase.child("forum").child(forumType).child(postId).child("comments").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { progressBar.setVisibility(View.VISIBLE); linearLayout.setVisibility(View.INVISIBLE); commentArrayList.clear(); for(DataSnapshot commentSnapshot : snapshot.getChildren()) { Comment comment = commentSnapshot.getValue(Comment.class); comment.setCommentId(commentSnapshot.getKey()); commentArrayList.add(comment); } commentAdapter.notifyDataSetChanged(); if(commentArrayList.size() == 0) { progressBar.setVisibility(View.GONE); linearLayout.setVisibility(View.VISIBLE); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); // StorageReference mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://cock-fit-ebaa7.appspot.com"); mStorage.child("Users").child(writerUid).child("CocktailImage").child(recipeId + ".jpg").getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { Glide.with(v) .load(task.getResult()) .into(imageView_picture); } }); mDatabase.child("user").child(writerUid).child("MyRecipe").child(recipeId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { MyRecipe recipe = snapshot.getValue(MyRecipe.class); if(recipe == null) { return; } textView_recipeName.setText(recipe.getName()); List<String> list = recipe.getTags(); String totalText = ""; for (String tag : list) { totalText += tag + " "; } textView_tags.setText(totalText); textView_proof.setText(recipe.getProof()); textView_base.setText(recipe.getBase()); list = recipe.getIngredient(); totalText = ""; for (String ingredient : list) { totalText += ingredient + " "; } textView_ingredient.setText(totalText); list = recipe.getEquipment(); totalText = ""; for (String equipment : list) { totalText += equipment + " "; } textView_equipment.setText(totalText); textView_description.setText(recipe.getDescription()); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); return v; } private class LikeListener implements View.OnClickListener { @Override public void onClick(View v) { Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(mAuth.getUid(), mAuth.getCurrentUser().getDisplayName()); mDatabase.child("forum").child(forumType).child(postId).child("likeUidMap").updateChildren(childUpdates); } } private class UnLikeListener implements View.OnClickListener { @Override public void onClick(View v) { mDatabase.child("forum").child(forumType).child(postId).child("likeUidMap").child(mAuth.getUid()).removeValue(); } } private class BookmarkListener implements View.OnClickListener { @Override public void onClick(View v) { mDatabase.child("user").child(mAuth.getUid()).child("bookmarkedPost").child(postId).setValue("true"); Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put(mAuth.getUid(), mAuth.getCurrentUser().getDisplayName()); mDatabase.child("forum").child(forumType).child(postId).child("bookmarkUidMap").updateChildren(childUpdates); } } private class UnBookmarkListener implements View.OnClickListener { @Override public void onClick(View v) { mDatabase.child("user").child(mAuth.getUid()).child("bookmarkedPost").child(postId).removeValue(); mDatabase.child("forum").child(forumType).child(postId).child("bookmarkUidMap").child(mAuth.getUid()).removeValue(); } } private class ReplyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private ArrayList<Comment> replyArrayList; private String parentCommentId; ReplyAdapter(ArrayList<Comment> replyArrayList, String parentCommentId) { this.replyArrayList = replyArrayList; this.parentCommentId = parentCommentId; Log.d("test", "?"); Log.d("test", String.valueOf(replyArrayList.size())); for(Comment reply : replyArrayList) { Log.d("test", reply.getCommentId()); } } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reply_item_layout, parent, false); ReplyViewHolder replyViewHolder = new ReplyViewHolder(view); replyViewHolder.imageButton_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext()); View dialogView = View.inflate(getContext(), R.layout.comment_dialog_layout, null); Button button_delete = dialogView.findViewById(R.id.commentDialog_button_delete); Button button_edit = dialogView.findViewById(R.id.commentDialog_button_edit); dialogBuilder.setView(dialogView); AlertDialog alertDialog = dialogBuilder.create(); button_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Comment comment = replyArrayList.get(replyViewHolder.getAdapterPosition()); Log.d("test", comment.getCommentId()); mDatabase.child("forum").child(forumType).child(postId).child("comments").child(parentCommentId).child("replys").child(comment.getCommentId()).removeValue(); alertDialog.dismiss(); } }); button_edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); alertDialog.show(); } }); return replyViewHolder; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { ReplyViewHolder replyViewHolder = (ReplyViewHolder) holder; Comment comment = replyArrayList.get(holder.getAdapterPosition()); Log.d("test", "bindsize : " + replyArrayList.size()); if(!comment.getUid().equals(mAuth.getUid())) { replyViewHolder.imageButton_more.setVisibility(View.INVISIBLE); } StorageReference mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://cock-fit-ebaa7.appspot.com"); mStorage.child("Users").child(comment.getUid()).child("profileImage.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { //프로필 사진이 있는 댓글사용자 Glide.with(getContext()) .load(uri) .into(replyViewHolder.imageView_profile); if(holder.getAdapterPosition() == getItemCount() - 1) { progressBar.setVisibility(View.GONE); linearLayout.setVisibility(View.VISIBLE); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { //프로필 사진이 없는 댓글사용자 progressBar.setVisibility(View.GONE); linearLayout.setVisibility(View.VISIBLE); } }); replyViewHolder.textView_nickname.setText(comment.getNickname()); replyViewHolder.textView_text.setText(comment.getText()); try { replyViewHolder.textView_date.setText(UtilitySet.formatTimeString(comment.getDate())); } catch (ParseException e) { e.printStackTrace(); } if(comment.getLikeUidMap() != null) { replyViewHolder.textView_likeCount.setText(comment.getLikeUidMap().size()); } else { replyViewHolder.textView_likeCount.setText("0"); } } @Override public int getItemCount() { return this.replyArrayList.size(); } private class ReplyViewHolder extends RecyclerView.ViewHolder { protected ImageView imageView_profile; protected TextView textView_nickname; protected TextView textView_text; protected TextView textView_date; protected TextView textView_likeCount; //protected ImageButton imageButton_reply; //protected ImageButton imageButton_like; protected ImageButton imageButton_more; //protected RecyclerView recyclerView_reply; public ReplyViewHolder(@NonNull View itemView) { super(itemView); imageView_profile = itemView.findViewById(R.id.reply_imageView_profile); textView_nickname = itemView.findViewById(R.id.reply_textView_nickname); textView_text = itemView.findViewById(R.id.reply_textView_text); textView_date = itemView.findViewById(R.id.reply_textView_date); textView_likeCount = itemView.findViewById(R.id.reply_textView_likeCount); imageButton_more = itemView.findViewById(R.id.reply_imageButton_more); } } } private class CommentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private ArrayList<Comment> commentArrayList; CommentAdapter(ArrayList<Comment> commentArrayList) { this.commentArrayList = commentArrayList; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item_layout, parent, false); CommentAdapter.CommentViewHolder commentViewHolder = new CommentAdapter.CommentViewHolder(view); commentViewHolder.imageButton_reply.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext()); View dialogView = View.inflate(getContext(), R.layout.reply_dialog_layout, null); Button button_write = dialogView.findViewById(R.id.reply_dialog_button_write); EditText editText_reply = dialogView.findViewById(R.id.reply_dialog_editText_reply); dialogBuilder.setView(dialogView); AlertDialog alertDialog = dialogBuilder.create(); button_write.setOnClickListener(new UtilitySet.OnSingleClickListener() { @Override public void onSingleClick(View v) { String text = editText_reply.getText().toString(); if(text.trim().equals("")) { Toast.makeText(getContext(), "내용을 입력해주세요.", Toast.LENGTH_SHORT).show(); } Comment comment = commentArrayList.get(commentViewHolder.getAdapterPosition()); String nickname = mAuth.getCurrentUser().getDisplayName(); String uid = mAuth.getUid(); String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())); Comment reply = new Comment(text, nickname, uid, date); String type = "새로운 대댓글이 달렸습니다."; mDatabase.child("forum").child(forumType).child(postId).child("title").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String value = snapshot.getValue(String.class); title = value; Notify notify = new Notify(title, text, type, date, uid); //대댓글을 남긴 댓글의 작성자의 DB에 대댓글 남겼음을 추가 mDatabase.child("forum").child(forumType).child(postId).child("comments").child(comment.getCommentId()).child("uid").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String value = dataSnapshot.getValue(String.class); mDatabase.child("user").child(value).child("notify").push().setValue(notify); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { //Log.e("MainActivity", String.valueOf(databaseError.toException())); // 에러문 출력 } }); } @Override public void onCancelled(@NonNull DatabaseError error) { //Log.e("MainActivity", String.valueOf(databaseError.toException())); // 에러문 출력 } }); mDatabase.child("forum").child(forumType).child(postId).child("comments").child(comment.getCommentId()).child("replys").push().setValue(reply); alertDialog.dismiss(); } }); alertDialog.show(); } }); commentViewHolder.imageButton_like.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); commentViewHolder.imageButton_more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext()); View dialogView = View.inflate(getContext(), R.layout.comment_dialog_layout, null); Button button_delete = dialogView.findViewById(R.id.commentDialog_button_delete); Button button_edit = dialogView.findViewById(R.id.commentDialog_button_edit); dialogBuilder.setView(dialogView); AlertDialog alertDialog = dialogBuilder.create(); button_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Comment comment = commentArrayList.get(commentViewHolder.getAdapterPosition()); mDatabase.child("forum").child(forumType).child(postId).child("comments").child(comment.getCommentId()).removeValue(); alertDialog.dismiss(); } }); button_edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); alertDialog.show(); } }); return commentViewHolder; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { CommentAdapter.CommentViewHolder commentViewHolder = (CommentAdapter.CommentViewHolder) holder; Comment comment = commentArrayList.get(holder.getAdapterPosition()); if(!comment.getUid().equals(mAuth.getUid())) { commentViewHolder.imageButton_more.setVisibility(View.INVISIBLE); } ArrayList<Comment> replyArrayList = new ArrayList<>(); ReplyAdapter replyAdapter = new ReplyAdapter(replyArrayList, comment.getCommentId()); ((CommentViewHolder) holder).recyclerView_reply.setAdapter(replyAdapter); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false) { @Override public boolean canScrollVertically() { return false; } }; ((CommentViewHolder) holder).recyclerView_reply.setLayoutManager(linearLayoutManager); mDatabase.child("forum").child(forumType).child(postId).child("comments").child(comment.getCommentId()).child("replys").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot replySnapshot : snapshot.getChildren()) { Comment reply = replySnapshot.getValue(Comment.class); reply.setCommentId(replySnapshot.getKey()); replyArrayList.add(reply); } replyAdapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); StorageReference mStorage = FirebaseStorage.getInstance().getReferenceFromUrl("gs://cock-fit-ebaa7.appspot.com"); mStorage.child("Users").child(comment.getUid()).child("profileImage.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri uri) { //프로필 사진이 있는 댓글사용자 Glide.with(getContext()) .load(uri) .into(commentViewHolder.imageView_profile); if(holder.getAdapterPosition() == getItemCount() - 1) { progressBar.setVisibility(View.GONE); linearLayout.setVisibility(View.VISIBLE); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { //프로필 사진이 없는 댓글사용자 progressBar.setVisibility(View.GONE); linearLayout.setVisibility(View.VISIBLE); } }); commentViewHolder.textView_nickname.setText(comment.getNickname()); commentViewHolder.textView_text.setText(comment.getText()); try { commentViewHolder.textView_date.setText(UtilitySet.formatTimeString(comment.getDate())); } catch (ParseException e) { e.printStackTrace(); } if(comment.getLikeUidMap() != null) { commentViewHolder.textView_likeCount.setText(comment.getLikeUidMap().size()); } else { commentViewHolder.textView_likeCount.setText("0"); } } @Override public int getItemCount() { return commentArrayList.size(); } private class CommentViewHolder extends RecyclerView.ViewHolder { protected ImageView imageView_profile; protected TextView textView_nickname; protected TextView textView_text; protected TextView textView_date; protected TextView textView_likeCount; protected ImageButton imageButton_reply; protected ImageButton imageButton_like; protected ImageButton imageButton_more; protected RecyclerView recyclerView_reply; public CommentViewHolder(@NonNull View itemView) { super(itemView); imageView_profile = itemView.findViewById(R.id.comment_imageView_profile); textView_nickname = itemView.findViewById(R.id.comment_textView_nickname); textView_text = itemView.findViewById(R.id.comment_textView_text); textView_date = itemView.findViewById(R.id.comment_textView_date); textView_likeCount = itemView.findViewById(R.id.comment_textView_likeCount); imageButton_reply = itemView.findViewById(R.id.comment_imageButton_reply); imageButton_like = itemView.findViewById(R.id.comment_imageButton_like); imageButton_more = itemView.findViewById(R.id.comment_imageButton_more); recyclerView_reply = itemView.findViewById(R.id.comment_recycler_reply); } } } }
/* * Copyright 2002-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.springframework.test.context.junit4; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Ignore; import org.junit.Test; import org.junit.internal.runners.model.ReflectiveCallable; import org.junit.internal.runners.statements.ExpectException; import org.junit.internal.runners.statements.Fail; import org.junit.internal.runners.statements.FailOnTimeout; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.springframework.lang.Nullable; import org.springframework.test.annotation.ProfileValueUtils; import org.springframework.test.annotation.TestAnnotationUtils; import org.springframework.test.context.TestContextManager; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; import org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks; import org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks; import org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks; import org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks; import org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks; import org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks; import org.springframework.test.context.junit4.statements.SpringFailOnTimeout; import org.springframework.test.context.junit4.statements.SpringRepeat; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** * {@code SpringJUnit4ClassRunner} is a custom extension of JUnit's * {@link BlockJUnit4ClassRunner} which provides functionality of the * <em>Spring TestContext Framework</em> to standard JUnit tests by means of the * {@link TestContextManager} and associated support classes and annotations. * * <p>To use this class, simply annotate a JUnit 4 based test class with * {@code @RunWith(SpringJUnit4ClassRunner.class)} or {@code @RunWith(SpringRunner.class)}. * * <p>The following list constitutes all annotations currently supported directly * or indirectly by {@code SpringJUnit4ClassRunner}. <em>(Note that additional * annotations may be supported by various * {@link org.springframework.test.context.TestExecutionListener TestExecutionListener} * or {@link org.springframework.test.context.TestContextBootstrapper TestContextBootstrapper} * implementations.)</em> * * <ul> * <li>{@link Test#expected() @Test(expected=...)}</li> * <li>{@link Test#timeout() @Test(timeout=...)}</li> * <li>{@link org.springframework.test.annotation.Timed @Timed}</li> * <li>{@link org.springframework.test.annotation.Repeat @Repeat}</li> * <li>{@link Ignore @Ignore}</li> * <li>{@link org.springframework.test.annotation.ProfileValueSourceConfiguration @ProfileValueSourceConfiguration}</li> * <li>{@link org.springframework.test.annotation.IfProfileValue @IfProfileValue}</li> * </ul> * * <p>If you would like to use the Spring TestContext Framework with a runner * other than this one, use {@link SpringClassRule} and {@link SpringMethodRule}. * * <p><strong>NOTE:</strong> As of Spring Framework 4.3, this class requires JUnit 4.12 or higher. * * @author Sam Brannen * @author Juergen Hoeller * @since 2.5 * @see SpringRunner * @see TestContextManager * @see AbstractJUnit4SpringContextTests * @see AbstractTransactionalJUnit4SpringContextTests * @see org.springframework.test.context.junit4.rules.SpringClassRule * @see org.springframework.test.context.junit4.rules.SpringMethodRule */ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner { private static final Log logger = LogFactory.getLog(SpringJUnit4ClassRunner.class); private static final Method withRulesMethod; static { Assert.state(ClassUtils.isPresent("org.junit.internal.Throwables", SpringJUnit4ClassRunner.class.getClassLoader()), "SpringJUnit4ClassRunner requires JUnit 4.12 or higher."); Method method = ReflectionUtils.findMethod(SpringJUnit4ClassRunner.class, "withRules", FrameworkMethod.class, Object.class, Statement.class); Assert.state(method != null, "SpringJUnit4ClassRunner requires JUnit 4.12 or higher"); ReflectionUtils.makeAccessible(method); withRulesMethod = method; } private final TestContextManager testContextManager; private static void ensureSpringRulesAreNotPresent(Class<?> testClass) { for (Field field : testClass.getFields()) { Assert.state(!SpringClassRule.class.isAssignableFrom(field.getType()), () -> String.format( "Detected SpringClassRule field in test class [%s], " + "but SpringClassRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName())); Assert.state(!SpringMethodRule.class.isAssignableFrom(field.getType()), () -> String.format( "Detected SpringMethodRule field in test class [%s], " + "but SpringMethodRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName())); } } /** * Construct a new {@code SpringJUnit4ClassRunner} and initialize a * {@link TestContextManager} to provide Spring testing functionality to * standard JUnit tests. * @param clazz the test class to be run * @see #createTestContextManager(Class) */ public SpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError { super(clazz); if (logger.isDebugEnabled()) { logger.debug("SpringJUnit4ClassRunner constructor called with [" + clazz + "]"); } ensureSpringRulesAreNotPresent(clazz); this.testContextManager = createTestContextManager(clazz); } /** * Create a new {@link TestContextManager} for the supplied test class. * <p>Can be overridden by subclasses. * @param clazz the test class to be managed */ protected TestContextManager createTestContextManager(Class<?> clazz) { return new TestContextManager(clazz); } /** * Get the {@link TestContextManager} associated with this runner. */ protected final TestContextManager getTestContextManager() { return this.testContextManager; } /** * Return a description suitable for an ignored test class if the test is * disabled via {@code @IfProfileValue} at the class-level, and * otherwise delegate to the parent implementation. * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Class) */ @Override public Description getDescription() { if (!ProfileValueUtils.isTestEnabledInThisEnvironment(getTestClass().getJavaClass())) { return Description.createSuiteDescription(getTestClass().getJavaClass()); } return super.getDescription(); } /** * Check whether the test is enabled in the current execution environment. * <p>This prevents classes with a non-matching {@code @IfProfileValue} * annotation from running altogether, even skipping the execution of * {@code prepareTestInstance()} methods in {@code TestExecutionListeners}. * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Class) * @see org.springframework.test.annotation.IfProfileValue * @see org.springframework.test.context.TestExecutionListener */ @Override public void run(RunNotifier notifier) { if (!ProfileValueUtils.isTestEnabledInThisEnvironment(getTestClass().getJavaClass())) { notifier.fireTestIgnored(getDescription()); return; } super.run(notifier); } /** * Wrap the {@link Statement} returned by the parent implementation with a * {@code RunBeforeTestClassCallbacks} statement, thus preserving the * default JUnit functionality while adding support for the Spring TestContext * Framework. * @see RunBeforeTestClassCallbacks */ @Override protected Statement withBeforeClasses(Statement statement) { Statement junitBeforeClasses = super.withBeforeClasses(statement); return new RunBeforeTestClassCallbacks(junitBeforeClasses, getTestContextManager()); } /** * Wrap the {@link Statement} returned by the parent implementation with a * {@code RunAfterTestClassCallbacks} statement, thus preserving the default * JUnit functionality while adding support for the Spring TestContext Framework. * @see RunAfterTestClassCallbacks */ @Override protected Statement withAfterClasses(Statement statement) { Statement junitAfterClasses = super.withAfterClasses(statement); return new RunAfterTestClassCallbacks(junitAfterClasses, getTestContextManager()); } /** * Delegate to the parent implementation for creating the test instance and * then allow the {@link #getTestContextManager() TestContextManager} to * prepare the test instance before returning it. * @see TestContextManager#prepareTestInstance */ @Override protected Object createTest() throws Exception { Object testInstance = super.createTest(); getTestContextManager().prepareTestInstance(testInstance); return testInstance; } /** * Perform the same logic as * {@link BlockJUnit4ClassRunner#runChild(FrameworkMethod, RunNotifier)}, * except that tests are determined to be <em>ignored</em> by * {@link #isTestMethodIgnored(FrameworkMethod)}. */ @Override protected void runChild(FrameworkMethod frameworkMethod, RunNotifier notifier) { Description description = describeChild(frameworkMethod); if (isTestMethodIgnored(frameworkMethod)) { notifier.fireTestIgnored(description); } else { Statement statement; try { statement = methodBlock(frameworkMethod); } catch (Throwable ex) { statement = new Fail(ex); } runLeaf(statement, description, notifier); } } /** * Augment the default JUnit behavior * {@linkplain #withPotentialRepeat with potential repeats} of the entire * execution chain. * <p>Furthermore, support for timeouts has been moved down the execution * chain in order to include execution of {@link org.junit.Before @Before} * and {@link org.junit.After @After} methods within the timed execution. * Note that this differs from the default JUnit behavior of executing * {@code @Before} and {@code @After} methods in the main thread while * executing the actual test method in a separate thread. Thus, the net * effect is that {@code @Before} and {@code @After} methods will be * executed in the same thread as the test method. As a consequence, * JUnit-specified timeouts will work fine in combination with Spring * transactions. However, JUnit-specific timeouts still differ from * Spring-specific timeouts in that the former execute in a separate * thread while the latter simply execute in the main thread (like regular * tests). * @see #methodInvoker(FrameworkMethod, Object) * @see #withBeforeTestExecutionCallbacks(FrameworkMethod, Object, Statement) * @see #withAfterTestExecutionCallbacks(FrameworkMethod, Object, Statement) * @see #possiblyExpectingExceptions(FrameworkMethod, Object, Statement) * @see #withBefores(FrameworkMethod, Object, Statement) * @see #withAfters(FrameworkMethod, Object, Statement) * @see #withRulesReflectively(FrameworkMethod, Object, Statement) * @see #withPotentialRepeat(FrameworkMethod, Object, Statement) * @see #withPotentialTimeout(FrameworkMethod, Object, Statement) */ @Override protected Statement methodBlock(FrameworkMethod frameworkMethod) { Object testInstance; try { testInstance = new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return createTest(); } }.run(); } catch (Throwable ex) { return new Fail(ex); } Statement statement = methodInvoker(frameworkMethod, testInstance); statement = withBeforeTestExecutionCallbacks(frameworkMethod, testInstance, statement); statement = withAfterTestExecutionCallbacks(frameworkMethod, testInstance, statement); statement = possiblyExpectingExceptions(frameworkMethod, testInstance, statement); statement = withBefores(frameworkMethod, testInstance, statement); statement = withAfters(frameworkMethod, testInstance, statement); statement = withRulesReflectively(frameworkMethod, testInstance, statement); statement = withPotentialRepeat(frameworkMethod, testInstance, statement); statement = withPotentialTimeout(frameworkMethod, testInstance, statement); return statement; } /** * Invoke JUnit's private {@code withRules()} method using reflection. */ private Statement withRulesReflectively(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { Object result = ReflectionUtils.invokeMethod(withRulesMethod, this, frameworkMethod, testInstance, statement); Assert.state(result instanceof Statement, "withRules mismatch"); return (Statement) result; } /** * Return {@code true} if {@link Ignore @Ignore} is present for the supplied * {@linkplain FrameworkMethod test method} or if the test method is disabled * via {@code @IfProfileValue}. * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Method, Class) */ protected boolean isTestMethodIgnored(FrameworkMethod frameworkMethod) { Method method = frameworkMethod.getMethod(); return (method.isAnnotationPresent(Ignore.class) || !ProfileValueUtils.isTestEnabledInThisEnvironment(method, getTestClass().getJavaClass())); } /** * Perform the same logic as * {@link BlockJUnit4ClassRunner#possiblyExpectingExceptions(FrameworkMethod, Object, Statement)} * except that the <em>expected exception</em> is retrieved using * {@link #getExpectedException(FrameworkMethod)}. */ @Override protected Statement possiblyExpectingExceptions(FrameworkMethod frameworkMethod, Object testInstance, Statement next) { Class<? extends Throwable> expectedException = getExpectedException(frameworkMethod); return (expectedException != null ? new ExpectException(next, expectedException) : next); } /** * Get the {@code exception} that the supplied {@linkplain FrameworkMethod * test method} is expected to throw. * <p>Supports JUnit's {@link Test#expected() @Test(expected=...)} annotation. * <p>Can be overridden by subclasses. * @return the expected exception, or {@code null} if none was specified */ @Nullable protected Class<? extends Throwable> getExpectedException(FrameworkMethod frameworkMethod) { Test test = frameworkMethod.getAnnotation(Test.class); return (test != null && test.expected() != Test.None.class ? test.expected() : null); } /** * Perform the same logic as * {@link BlockJUnit4ClassRunner#withPotentialTimeout(FrameworkMethod, Object, Statement)} * but with additional support for Spring's {@code @Timed} annotation. * <p>Supports both Spring's {@link org.springframework.test.annotation.Timed @Timed} * and JUnit's {@link Test#timeout() @Test(timeout=...)} annotations, but not both * simultaneously. * @return either a {@link SpringFailOnTimeout}, a {@link FailOnTimeout}, * or the supplied {@link Statement} as appropriate * @see #getSpringTimeout(FrameworkMethod) * @see #getJUnitTimeout(FrameworkMethod) */ @Override // Retain the following warning suppression for deprecation (even if Eclipse // states it is unnecessary) since withPotentialTimeout(FrameworkMethod,Object,Statement) // in BlockJUnit4ClassRunner has been deprecated. @SuppressWarnings("deprecation") protected Statement withPotentialTimeout(FrameworkMethod frameworkMethod, Object testInstance, Statement next) { Statement statement = null; long springTimeout = getSpringTimeout(frameworkMethod); long junitTimeout = getJUnitTimeout(frameworkMethod); if (springTimeout > 0 && junitTimeout > 0) { String msg = String.format("Test method [%s] has been configured with Spring's @Timed(millis=%s) and " + "JUnit's @Test(timeout=%s) annotations, but only one declaration of a 'timeout' is " + "permitted per test method.", frameworkMethod.getMethod(), springTimeout, junitTimeout); logger.error(msg); throw new IllegalStateException(msg); } else if (springTimeout > 0) { statement = new SpringFailOnTimeout(next, springTimeout); } else if (junitTimeout > 0) { statement = FailOnTimeout.builder().withTimeout(junitTimeout, TimeUnit.MILLISECONDS).build(next); } else { statement = next; } return statement; } /** * Retrieve the configured JUnit {@code timeout} from the {@link Test @Test} * annotation on the supplied {@linkplain FrameworkMethod test method}. * @return the timeout, or {@code 0} if none was specified */ protected long getJUnitTimeout(FrameworkMethod frameworkMethod) { Test test = frameworkMethod.getAnnotation(Test.class); return (test == null ? 0 : Math.max(0, test.timeout())); } /** * Retrieve the configured Spring-specific {@code timeout} from the * {@link org.springframework.test.annotation.Timed @Timed} annotation * on the supplied {@linkplain FrameworkMethod test method}. * @return the timeout, or {@code 0} if none was specified * @see TestAnnotationUtils#getTimeout(Method) */ protected long getSpringTimeout(FrameworkMethod frameworkMethod) { return TestAnnotationUtils.getTimeout(frameworkMethod.getMethod()); } /** * Wrap the supplied {@link Statement} with a {@code RunBeforeTestExecutionCallbacks} * statement, thus preserving the default functionality while adding support for the * Spring TestContext Framework. * @see RunBeforeTestExecutionCallbacks */ protected Statement withBeforeTestExecutionCallbacks(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { return new RunBeforeTestExecutionCallbacks(statement, testInstance, frameworkMethod.getMethod(), getTestContextManager()); } /** * Wrap the supplied {@link Statement} with a {@code RunAfterTestExecutionCallbacks} * statement, thus preserving the default functionality while adding support for the * Spring TestContext Framework. * @see RunAfterTestExecutionCallbacks */ protected Statement withAfterTestExecutionCallbacks(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { return new RunAfterTestExecutionCallbacks(statement, testInstance, frameworkMethod.getMethod(), getTestContextManager()); } /** * Wrap the {@link Statement} returned by the parent implementation with a * {@code RunBeforeTestMethodCallbacks} statement, thus preserving the * default functionality while adding support for the Spring TestContext * Framework. * @see RunBeforeTestMethodCallbacks */ @Override protected Statement withBefores(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { Statement junitBefores = super.withBefores(frameworkMethod, testInstance, statement); return new RunBeforeTestMethodCallbacks(junitBefores, testInstance, frameworkMethod.getMethod(), getTestContextManager()); } /** * Wrap the {@link Statement} returned by the parent implementation with a * {@code RunAfterTestMethodCallbacks} statement, thus preserving the * default functionality while adding support for the Spring TestContext * Framework. * @see RunAfterTestMethodCallbacks */ @Override protected Statement withAfters(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { Statement junitAfters = super.withAfters(frameworkMethod, testInstance, statement); return new RunAfterTestMethodCallbacks(junitAfters, testInstance, frameworkMethod.getMethod(), getTestContextManager()); } /** * Wrap the supplied {@link Statement} with a {@code SpringRepeat} statement. * <p>Supports Spring's {@link org.springframework.test.annotation.Repeat @Repeat} * annotation. * @see TestAnnotationUtils#getRepeatCount(Method) * @see SpringRepeat */ protected Statement withPotentialRepeat(FrameworkMethod frameworkMethod, Object testInstance, Statement next) { return new SpringRepeat(next, frameworkMethod.getMethod()); } }
/********************************************************************************* * * * The MIT License (MIT) * * * * Copyright (c) 2015-2020 aoju.org and other contributors. * * * * 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.aoju.bus.image.nimble.codec.jpeg; import org.aoju.bus.core.lang.Symbol; import org.aoju.bus.core.toolkit.ByteKit; /** * @author Kimi Liu * @version 6.0.1 * @since JDK 1.8+ */ public class SOSSegment { private final byte[] data; private final int offset; private final int numComponents; public SOSSegment(byte[] data, int offset) { this.data = data; this.offset = offset; this.numComponents = data[offset + 3] & 255; getAl(); } public int offset() { return offset; } public int getMarker() { return data[offset] & 255; } public int getHeaderLength() { return ByteKit.bytesToUShortBE(data, offset + 1); } public int getNumComponents() { return numComponents; } public int getComponentID(int index) { return data[offset + 4 + index * 2] & 255; } public int getTa(int index) { return (data[offset + 5 + index * 2] >> 4) & 15; } public int getTd(int index) { return (data[offset + 5 + index * 2]) & 15; } public int getSs() { return data[offset + 4 + numComponents * 2] & 255; } public int getSe() { return data[offset + 5 + numComponents * 2] & 255; } public int getAh() { return (data[offset + 6 + numComponents * 2] >> 4) & 15; } public int getAl() { return (data[offset + 6 + numComponents * 2]) & 15; } public int getNear() { return getSs(); } public int getILV() { return getSe(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SOS=[Ls=").append(getHeaderLength()) .append(", Ns=").append(numComponents); for (int i = 0; i < numComponents; i++) { sb.append(", C").append(i + 1).append(Symbol.C_EQUAL).append(getComponentID(i)) .append(", Td").append(i + 1).append(Symbol.C_EQUAL).append(getTd(i)) .append(", Ta").append(i + 1).append(Symbol.C_EQUAL).append(getTa(i)); } sb.append(", Ss=").append(getSs()) .append(", Se=").append(getSe()) .append(", Ah=").append(getAh()) .append(", Al=").append(getAl()) .append(']'); return sb.toString(); } }
package com.deeal.exchange.view.activity_transition.fragment; import android.animation.TimeInterpolator; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.animation.DecelerateInterpolator; import com.deeal.exchange.view.activity_transition.core.MoveData; import com.deeal.exchange.view.activity_transition.core.TransitionAnimation; /** * Created by takam on 2015/03/26. */ public class FragmentTransition { private static final TimeInterpolator sDecelerator = new DecelerateInterpolator(); private android.support.v4.app.Fragment supportFragment; private Fragment fragment; int duration = 1000; View toView; private FragmentTransition(Fragment fragment) { this.fragment = fragment; } private FragmentTransition(android.support.v4.app.Fragment fragment) { this.supportFragment = fragment; } public static FragmentTransition with(Fragment fragment) { return new FragmentTransition(fragment); } public static FragmentTransition with(android.support.v4.app.Fragment fragment) { return new FragmentTransition(fragment); } public FragmentTransition to(View toView) { this.toView = toView; return this; } public FragmentTransition duration(int duration) { this.duration = duration; return this; } public ExitFragmentTransition start(Bundle savedInstanceState) { final Context context = toView.getContext(); final Bundle bundle; if (fragment == null) { bundle = supportFragment.getArguments(); } else { bundle = fragment.getArguments(); } final MoveData moveData = TransitionAnimation.startAnimation(context, toView, bundle, savedInstanceState, duration, sDecelerator); if (fragment == null) { return new ExitFragmentTransition(supportFragment, moveData); } return new ExitFragmentTransition(fragment, moveData); } }
package com.worm.web_images20.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartFile; import javax.persistence.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Core model. stores metadata of the image. * Used Lombok to avoid getters and setters in this model * Override setter for comment to give it proper functionality * */ @Entity @Data @AllArgsConstructor @NoArgsConstructor public class ImageEntity { @Id @GeneratedValue private Long id; @Column(name = "uuid") private String uuid; @Column(name = "file_name") private String fileName; @Column(name = "path_and_name") private String pathAndName; @Transient private MultipartFile multipartFile; @ElementCollection private List<String> comments = new ArrayList<>(); }
package me.skiincraft.api.osu.impl.v1.user; import com.google.gson.annotations.SerializedName; import me.skiincraft.api.osu.impl.v2.user.UserCompactImpl; public class UserV1CompactImpl extends UserCompactImpl { @SerializedName(value = "country") private final String countryCode; public UserV1CompactImpl(long id, String username, String profileColour, String avatarUrl, String countryCode, boolean isActive, boolean isBot, boolean isOnline, boolean isSupporter) { super(id, username, profileColour, avatarUrl, countryCode, isActive, isBot, isOnline, isSupporter); this.countryCode = countryCode; } @Override public String getCountryCode() { return countryCode; } }
/* * Copyright 2015-2017 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.docksidestage.mylasta.direction; import org.docksidestage.mylasta.direction.MaihamaConfig; import org.lastaflute.core.direction.exception.ConfigPropertyNotFoundException; /** * @author FreeGen */ public interface HangarEnv extends MaihamaConfig { /** The key of the configuration. e.g. hangar-support@saw.example.com */ String MAIL_ADDRESS_SUPPORT = "mail.address.support"; /** The key of the configuration. e.g. localhost:8092 */ String SERVER_DOMAIN = "server.domain"; /** * Get the value of property as {@link String}. * @param propertyKey The key of the property. (NotNull) * @return The value of found property. (NotNull: if not found, exception) * @throws ConfigPropertyNotFoundException When the property is not found. */ String get(String propertyKey); /** * Is the property true? * @param propertyKey The key of the property which is boolean type. (NotNull) * @return The determination, true or false. (if not found, exception) * @throws ConfigPropertyNotFoundException When the property is not found. */ boolean is(String propertyKey); /** * Get the value for the key 'mail.address.support'. <br> * The value is, e.g. hangar-support@saw.example.com <br> * comment: Mail Address for Hangar Support * @return The value of found property. (NotNull: if not found, exception but basically no way) */ String getMailAddressSupport(); /** * Get the value for the key 'server.domain'. <br> * The value is, e.g. localhost:8092 <br> * comment: domain to access this application from internet, e.g. for registration mail * @return The value of found property. (NotNull: if not found, exception but basically no way) */ String getServerDomain(); /** * The simple implementation for configuration. * @author FreeGen */ public static class SimpleImpl extends MaihamaConfig.SimpleImpl implements HangarEnv { /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; public String getMailAddressSupport() { return get(HangarEnv.MAIL_ADDRESS_SUPPORT); } public String getServerDomain() { return get(HangarEnv.SERVER_DOMAIN); } } }
package jetbrains.mps.lang.messages.constraints; /*Generated by MPS */ import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor; import org.jetbrains.mps.openapi.language.SConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; public class MacroMessageExpression_Constraints extends BaseConstraintsDescriptor { public MacroMessageExpression_Constraints() { super(CONCEPTS.MacroMessageExpression$DF); } private static final class CONCEPTS { /*package*/ static final SConcept MacroMessageExpression$DF = MetaAdapterFactory.getConcept(0xad93155d79b24759L, 0xb10c55123e763903L, 0x48f860fc0e41e4a2L, "jetbrains.mps.lang.messages.structure.MacroMessageExpression"); } }
package de.mhus.dboss.core.impl.ql; import java.io.File; import java.io.IOException; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import org.apache.log4j.Logger; import de.mhus.dboss.core.DBossException; public class QueryParser { private boolean DEBUG = false; private static Logger log = Logger.getLogger( QueryParser.class ); private QDNode node; public Hashtable globalDefinitions = new Hashtable(); private IQueryDefinition qd; public QueryParser( IQueryDefinition pQd ) { qd = pQd; node = new QDNode(); node.parseDefinition( qd.getQueryDefinition( null ).split( " " ), 0 ); } public ICompiledQuery compile(String[] parts, int offset, int end) throws DBossException { CompiledQuery code = new CompiledQuery(); if ( parts[ end-1 ].startsWith( "enable:" ) ) { code.setFeatures( parts[ end-1 ].substring( 7 ).split( "," ) ); end--; if ( code.isFeature( "debug_parser" ) ) DEBUG = true; if ( DEBUG ) { String[] f = code.getFeatures(); if ( log.isDebugEnabled() ) for ( int i = 0; i < f.length; i++ ) log.info( "FEATURE: " + f[ i ] ); } } int start = offset; offset = node.compile( parts, offset, end, code ); if ( offset != end ) throw new DBossException( "PARSE_ERROR " + toErrorMessage( parts, start, end, offset ) ); if ( DEBUG ) log.info( "CODE" + toString() ); return code; } private String toErrorMessage(String[] parts, int start, int end, int offset) { StringBuffer out = new StringBuffer( "ERROR: " ); for ( int i = start; i < end; i++ ) { if ( i == offset ) out.append( "--> " ); out.append( parts[ i ] ); out.append( ' ' ); } out.append( "<--" ); return out.toString(); } private class QDNode { LinkedList definition = new LinkedList(); int parseDefinition( String[] def, int offset ) { for ( int i = offset; i < def.length; i++ ) { String part = def[i]; if ( part.startsWith("<" ) && part.endsWith( ">" ) ) { // is other definition definition.add( new QDRef( part ) ); } else if ( part.endsWith( "[" ) ) { // start of choice QDChoice choice = new QDChoice( part ); i = choice.parse( def, i ); definition.add( choice ); } else if ( "]".equals( part ) ) { return -i; } else if ( "|".equals( part ) ) { return i; } else if ( part.startsWith( "?" ) ) { // attribute definition.add( new QDAttr( part ) ); } else definition.add( new QDConst( part ) ); } return -def.length; } public String toString() { StringBuffer sb = new StringBuffer(); for ( Iterator i = definition.iterator(); i.hasNext(); ) { QDObj obj = (QDObj)i.next(); sb.append( obj.toString() ); sb.append( ' ' ); } return sb.toString(); } public int compile(String[] parts, int offset, int end, CompiledQuery code) { for ( Iterator i = definition.iterator(); i.hasNext(); ) { QDObj obj = (QDObj)i.next(); if ( DEBUG && offset < end ) log.info( space( offset ) + ">>> NODE " + offset + ' ' + parts[ offset ] + " -------------------"); int ret = obj.compile( parts, offset, end, code ); if ( DEBUG && offset < end ) log.info( space( offset ) + "<<< NODE " + offset + ' ' + parts[ offset ] + " -------------------"); if ( ret < 0 ) return ret; offset = ret; } return offset; } } private String space( int l ) { StringBuffer sb = new StringBuffer(); for ( int i =0; i < l ; i++ ) sb.append( " " ); return sb.toString(); } private interface QDObj { public int compile(String[] parts, int offset, int end, CompiledQuery code); } private class QDConst implements QDObj { private String value; private int id; public QDConst(String part) { int pos = part.lastIndexOf( '|' ); if ( pos < 0 ) { value = part.toUpperCase(); id = qd.getConstantId( part ); } else { value = part.substring( 0, pos ); id = Integer.parseInt( part.substring( pos+1 ) ); } } public String toString() { return value + '|' + id; } public int compile(String[] parts, int offset, int end, CompiledQuery code) { if ( DEBUG ) log.info( space( offset ) + "--- CONST " + value ); if ( offset >= end ) return -1; if ( parts[ offset ].toUpperCase().equals( value ) ) { code.add( id ); return offset+1; } return -1; } } private class QDRef implements QDObj { private String name; private QDNode myNode; public QDRef(String part) { name = part.substring( 1, part.length()-1 ); if ( !globalDefinitions.containsKey( name ) ) { globalDefinitions.put( name, "" ); QDNode newNode = new QDNode(); newNode.parseDefinition( qd.getQueryDefinition( name ).split( " " ), 0 ); globalDefinitions.put( name, newNode ); } // myNode = (QDNode)globalDefinitions.get( name ); } public String toString() { return '<' + name + '>'; } public int compile(String[] parts, int offset, int end, CompiledQuery code) { if ( DEBUG ) log.info( space( offset ) + "--- REF " + name ); if ( myNode == null ) myNode = (QDNode)globalDefinitions.get( name ); return myNode.compile( parts, offset, end, code ); } } private class QDChoice implements QDObj { private LinkedList choices = new LinkedList(); private boolean maybe = false; private boolean multi = false; public QDChoice(String part) { maybe = part.equals( "0,1[" ); if ( part.equals( "*[") ) { maybe = true; multi = true; } } public int parse(String[] def, int i) { while ( true ) { QDNode newNode = new QDNode(); int j = newNode.parseDefinition( def, i+1 ); choices.add( newNode ); if ( j < 0 ) { i = -j; break; } i = j; } return i; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append( "[ " ); boolean first = true; for ( Iterator i = choices.iterator(); i.hasNext(); ) { if ( !first ) sb.append( "| " ); first = false; QDNode n = (QDNode)i.next(); sb.append( n.toString() ); } sb.append( ']' ); return sb.toString(); } public int compile(String[] parts, int offset, int end, CompiledQuery code) { if ( DEBUG ) log.info(space( offset ) + "--- CHOICE " + choices ); while ( true ) { if ( offset >= end ) return offset; for ( Iterator i = choices.iterator(); i.hasNext(); ) { QDNode n = (QDNode)i.next(); CompiledQuery code2 = new CompiledQuery(); int ret = n.compile( parts, offset, end, code2 ); if ( ret >= 0 ) { code.addAll( code2 ); if ( DEBUG ) log.info(space( offset ) + "+++ CHOICE OK " + ret + ' ' + n.toString() ); if ( !multi ) return ret; offset = ret; continue; } } if ( choices.size() == 1 || maybe ) { if ( DEBUG ) log.info(space( offset ) + "--- CHOICE NONE" ); return offset; } if ( DEBUG ) log.info(space( offset ) + "*** CHOICE ERROR" ); return -1; } } } private class QDAttr implements QDObj { private String ext; public QDAttr(String part) { ext = part.substring( 1 ); } public String toString() { return "?" + ext; } public int compile(String[] parts, int offset, int end, CompiledQuery code) { if ( DEBUG ) log.info( space( offset ) + "+++ ATTR " + parts[ offset ] ); code.add( parts[ offset ] ); return offset+1; } } public String toString() { StringBuffer sb = new StringBuffer(); sb.append( ':' ); sb.append( node.toString() ); for ( Iterator i = globalDefinitions.keySet().iterator(); i.hasNext(); ) { sb.append( "\n" ); String name = (String)i.next(); QDNode n = (QDNode)globalDefinitions.get( name ); sb.append( name ); sb.append( ": " ); sb.append( n.toString() ); } return sb.toString(); } }
/* * Copyright 2018 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 androidx.core.view; import static androidx.test.espresso.matcher.ViewMatchers.assertThat; import static org.hamcrest.CoreMatchers.is; import android.content.Context; import android.view.View; import android.widget.FrameLayout; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @SmallTest public class NestedScrollingParentHelperTest { private NestedScrollingParentHelper mNestedScrollingParentHelper; private View mView; @Before public void setup() { Context context = ApplicationProvider.getApplicationContext(); mNestedScrollingParentHelper = new NestedScrollingParentHelper(new FrameLayout(context)); mView = new View(context); } @Test public void getNestedScrollAxes_didNotAccept_returnsNone() { assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_NONE)); } @Test public void getNestedScrollAxes_acceptedTouch_returnsTouch() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_VERTICAL)); } @Test public void getNestedScrollAxes_acceptedNonTouch_returnsNonTouch() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_HORIZONTAL, ViewCompat.TYPE_NON_TOUCH); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_HORIZONTAL)); } @Test public void getNestedScrollAxes_acceptedTouchThenStopsTouch_returnsNone() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); mNestedScrollingParentHelper.onStopNestedScroll(mView, ViewCompat.TYPE_TOUCH); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_NONE)); } @Test public void getNestedScrollAxes_acceptedNonTouchThenStopsNonTouch_returnsNone() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_HORIZONTAL, ViewCompat.TYPE_NON_TOUCH); mNestedScrollingParentHelper.onStopNestedScroll(mView, ViewCompat.TYPE_NON_TOUCH); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_NONE)); } @Test public void getNestedScrollAxes_acceptedViaV1_returnsTouch() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_VERTICAL); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_VERTICAL)); } @Test public void getNestedScrollAxes_acceptedBoth_returnsDisjunction() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_HORIZONTAL, ViewCompat.TYPE_NON_TOUCH); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_VERTICAL | ViewCompat.SCROLL_AXIS_HORIZONTAL)); } @Test public void getNestedScrollAxes_acceptBothThenStopTouch_returnsNonTouch() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_HORIZONTAL, ViewCompat.TYPE_NON_TOUCH); mNestedScrollingParentHelper.onStopNestedScroll(mView, ViewCompat.TYPE_TOUCH); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_HORIZONTAL)); } @Test public void getNestedScrollAxes_acceptBothThenStopNonTouch_returnsTouch() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_HORIZONTAL, ViewCompat.TYPE_NON_TOUCH); mNestedScrollingParentHelper.onStopNestedScroll(mView, ViewCompat.TYPE_NON_TOUCH); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_VERTICAL)); } @Test public void getNestedScrollAxes_acceptBothThenStopV1_returnsNonTouch() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_HORIZONTAL, ViewCompat.TYPE_NON_TOUCH); mNestedScrollingParentHelper.onStopNestedScroll(mView); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_HORIZONTAL)); } @Test public void getNestedScrollAxes_acceptBothThenStopBoth_returnsNone() { mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_TOUCH); mNestedScrollingParentHelper.onNestedScrollAccepted( mView, mView, ViewCompat.SCROLL_AXIS_HORIZONTAL, ViewCompat.TYPE_NON_TOUCH); mNestedScrollingParentHelper.onStopNestedScroll(mView, ViewCompat.TYPE_TOUCH); mNestedScrollingParentHelper.onStopNestedScroll(mView, ViewCompat.TYPE_NON_TOUCH); assertThat(mNestedScrollingParentHelper.getNestedScrollAxes(), is(ViewCompat.SCROLL_AXIS_NONE)); } }
public class Exercicio_3_13_3 { public static void main(String[] args) { for (int i = 1; i <= 100; i++) if (i % 3 == 0) System.out.println(i); } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.am.gateway.handler.context.provider; import io.gravitee.am.model.Domain; import io.gravitee.el.TemplateContext; import io.gravitee.el.TemplateVariableProvider; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author GraviteeSource Team */ public class DomainTemplateVariableProvider implements TemplateVariableProvider, InitializingBean { @Autowired private Domain domain; private DomainProperties domainProperties; public void afterPropertiesSet() { domainProperties = new DomainProperties(); domainProperties.setId(domain.getId()); domainProperties.setName(domain.getName()); domainProperties.setPath(domain.getPath()); } @Override public void provide(TemplateContext templateContext) { templateContext.setVariable("domain", domainProperties); } }
package org.apdoer.condition.core.utils; public class RedisKeyBuildUtils { private static final String PUSH_USER_GROUP_REDIS_KEY = "PUG_";// 用户组 public static String buildPushUserGroupRedisKey(Integer userId) { return PUSH_USER_GROUP_REDIS_KEY + userId; } }
package com.example.luciano.testesantigo.Intent.IntentEnviarSMS; import android.app.ListActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class MenuIntentEnviarSMS extends ListActivity{ @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); String[] opcoes = new String[] { "Enviar SMS pre Definido1", "Enviar SMS pre Definido2", "Enviar SMS pre Definido3", "Enviar SMS", "Voltar" }; setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, opcoes)); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); switch(position) { case 0: Intent enviarSMS = new Intent(Intent.ACTION_VIEW); //enviarSMS.putExtra("address","tel:03899444287"); enviarSMS.putExtra("address","03899444287"); enviarSMS.putExtra("sms_body","Mensagem a ser enviada pelo SMS"); enviarSMS.setType("vnd.android-dir/mms-sms"); startActivity(enviarSMS); break; case 1: Uri number = Uri.parse("sms:03899444287"); Intent enviarSMS1 = new Intent(Intent.ACTION_VIEW, number); //erro com SEND //enviarSMS1.setData(Uri.parse("sms:03899444287")); enviarSMS1.putExtra("sms_body", "Enviando mensagem para APP com VIEW\n" + ":)"); startActivity(enviarSMS1); break; case 2: Intent enviarSMS2 = new Intent(Intent.ACTION_SENDTO); enviarSMS2.setData(Uri.parse("smsto:03899444287")); enviarSMS2.putExtra("sms_body", "Enviando mensagem para APP com SENDTO\n:)"); startActivity(enviarSMS2); break; case 3: startActivity(new Intent(this, enviarSMS1.class)); default: finish(); } } }
package org.xtext.service.roboticMiddleware.ide.contentassist.antlr.internal; import java.io.InputStream; import org.eclipse.xtext.*; import org.eclipse.xtext.parser.*; import org.eclipse.xtext.parser.impl.*; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.parser.antlr.XtextTokenStream; import org.eclipse.xtext.parser.antlr.XtextTokenStream.HiddenTokens; import org.eclipse.xtext.ide.editor.contentassist.antlr.internal.AbstractInternalContentAssistParser; import org.eclipse.xtext.ide.editor.contentassist.antlr.internal.DFA; import org.xtext.service.roboticMiddleware.services.RoboticMiddlewareGrammarAccess; import org.antlr.runtime.*; import java.util.Stack; import java.util.List; import java.util.ArrayList; @SuppressWarnings("all") public class InternalRoboticMiddlewareParser extends AbstractInternalContentAssistParser { public static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "RULE_STRING", "RULE_ID", "RULE_INT", "RULE_ML_COMMENT", "RULE_SL_COMMENT", "RULE_WS", "RULE_ANY_OTHER", "'.'", "'ACE_SmartSoft'", "'description'", "'OpcUa_SeRoNet'", "'CORBA_SmartSoft'", "'DDS_SmartSoft'" }; public static final int RULE_ID=5; public static final int RULE_WS=9; public static final int RULE_STRING=4; public static final int RULE_ANY_OTHER=10; public static final int RULE_SL_COMMENT=8; public static final int T__15=15; public static final int T__16=16; public static final int RULE_INT=6; public static final int T__11=11; public static final int RULE_ML_COMMENT=7; public static final int T__12=12; public static final int T__13=13; public static final int T__14=14; public static final int EOF=-1; // delegates // delegators public InternalRoboticMiddlewareParser(TokenStream input) { this(input, new RecognizerSharedState()); } public InternalRoboticMiddlewareParser(TokenStream input, RecognizerSharedState state) { super(input, state); } public String[] getTokenNames() { return InternalRoboticMiddlewareParser.tokenNames; } public String getGrammarFileName() { return "InternalRoboticMiddleware.g"; } private RoboticMiddlewareGrammarAccess grammarAccess; public void setGrammarAccess(RoboticMiddlewareGrammarAccess grammarAccess) { this.grammarAccess = grammarAccess; } @Override protected Grammar getGrammar() { return grammarAccess.getGrammar(); } @Override protected String getValueForTokenName(String tokenName) { return tokenName; } // $ANTLR start "entryRuleRoboticMiddleware" // InternalRoboticMiddleware.g:94:1: entryRuleRoboticMiddleware : ruleRoboticMiddleware EOF ; public final void entryRuleRoboticMiddleware() throws RecognitionException { try { // InternalRoboticMiddleware.g:95:1: ( ruleRoboticMiddleware EOF ) // InternalRoboticMiddleware.g:96:1: ruleRoboticMiddleware EOF { before(grammarAccess.getRoboticMiddlewareRule()); pushFollow(FOLLOW_1); ruleRoboticMiddleware(); state._fsp--; after(grammarAccess.getRoboticMiddlewareRule()); match(input,EOF,FOLLOW_2); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { } return ; } // $ANTLR end "entryRuleRoboticMiddleware" // $ANTLR start "ruleRoboticMiddleware" // InternalRoboticMiddleware.g:103:1: ruleRoboticMiddleware : ( ( rule__RoboticMiddleware__Alternatives ) ) ; public final void ruleRoboticMiddleware() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:107:2: ( ( ( rule__RoboticMiddleware__Alternatives ) ) ) // InternalRoboticMiddleware.g:108:2: ( ( rule__RoboticMiddleware__Alternatives ) ) { // InternalRoboticMiddleware.g:108:2: ( ( rule__RoboticMiddleware__Alternatives ) ) // InternalRoboticMiddleware.g:109:3: ( rule__RoboticMiddleware__Alternatives ) { before(grammarAccess.getRoboticMiddlewareAccess().getAlternatives()); // InternalRoboticMiddleware.g:110:3: ( rule__RoboticMiddleware__Alternatives ) // InternalRoboticMiddleware.g:110:4: rule__RoboticMiddleware__Alternatives { pushFollow(FOLLOW_2); rule__RoboticMiddleware__Alternatives(); state._fsp--; } after(grammarAccess.getRoboticMiddlewareAccess().getAlternatives()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "ruleRoboticMiddleware" // $ANTLR start "entryRuleFQN" // InternalRoboticMiddleware.g:119:1: entryRuleFQN : ruleFQN EOF ; public final void entryRuleFQN() throws RecognitionException { try { // InternalRoboticMiddleware.g:120:1: ( ruleFQN EOF ) // InternalRoboticMiddleware.g:121:1: ruleFQN EOF { before(grammarAccess.getFQNRule()); pushFollow(FOLLOW_1); ruleFQN(); state._fsp--; after(grammarAccess.getFQNRule()); match(input,EOF,FOLLOW_2); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { } return ; } // $ANTLR end "entryRuleFQN" // $ANTLR start "ruleFQN" // InternalRoboticMiddleware.g:128:1: ruleFQN : ( ( rule__FQN__Group__0 ) ) ; public final void ruleFQN() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:132:2: ( ( ( rule__FQN__Group__0 ) ) ) // InternalRoboticMiddleware.g:133:2: ( ( rule__FQN__Group__0 ) ) { // InternalRoboticMiddleware.g:133:2: ( ( rule__FQN__Group__0 ) ) // InternalRoboticMiddleware.g:134:3: ( rule__FQN__Group__0 ) { before(grammarAccess.getFQNAccess().getGroup()); // InternalRoboticMiddleware.g:135:3: ( rule__FQN__Group__0 ) // InternalRoboticMiddleware.g:135:4: rule__FQN__Group__0 { pushFollow(FOLLOW_2); rule__FQN__Group__0(); state._fsp--; } after(grammarAccess.getFQNAccess().getGroup()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "ruleFQN" // $ANTLR start "entryRuleEString" // InternalRoboticMiddleware.g:144:1: entryRuleEString : ruleEString EOF ; public final void entryRuleEString() throws RecognitionException { try { // InternalRoboticMiddleware.g:145:1: ( ruleEString EOF ) // InternalRoboticMiddleware.g:146:1: ruleEString EOF { before(grammarAccess.getEStringRule()); pushFollow(FOLLOW_1); ruleEString(); state._fsp--; after(grammarAccess.getEStringRule()); match(input,EOF,FOLLOW_2); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { } return ; } // $ANTLR end "entryRuleEString" // $ANTLR start "ruleEString" // InternalRoboticMiddleware.g:153:1: ruleEString : ( RULE_STRING ) ; public final void ruleEString() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:157:2: ( ( RULE_STRING ) ) // InternalRoboticMiddleware.g:158:2: ( RULE_STRING ) { // InternalRoboticMiddleware.g:158:2: ( RULE_STRING ) // InternalRoboticMiddleware.g:159:3: RULE_STRING { before(grammarAccess.getEStringAccess().getSTRINGTerminalRuleCall()); match(input,RULE_STRING,FOLLOW_2); after(grammarAccess.getEStringAccess().getSTRINGTerminalRuleCall()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "ruleEString" // $ANTLR start "entryRuleACE_SmartSoft" // InternalRoboticMiddleware.g:169:1: entryRuleACE_SmartSoft : ruleACE_SmartSoft EOF ; public final void entryRuleACE_SmartSoft() throws RecognitionException { try { // InternalRoboticMiddleware.g:170:1: ( ruleACE_SmartSoft EOF ) // InternalRoboticMiddleware.g:171:1: ruleACE_SmartSoft EOF { before(grammarAccess.getACE_SmartSoftRule()); pushFollow(FOLLOW_1); ruleACE_SmartSoft(); state._fsp--; after(grammarAccess.getACE_SmartSoftRule()); match(input,EOF,FOLLOW_2); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { } return ; } // $ANTLR end "entryRuleACE_SmartSoft" // $ANTLR start "ruleACE_SmartSoft" // InternalRoboticMiddleware.g:178:1: ruleACE_SmartSoft : ( ( rule__ACE_SmartSoft__Group__0 ) ) ; public final void ruleACE_SmartSoft() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:182:2: ( ( ( rule__ACE_SmartSoft__Group__0 ) ) ) // InternalRoboticMiddleware.g:183:2: ( ( rule__ACE_SmartSoft__Group__0 ) ) { // InternalRoboticMiddleware.g:183:2: ( ( rule__ACE_SmartSoft__Group__0 ) ) // InternalRoboticMiddleware.g:184:3: ( rule__ACE_SmartSoft__Group__0 ) { before(grammarAccess.getACE_SmartSoftAccess().getGroup()); // InternalRoboticMiddleware.g:185:3: ( rule__ACE_SmartSoft__Group__0 ) // InternalRoboticMiddleware.g:185:4: rule__ACE_SmartSoft__Group__0 { pushFollow(FOLLOW_2); rule__ACE_SmartSoft__Group__0(); state._fsp--; } after(grammarAccess.getACE_SmartSoftAccess().getGroup()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "ruleACE_SmartSoft" // $ANTLR start "entryRuleOpcUa_SeRoNet" // InternalRoboticMiddleware.g:194:1: entryRuleOpcUa_SeRoNet : ruleOpcUa_SeRoNet EOF ; public final void entryRuleOpcUa_SeRoNet() throws RecognitionException { try { // InternalRoboticMiddleware.g:195:1: ( ruleOpcUa_SeRoNet EOF ) // InternalRoboticMiddleware.g:196:1: ruleOpcUa_SeRoNet EOF { before(grammarAccess.getOpcUa_SeRoNetRule()); pushFollow(FOLLOW_1); ruleOpcUa_SeRoNet(); state._fsp--; after(grammarAccess.getOpcUa_SeRoNetRule()); match(input,EOF,FOLLOW_2); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { } return ; } // $ANTLR end "entryRuleOpcUa_SeRoNet" // $ANTLR start "ruleOpcUa_SeRoNet" // InternalRoboticMiddleware.g:203:1: ruleOpcUa_SeRoNet : ( ( rule__OpcUa_SeRoNet__Group__0 ) ) ; public final void ruleOpcUa_SeRoNet() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:207:2: ( ( ( rule__OpcUa_SeRoNet__Group__0 ) ) ) // InternalRoboticMiddleware.g:208:2: ( ( rule__OpcUa_SeRoNet__Group__0 ) ) { // InternalRoboticMiddleware.g:208:2: ( ( rule__OpcUa_SeRoNet__Group__0 ) ) // InternalRoboticMiddleware.g:209:3: ( rule__OpcUa_SeRoNet__Group__0 ) { before(grammarAccess.getOpcUa_SeRoNetAccess().getGroup()); // InternalRoboticMiddleware.g:210:3: ( rule__OpcUa_SeRoNet__Group__0 ) // InternalRoboticMiddleware.g:210:4: rule__OpcUa_SeRoNet__Group__0 { pushFollow(FOLLOW_2); rule__OpcUa_SeRoNet__Group__0(); state._fsp--; } after(grammarAccess.getOpcUa_SeRoNetAccess().getGroup()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "ruleOpcUa_SeRoNet" // $ANTLR start "entryRuleCORBA_SmartSoft" // InternalRoboticMiddleware.g:219:1: entryRuleCORBA_SmartSoft : ruleCORBA_SmartSoft EOF ; public final void entryRuleCORBA_SmartSoft() throws RecognitionException { try { // InternalRoboticMiddleware.g:220:1: ( ruleCORBA_SmartSoft EOF ) // InternalRoboticMiddleware.g:221:1: ruleCORBA_SmartSoft EOF { before(grammarAccess.getCORBA_SmartSoftRule()); pushFollow(FOLLOW_1); ruleCORBA_SmartSoft(); state._fsp--; after(grammarAccess.getCORBA_SmartSoftRule()); match(input,EOF,FOLLOW_2); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { } return ; } // $ANTLR end "entryRuleCORBA_SmartSoft" // $ANTLR start "ruleCORBA_SmartSoft" // InternalRoboticMiddleware.g:228:1: ruleCORBA_SmartSoft : ( ( rule__CORBA_SmartSoft__Group__0 ) ) ; public final void ruleCORBA_SmartSoft() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:232:2: ( ( ( rule__CORBA_SmartSoft__Group__0 ) ) ) // InternalRoboticMiddleware.g:233:2: ( ( rule__CORBA_SmartSoft__Group__0 ) ) { // InternalRoboticMiddleware.g:233:2: ( ( rule__CORBA_SmartSoft__Group__0 ) ) // InternalRoboticMiddleware.g:234:3: ( rule__CORBA_SmartSoft__Group__0 ) { before(grammarAccess.getCORBA_SmartSoftAccess().getGroup()); // InternalRoboticMiddleware.g:235:3: ( rule__CORBA_SmartSoft__Group__0 ) // InternalRoboticMiddleware.g:235:4: rule__CORBA_SmartSoft__Group__0 { pushFollow(FOLLOW_2); rule__CORBA_SmartSoft__Group__0(); state._fsp--; } after(grammarAccess.getCORBA_SmartSoftAccess().getGroup()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "ruleCORBA_SmartSoft" // $ANTLR start "entryRuleDDS_SmartSoft" // InternalRoboticMiddleware.g:244:1: entryRuleDDS_SmartSoft : ruleDDS_SmartSoft EOF ; public final void entryRuleDDS_SmartSoft() throws RecognitionException { try { // InternalRoboticMiddleware.g:245:1: ( ruleDDS_SmartSoft EOF ) // InternalRoboticMiddleware.g:246:1: ruleDDS_SmartSoft EOF { before(grammarAccess.getDDS_SmartSoftRule()); pushFollow(FOLLOW_1); ruleDDS_SmartSoft(); state._fsp--; after(grammarAccess.getDDS_SmartSoftRule()); match(input,EOF,FOLLOW_2); } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { } return ; } // $ANTLR end "entryRuleDDS_SmartSoft" // $ANTLR start "ruleDDS_SmartSoft" // InternalRoboticMiddleware.g:253:1: ruleDDS_SmartSoft : ( ( rule__DDS_SmartSoft__Group__0 ) ) ; public final void ruleDDS_SmartSoft() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:257:2: ( ( ( rule__DDS_SmartSoft__Group__0 ) ) ) // InternalRoboticMiddleware.g:258:2: ( ( rule__DDS_SmartSoft__Group__0 ) ) { // InternalRoboticMiddleware.g:258:2: ( ( rule__DDS_SmartSoft__Group__0 ) ) // InternalRoboticMiddleware.g:259:3: ( rule__DDS_SmartSoft__Group__0 ) { before(grammarAccess.getDDS_SmartSoftAccess().getGroup()); // InternalRoboticMiddleware.g:260:3: ( rule__DDS_SmartSoft__Group__0 ) // InternalRoboticMiddleware.g:260:4: rule__DDS_SmartSoft__Group__0 { pushFollow(FOLLOW_2); rule__DDS_SmartSoft__Group__0(); state._fsp--; } after(grammarAccess.getDDS_SmartSoftAccess().getGroup()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "ruleDDS_SmartSoft" // $ANTLR start "rule__RoboticMiddleware__Alternatives" // InternalRoboticMiddleware.g:268:1: rule__RoboticMiddleware__Alternatives : ( ( ruleACE_SmartSoft ) | ( ruleOpcUa_SeRoNet ) | ( ruleCORBA_SmartSoft ) | ( ruleDDS_SmartSoft ) ); public final void rule__RoboticMiddleware__Alternatives() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:272:1: ( ( ruleACE_SmartSoft ) | ( ruleOpcUa_SeRoNet ) | ( ruleCORBA_SmartSoft ) | ( ruleDDS_SmartSoft ) ) int alt1=4; switch ( input.LA(1) ) { case 12: { alt1=1; } break; case 14: { alt1=2; } break; case 15: { alt1=3; } break; case 16: { alt1=4; } break; default: NoViableAltException nvae = new NoViableAltException("", 1, 0, input); throw nvae; } switch (alt1) { case 1 : // InternalRoboticMiddleware.g:273:2: ( ruleACE_SmartSoft ) { // InternalRoboticMiddleware.g:273:2: ( ruleACE_SmartSoft ) // InternalRoboticMiddleware.g:274:3: ruleACE_SmartSoft { before(grammarAccess.getRoboticMiddlewareAccess().getACE_SmartSoftParserRuleCall_0()); pushFollow(FOLLOW_2); ruleACE_SmartSoft(); state._fsp--; after(grammarAccess.getRoboticMiddlewareAccess().getACE_SmartSoftParserRuleCall_0()); } } break; case 2 : // InternalRoboticMiddleware.g:279:2: ( ruleOpcUa_SeRoNet ) { // InternalRoboticMiddleware.g:279:2: ( ruleOpcUa_SeRoNet ) // InternalRoboticMiddleware.g:280:3: ruleOpcUa_SeRoNet { before(grammarAccess.getRoboticMiddlewareAccess().getOpcUa_SeRoNetParserRuleCall_1()); pushFollow(FOLLOW_2); ruleOpcUa_SeRoNet(); state._fsp--; after(grammarAccess.getRoboticMiddlewareAccess().getOpcUa_SeRoNetParserRuleCall_1()); } } break; case 3 : // InternalRoboticMiddleware.g:285:2: ( ruleCORBA_SmartSoft ) { // InternalRoboticMiddleware.g:285:2: ( ruleCORBA_SmartSoft ) // InternalRoboticMiddleware.g:286:3: ruleCORBA_SmartSoft { before(grammarAccess.getRoboticMiddlewareAccess().getCORBA_SmartSoftParserRuleCall_2()); pushFollow(FOLLOW_2); ruleCORBA_SmartSoft(); state._fsp--; after(grammarAccess.getRoboticMiddlewareAccess().getCORBA_SmartSoftParserRuleCall_2()); } } break; case 4 : // InternalRoboticMiddleware.g:291:2: ( ruleDDS_SmartSoft ) { // InternalRoboticMiddleware.g:291:2: ( ruleDDS_SmartSoft ) // InternalRoboticMiddleware.g:292:3: ruleDDS_SmartSoft { before(grammarAccess.getRoboticMiddlewareAccess().getDDS_SmartSoftParserRuleCall_3()); pushFollow(FOLLOW_2); ruleDDS_SmartSoft(); state._fsp--; after(grammarAccess.getRoboticMiddlewareAccess().getDDS_SmartSoftParserRuleCall_3()); } } break; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__RoboticMiddleware__Alternatives" // $ANTLR start "rule__FQN__Group__0" // InternalRoboticMiddleware.g:301:1: rule__FQN__Group__0 : rule__FQN__Group__0__Impl rule__FQN__Group__1 ; public final void rule__FQN__Group__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:305:1: ( rule__FQN__Group__0__Impl rule__FQN__Group__1 ) // InternalRoboticMiddleware.g:306:2: rule__FQN__Group__0__Impl rule__FQN__Group__1 { pushFollow(FOLLOW_3); rule__FQN__Group__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__FQN__Group__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__FQN__Group__0" // $ANTLR start "rule__FQN__Group__0__Impl" // InternalRoboticMiddleware.g:313:1: rule__FQN__Group__0__Impl : ( RULE_ID ) ; public final void rule__FQN__Group__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:317:1: ( ( RULE_ID ) ) // InternalRoboticMiddleware.g:318:1: ( RULE_ID ) { // InternalRoboticMiddleware.g:318:1: ( RULE_ID ) // InternalRoboticMiddleware.g:319:2: RULE_ID { before(grammarAccess.getFQNAccess().getIDTerminalRuleCall_0()); match(input,RULE_ID,FOLLOW_2); after(grammarAccess.getFQNAccess().getIDTerminalRuleCall_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__FQN__Group__0__Impl" // $ANTLR start "rule__FQN__Group__1" // InternalRoboticMiddleware.g:328:1: rule__FQN__Group__1 : rule__FQN__Group__1__Impl ; public final void rule__FQN__Group__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:332:1: ( rule__FQN__Group__1__Impl ) // InternalRoboticMiddleware.g:333:2: rule__FQN__Group__1__Impl { pushFollow(FOLLOW_2); rule__FQN__Group__1__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__FQN__Group__1" // $ANTLR start "rule__FQN__Group__1__Impl" // InternalRoboticMiddleware.g:339:1: rule__FQN__Group__1__Impl : ( ( rule__FQN__Group_1__0 )* ) ; public final void rule__FQN__Group__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:343:1: ( ( ( rule__FQN__Group_1__0 )* ) ) // InternalRoboticMiddleware.g:344:1: ( ( rule__FQN__Group_1__0 )* ) { // InternalRoboticMiddleware.g:344:1: ( ( rule__FQN__Group_1__0 )* ) // InternalRoboticMiddleware.g:345:2: ( rule__FQN__Group_1__0 )* { before(grammarAccess.getFQNAccess().getGroup_1()); // InternalRoboticMiddleware.g:346:2: ( rule__FQN__Group_1__0 )* loop2: do { int alt2=2; int LA2_0 = input.LA(1); if ( (LA2_0==11) ) { alt2=1; } switch (alt2) { case 1 : // InternalRoboticMiddleware.g:346:3: rule__FQN__Group_1__0 { pushFollow(FOLLOW_4); rule__FQN__Group_1__0(); state._fsp--; } break; default : break loop2; } } while (true); after(grammarAccess.getFQNAccess().getGroup_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__FQN__Group__1__Impl" // $ANTLR start "rule__FQN__Group_1__0" // InternalRoboticMiddleware.g:355:1: rule__FQN__Group_1__0 : rule__FQN__Group_1__0__Impl rule__FQN__Group_1__1 ; public final void rule__FQN__Group_1__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:359:1: ( rule__FQN__Group_1__0__Impl rule__FQN__Group_1__1 ) // InternalRoboticMiddleware.g:360:2: rule__FQN__Group_1__0__Impl rule__FQN__Group_1__1 { pushFollow(FOLLOW_5); rule__FQN__Group_1__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__FQN__Group_1__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__FQN__Group_1__0" // $ANTLR start "rule__FQN__Group_1__0__Impl" // InternalRoboticMiddleware.g:367:1: rule__FQN__Group_1__0__Impl : ( '.' ) ; public final void rule__FQN__Group_1__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:371:1: ( ( '.' ) ) // InternalRoboticMiddleware.g:372:1: ( '.' ) { // InternalRoboticMiddleware.g:372:1: ( '.' ) // InternalRoboticMiddleware.g:373:2: '.' { before(grammarAccess.getFQNAccess().getFullStopKeyword_1_0()); match(input,11,FOLLOW_2); after(grammarAccess.getFQNAccess().getFullStopKeyword_1_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__FQN__Group_1__0__Impl" // $ANTLR start "rule__FQN__Group_1__1" // InternalRoboticMiddleware.g:382:1: rule__FQN__Group_1__1 : rule__FQN__Group_1__1__Impl ; public final void rule__FQN__Group_1__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:386:1: ( rule__FQN__Group_1__1__Impl ) // InternalRoboticMiddleware.g:387:2: rule__FQN__Group_1__1__Impl { pushFollow(FOLLOW_2); rule__FQN__Group_1__1__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__FQN__Group_1__1" // $ANTLR start "rule__FQN__Group_1__1__Impl" // InternalRoboticMiddleware.g:393:1: rule__FQN__Group_1__1__Impl : ( RULE_ID ) ; public final void rule__FQN__Group_1__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:397:1: ( ( RULE_ID ) ) // InternalRoboticMiddleware.g:398:1: ( RULE_ID ) { // InternalRoboticMiddleware.g:398:1: ( RULE_ID ) // InternalRoboticMiddleware.g:399:2: RULE_ID { before(grammarAccess.getFQNAccess().getIDTerminalRuleCall_1_1()); match(input,RULE_ID,FOLLOW_2); after(grammarAccess.getFQNAccess().getIDTerminalRuleCall_1_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__FQN__Group_1__1__Impl" // $ANTLR start "rule__ACE_SmartSoft__Group__0" // InternalRoboticMiddleware.g:409:1: rule__ACE_SmartSoft__Group__0 : rule__ACE_SmartSoft__Group__0__Impl rule__ACE_SmartSoft__Group__1 ; public final void rule__ACE_SmartSoft__Group__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:413:1: ( rule__ACE_SmartSoft__Group__0__Impl rule__ACE_SmartSoft__Group__1 ) // InternalRoboticMiddleware.g:414:2: rule__ACE_SmartSoft__Group__0__Impl rule__ACE_SmartSoft__Group__1 { pushFollow(FOLLOW_6); rule__ACE_SmartSoft__Group__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__ACE_SmartSoft__Group__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group__0" // $ANTLR start "rule__ACE_SmartSoft__Group__0__Impl" // InternalRoboticMiddleware.g:421:1: rule__ACE_SmartSoft__Group__0__Impl : ( () ) ; public final void rule__ACE_SmartSoft__Group__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:425:1: ( ( () ) ) // InternalRoboticMiddleware.g:426:1: ( () ) { // InternalRoboticMiddleware.g:426:1: ( () ) // InternalRoboticMiddleware.g:427:2: () { before(grammarAccess.getACE_SmartSoftAccess().getACE_SmartSoftAction_0()); // InternalRoboticMiddleware.g:428:2: () // InternalRoboticMiddleware.g:428:3: { } after(grammarAccess.getACE_SmartSoftAccess().getACE_SmartSoftAction_0()); } } } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group__0__Impl" // $ANTLR start "rule__ACE_SmartSoft__Group__1" // InternalRoboticMiddleware.g:436:1: rule__ACE_SmartSoft__Group__1 : rule__ACE_SmartSoft__Group__1__Impl rule__ACE_SmartSoft__Group__2 ; public final void rule__ACE_SmartSoft__Group__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:440:1: ( rule__ACE_SmartSoft__Group__1__Impl rule__ACE_SmartSoft__Group__2 ) // InternalRoboticMiddleware.g:441:2: rule__ACE_SmartSoft__Group__1__Impl rule__ACE_SmartSoft__Group__2 { pushFollow(FOLLOW_7); rule__ACE_SmartSoft__Group__1__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__ACE_SmartSoft__Group__2(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group__1" // $ANTLR start "rule__ACE_SmartSoft__Group__1__Impl" // InternalRoboticMiddleware.g:448:1: rule__ACE_SmartSoft__Group__1__Impl : ( 'ACE_SmartSoft' ) ; public final void rule__ACE_SmartSoft__Group__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:452:1: ( ( 'ACE_SmartSoft' ) ) // InternalRoboticMiddleware.g:453:1: ( 'ACE_SmartSoft' ) { // InternalRoboticMiddleware.g:453:1: ( 'ACE_SmartSoft' ) // InternalRoboticMiddleware.g:454:2: 'ACE_SmartSoft' { before(grammarAccess.getACE_SmartSoftAccess().getACE_SmartSoftKeyword_1()); match(input,12,FOLLOW_2); after(grammarAccess.getACE_SmartSoftAccess().getACE_SmartSoftKeyword_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group__1__Impl" // $ANTLR start "rule__ACE_SmartSoft__Group__2" // InternalRoboticMiddleware.g:463:1: rule__ACE_SmartSoft__Group__2 : rule__ACE_SmartSoft__Group__2__Impl ; public final void rule__ACE_SmartSoft__Group__2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:467:1: ( rule__ACE_SmartSoft__Group__2__Impl ) // InternalRoboticMiddleware.g:468:2: rule__ACE_SmartSoft__Group__2__Impl { pushFollow(FOLLOW_2); rule__ACE_SmartSoft__Group__2__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group__2" // $ANTLR start "rule__ACE_SmartSoft__Group__2__Impl" // InternalRoboticMiddleware.g:474:1: rule__ACE_SmartSoft__Group__2__Impl : ( ( rule__ACE_SmartSoft__Group_2__0 )? ) ; public final void rule__ACE_SmartSoft__Group__2__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:478:1: ( ( ( rule__ACE_SmartSoft__Group_2__0 )? ) ) // InternalRoboticMiddleware.g:479:1: ( ( rule__ACE_SmartSoft__Group_2__0 )? ) { // InternalRoboticMiddleware.g:479:1: ( ( rule__ACE_SmartSoft__Group_2__0 )? ) // InternalRoboticMiddleware.g:480:2: ( rule__ACE_SmartSoft__Group_2__0 )? { before(grammarAccess.getACE_SmartSoftAccess().getGroup_2()); // InternalRoboticMiddleware.g:481:2: ( rule__ACE_SmartSoft__Group_2__0 )? int alt3=2; int LA3_0 = input.LA(1); if ( (LA3_0==13) ) { alt3=1; } switch (alt3) { case 1 : // InternalRoboticMiddleware.g:481:3: rule__ACE_SmartSoft__Group_2__0 { pushFollow(FOLLOW_2); rule__ACE_SmartSoft__Group_2__0(); state._fsp--; } break; } after(grammarAccess.getACE_SmartSoftAccess().getGroup_2()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group__2__Impl" // $ANTLR start "rule__ACE_SmartSoft__Group_2__0" // InternalRoboticMiddleware.g:490:1: rule__ACE_SmartSoft__Group_2__0 : rule__ACE_SmartSoft__Group_2__0__Impl rule__ACE_SmartSoft__Group_2__1 ; public final void rule__ACE_SmartSoft__Group_2__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:494:1: ( rule__ACE_SmartSoft__Group_2__0__Impl rule__ACE_SmartSoft__Group_2__1 ) // InternalRoboticMiddleware.g:495:2: rule__ACE_SmartSoft__Group_2__0__Impl rule__ACE_SmartSoft__Group_2__1 { pushFollow(FOLLOW_8); rule__ACE_SmartSoft__Group_2__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__ACE_SmartSoft__Group_2__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group_2__0" // $ANTLR start "rule__ACE_SmartSoft__Group_2__0__Impl" // InternalRoboticMiddleware.g:502:1: rule__ACE_SmartSoft__Group_2__0__Impl : ( 'description' ) ; public final void rule__ACE_SmartSoft__Group_2__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:506:1: ( ( 'description' ) ) // InternalRoboticMiddleware.g:507:1: ( 'description' ) { // InternalRoboticMiddleware.g:507:1: ( 'description' ) // InternalRoboticMiddleware.g:508:2: 'description' { before(grammarAccess.getACE_SmartSoftAccess().getDescriptionKeyword_2_0()); match(input,13,FOLLOW_2); after(grammarAccess.getACE_SmartSoftAccess().getDescriptionKeyword_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group_2__0__Impl" // $ANTLR start "rule__ACE_SmartSoft__Group_2__1" // InternalRoboticMiddleware.g:517:1: rule__ACE_SmartSoft__Group_2__1 : rule__ACE_SmartSoft__Group_2__1__Impl ; public final void rule__ACE_SmartSoft__Group_2__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:521:1: ( rule__ACE_SmartSoft__Group_2__1__Impl ) // InternalRoboticMiddleware.g:522:2: rule__ACE_SmartSoft__Group_2__1__Impl { pushFollow(FOLLOW_2); rule__ACE_SmartSoft__Group_2__1__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group_2__1" // $ANTLR start "rule__ACE_SmartSoft__Group_2__1__Impl" // InternalRoboticMiddleware.g:528:1: rule__ACE_SmartSoft__Group_2__1__Impl : ( ( rule__ACE_SmartSoft__DescriptionAssignment_2_1 ) ) ; public final void rule__ACE_SmartSoft__Group_2__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:532:1: ( ( ( rule__ACE_SmartSoft__DescriptionAssignment_2_1 ) ) ) // InternalRoboticMiddleware.g:533:1: ( ( rule__ACE_SmartSoft__DescriptionAssignment_2_1 ) ) { // InternalRoboticMiddleware.g:533:1: ( ( rule__ACE_SmartSoft__DescriptionAssignment_2_1 ) ) // InternalRoboticMiddleware.g:534:2: ( rule__ACE_SmartSoft__DescriptionAssignment_2_1 ) { before(grammarAccess.getACE_SmartSoftAccess().getDescriptionAssignment_2_1()); // InternalRoboticMiddleware.g:535:2: ( rule__ACE_SmartSoft__DescriptionAssignment_2_1 ) // InternalRoboticMiddleware.g:535:3: rule__ACE_SmartSoft__DescriptionAssignment_2_1 { pushFollow(FOLLOW_2); rule__ACE_SmartSoft__DescriptionAssignment_2_1(); state._fsp--; } after(grammarAccess.getACE_SmartSoftAccess().getDescriptionAssignment_2_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__Group_2__1__Impl" // $ANTLR start "rule__OpcUa_SeRoNet__Group__0" // InternalRoboticMiddleware.g:544:1: rule__OpcUa_SeRoNet__Group__0 : rule__OpcUa_SeRoNet__Group__0__Impl rule__OpcUa_SeRoNet__Group__1 ; public final void rule__OpcUa_SeRoNet__Group__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:548:1: ( rule__OpcUa_SeRoNet__Group__0__Impl rule__OpcUa_SeRoNet__Group__1 ) // InternalRoboticMiddleware.g:549:2: rule__OpcUa_SeRoNet__Group__0__Impl rule__OpcUa_SeRoNet__Group__1 { pushFollow(FOLLOW_9); rule__OpcUa_SeRoNet__Group__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__OpcUa_SeRoNet__Group__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group__0" // $ANTLR start "rule__OpcUa_SeRoNet__Group__0__Impl" // InternalRoboticMiddleware.g:556:1: rule__OpcUa_SeRoNet__Group__0__Impl : ( () ) ; public final void rule__OpcUa_SeRoNet__Group__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:560:1: ( ( () ) ) // InternalRoboticMiddleware.g:561:1: ( () ) { // InternalRoboticMiddleware.g:561:1: ( () ) // InternalRoboticMiddleware.g:562:2: () { before(grammarAccess.getOpcUa_SeRoNetAccess().getOpcUa_SeRoNetAction_0()); // InternalRoboticMiddleware.g:563:2: () // InternalRoboticMiddleware.g:563:3: { } after(grammarAccess.getOpcUa_SeRoNetAccess().getOpcUa_SeRoNetAction_0()); } } } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group__0__Impl" // $ANTLR start "rule__OpcUa_SeRoNet__Group__1" // InternalRoboticMiddleware.g:571:1: rule__OpcUa_SeRoNet__Group__1 : rule__OpcUa_SeRoNet__Group__1__Impl rule__OpcUa_SeRoNet__Group__2 ; public final void rule__OpcUa_SeRoNet__Group__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:575:1: ( rule__OpcUa_SeRoNet__Group__1__Impl rule__OpcUa_SeRoNet__Group__2 ) // InternalRoboticMiddleware.g:576:2: rule__OpcUa_SeRoNet__Group__1__Impl rule__OpcUa_SeRoNet__Group__2 { pushFollow(FOLLOW_7); rule__OpcUa_SeRoNet__Group__1__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__OpcUa_SeRoNet__Group__2(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group__1" // $ANTLR start "rule__OpcUa_SeRoNet__Group__1__Impl" // InternalRoboticMiddleware.g:583:1: rule__OpcUa_SeRoNet__Group__1__Impl : ( 'OpcUa_SeRoNet' ) ; public final void rule__OpcUa_SeRoNet__Group__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:587:1: ( ( 'OpcUa_SeRoNet' ) ) // InternalRoboticMiddleware.g:588:1: ( 'OpcUa_SeRoNet' ) { // InternalRoboticMiddleware.g:588:1: ( 'OpcUa_SeRoNet' ) // InternalRoboticMiddleware.g:589:2: 'OpcUa_SeRoNet' { before(grammarAccess.getOpcUa_SeRoNetAccess().getOpcUa_SeRoNetKeyword_1()); match(input,14,FOLLOW_2); after(grammarAccess.getOpcUa_SeRoNetAccess().getOpcUa_SeRoNetKeyword_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group__1__Impl" // $ANTLR start "rule__OpcUa_SeRoNet__Group__2" // InternalRoboticMiddleware.g:598:1: rule__OpcUa_SeRoNet__Group__2 : rule__OpcUa_SeRoNet__Group__2__Impl ; public final void rule__OpcUa_SeRoNet__Group__2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:602:1: ( rule__OpcUa_SeRoNet__Group__2__Impl ) // InternalRoboticMiddleware.g:603:2: rule__OpcUa_SeRoNet__Group__2__Impl { pushFollow(FOLLOW_2); rule__OpcUa_SeRoNet__Group__2__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group__2" // $ANTLR start "rule__OpcUa_SeRoNet__Group__2__Impl" // InternalRoboticMiddleware.g:609:1: rule__OpcUa_SeRoNet__Group__2__Impl : ( ( rule__OpcUa_SeRoNet__Group_2__0 )? ) ; public final void rule__OpcUa_SeRoNet__Group__2__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:613:1: ( ( ( rule__OpcUa_SeRoNet__Group_2__0 )? ) ) // InternalRoboticMiddleware.g:614:1: ( ( rule__OpcUa_SeRoNet__Group_2__0 )? ) { // InternalRoboticMiddleware.g:614:1: ( ( rule__OpcUa_SeRoNet__Group_2__0 )? ) // InternalRoboticMiddleware.g:615:2: ( rule__OpcUa_SeRoNet__Group_2__0 )? { before(grammarAccess.getOpcUa_SeRoNetAccess().getGroup_2()); // InternalRoboticMiddleware.g:616:2: ( rule__OpcUa_SeRoNet__Group_2__0 )? int alt4=2; int LA4_0 = input.LA(1); if ( (LA4_0==13) ) { alt4=1; } switch (alt4) { case 1 : // InternalRoboticMiddleware.g:616:3: rule__OpcUa_SeRoNet__Group_2__0 { pushFollow(FOLLOW_2); rule__OpcUa_SeRoNet__Group_2__0(); state._fsp--; } break; } after(grammarAccess.getOpcUa_SeRoNetAccess().getGroup_2()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group__2__Impl" // $ANTLR start "rule__OpcUa_SeRoNet__Group_2__0" // InternalRoboticMiddleware.g:625:1: rule__OpcUa_SeRoNet__Group_2__0 : rule__OpcUa_SeRoNet__Group_2__0__Impl rule__OpcUa_SeRoNet__Group_2__1 ; public final void rule__OpcUa_SeRoNet__Group_2__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:629:1: ( rule__OpcUa_SeRoNet__Group_2__0__Impl rule__OpcUa_SeRoNet__Group_2__1 ) // InternalRoboticMiddleware.g:630:2: rule__OpcUa_SeRoNet__Group_2__0__Impl rule__OpcUa_SeRoNet__Group_2__1 { pushFollow(FOLLOW_8); rule__OpcUa_SeRoNet__Group_2__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__OpcUa_SeRoNet__Group_2__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group_2__0" // $ANTLR start "rule__OpcUa_SeRoNet__Group_2__0__Impl" // InternalRoboticMiddleware.g:637:1: rule__OpcUa_SeRoNet__Group_2__0__Impl : ( 'description' ) ; public final void rule__OpcUa_SeRoNet__Group_2__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:641:1: ( ( 'description' ) ) // InternalRoboticMiddleware.g:642:1: ( 'description' ) { // InternalRoboticMiddleware.g:642:1: ( 'description' ) // InternalRoboticMiddleware.g:643:2: 'description' { before(grammarAccess.getOpcUa_SeRoNetAccess().getDescriptionKeyword_2_0()); match(input,13,FOLLOW_2); after(grammarAccess.getOpcUa_SeRoNetAccess().getDescriptionKeyword_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group_2__0__Impl" // $ANTLR start "rule__OpcUa_SeRoNet__Group_2__1" // InternalRoboticMiddleware.g:652:1: rule__OpcUa_SeRoNet__Group_2__1 : rule__OpcUa_SeRoNet__Group_2__1__Impl ; public final void rule__OpcUa_SeRoNet__Group_2__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:656:1: ( rule__OpcUa_SeRoNet__Group_2__1__Impl ) // InternalRoboticMiddleware.g:657:2: rule__OpcUa_SeRoNet__Group_2__1__Impl { pushFollow(FOLLOW_2); rule__OpcUa_SeRoNet__Group_2__1__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group_2__1" // $ANTLR start "rule__OpcUa_SeRoNet__Group_2__1__Impl" // InternalRoboticMiddleware.g:663:1: rule__OpcUa_SeRoNet__Group_2__1__Impl : ( ( rule__OpcUa_SeRoNet__DescriptionAssignment_2_1 ) ) ; public final void rule__OpcUa_SeRoNet__Group_2__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:667:1: ( ( ( rule__OpcUa_SeRoNet__DescriptionAssignment_2_1 ) ) ) // InternalRoboticMiddleware.g:668:1: ( ( rule__OpcUa_SeRoNet__DescriptionAssignment_2_1 ) ) { // InternalRoboticMiddleware.g:668:1: ( ( rule__OpcUa_SeRoNet__DescriptionAssignment_2_1 ) ) // InternalRoboticMiddleware.g:669:2: ( rule__OpcUa_SeRoNet__DescriptionAssignment_2_1 ) { before(grammarAccess.getOpcUa_SeRoNetAccess().getDescriptionAssignment_2_1()); // InternalRoboticMiddleware.g:670:2: ( rule__OpcUa_SeRoNet__DescriptionAssignment_2_1 ) // InternalRoboticMiddleware.g:670:3: rule__OpcUa_SeRoNet__DescriptionAssignment_2_1 { pushFollow(FOLLOW_2); rule__OpcUa_SeRoNet__DescriptionAssignment_2_1(); state._fsp--; } after(grammarAccess.getOpcUa_SeRoNetAccess().getDescriptionAssignment_2_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__Group_2__1__Impl" // $ANTLR start "rule__CORBA_SmartSoft__Group__0" // InternalRoboticMiddleware.g:679:1: rule__CORBA_SmartSoft__Group__0 : rule__CORBA_SmartSoft__Group__0__Impl rule__CORBA_SmartSoft__Group__1 ; public final void rule__CORBA_SmartSoft__Group__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:683:1: ( rule__CORBA_SmartSoft__Group__0__Impl rule__CORBA_SmartSoft__Group__1 ) // InternalRoboticMiddleware.g:684:2: rule__CORBA_SmartSoft__Group__0__Impl rule__CORBA_SmartSoft__Group__1 { pushFollow(FOLLOW_10); rule__CORBA_SmartSoft__Group__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__CORBA_SmartSoft__Group__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group__0" // $ANTLR start "rule__CORBA_SmartSoft__Group__0__Impl" // InternalRoboticMiddleware.g:691:1: rule__CORBA_SmartSoft__Group__0__Impl : ( () ) ; public final void rule__CORBA_SmartSoft__Group__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:695:1: ( ( () ) ) // InternalRoboticMiddleware.g:696:1: ( () ) { // InternalRoboticMiddleware.g:696:1: ( () ) // InternalRoboticMiddleware.g:697:2: () { before(grammarAccess.getCORBA_SmartSoftAccess().getCORBA_SmartSoftAction_0()); // InternalRoboticMiddleware.g:698:2: () // InternalRoboticMiddleware.g:698:3: { } after(grammarAccess.getCORBA_SmartSoftAccess().getCORBA_SmartSoftAction_0()); } } } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group__0__Impl" // $ANTLR start "rule__CORBA_SmartSoft__Group__1" // InternalRoboticMiddleware.g:706:1: rule__CORBA_SmartSoft__Group__1 : rule__CORBA_SmartSoft__Group__1__Impl rule__CORBA_SmartSoft__Group__2 ; public final void rule__CORBA_SmartSoft__Group__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:710:1: ( rule__CORBA_SmartSoft__Group__1__Impl rule__CORBA_SmartSoft__Group__2 ) // InternalRoboticMiddleware.g:711:2: rule__CORBA_SmartSoft__Group__1__Impl rule__CORBA_SmartSoft__Group__2 { pushFollow(FOLLOW_7); rule__CORBA_SmartSoft__Group__1__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__CORBA_SmartSoft__Group__2(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group__1" // $ANTLR start "rule__CORBA_SmartSoft__Group__1__Impl" // InternalRoboticMiddleware.g:718:1: rule__CORBA_SmartSoft__Group__1__Impl : ( 'CORBA_SmartSoft' ) ; public final void rule__CORBA_SmartSoft__Group__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:722:1: ( ( 'CORBA_SmartSoft' ) ) // InternalRoboticMiddleware.g:723:1: ( 'CORBA_SmartSoft' ) { // InternalRoboticMiddleware.g:723:1: ( 'CORBA_SmartSoft' ) // InternalRoboticMiddleware.g:724:2: 'CORBA_SmartSoft' { before(grammarAccess.getCORBA_SmartSoftAccess().getCORBA_SmartSoftKeyword_1()); match(input,15,FOLLOW_2); after(grammarAccess.getCORBA_SmartSoftAccess().getCORBA_SmartSoftKeyword_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group__1__Impl" // $ANTLR start "rule__CORBA_SmartSoft__Group__2" // InternalRoboticMiddleware.g:733:1: rule__CORBA_SmartSoft__Group__2 : rule__CORBA_SmartSoft__Group__2__Impl ; public final void rule__CORBA_SmartSoft__Group__2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:737:1: ( rule__CORBA_SmartSoft__Group__2__Impl ) // InternalRoboticMiddleware.g:738:2: rule__CORBA_SmartSoft__Group__2__Impl { pushFollow(FOLLOW_2); rule__CORBA_SmartSoft__Group__2__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group__2" // $ANTLR start "rule__CORBA_SmartSoft__Group__2__Impl" // InternalRoboticMiddleware.g:744:1: rule__CORBA_SmartSoft__Group__2__Impl : ( ( rule__CORBA_SmartSoft__Group_2__0 )? ) ; public final void rule__CORBA_SmartSoft__Group__2__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:748:1: ( ( ( rule__CORBA_SmartSoft__Group_2__0 )? ) ) // InternalRoboticMiddleware.g:749:1: ( ( rule__CORBA_SmartSoft__Group_2__0 )? ) { // InternalRoboticMiddleware.g:749:1: ( ( rule__CORBA_SmartSoft__Group_2__0 )? ) // InternalRoboticMiddleware.g:750:2: ( rule__CORBA_SmartSoft__Group_2__0 )? { before(grammarAccess.getCORBA_SmartSoftAccess().getGroup_2()); // InternalRoboticMiddleware.g:751:2: ( rule__CORBA_SmartSoft__Group_2__0 )? int alt5=2; int LA5_0 = input.LA(1); if ( (LA5_0==13) ) { alt5=1; } switch (alt5) { case 1 : // InternalRoboticMiddleware.g:751:3: rule__CORBA_SmartSoft__Group_2__0 { pushFollow(FOLLOW_2); rule__CORBA_SmartSoft__Group_2__0(); state._fsp--; } break; } after(grammarAccess.getCORBA_SmartSoftAccess().getGroup_2()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group__2__Impl" // $ANTLR start "rule__CORBA_SmartSoft__Group_2__0" // InternalRoboticMiddleware.g:760:1: rule__CORBA_SmartSoft__Group_2__0 : rule__CORBA_SmartSoft__Group_2__0__Impl rule__CORBA_SmartSoft__Group_2__1 ; public final void rule__CORBA_SmartSoft__Group_2__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:764:1: ( rule__CORBA_SmartSoft__Group_2__0__Impl rule__CORBA_SmartSoft__Group_2__1 ) // InternalRoboticMiddleware.g:765:2: rule__CORBA_SmartSoft__Group_2__0__Impl rule__CORBA_SmartSoft__Group_2__1 { pushFollow(FOLLOW_8); rule__CORBA_SmartSoft__Group_2__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__CORBA_SmartSoft__Group_2__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group_2__0" // $ANTLR start "rule__CORBA_SmartSoft__Group_2__0__Impl" // InternalRoboticMiddleware.g:772:1: rule__CORBA_SmartSoft__Group_2__0__Impl : ( 'description' ) ; public final void rule__CORBA_SmartSoft__Group_2__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:776:1: ( ( 'description' ) ) // InternalRoboticMiddleware.g:777:1: ( 'description' ) { // InternalRoboticMiddleware.g:777:1: ( 'description' ) // InternalRoboticMiddleware.g:778:2: 'description' { before(grammarAccess.getCORBA_SmartSoftAccess().getDescriptionKeyword_2_0()); match(input,13,FOLLOW_2); after(grammarAccess.getCORBA_SmartSoftAccess().getDescriptionKeyword_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group_2__0__Impl" // $ANTLR start "rule__CORBA_SmartSoft__Group_2__1" // InternalRoboticMiddleware.g:787:1: rule__CORBA_SmartSoft__Group_2__1 : rule__CORBA_SmartSoft__Group_2__1__Impl ; public final void rule__CORBA_SmartSoft__Group_2__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:791:1: ( rule__CORBA_SmartSoft__Group_2__1__Impl ) // InternalRoboticMiddleware.g:792:2: rule__CORBA_SmartSoft__Group_2__1__Impl { pushFollow(FOLLOW_2); rule__CORBA_SmartSoft__Group_2__1__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group_2__1" // $ANTLR start "rule__CORBA_SmartSoft__Group_2__1__Impl" // InternalRoboticMiddleware.g:798:1: rule__CORBA_SmartSoft__Group_2__1__Impl : ( ( rule__CORBA_SmartSoft__DescriptionAssignment_2_1 ) ) ; public final void rule__CORBA_SmartSoft__Group_2__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:802:1: ( ( ( rule__CORBA_SmartSoft__DescriptionAssignment_2_1 ) ) ) // InternalRoboticMiddleware.g:803:1: ( ( rule__CORBA_SmartSoft__DescriptionAssignment_2_1 ) ) { // InternalRoboticMiddleware.g:803:1: ( ( rule__CORBA_SmartSoft__DescriptionAssignment_2_1 ) ) // InternalRoboticMiddleware.g:804:2: ( rule__CORBA_SmartSoft__DescriptionAssignment_2_1 ) { before(grammarAccess.getCORBA_SmartSoftAccess().getDescriptionAssignment_2_1()); // InternalRoboticMiddleware.g:805:2: ( rule__CORBA_SmartSoft__DescriptionAssignment_2_1 ) // InternalRoboticMiddleware.g:805:3: rule__CORBA_SmartSoft__DescriptionAssignment_2_1 { pushFollow(FOLLOW_2); rule__CORBA_SmartSoft__DescriptionAssignment_2_1(); state._fsp--; } after(grammarAccess.getCORBA_SmartSoftAccess().getDescriptionAssignment_2_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__Group_2__1__Impl" // $ANTLR start "rule__DDS_SmartSoft__Group__0" // InternalRoboticMiddleware.g:814:1: rule__DDS_SmartSoft__Group__0 : rule__DDS_SmartSoft__Group__0__Impl rule__DDS_SmartSoft__Group__1 ; public final void rule__DDS_SmartSoft__Group__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:818:1: ( rule__DDS_SmartSoft__Group__0__Impl rule__DDS_SmartSoft__Group__1 ) // InternalRoboticMiddleware.g:819:2: rule__DDS_SmartSoft__Group__0__Impl rule__DDS_SmartSoft__Group__1 { pushFollow(FOLLOW_11); rule__DDS_SmartSoft__Group__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__DDS_SmartSoft__Group__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group__0" // $ANTLR start "rule__DDS_SmartSoft__Group__0__Impl" // InternalRoboticMiddleware.g:826:1: rule__DDS_SmartSoft__Group__0__Impl : ( () ) ; public final void rule__DDS_SmartSoft__Group__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:830:1: ( ( () ) ) // InternalRoboticMiddleware.g:831:1: ( () ) { // InternalRoboticMiddleware.g:831:1: ( () ) // InternalRoboticMiddleware.g:832:2: () { before(grammarAccess.getDDS_SmartSoftAccess().getDDS_SmartSoftAction_0()); // InternalRoboticMiddleware.g:833:2: () // InternalRoboticMiddleware.g:833:3: { } after(grammarAccess.getDDS_SmartSoftAccess().getDDS_SmartSoftAction_0()); } } } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group__0__Impl" // $ANTLR start "rule__DDS_SmartSoft__Group__1" // InternalRoboticMiddleware.g:841:1: rule__DDS_SmartSoft__Group__1 : rule__DDS_SmartSoft__Group__1__Impl rule__DDS_SmartSoft__Group__2 ; public final void rule__DDS_SmartSoft__Group__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:845:1: ( rule__DDS_SmartSoft__Group__1__Impl rule__DDS_SmartSoft__Group__2 ) // InternalRoboticMiddleware.g:846:2: rule__DDS_SmartSoft__Group__1__Impl rule__DDS_SmartSoft__Group__2 { pushFollow(FOLLOW_7); rule__DDS_SmartSoft__Group__1__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__DDS_SmartSoft__Group__2(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group__1" // $ANTLR start "rule__DDS_SmartSoft__Group__1__Impl" // InternalRoboticMiddleware.g:853:1: rule__DDS_SmartSoft__Group__1__Impl : ( 'DDS_SmartSoft' ) ; public final void rule__DDS_SmartSoft__Group__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:857:1: ( ( 'DDS_SmartSoft' ) ) // InternalRoboticMiddleware.g:858:1: ( 'DDS_SmartSoft' ) { // InternalRoboticMiddleware.g:858:1: ( 'DDS_SmartSoft' ) // InternalRoboticMiddleware.g:859:2: 'DDS_SmartSoft' { before(grammarAccess.getDDS_SmartSoftAccess().getDDS_SmartSoftKeyword_1()); match(input,16,FOLLOW_2); after(grammarAccess.getDDS_SmartSoftAccess().getDDS_SmartSoftKeyword_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group__1__Impl" // $ANTLR start "rule__DDS_SmartSoft__Group__2" // InternalRoboticMiddleware.g:868:1: rule__DDS_SmartSoft__Group__2 : rule__DDS_SmartSoft__Group__2__Impl ; public final void rule__DDS_SmartSoft__Group__2() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:872:1: ( rule__DDS_SmartSoft__Group__2__Impl ) // InternalRoboticMiddleware.g:873:2: rule__DDS_SmartSoft__Group__2__Impl { pushFollow(FOLLOW_2); rule__DDS_SmartSoft__Group__2__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group__2" // $ANTLR start "rule__DDS_SmartSoft__Group__2__Impl" // InternalRoboticMiddleware.g:879:1: rule__DDS_SmartSoft__Group__2__Impl : ( ( rule__DDS_SmartSoft__Group_2__0 )? ) ; public final void rule__DDS_SmartSoft__Group__2__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:883:1: ( ( ( rule__DDS_SmartSoft__Group_2__0 )? ) ) // InternalRoboticMiddleware.g:884:1: ( ( rule__DDS_SmartSoft__Group_2__0 )? ) { // InternalRoboticMiddleware.g:884:1: ( ( rule__DDS_SmartSoft__Group_2__0 )? ) // InternalRoboticMiddleware.g:885:2: ( rule__DDS_SmartSoft__Group_2__0 )? { before(grammarAccess.getDDS_SmartSoftAccess().getGroup_2()); // InternalRoboticMiddleware.g:886:2: ( rule__DDS_SmartSoft__Group_2__0 )? int alt6=2; int LA6_0 = input.LA(1); if ( (LA6_0==13) ) { alt6=1; } switch (alt6) { case 1 : // InternalRoboticMiddleware.g:886:3: rule__DDS_SmartSoft__Group_2__0 { pushFollow(FOLLOW_2); rule__DDS_SmartSoft__Group_2__0(); state._fsp--; } break; } after(grammarAccess.getDDS_SmartSoftAccess().getGroup_2()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group__2__Impl" // $ANTLR start "rule__DDS_SmartSoft__Group_2__0" // InternalRoboticMiddleware.g:895:1: rule__DDS_SmartSoft__Group_2__0 : rule__DDS_SmartSoft__Group_2__0__Impl rule__DDS_SmartSoft__Group_2__1 ; public final void rule__DDS_SmartSoft__Group_2__0() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:899:1: ( rule__DDS_SmartSoft__Group_2__0__Impl rule__DDS_SmartSoft__Group_2__1 ) // InternalRoboticMiddleware.g:900:2: rule__DDS_SmartSoft__Group_2__0__Impl rule__DDS_SmartSoft__Group_2__1 { pushFollow(FOLLOW_8); rule__DDS_SmartSoft__Group_2__0__Impl(); state._fsp--; pushFollow(FOLLOW_2); rule__DDS_SmartSoft__Group_2__1(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group_2__0" // $ANTLR start "rule__DDS_SmartSoft__Group_2__0__Impl" // InternalRoboticMiddleware.g:907:1: rule__DDS_SmartSoft__Group_2__0__Impl : ( 'description' ) ; public final void rule__DDS_SmartSoft__Group_2__0__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:911:1: ( ( 'description' ) ) // InternalRoboticMiddleware.g:912:1: ( 'description' ) { // InternalRoboticMiddleware.g:912:1: ( 'description' ) // InternalRoboticMiddleware.g:913:2: 'description' { before(grammarAccess.getDDS_SmartSoftAccess().getDescriptionKeyword_2_0()); match(input,13,FOLLOW_2); after(grammarAccess.getDDS_SmartSoftAccess().getDescriptionKeyword_2_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group_2__0__Impl" // $ANTLR start "rule__DDS_SmartSoft__Group_2__1" // InternalRoboticMiddleware.g:922:1: rule__DDS_SmartSoft__Group_2__1 : rule__DDS_SmartSoft__Group_2__1__Impl ; public final void rule__DDS_SmartSoft__Group_2__1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:926:1: ( rule__DDS_SmartSoft__Group_2__1__Impl ) // InternalRoboticMiddleware.g:927:2: rule__DDS_SmartSoft__Group_2__1__Impl { pushFollow(FOLLOW_2); rule__DDS_SmartSoft__Group_2__1__Impl(); state._fsp--; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group_2__1" // $ANTLR start "rule__DDS_SmartSoft__Group_2__1__Impl" // InternalRoboticMiddleware.g:933:1: rule__DDS_SmartSoft__Group_2__1__Impl : ( ( rule__DDS_SmartSoft__DescriptionAssignment_2_1 ) ) ; public final void rule__DDS_SmartSoft__Group_2__1__Impl() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:937:1: ( ( ( rule__DDS_SmartSoft__DescriptionAssignment_2_1 ) ) ) // InternalRoboticMiddleware.g:938:1: ( ( rule__DDS_SmartSoft__DescriptionAssignment_2_1 ) ) { // InternalRoboticMiddleware.g:938:1: ( ( rule__DDS_SmartSoft__DescriptionAssignment_2_1 ) ) // InternalRoboticMiddleware.g:939:2: ( rule__DDS_SmartSoft__DescriptionAssignment_2_1 ) { before(grammarAccess.getDDS_SmartSoftAccess().getDescriptionAssignment_2_1()); // InternalRoboticMiddleware.g:940:2: ( rule__DDS_SmartSoft__DescriptionAssignment_2_1 ) // InternalRoboticMiddleware.g:940:3: rule__DDS_SmartSoft__DescriptionAssignment_2_1 { pushFollow(FOLLOW_2); rule__DDS_SmartSoft__DescriptionAssignment_2_1(); state._fsp--; } after(grammarAccess.getDDS_SmartSoftAccess().getDescriptionAssignment_2_1()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__Group_2__1__Impl" // $ANTLR start "rule__ACE_SmartSoft__DescriptionAssignment_2_1" // InternalRoboticMiddleware.g:949:1: rule__ACE_SmartSoft__DescriptionAssignment_2_1 : ( ruleEString ) ; public final void rule__ACE_SmartSoft__DescriptionAssignment_2_1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:953:1: ( ( ruleEString ) ) // InternalRoboticMiddleware.g:954:2: ( ruleEString ) { // InternalRoboticMiddleware.g:954:2: ( ruleEString ) // InternalRoboticMiddleware.g:955:3: ruleEString { before(grammarAccess.getACE_SmartSoftAccess().getDescriptionEStringParserRuleCall_2_1_0()); pushFollow(FOLLOW_2); ruleEString(); state._fsp--; after(grammarAccess.getACE_SmartSoftAccess().getDescriptionEStringParserRuleCall_2_1_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__ACE_SmartSoft__DescriptionAssignment_2_1" // $ANTLR start "rule__OpcUa_SeRoNet__DescriptionAssignment_2_1" // InternalRoboticMiddleware.g:964:1: rule__OpcUa_SeRoNet__DescriptionAssignment_2_1 : ( ruleEString ) ; public final void rule__OpcUa_SeRoNet__DescriptionAssignment_2_1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:968:1: ( ( ruleEString ) ) // InternalRoboticMiddleware.g:969:2: ( ruleEString ) { // InternalRoboticMiddleware.g:969:2: ( ruleEString ) // InternalRoboticMiddleware.g:970:3: ruleEString { before(grammarAccess.getOpcUa_SeRoNetAccess().getDescriptionEStringParserRuleCall_2_1_0()); pushFollow(FOLLOW_2); ruleEString(); state._fsp--; after(grammarAccess.getOpcUa_SeRoNetAccess().getDescriptionEStringParserRuleCall_2_1_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__OpcUa_SeRoNet__DescriptionAssignment_2_1" // $ANTLR start "rule__CORBA_SmartSoft__DescriptionAssignment_2_1" // InternalRoboticMiddleware.g:979:1: rule__CORBA_SmartSoft__DescriptionAssignment_2_1 : ( ruleEString ) ; public final void rule__CORBA_SmartSoft__DescriptionAssignment_2_1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:983:1: ( ( ruleEString ) ) // InternalRoboticMiddleware.g:984:2: ( ruleEString ) { // InternalRoboticMiddleware.g:984:2: ( ruleEString ) // InternalRoboticMiddleware.g:985:3: ruleEString { before(grammarAccess.getCORBA_SmartSoftAccess().getDescriptionEStringParserRuleCall_2_1_0()); pushFollow(FOLLOW_2); ruleEString(); state._fsp--; after(grammarAccess.getCORBA_SmartSoftAccess().getDescriptionEStringParserRuleCall_2_1_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__CORBA_SmartSoft__DescriptionAssignment_2_1" // $ANTLR start "rule__DDS_SmartSoft__DescriptionAssignment_2_1" // InternalRoboticMiddleware.g:994:1: rule__DDS_SmartSoft__DescriptionAssignment_2_1 : ( ruleEString ) ; public final void rule__DDS_SmartSoft__DescriptionAssignment_2_1() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalRoboticMiddleware.g:998:1: ( ( ruleEString ) ) // InternalRoboticMiddleware.g:999:2: ( ruleEString ) { // InternalRoboticMiddleware.g:999:2: ( ruleEString ) // InternalRoboticMiddleware.g:1000:3: ruleEString { before(grammarAccess.getDDS_SmartSoftAccess().getDescriptionEStringParserRuleCall_2_1_0()); pushFollow(FOLLOW_2); ruleEString(); state._fsp--; after(grammarAccess.getDDS_SmartSoftAccess().getDescriptionEStringParserRuleCall_2_1_0()); } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { restoreStackSize(stackSize); } return ; } // $ANTLR end "rule__DDS_SmartSoft__DescriptionAssignment_2_1" // Delegated rules public static final BitSet FOLLOW_1 = new BitSet(new long[]{0x0000000000000000L}); public static final BitSet FOLLOW_2 = new BitSet(new long[]{0x0000000000000002L}); public static final BitSet FOLLOW_3 = new BitSet(new long[]{0x0000000000000800L}); public static final BitSet FOLLOW_4 = new BitSet(new long[]{0x0000000000000802L}); public static final BitSet FOLLOW_5 = new BitSet(new long[]{0x0000000000000020L}); public static final BitSet FOLLOW_6 = new BitSet(new long[]{0x0000000000001000L}); public static final BitSet FOLLOW_7 = new BitSet(new long[]{0x0000000000002000L}); public static final BitSet FOLLOW_8 = new BitSet(new long[]{0x0000000000000010L}); public static final BitSet FOLLOW_9 = new BitSet(new long[]{0x0000000000004000L}); public static final BitSet FOLLOW_10 = new BitSet(new long[]{0x0000000000008000L}); public static final BitSet FOLLOW_11 = new BitSet(new long[]{0x0000000000010000L}); }
package ru.job4j.loop; /** * Class Fitness calculates number of month needed one bodybuilder to overtake another in dead lift. * @author Vit Efremov (freshman4000@gmail.com) * @since 04.07.2019. * @version 1.0. */ public class Fitness { /** * Month calculation. * @param ivan 1st bodybuilder. * @param nik 2nd bodybuilder. * @return number of month. */ public int calc(int ivan, int nik) { int month = 0; while (ivan < nik) { ivan *= 3; nik *= 2; month++; } return month; } }
/* * 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.catalina.ant; import org.apache.tools.ant.BuildException; /** * Ant task that implements the <code>/roles</code> command, supported by the * Tomcat manager application. * * @author Craig R. McClanahan * @version $Revision: 466595 $ $Date: 2006-10-21 23:24:41 +0100 (Sat, 21 Oct 2006) $ * @since 4.1 */ public class RolesTask extends AbstractCatalinaTask { // ------------------------------------------------------------- Properties // --------------------------------------------------------- Public Methods /** * Execute the requested operation. * * @exception BuildException if an error occurs */ public void execute() throws BuildException { super.execute(); execute("/roles"); } }
package io.github.hotstu.moui.widget.recycler; import androidx.recyclerview.widget.RecyclerView; /** * 判断recyclerview到底部的辅助类,继承fetchdata方法实现加载更多功能 */ public abstract class ReachBottomListener extends RecyclerView.OnScrollListener { private static final String TAG = ReachBottomListener.class.getSimpleName(); private boolean loading; public void resetLoading() { this.loading = false; } @Override public void onScrolled(RecyclerView r, int dx, int dy) { if (loading) return; int contentHeight = r.getHeight() - (r.getPaddingTop() + r.getPaddingBottom()); int scrollRange = r.computeVerticalScrollRange(); int scrollOffset = r.computeVerticalScrollOffset(); boolean reachBottom = scrollRange <= scrollOffset + contentHeight; if (reachBottom) { this.loading = true; onReachBottom(); } } /** * 加载数据,加载完成后需要手动调用resetLoading() * */ protected abstract void onReachBottom(); }
package org.atlasapi.query.v4.schedule; import java.time.ZonedDateTime; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import com.google.api.client.util.Lists; import com.metabroadcast.applications.client.model.internal.AccessRoles; import com.metabroadcast.applications.client.model.internal.Application; import com.metabroadcast.applications.client.model.internal.ApplicationConfiguration; import com.metabroadcast.applications.client.model.internal.Environment; import org.atlasapi.application.v3.ApplicationAccessRole; import org.atlasapi.channel.Channel; import org.atlasapi.channel.ChannelResolver; import org.atlasapi.content.Broadcast; import org.atlasapi.content.Content; import org.atlasapi.content.Item; import org.atlasapi.content.ItemAndBroadcast; import org.atlasapi.entity.Id; import org.atlasapi.entity.util.Resolved; import org.atlasapi.equivalence.ApplicationEquivalentsMerger; import org.atlasapi.equivalence.EquivalenceGraph; import org.atlasapi.equivalence.Equivalent; import org.atlasapi.media.entity.Publisher; import org.atlasapi.output.NotFoundException; import org.atlasapi.query.annotation.ActiveAnnotations; import org.atlasapi.query.common.QueryResult; import org.atlasapi.query.common.context.QueryContext; import org.atlasapi.query.common.exceptions.QueryExecutionException; import org.atlasapi.schedule.ChannelSchedule; import org.atlasapi.schedule.EquivalentChannelSchedule; import org.atlasapi.schedule.EquivalentSchedule; import org.atlasapi.schedule.EquivalentScheduleEntry; import org.atlasapi.schedule.EquivalentScheduleResolver; import org.atlasapi.schedule.FlexibleBroadcastMatcher; import com.metabroadcast.common.time.DateTimeZones; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.Futures; import org.joda.time.DateTime; import org.joda.time.Interval; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.atlasapi.media.entity.Publisher.METABROADCAST; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class EquivalentScheduleQueryExecutorTest { @Mock private ApplicationEquivalentsMerger<Content> equivalentsMerger; @Mock private ChannelResolver channelResolver; @Mock private EquivalentScheduleResolver scheduleResolver; @Mock private FlexibleBroadcastMatcher broadcastMatcher; @Mock private Application application = mock(Application.class); @Mock private HttpServletRequest request = mock(HttpServletRequest.class); private QueryContext queryContext; private EquivalentScheduleQueryExecutor executor; @Before public void setup() { executor = new EquivalentScheduleQueryExecutor( channelResolver, scheduleResolver, equivalentsMerger, broadcastMatcher ); AccessRoles accessRoles = mock(AccessRoles.class); when(accessRoles.hasRole(ApplicationAccessRole.PREFER_EBS_SCHEDULE.getRole())).thenReturn(false); when(application.getAccessRoles()).thenReturn(accessRoles); when(application.getConfiguration()).thenReturn(getConfig()); queryContext = QueryContext.create( application, ActiveAnnotations.standard(), request ); } @Test public void testExecutingSingleScheduleQuery() throws Exception { Channel channel = Channel.builder(Publisher.BBC).build(); channel.setId(1L); channel.setCanonicalUri("one"); DateTime start = new DateTime(0, DateTimeZones.UTC); DateTime end = new DateTime(0, DateTimeZones.UTC); Interval interval = new Interval(start, end); ScheduleQuery query = ScheduleQuery.builder() .withSource(METABROADCAST) .withStart(start) .withEnd(end) .withContext(queryContext) .withId(channel.getId()) .build(); EquivalentChannelSchedule channelSchedule = new EquivalentChannelSchedule( channel, interval, ImmutableList.<EquivalentScheduleEntry>of() ); when(channelResolver.resolveIds(ImmutableSet.of(channel.getId()))) .thenReturn(Futures.immediateFuture(Resolved.valueOf(ImmutableList.of(channel)))); when(scheduleResolver.resolveSchedules(argThat(hasItems(channel)), eq(interval), eq(query.getSource()), argThat(is(ImmutableSet.of(query.getSource()))) )) .thenReturn(Futures.immediateFuture(new EquivalentSchedule(ImmutableList.of( channelSchedule), interval))); QueryResult<ChannelSchedule> result = executor.execute(query); assertThat( result.getOnlyResource(), is(new ChannelSchedule(channel, interval, ImmutableList.<ItemAndBroadcast>of())) ); } @Test public void testExecutingMultiScheduleQuery() throws Exception { Channel channelOne = Channel.builder(Publisher.BBC) .withKey("key1") .withId(1L) .withUri("one") .build(); Channel channelTwo = Channel.builder(Publisher.BBC) .withKey("key2") .withId(2L) .withUri("two") .build(); DateTime start = new DateTime(0, DateTimeZones.UTC); DateTime end = new DateTime(0, DateTimeZones.UTC); Interval interval = new Interval(start, end); List<Id> cids = ImmutableList.of(channelOne.getId(), channelTwo.getId()); ScheduleQuery query = ScheduleQuery.builder() .withSource(METABROADCAST) .withStart(start) .withEnd(end) .withContext(queryContext) .withIds(cids) .build(); EquivalentChannelSchedule cs1 = new EquivalentChannelSchedule( channelOne, interval, ImmutableList.<EquivalentScheduleEntry>of() ); EquivalentChannelSchedule cs2 = new EquivalentChannelSchedule( channelTwo, interval, ImmutableList.<EquivalentScheduleEntry>of() ); when(channelResolver.resolveIds(argThat(org.hamcrest.Matchers.<Id>iterableWithSize(2)))) .thenReturn(Futures.immediateFuture(Resolved.valueOf(ImmutableList.of( channelOne, channelTwo )))); when(scheduleResolver.resolveSchedules(argThat(hasItems(channelOne, channelTwo)), eq(interval), eq(query.getSource()), argThat(is(ImmutableSet.of(query.getSource()))) )) .thenReturn(Futures.immediateFuture(new EquivalentSchedule(ImmutableList.of( cs1, cs2 ), interval))); QueryResult<ChannelSchedule> result = executor.execute(query); assertThat(result.getResources().toList(), is(ImmutableList.of( new ChannelSchedule(channelOne, interval, ImmutableList.<ItemAndBroadcast>of()), new ChannelSchedule(channelTwo, interval, ImmutableList.<ItemAndBroadcast>of()) ))); } @Test public void testThrowsExceptionIfChannelIsMissing() { when(channelResolver.resolveIds(any(List.class))) .thenReturn(Futures.immediateFuture(Resolved.<Channel>empty())); DateTime start = new DateTime(0, DateTimeZones.UTC); DateTime end = new DateTime(0, DateTimeZones.UTC); Interval interval = new Interval(start, end); ScheduleQuery query = ScheduleQuery.builder() .withSource(METABROADCAST) .withStart(start) .withEnd(end) .withContext(queryContext) .withId(Id.valueOf(1)) .build(); try { executor.execute(query); fail("expected NotFoundException"); } catch (QueryExecutionException qee) { assertThat(qee, is(instanceOf(NotFoundException.class))); verifyZeroInteractions(scheduleResolver); } } @Test public void testResolvesEquivalentContentForApiKeyWithPrecedenceEnabled() throws Exception { Channel channel = Channel.builder(Publisher.BBC).build(); channel.setId(1L); channel.setCanonicalUri("one"); Channel channel2 = Channel.builder(Publisher.BBC).build(); channel2.setId(2L); channel2.setCanonicalUri("two"); DateTime start = new DateTime(0, DateTimeZones.UTC); DateTime end = new DateTime(0, DateTimeZones.UTC); Interval interval = new Interval(start, end); Application application = Application.builder() .withId(-1l) .withTitle("test") .withDescription("desc") .withEnvironment(Environment.STAGE) .withCreated(ZonedDateTime.now()) .withApiKey("apiKey") .withSources(ApplicationConfiguration.builder() .withPrecedence(Publisher.all().asList()) .withEnabledWriteSources(Lists.newArrayList()) .build()) .withAllowedDomains(Lists.newArrayList()) .withAccessRoles(mock(AccessRoles.class)) .withRevoked(false) .build(); QueryContext context = QueryContext.create( application, ActiveAnnotations.standard(), mock(HttpServletRequest.class) ); Id itemId = Id.valueOf(1); Item scheduleItem = new Item(itemId, METABROADCAST); Item equivalentItem = new Item(Id.valueOf(2), METABROADCAST); Broadcast targetBroadcast = new Broadcast(channel, interval); Set<Broadcast> equivalentBroadcasts = ImmutableSet.of( targetBroadcast, new Broadcast(channel2, interval) ); equivalentItem.setBroadcasts(equivalentBroadcasts); scheduleItem.setThisOrChildLastUpdated(DateTime.now(DateTimeZones.UTC)); Broadcast originalBroadcast = new Broadcast(channel, interval); EquivalentChannelSchedule channelSchedule = new EquivalentChannelSchedule(channel, interval, ImmutableList.of( EquivalentScheduleEntry.create( originalBroadcast, scheduleItem.getId(), new Equivalent<>( EquivalenceGraph.valueOf(scheduleItem.toRef()), ImmutableList.of(scheduleItem, equivalentItem) ) ) ) ); ScheduleQuery query = ScheduleQuery.builder() .withSource(METABROADCAST) .withStart(start) .withEnd(end) .withContext(context) .withId(channel.getId()) .build(); when(channelResolver.resolveIds(argThat(org.hamcrest.Matchers.iterableWithSize(1)))) .thenReturn(Futures.immediateFuture(Resolved.valueOf(ImmutableList.of(channel)))); when(scheduleResolver.resolveSchedules(argThat(hasItems(channel)), eq(interval), eq(query.getSource()), argThat(is(query.getContext() .getApplication() .getConfiguration() .getEnabledReadSources()) ))) .thenReturn(Futures.immediateFuture(new EquivalentSchedule(ImmutableList.of( channelSchedule), interval))); when(equivalentsMerger.merge( Optional.absent(), ImmutableSet.of(scheduleItem, equivalentItem), application, context.getAnnotations().all() )) .thenReturn(ImmutableList.of(equivalentItem)); when(broadcastMatcher.findMatchingBroadcast(originalBroadcast, equivalentBroadcasts)) .thenReturn(Optional.of(targetBroadcast)); QueryResult<ChannelSchedule> result = executor.execute(query); assertThat( result.getOnlyResource().getEntries().get(0).getItem(), sameInstance(equivalentItem) ); assertThat( result.getOnlyResource().getEntries().get(0).getBroadcast(), sameInstance(targetBroadcast) ); verify(equivalentsMerger).merge( Optional.<Id>absent(), ImmutableSet.of(scheduleItem, equivalentItem), application, context.getAnnotations().all() ); } private ApplicationConfiguration getConfig() { return ApplicationConfiguration.builder() .withNoPrecedence(Publisher.all().stream() .filter(Publisher::enabledWithNoApiKey) .collect(Collectors.toList())) .withEnabledWriteSources(ImmutableList.of()) .build(); } }
/* * Copyright Strimzi authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.strimzi.operator.cluster.operator.resource; import org.junit.jupiter.api.Test; import static io.strimzi.operator.cluster.operator.resource.Quantities.formatMemory; import static io.strimzi.operator.cluster.operator.resource.Quantities.formatMilliCpu; import static io.strimzi.operator.cluster.operator.resource.Quantities.normalizeCpu; import static io.strimzi.operator.cluster.operator.resource.Quantities.normalizeMemory; import static io.strimzi.operator.cluster.operator.resource.Quantities.parseCpuAsMilliCpus; import static io.strimzi.operator.cluster.operator.resource.Quantities.parseMemory; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; public class QuantitiesTest { @Test public void testParseMemory() { assertThat(parseMemory("1234"), is(1234L)); assertThat(parseMemory("0"), is(0L)); assertThat(parseMemory("1K"), is(1000L)); assertThat(parseMemory("1Ki"), is(1024L)); assertThat(parseMemory("512Ki"), is(512 * 1024L)); assertThat(parseMemory("1e6"), is(1_000_000L)); assertThat(parseMemory("0"), is(0L)); assertThat(parseMemory("0K"), is(0L)); assertThat(parseMemory("0e6"), is(0L)); assertThat(parseMemory("500Mi"), is(524288000L)); assertThat(parseMemory("1.1Gi"), is(1181116006L)); assertThat(parseMemory("1.1G"), is(1100000000L)); assertThat(parseMemory("1.1e3K"), is(1100000L)); try { parseMemory("-1K"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("K"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("1Kb"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("foo"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("1.1x"); fail(); } catch (IllegalArgumentException e) { } try { parseMemory("1.1e-1"); fail(); } catch (IllegalArgumentException e) { } } @Test public void testFormatMemory() { assertThat(formatMemory(0), is("0")); assertThat(formatMemory(1), is("1")); assertThat(formatMemory(1023), is("1023")); assertThat(formatMemory(1024), is("1024")); assertThat(formatMemory(1000), is("1000")); assertThat(formatMemory(2048), is("2048")); assertThat(formatMemory(2000), is("2000")); assertThat(formatMemory(2048 * 1024), is("2097152")); assertThat(formatMemory(2048 * 2000), is("4096000")); assertThat(formatMemory(2000 * 2000), is("4000000")); assertThat(formatMemory(1_000_000_000_000_000L), is("1000000000000000")); assertThat(formatMemory(1_000_000_000_000_000_000L), is("1000000000000000000")); assertThat(formatMemory(parseMemory("1Ei")), is("1125899906842624")); assertThat(formatMemory(parseMemory("1024Ei")), is("1152921504606846976")); assertThat(formatMemory(524288000L), is("524288000")); } @Test public void testNormalizeMemory() { assertThat(normalizeMemory("1K"), is("1000")); assertThat(normalizeMemory("1Ki"), is("1024")); assertThat(normalizeMemory("1M"), is("1000000")); assertThat(normalizeMemory("1Mi"), is("1048576")); assertThat(normalizeMemory("12345"), is("12345")); assertThat(normalizeMemory("500Mi"), is("524288000")); assertThat(normalizeMemory("1.1Gi"), is("1181116006")); assertThat(normalizeMemory("1.2Gi"), is("1288490188")); } @Test public void testParse() { assertThat(parseCpuAsMilliCpus("1"), is(1000)); assertThat(parseCpuAsMilliCpus("1m"), is(1)); assertThat(parseCpuAsMilliCpus("0.5"), is(500)); assertThat(parseCpuAsMilliCpus("0"), is(0)); assertThat(parseCpuAsMilliCpus("0m"), is(0)); assertThat(parseCpuAsMilliCpus("0.0"), is(0)); assertThat(parseCpuAsMilliCpus("0.000001"), is(0)); try { parseCpuAsMilliCpus("0.0m"); fail(); } catch (NumberFormatException e) { } try { parseCpuAsMilliCpus("0.1m"); fail(); } catch (NumberFormatException e) { } } @Test public void testFormat() { assertThat(formatMilliCpu(1000), is("1")); assertThat(formatMilliCpu(500), is("500m")); assertThat(formatMilliCpu(1), is("1m")); } @Test public void testRt() { assertThat(formatMilliCpu(parseCpuAsMilliCpus("1")), is("1")); assertThat(formatMilliCpu(parseCpuAsMilliCpus("500m")), is("500m")); assertThat(formatMilliCpu(parseCpuAsMilliCpus("1m")), is("1m")); } @Test public void testNormalizeCpu() { assertThat(normalizeCpu("1"), is("1")); assertThat(normalizeCpu("1000m"), is("1")); assertThat(normalizeCpu("500m"), is("500m")); assertThat(normalizeCpu("0.5"), is("500m")); assertThat(normalizeCpu("0.1"), is("100m")); assertThat(normalizeCpu("0.01"), is("10m")); assertThat(normalizeCpu("0.001"), is("1m")); } }
package arrays.arraylistnumbers; import java.util.ArrayList; public class Classifier { private ArrayList<Integer> listA; private ArrayList<Integer> listB; private ArrayList<Integer> listC; private ArrayList<Integer> listD; public void classify(ArrayList<Integer> a, ArrayList<Integer> b){ this.listA = a; this.listB = b; this.listC = new ArrayList<Integer>(); this.listD = new ArrayList<Integer>(); ArrayList<Integer> checked = new ArrayList<Integer>(); int num; for (int i = 0; i < listB.size(); i++){ num = listB.get(i); if(!checked.contains(num)) { if (listA.contains(num)) { this.listC.add(num); } else { this.listD.add(num); } checked.add(num); } } } public ArrayList<Integer> getListC(){ return this.listC; } public ArrayList<Integer> getListD(){ return this.listD; } }
package com.qa.ims.utils; import java.util.Scanner; public class Utils { public static final String MYSQL_URL = "35.197.254.95:3306"; public static final Scanner SCANNER = new Scanner(System.in); private Utils() { } public static String getInput() { return SCANNER.nextLine(); } public static int getInt() { return SCANNER.nextInt(); } }
package com.ensaf.etudiant.mtapplication.util; import android.util.EventLogTags; import com.ensaf.etudiant.mtapplication.R; import com.ensaf.etudiant.mtapplication.model.DummyModel; import com.ensaf.etudiant.mtapplication.model.ImageGalleryCategoryModel; import com.ensaf.etudiant.mtapplication.model.ImageGallerySubcategoryModel; import java.util.ArrayList; import java.util.Random; public class DummyContent { public static ArrayList<DummyModel> getDummyModelList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "http://pengaja.com/uiapptemplate/newphotos/profileimages/0.jpg", "Isaac Reid", R.string.fontello_heart_empty)); list.add(new DummyModel(1, "http://pengaja.com/uiapptemplate/newphotos/profileimages/1.jpg", "Jason Graham", R.string.fontello_heart_empty)); list.add(new DummyModel(2, "http://pengaja.com/uiapptemplate/newphotos/profileimages/2.jpg", "Abigail Ross", R.string.fontello_heart_empty)); list.add(new DummyModel(3, "http://pengaja.com/uiapptemplate/newphotos/profileimages/3.jpg", "Justin Rutherford", R.string.fontello_heart_empty)); list.add(new DummyModel(4, "http://pengaja.com/uiapptemplate/newphotos/profileimages/4.jpg", "Nicholas Henderson", R.string.fontello_heart_empty)); list.add(new DummyModel(5, "http://pengaja.com/uiapptemplate/newphotos/profileimages/5.jpg", "Elizabeth Mackenzie", R.string.fontello_heart_empty)); list.add(new DummyModel(6, "http://pengaja.com/uiapptemplate/newphotos/profileimages/6.jpg", "Melanie Ferguson", R.string.fontello_heart_empty)); list.add(new DummyModel(7, "http://pengaja.com/uiapptemplate/newphotos/profileimages/7.jpg", "Fiona Kelly", R.string.fontello_heart_empty)); list.add(new DummyModel(8, "http://pengaja.com/uiapptemplate/newphotos/profileimages/8.jpg", "Nicholas King", R.string.fontello_heart_empty)); list.add(new DummyModel(9, "http://pengaja.com/uiapptemplate/newphotos/profileimages/9.jpg", "Victoria Mitchell", R.string.fontello_heart_empty)); list.add(new DummyModel(10, "http://pengaja.com/uiapptemplate/newphotos/profileimages/10.jpg", "Sophie Lyman", R.string.fontello_heart_empty)); list.add(new DummyModel(11, "http://pengaja.com/uiapptemplate/newphotos/profileimages/11.jpg", "Carl Ince", R.string.fontello_heart_empty)); list.add(new DummyModel(12, "http://pengaja.com/uiapptemplate/newphotos/profileimages/12.jpg", "Michelle Slater", R.string.fontello_heart_empty)); list.add(new DummyModel(13, "http://pengaja.com/uiapptemplate/newphotos/profileimages/13.jpg", "Ryan Mathis", R.string.fontello_heart_empty)); list.add(new DummyModel(14, "http://pengaja.com/uiapptemplate/newphotos/profileimages/14.jpg", "Julia Grant", R.string.fontello_heart_empty)); list.add(new DummyModel(15, "http://pengaja.com/uiapptemplate/newphotos/profileimages/15.jpg", "Hannah Martin", R.string.fontello_heart_empty)); return list; } public static ArrayList<DummyModel> getDummyModelSwipeToDissmissTravelList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "http://pengaja.com/uiapptemplate/newphotos/listviews/swipetodissmiss/travel/0.jpg", "Monument walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(1, "http://pengaja.com/uiapptemplate/newphotos/listviews/swipetodissmiss/travel/1.jpg", "River walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(2, "http://pengaja.com/uiapptemplate/newphotos/listviews/swipetodissmiss/travel/2.jpg", "City walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(3, "http://pengaja.com/uiapptemplate/newphotos/listviews/swipetodissmiss/travel/3.jpg", "Park walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(4, "http://pengaja.com/uiapptemplate/newphotos/listviews/swipetodissmiss/travel/4.jpg", "Vilage walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(5, "http://pengaja.com/uiapptemplate/newphotos/listviews/swipetodissmiss/travel/5.jpg", "Lake walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(6, "http://pengaja.com/uiapptemplate/newphotos/listviews/swipetodissmiss/travel/6.jpg", "Castle walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(7, "http://pengaja.com/uiapptemplate/newphotos/listviews/swipetodissmiss/travel/7.jpg", "Beach walk tour", R.string.fontello_heart_empty)); return list; } public static ArrayList<DummyModel> getDummyModelSwipeToDissmissSocialList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "http://pengaja.com/uiapptemplate/newphotos/profileimages/3.jpg", "Monument walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(1, "http://pengaja.com/uiapptemplate/newphotos/profileimages/4.jpg", "River walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(2, "http://pengaja.com/uiapptemplate/newphotos/profileimages/5.jpg", "City walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(3, "http://pengaja.com/uiapptemplate/newphotos/profileimages/6.jpg", "Park walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(4, "http://pengaja.com/uiapptemplate/newphotos/profileimages/7.jpg", "Vilage walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(5, "http://pengaja.com/uiapptemplate/newphotos/profileimages/8.jpg", "Lake walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(6, "http://pengaja.com/uiapptemplate/newphotos/profileimages/9.jpg", "Castle walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(7, "http://pengaja.com/uiapptemplate/newphotos/profileimages/10.jpg", "Beach walk tour", R.string.fontello_heart_empty)); return list; } public static ArrayList<DummyModel> getDummyModelGoogleCardsTravelList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/0.jpg", "Bab Boujloud", R.string.fontello_heart_empty)); list.add(new DummyModel(1, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/1.jpg", "Fontaine Nejjarine", R.string.fontello_heart_empty)); list.add(new DummyModel(2, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/2.jpg", "Palais El Mokri", R.string.fontello_heart_empty)); list.add(new DummyModel(3, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/3.jpg", "Borj Nord", R.string.fontello_heart_empty)); list.add(new DummyModel(4, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/4.jpg", "Vilage walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(5, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/5.jpg", "Lake walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(6, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/6.jpg", "Castle walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(7, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/7.jpg", "Beach walk tour", R.string.fontello_heart_empty)); return list; } public static ArrayList<DummyModel> getDummyModelDragAndDropTravelList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/0.jpg", "Bab Boujloud", R.string.fontello_heart_empty)); list.add(new DummyModel(1, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/1.jpg", "Fontaine Nejjarine", R.string.fontello_heart_empty)); list.add(new DummyModel(2, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/2.jpg", "Palais El Mokri", R.string.fontello_heart_empty)); list.add(new DummyModel(3, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/3.jpg", "Borj Nord", R.string.fontello_heart_empty)); list.add(new DummyModel(4, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/4.jpg", "Vilage walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(5, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/5.jpg", "Lake walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(6, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/6.jpg", "Castle walk tour", R.string.fontello_heart_empty)); list.add(new DummyModel(7, "http://pengaja.com/uiapptemplate/newphotos/listviews/draganddrop/travel/7.jpg", "Beach walk tour", R.string.fontello_heart_empty)); return list; } public static ArrayList<DummyModel> getDummyModelListSocial() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "http://pengaja.com/uiapptemplate/newphotos/listviews/googlecards/travel/0.jpg", "Jane Smith", R.string.fontello_heart_empty)); list.add(new DummyModel(1, "http://pengaja.com/uiapptemplate/newphotos/listviews/googlecards/travel/1.jpg", "Jane Smith", R.string.fontello_heart_empty)); list.add(new DummyModel(2, "http://pengaja.com/uiapptemplate/newphotos/listviews/googlecards/travel/2.jpg", "Jane Smith", R.string.fontello_heart_empty)); list.add(new DummyModel(3, "http://pengaja.com/uiapptemplate/newphotos/listviews/googlecards/travel/3.jpg", "Jane Smith", R.string.fontello_heart_empty)); list.add(new DummyModel(4, "http://pengaja.com/uiapptemplate/newphotos/listviews/googlecards/travel/4.jpg", "Jane Smith", R.string.fontello_heart_empty)); list.add(new DummyModel(5, "http://pengaja.com/uiapptemplate/newphotos/listviews/googlecards/travel/5.jpg", "Jane Smith", R.string.fontello_heart_empty)); list.add(new DummyModel(6, "http://pengaja.com/uiapptemplate/newphotos/listviews/googlecards/travel/6.jpg", "Jane Smith", R.string.fontello_heart_empty)); list.add(new DummyModel(7, "http://pengaja.com/uiapptemplate/newphotos/listviews/googlecards/travel/7.jpg", "Jane Smith", R.string.fontello_heart_empty)); return list; } public static ArrayList<DummyModel> getDummyModelListTravel() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "", "Joe's restaurant", R.string.fontello_heart_empty)); list.add(new DummyModel(1, "", "Good restaurant", R.string.fontello_heart_empty)); list.add(new DummyModel(2, "", "Express restaurant", R.string.fontello_heart_empty)); list.add(new DummyModel(3, "", "Mine restaurant", R.string.fontello_heart_empty)); list.add(new DummyModel(4, "", "Love restaurant", R.string.fontello_heart_empty)); list.add(new DummyModel(5, "", "Story restaurant", R.string.fontello_heart_empty)); return list; } public static ArrayList<DummyModel> getTravelDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "", "Where To Go", R.string.material_icon_go)); list.add(new DummyModel(1, "", "Where To Sleep", R.string.material_icon_sleep)); list.add(new DummyModel(2, "", "Where To Eat", R.string.material_icon_eat)); list.add(new DummyModel(3, "", "Where To Drink", R.string.material_icon_drink)); list.add(new DummyModel(4, "", "Where To Party", R.string.material_icon_party)); list.add(new DummyModel(5, "", "Where To Play", R.string.material_icon_play)); list.add(new DummyModel(6, "", "Where To Shop", R.string.material_icon_shop)); return list; } //TODO Change to social public static ArrayList<DummyModel> getSocialDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "", "Friends", R.string.material_icon_account)); list.add(new DummyModel(1, "", "Enemies", R.string.material_icon_account)); list.add(new DummyModel(2, "", "Natural", R.string.material_icon_account)); list.add(new DummyModel(3, "", "Family", R.string.material_icon_account)); list.add(new DummyModel(4, "", "Guests", R.string.material_icon_account)); list.add(new DummyModel(5, "", "Students", R.string.material_icon_account)); return list; } //TODO Change to media public static ArrayList<DummyModel> getMediaDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "", "", R.string.material_icon_go)); list.add(new DummyModel(1, "", "", R.string.material_icon_sleep)); list.add(new DummyModel(2, "", "", R.string.material_icon_eat)); list.add(new DummyModel(3, "", "", R.string.material_icon_drink)); list.add(new DummyModel(4, "", "", R.string.material_icon_party)); list.add(new DummyModel(5, "", "", R.string.material_icon_play)); list.add(new DummyModel(6, "", "", R.string.material_icon_shop)); return list; } //TODO Change to shopping public static ArrayList<DummyModel> getShoppingDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "", "", R.string.material_icon_go)); list.add(new DummyModel(1, "", "", R.string.material_icon_sleep)); list.add(new DummyModel(2, "", "", R.string.material_icon_eat)); list.add(new DummyModel(3, "", "", R.string.material_icon_drink)); list.add(new DummyModel(4, "", "", R.string.material_icon_party)); list.add(new DummyModel(5, "", "", R.string.material_icon_play)); list.add(new DummyModel(6, "", "", R.string.material_icon_shop)); return list; } //TODO Change to news public static ArrayList<DummyModel> getNewsDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, "", "", R.string.material_icon_go)); list.add(new DummyModel(1, "", "", R.string.material_icon_sleep)); list.add(new DummyModel(2, "", "", R.string.material_icon_eat)); list.add(new DummyModel(3, "", "", R.string.material_icon_drink)); list.add(new DummyModel(4, "", "", R.string.material_icon_party)); list.add(new DummyModel(5, "", "", R.string.material_icon_play)); list.add(new DummyModel(6, "", "", R.string.material_icon_shop)); return list; } private static String babBoujloudDescription = "Construite une première fois au XIème siècle," + " elle a été restaurée et réaménagée à plusieurs reprises.\n" + " En 1913, sous le règne du Sultan Alaouite Moulay Hafid," + " cette porte a été décorée en céramique émaillée, bleue d’un côté et" + " verte de l autre. \n" + "La face bleue de la porte donne sur l extérieur de la Médina"; private static String fontaineNejjarineDescription = "La fontaine Nejjarine est la plus belle des 70 fontaines publiques que compte Fès. "; private static String palaisElMokriDescription = "Le palais El Mokri fait partie du patrimoine du Maroc.\n" + "Construit en plein médina," + " il reflète l art ancestral du Maroc qui peut s\\'en orgueillir" + " d avoir une vingtaine de palais à la médina de Fès." + " Quelques uns ont gardé leur cachet d époque ou on peut aussi admirer" + " la finesse du travail du bois," + " des zelliges et du plâtre (escaliers et mobiliers...)" + " des menuisiers ébénistes ou encore la délicatesse des fers forgés" + " véritablement sculptés aux scalpels par des maîtres forges qui étaient" + " des artistes remarquables.\n" + "Le dallage de marbre blanc (de carrare) et noir se disputent" + " l attention avec de riches revêtements de mosaïques en céramique" + " finement découpées, les plafonds et coupoles sculpté et peint," + " les menuiseries baroques serties de verres sablés de Venise" + " et de couleur de Bagdad."; private static String borjNordDescription = "Le Borj Nord est un fort élevé en 1588 au nord de Fès, au Maroc, sur ordre du sultan Ahmed al-Mansur,\n" + " dont le plan s inspire de l architecture des forteresses portugaises du xvie siècle.\n" + " Il était l un des plus grands postes de surveillance de la ville de Fès et servait " + " également de fabrique de canons.\n" + "De plan carré, les quatre coins sont dotés de quatre bastions en forme de fers de lance.\n" + "La terrasse est conçue de manière à résister au poids et aux tirs des canons.\n" + "Ayant servi de caserne puis de prison du temps du Protectorat français," + " le monument abrite depuis 1963 le Musée des Armes.\n" + "aussi Borj Sud, Borj Touil, Borj Sidi Bounafaa, Borj Cheikh Ahmed"; public static ArrayList<DummyModel> getMonumentsDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.0617199, -4.9846022, "Bab Boujloud", "http://www.maroc-maroc.com/places/img45.jpg", "Bab Boujloud", babBoujloudDescription, R.string.material_icon_go)); list.add(new DummyModel(1, 34.0648044, -4.9781887, "Fontaine Nejjarine", "https://media-cdn.tripadvisor.com/media/photo-s/03/e0/65/2e/fontaine-nejjarine.jpg", "Fontaine Nejjarine", fontaineNejjarineDescription, R.string.material_icon_sleep)); list.add(new DummyModel(2, 34.0591279, -4.978817, "Palais El Mokri", "http://palaiselmokri.com/images/dar1/pa1g.jpg", "Palais El Mokri", palaisElMokriDescription, R.string.material_icon_eat)); list.add(new DummyModel(3, 34.0672336, -4.9872073, "Borj Nord", "http://static.panoramio.com/photos/original/24027986.jpg", "Borj Nord", borjNordDescription, R.string.material_icon_drink)); return list; } private static String KairaouineMosqueDescription = "Al Quaraouiyine (en arabe : القرويين) est une université située à Fès, au Maroc.\n" + "Selon la tradition, sa construction débute en 859 sous le règne de la dynastie idrisside.\n" + "Elle est considérée comme l une des plus anciennes universités dans" + " le monde encore en activité1."; private static String MedersaBouInaniaDescription = "La Médersa Bou Inania (arabe المدرسة أبو عنانية بفاس)" + " est une médersa édifiée à Fès, au Maroc, entre 1350 et 1355 pour" + " le sultan Abou Inan Faris (r. 1348 - 59)," + "soit sous la dynastie des Mérinides.\n" + " Elle est la seule médersa de la ville comportant un minaret," + " et elle jouxtait aussi des boutiques permettant son financement," + " ainsi que de vastes latrines, qui témoignent de son caractère public.\n" + "En effet, la médersa fonctionnait aussi bien comme une école" + " que comme mosquée du vendredi."; private static String AttarinMedersaDescription = "La Médersa Attarine est une ancienne école coranique de Fès au Maroc.\n" + "Elle fut construite entre 1323 et 1325 par le sultan mérinide Abou Saîd Othman.\n" + "Elle fut nommée d après le Souk de parfums et d épices attenant," + " Souk El Attarine. Elle se situe à proximité de la Quaraouiyine1"; public static ArrayList<DummyModel> getHistoriqueDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.064919, -4.9755786, "Kairaouine Mosque", "http://www.medias24.com/images/photos_artices/big/qaraouiyine.jpg", "Kairaouine Mosque", KairaouineMosqueDescription, R.string.material_icon_go)); list.add(new DummyModel(1, 34.0622501, -4.9848927, "Medersa Bou Inania", "https://upload.wikimedia.org/wikipedia/commons/a/a1/Bou_Inania_Madrasa_2011.jpg", "Medersa Bou Inania", MedersaBouInaniaDescription, R.string.material_icon_sleep)); list.add(new DummyModel(2, 34.0650832, -4.9759222, "Attarin Medersa", "http://blog.juliehall.net/wp-content/uploads/2011/06/fez-medersa-4.jpg", "Attarin Medersa", AttarinMedersaDescription, R.string.material_icon_eat)); return list; } private static String LancienneMedinaFèsDescription = ""; private static String FesMellahDescription = ""; private static String FesJdidDescription = ""; private static String BoujloudSquareDescription = ""; public static ArrayList<DummyModel> getTourismeDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 12, 150, "L'ancienne Médina de Fès", "http://p5.storage.canalblog.com/59/72/409639/30595950_p.jpg", "l'ancienne Médina de Fès", "", R.string.material_icon_go)); list.add(new DummyModel(1, 12, 150, "Fés Mellah", "http://img.actualidadviajes.com/wp-content/uploads/2012/07/fez.jpg", "Fés Mellah", "", R.string.material_icon_sleep)); list.add(new DummyModel(2, 12, 150, "Fés el-Jdid", "http://static.yabiladi.com/files/articles/670521195b6b22b5bc994f4fa1e38edb350.jpg", "Fés el-Jdid", "", R.string.material_icon_eat)); list.add(new DummyModel(3, 12, 150, "Boujloud Square", "http://static1.squarespace.com/static/527679aee4b06f1a7db2bffd/t/54e350d9e4b0a566f12e3c15/1424183525043/Fez+Morocco?format=1000w", "Boujloud Square", "", R.string.material_icon_drink)); return list; } private static String ComplexeSportifDescription = "Le Complexe sportif de Fès est un stade de football localisé dans" + " la ville de Fès et plus précisément sur la route menant à Sefrou," + " il est d un style architectural typiquement marocain." + "Situé sur une superficie de 40 hectares," + " le complexe sportif de Fès peut accueillir 37 000 spectateurs tous assis.\n" + "Il est doté d une piste d athlétisme" + " en tartan outre des annexes susceptibles" + " d accueillir des compétitions de haut niveau."; private static String ClubsFootballDescription = "La ville de Fés est représentée par deux équipes de football," + " la première est le Wydad athlétique de Fès WAF fondée en 1948 est" + " joue actuellement en deuxième division du championnat marocain," + " la seconde est le Maghreb Association sportive de Fès" + " (en arabe : المغرب الرياضي الفاسي) qui est un club omnisports" + " marocain fondé en 1946. Le MAS est la première équipe marocaine" + " à atteindre les seizièmes de finale de la Coupe de France en" + " 1954 contre Red Star à lépoque à Paris.\n" + "Le MAS est un des clubs les plus titrés du royaume," + " avec un palmarès remarquable : Championnat du Maroc : (4)"; public static ArrayList<DummyModel> getSportsDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.0023125, -4.9716972, "Complexe sportif de Fès", "http://www.somagec.ma/galerie/91-0.jpg", "Complexe sportif de Fès", ComplexeSportifDescription, R.string.material_icon_go)); list.add(new DummyModel(1, 34.0024394, -5.0564692, "Clubs de football", "http://www.festourism.org/images/football.jpg", "Clubs de football", ClubsFootballDescription, R.string.material_icon_sleep)); return list; } //Where sleep private static String BarceloDescription = "Accueil professionnel à la réception, " + "chambre très grande avec vue sur place principale. 1073 MAD la nuit, Excellente insonorisation.\n " + "Wifi top dans tout l'hotel. Parking gratuit si vous réservez sur un site sur Internet."; private static String IbisFesDescription = "Établi à quelque 15 km de l'aéroport Fès-Saïss et à " + "3 minutes à pied de la gare de Fès, l'hôtel ibis de Fès constitue une excellente " + "base pour explorer le centre-ville. \n" + "Dans un rayon de 3 km, vous aurez l'occasion d'admirer le palais royal, " + "les jardinsJnan Sbil, Bab Boujloud (la porte Bleue), la médersa Bou Inania, " + "le vieux quartier de Fès el-Bali et la fameuse médina de Fès. \n" + "Un peu plus loin, vous trouverez aussi le mausolée de Mouley Idriss, " + "la place Seffarine et les souks El Attarine et Nejjarine."; private static String RiadAlkantaraDescription = "Une fantastique oasis de paix sous " + "la forme d'une maison d'hote et spa à Fes au " + "Maroc. à 360 MAD la nuit"; public static ArrayList<DummyModel> getHotelsDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.04409, -4.997014, "Barcelo Fes Medina", "http://cls.cdn-hotels.com/hotels/5000000/4670000/4668700/4668670/4668670_20_b.jpg", "Barcelo Fes Medina", BarceloDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.24750, -4.9716972, "Ibis Fes", "http://www.ahstatic.com/photos/2033_ho_00_p_1024x768.jpg", "ibis Fes", IbisFesDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0023125, -4.9716972, "Riad Alkantara", "http://www.anatoliansky.co.uk/_cmsimages/El%20Yacout%203%20Edit.jpg", "Riad Alkantara", RiadAlkantaraDescription, R.string.material_icon_go)); return list; } private static String AUBERGEREDADescription = "L'Auberge de Jeunesse se trouve à 6 km du centre ville de Fès, dans une zone forestière d’une superficie de 2 hectares construites et de 5 hectares en mitoyenneté. \n" + "L'Auberge de Jeunesse comprend 75 lits avec air conditionné, TV, parabole, mini-bar, terrasse…"; private static String DarRabhaDescription = "Dar Rabha, l'endroit idéal pour vous plonger dans les parfums et les sons de la médina de Fès, " + "cette maison est simple et charmant dans le cœur de la capitale spirituelle du Maroc."; public static ArrayList<DummyModel> getAubergesDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.056715, -4.9928965, "AUBERGE DE JEUNESSE FESFES REDA", "http://ekladata.com/WEu_Lued0CPoHJ_cwcorlruLzPs.jpg", "AUBERGE DE JEUNESSE FES REDA", AUBERGEREDADescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0613494, -4.9842495, "Dar Rabha", "http://www.darrabha.com/images/homeSlider/2.jpg", "Dar Rabha", DarRabhaDescription, R.string.material_icon_go)); return list; } public static String RiadTaryanaDescription = "Nous vous accueillerons et vous guiderons pour faire de votre séjour à Fès un moment inoubliable et d’exception.\n" + "Bonnes adresses, conseils, bons plans, explications détaillées, recommandations. \nVous découvrirez l’art de vivre marocain.\n" + "Car au Riad Taryana tout est fait pour vous détendre et mettre vos sens en éveil."; public static String RiadFesPalaceteDescription = "Riad Fes Palacete est une des établissement les plus recunue dans le domaine de l'hébergement ....\n" + "Notre équipe d'interventions est hautement qualifié..."; public static String RiadLallaFatimaDescription = "Le Riad lalla fatima est situé dans la médina, en plein cœur de la vieille ville de Fès, et à seulement 20 mètres de la porte du Bab Ziat."; public static ArrayList<DummyModel> getRiadsDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.0624939, -4.9846065, "Riad Taryana", "http://riadtaryana.com/images/slide/19.jpg", "Riad Taryana", RiadTaryanaDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0599892, -4.9785075, "Riad Fes Palacete", "http://www.riadfespalacete.com/images/1.jpg", "Riad Fes Palacete", RiadFesPalaceteDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0611891, -4.9829586, "Riad Lalla Fatima", "http://www.riadlallafatima.com/wp-content/uploads/2014/08/r11.jpg", "Riad Lalla Fatima", RiadLallaFatimaDescription, R.string.material_icon_go)); return list; } public static String ChickenSpotDescription = "Chicken spot. Toute l'équipe du restaurant Chicken Spot sera heureuse de vous accueillir. Notre terrasse est ... 4 avenue Hassan II V.N Fes. 05 35 65 02 09."; public static String MacDonaldsDescription = "Chaîne emblématique de restauration rapide proposant des menus de burgers-frites, des desserts et milk-shakes.\n" + "Adresse : Ville Nouvelle, Fès 30000, Maroc\n" + "Horaires : Ouvert aujourd'hui · Ouvert 24h/24"; public static String TipicoDescription = "Tipico Pizza (Hay saada). Fast Food. Lot 12, Lotissement Jabri, magasin N° 1, Avenue Ibn El Atir, Fès, Maroc. +212 (0)5 35 60 24 54 / (0)5 35 53 11 12."; public static ArrayList<DummyModel> getFastFoodDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.0023125, -4.9716972, "Chicken spot", "https://entremidietdeux.files.wordpress.com/2012/05/1323885590155.jpg", "Chicken spot", ChickenSpotDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0443463, -4.9960245, "McDonald's", "http://sites.duke.edu/daw2014/files/2014/06/mcdonalds-fez.jpg", "McDonald's", MacDonaldsDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 33.5815954, -7.6285097, "Tipico", "http://www.blanee.com/uploads/pictures/000/120/770/large/e2b6afa17311a26f.jpg", "Tipico", TipicoDescription, R.string.material_icon_go)); return list; } public static String MBFeSDescription = "MB Fes Si ce restaurant tendance mérite le voyage, c’est qu'il est tout simplement le plus beau dans le registre contemporain, et que sa cuisine est tout aussi exceptionnelle."; public static String LAMAISONBLEUEDescription = "Construite en 1915 à Fès, cette sublime demeure garde l'empreinte de son premier et éminent propriétaire, Mohammed El Abbadi, à la fois grand astrologue, juriste et professeur à l'université El Qaraouiyine. " + "\nL'impressionnante et rare bibliothèque lui ayant appartenu est toujours là rappelant la culture et le savoir qui régnaient autrefois dans cette demeure de Fès . La cuisine traditionnelle marocaine y est réalisée dans la plus pure tradition. " + "\nFine, élégante, elle est à la hauteur du lieu."; public static String KAITAIDescription = "Situé en face de l'Hôtel Jnan Palace de Fès, c'est l'alliance de la Thaïlande et du Japon qui se ressent à travers l'espace de nombreux salons, dont la décoration est zen, calme et linéaire. Le Kaï Taï vous propose désormais une cuisine thaïe maîtrisée, tout en ayant conservé ses spécialités japonaises : sushis, makis, sashimis, et california rolls. " + "\nUne très bonne alternative à Fès entre deux repas de cuisine marocaine."; public static String ZENGARDENDescription = "Le Zen Garden est l'adresse située dans la ville nouvelle près de Fès City Center. Les propriétaires sont omniprésents en salle, comme en cuisine. \n" + "Le résultat donne une cuisine internationale goûteuse et raffinée, une clientèle chouchoutée, dans un très joli cadre avec un lounge à l'étage et deux terrasses."; public static ArrayList<DummyModel> getRestorantsDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.0336177, -5.0056991, "MB FÈS", "http://www.bestrestaurantsmaroc.com/public/images/image_list/63d1b176eef6312edd821f2676a486ef_head_format.jpg", "MB FÈS", MBFeSDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0336883, -5.03853, "LA MAISON BLEUE", "http://www.bestrestaurantsmaroc.com/public/images/image_list/be57617983fe11ee1ed7382a17f25f97_head_format.jpg", "LA MAISON BLEUE", LAMAISONBLEUEDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0322799, -5.0065654, "KAÏ TAÏ", "http://www.bestrestaurantsmaroc.com/public/images/image_list/d8405767d382840c539c5eb44d3b22de_head_format.jpg", "LA TERRASSE", KAITAIDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0372699, -5.0156464, "ZEN GARDEN", "http://www.bestrestaurantsmaroc.com/public/images/image_list/01ade148ac9a63c825415a08beb7007c_head_format.jpg", "ZEN GARDEN", ZENGARDENDescription, R.string.material_icon_go)); return list; } public static String AndalousDescription = "Andalous est la combinaison d'un monde d'exception de fusion de styles et d’ambiances. " + "\nSes deux étages, ses ambiances diverse et variées lui donnent une personnalité hors du commun."; public static ArrayList<DummyModel> getDummyBistrotList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.020617, -4.998823, "Andalous", "http://media-cdn.tripadvisor.com/media/photo-s/05/d4/96/41/andalous.jpg", "Andalous", AndalousDescription, R.string.material_icon_go)); return list; } public static String BarcelonaCafeDescription = "Ce café Barcelona et un endroit sympa pleins de jeunes s'y retrouvent pour dialoguer chanter quelques chanson avec guitare ou tam tam trés sympa comme endroit"; public static String Le44Description = "Le 44 est bien fléché et bien situé pour une petite pause dans la Medina. " + "\nL'accueil y est très sympathique. " + "\nQue ce soit le plat du jour ou les menus simples proposés, tout est bien préparé et présenté."; public static String LAVILLADescription = "LA VILLA: boulangerie pâtisserie à Fès, elle vous propose une variété de pâtisseries de style marocain et international. " + "\nRestaurant glacier La villa à Fes."; public static String LaSuiteDescription = "Café La Suite. " + "\nCoffee Shop, Café et Restaurant français. " + "\nRoute Imouzzar, Fès, Maroc. " + "\nItinéraire. Heures: Aucun répertorié (Voir à quel moment les utilisateurs ..."; public static ArrayList<DummyModel> getCaffeDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.0632534, -4.9839309, "Café Barcelona", "https://media-cdn.tripadvisor.com/media/photo-s/02/4d/41/bc/filename-384746-173376929418171.jpg", "Café Barcelona", BarcelonaCafeDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.062919, -4.9851349, "Le 44", "https://media-cdn.tripadvisor.com/media/photo-s/02/c4/64/cb/le-44-cafe-restaurant.jpg", "Le 44", Le44Description, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0159056, -5.0165925, "LA VILLA", "http://www.blanee.com/uploads/pictures/000/076/878/large/2561316cc09cb2bd.jpg", "LA VILLA", LAVILLADescription, R.string.material_icon_go)); list.add(new DummyModel(0, 33.9933262, -4.9968481, "La Suite", "http://www.lasuitefes.com/wp-content/uploads/galleryimages/4T5Kj2KIJHOFU84T.jpg", "La Suite", LaSuiteDescription, R.string.material_icon_go)); return list; } public static String FesCountryClubDescription = ""; public static String FelixClubFesDescription = ""; public static String ActOrNightClubDescription = ""; public static ArrayList<DummyModel> getClubsDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.0398981, -5.0467706, "Fès Country Club", "https://i.ytimg.com/vi/nps5_yrfCsc/maxresdefault.jpg", "Fès Country Club", FesCountryClubDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0416813, -5.0209607, "Felix Club Fes", "http://vampire-fes-3as.vip-blog.com/medias/0906/900524549201075[1].jpg", "Felix Club Fes", FelixClubFesDescription, R.string.material_icon_go)); list.add(new DummyModel(0, 34.0486458, -4.9950456, "ActOr's Night-club", "http://www.blanee.com/uploads/pictures/000/091/626/large/d92012a1838588f0.jpg", "ActOr's Night-club", ActOrNightClubDescription, R.string.material_icon_go)); return list; } public static String Description = ""; public static ArrayList<DummyModel> getDummyList() { ArrayList<DummyModel> list = new ArrayList<>(); list.add(new DummyModel(0, 34.0023125, -4.9716972, "", "", "", ComplexeSportifDescription, R.string.material_icon_go)); return list; } }
package com.ToxicBakery.viewpager.transforms; import android.view.View; public class ZoomOutTranformer extends ABaseTransformer { protected void onTransform(View view, float position) { float scale = 1.0f + Math.abs(position); view.setScaleX(scale); view.setScaleY(scale); view.setPivotX(((float) view.getWidth()) * 0.5f); view.setPivotY(((float) view.getHeight()) * 0.5f); float f = (position < -1.0f || position > 1.0f) ? 0.0f : 1.0f - (scale - 1.0f); view.setAlpha(f); if (position == -1.0f) { view.setTranslationX((float) (view.getWidth() * -1)); } } }
package com.axiba.blockloading; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.util.AttributeSet; import android.view.View; /** * Created by axiba on 2016/11/17. */ public class BlockLoading extends View { public static final String TAG = BlockLoading.class.getSimpleName(); //画笔 private Paint paint; //默认模块颜色 private int defaultColor = Color.rgb(200, 200, 200); //block颜色 private int blockColor; //绘制区域的宽高 private int width; private int height; private static final int DEFAULT_MIN_WIDTH = 200; //默认宽度 private static final int DEFAULT_MIN_HEIGHT = 100; //默认高度 private static final int MIN_ALPHA = 100; //透明度最小值 private static final int MAX_ALPHA = 200; //透明度最大值 private static final int BLOCK_STATE_IN = 1; //增加 private static final int BLOCK_STATE_DE = 2; //减小 private static final int STEP_NUM = 15; //总帧数,从0开始为第一帧 private float blockStepHeight; //每次变化的高度 private int blockStepAlpha; //每次透明度变化的量 // private int blockStep; //当前帧 //当前帧 private int block1Step; private int block2Step; private int block3Step; private int[] blocksStep; //方块的间距 private float blockSpace; //方块的宽和高 private float blockWidth; // private float blockHeight; private float blockMinHeight; //最小的高度 private float blockMaxHeight; //最大的高度 // //方块的顶坐标 // private float blockTop; //方块的左坐标 private float block1Left; private float block2Left; private float block3Left; private float[] blocksLeft; //状态 增加或减小 // private int blockState; private int block1State; private int block2State; private int block3State; private int[] blocksState; private float r; public BlockLoading(Context context) { super(context); } public BlockLoading(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BlockLoading(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.loading); //获取block_color blockColor = a.getColor(R.styleable.loading_block_color, defaultColor); } //初始化参数 private void init(){ //创建画笔 paint = new Paint(Paint.ANTI_ALIAS_FLAG); //设置画笔颜色 // paint.setColor(defaultColor); paint.setColor(blockColor); //设置透明度 paint.setAlpha(100); width = getMeasuredWidth() - getPaddingLeft() - getPaddingRight(); height = getMeasuredHeight() - getPaddingTop() - getPaddingBottom(); //为了保持比例 if ((width / 2) > height) { width = height * 2; } // blockSpace = 25; // blockWidth = 100; // blockHeight = 110; blockSpace = width * 0.05f; blockWidth = width * 0.2f; blockMinHeight = blockWidth * 1.1f; blockMaxHeight = blockWidth * 1.5f; // blockHeight = blockMinHeight; // blockTop = (height - blockHeight) / 2; block2Left = (width - blockWidth) / 2; block1Left = block2Left - blockSpace - blockWidth; block3Left = block2Left + blockSpace + blockWidth; //初始化方块起始状态为变大 // blockState = BLOCK_STATE_IN; block1State = BLOCK_STATE_IN; block2State = BLOCK_STATE_IN; block3State = BLOCK_STATE_IN; //初始化每一帧height变化量 blockStepHeight = (blockMaxHeight - blockMinHeight) / STEP_NUM; blockStepAlpha = Math.round((MAX_ALPHA - MIN_ALPHA) / STEP_NUM); // blockStep = 0; //为每个block初始化不同的起点 block1Step = 14; block2Step = 7; block3Step = 0; r = blockWidth / 8; blocksStep = new int[]{block1Step, block2Step, block3Step}; blocksState = new int[]{block1State, block2State, block3State}; blocksLeft = new float[]{block1Left, block2Left, block3Left}; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getMode(heightMeasureSpec); if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(DEFAULT_MIN_WIDTH, DEFAULT_MIN_HEIGHT); } else if (widthSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(DEFAULT_MIN_WIDTH, heightSpecSize); } else if (heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(widthSpecSize, DEFAULT_MIN_HEIGHT); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); init(); } @Override protected void onDraw(Canvas canvas) { for (int i = 0; i < 3; i++) { drawBlock(canvas, i); } //触动刷新 postInvalidate(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void drawBlock(Canvas canvas, int index){ float blockTop; float blockLeft = blocksLeft[index]; float blockHeight; int blockAlpha; if (blocksState[index] == BLOCK_STATE_IN) { //如果是变大状态,帧数+1 blocksStep[index]++; } else { //如果是变小状态,帧数-1 blocksStep[index]--; } //根据当前帧数获得高度 blockHeight = blockMinHeight + blocksStep[index] * blockStepHeight; //根据当前帧数获得透明度 blockAlpha = MIN_ALPHA + blocksStep[index] * blockStepAlpha; //保持height值在最大值和最小值范围之内 blockHeight = Math.min(blockMaxHeight, Math.max(blockMinHeight, blockHeight)); //保持alpha值在最大值和最小值范围之内 blockAlpha = Math.min(MAX_ALPHA, Math.max(MIN_ALPHA, blockAlpha)); //获取顶点坐标 blockTop = (height - blockHeight) / 2; //设置透明度 paint.setAlpha(blockAlpha); //绘制方块 canvas.drawRoundRect(blockLeft, blockTop, blockLeft + blockWidth, blockTop + blockHeight, r, r, paint); // -5 是为了增加一个停顿感 if (blocksStep[index] >= STEP_NUM) { //如果帧数已经是最后一帧,状态改为变小状态 blocksState[index] = BLOCK_STATE_DE; } else if(blocksStep[index] <= 0 - 5){ //如果帧数已经是第一帧,状态改为变大状态 blocksState[index] = BLOCK_STATE_IN; } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package taskmgt; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.*; import java.util.*; import javax.swing.*; import javax.swing.JOptionPane; import taskmgt.Models.*; /** * * @author Ray */ public class EditProjectGUI extends javax.swing.JDialog implements ActionListener { DefaultListModel listmodel = new DefaultListModel(); ProjectTaskGUI projectgui; Project proj; Date sDate = null; Date eDate = null; String title; String startDate; String endDate; String owner = TaskSystem.getCurrentUser().getEmail(); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); boolean weAreCreating = false; boolean clicked = false; /** * * Creates new weAreCreating CreateProject * * @param parent * @param modal */ public EditProjectGUI(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } public EditProjectGUI(java.awt.Frame parent, boolean modal, String flag) { super(parent, modal); initComponents(); //Fill in dates Date today = new Date(); jTextField2.setText(sdf.format(today)); jTextField3.setText(sdf.format(today)); if (flag.equals("create")) { projectgui = (ProjectTaskGUI) parent; setFormCreate(); } else { projectgui = (ProjectTaskGUI) parent; setFormEdit(); } } private void setFormCreate() { this.setTitle("Create Project"); jButtonCreateProject.setText("Create"); refreshMemberList(); jButton1.hide(); weAreCreating = true; } private void setFormEdit() { this.setTitle("Edit Project"); jButtonCreateProject.setText("Save"); refreshEditMemberList(); setTextFields(); jButton1.show(); jButton1.setText("Delete Project"); weAreCreating = false; } private void setTextFields() { String title = projectgui.getSelectProject().getTitle(); LinkedList<User> members = projectgui.getSelectProject().getMembers(); DefaultListModel jListModel = new DefaultListModel(); for (User membersOnProject : members) { jListModel.addElement(membersOnProject.getEmail()); } jList2.setModel(jListModel); jTextField1.setText(title); Date sDate = projectgui.getSelectProject().getStartDate(); Date eDate = projectgui.getSelectProject().getEndDate(); String startDate = sdf.format(sDate); String endDate = sdf.format(eDate); jTextField2.setText(startDate); jTextField3.setText(endDate); } public void refreshMemberList() { //Update Member List DefaultListModel jListModel = new DefaultListModel(); for (User member : TaskSystem.getMembers()) { if (member.checkActive() && !member.equals(TaskSystem.getCurrentUser())) { jListModel.addElement(member.getEmail()); } } jList1.setModel(jListModel); } public void refreshEditMemberList() { boolean flag = true; DefaultListModel jListModel = new DefaultListModel(); LinkedList<User> projectMembers = projectgui.getSelectProject().getMembers(); for (User member : TaskSystem.getMembers()) { for (User projMember : projectMembers) { if (member.equals(projMember)) { flag = false; } } if (member.checkActive() && !member.equals(TaskSystem.getCurrentUser()) && flag) { jListModel.addElement(member.getEmail()); } flag = true; } jList1.setModel(jListModel); } /** * This method is called from within the constructor to initialize the * weAreCreating. WARNING: Do NOT modify this code. The content of this * method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButtonCreateProject = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jList2 = new javax.swing.JList(); jScrollPane1 = new javax.swing.JScrollPane(); jList1 = new javax.swing.JList(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jButtonAddMember = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jButtonRemoveMember = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jButtonCreateProject.setText("Create Project"); jButtonCreateProject.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCreateProjectActionPerformed(evt); } }); jList2.setName(""); // NOI18N jScrollPane2.setViewportView(jList2); jList1.setName("currentMemberList"); // NOI18N jScrollPane1.setViewportView(jList1); jLabel1.setText("Project Name:"); jLabel2.setText("Start Date:"); jButtonAddMember.setText("Add"); jButtonAddMember.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonAddMemberActionPerformed(evt); } }); jLabel3.setText("End Date:"); jButtonRemoveMember.setText("Remove"); jButtonRemoveMember.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonRemoveMemberActionPerformed(evt); } }); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { jTextField1KeyTyped(evt); } }); jLabel4.setText("Members:"); jLabel5.setText("Members on Project:"); jTextField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField2ActionPerformed(evt); } }); jTextField3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField3ActionPerformed(evt); } }); jButton1.setText("Delete Project"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButtonCreateProject) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1)) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButtonAddMember, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonRemoveMember, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jLabel4)) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel5) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jTextField1))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(91, 91, 91))) .addContainerGap(27, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(50, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(71, 71, 71) .addComponent(jButtonAddMember) .addGap(62, 62, 62) .addComponent(jButtonRemoveMember)) .addGroup(layout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jLabel5)) .addGap(7, 7, 7) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonCreateProject) .addComponent(jButton1)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonCreateProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCreateProjectActionPerformed if (jList2.getModel().getSize() <= 0) { JOptionPane.showMessageDialog(null, "Please choose members to fullfil this project!", "Empty Member List", JOptionPane.WARNING_MESSAGE); return; } if (weAreCreating) { title = jTextField1.getText().toString(); startDate = jTextField2.getText().toString(); endDate = jTextField3.getText().toString(); for (Project p : TaskSystem.getProjectList()) { if (p.getTitle().equalsIgnoreCase(title)) { System.out.print(title); JOptionPane.showMessageDialog(null, "The Project Title you enetered already exists.\nPlease choose a different title.", "Duplication", JOptionPane.WARNING_MESSAGE); return; } } if (!title.isEmpty()) { try { sDate = sdf.parse(startDate); eDate = sdf.parse(endDate); if (!sdf.format(sDate).equals(startDate) || !sdf.format(eDate).equals(endDate)) { JOptionPane.showMessageDialog(null, "Please enter a valid date.", "Invalid Date", JOptionPane.WARNING_MESSAGE); } else { proj = new Project(title, owner, sDate, eDate); TaskSystem.setProjectList(proj); User userEmail = null; List<String> emails = new ArrayList<>(); if (jList2.getModel().getSize() > 0) { for (int i = 0; i < jList2.getModel().getSize(); i++) { emails.add((String) jList2.getModel().getElementAt(i)); } for (String s : emails) { userEmail = TaskSystem.getUserByEmail(s); proj.addMember(userEmail); } } this.dispose(); } } catch (ParseException ex) { JOptionPane.showMessageDialog(null, "Please enter date in mm/dd/yyyy format.", "Incorrect Date Value", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Please make sure the following are correct:\n\n-There is a title\n-The date is valid", "Invalid Input", JOptionPane.WARNING_MESSAGE); } if (projectgui != null) { projectgui.refreshProjectsList(); } } //functionality is when editprojGUI appears else if (!weAreCreating) { title = jTextField1.getText().toString(); startDate = jTextField2.getText().toString(); endDate = jTextField3.getText().toString(); if (title.compareToIgnoreCase(projectgui.getSelectProject().getTitle()) != 0) { for (Project p : TaskSystem.getProjectList()) { if (p.getTitle().equalsIgnoreCase(title)) { JOptionPane.showMessageDialog(null, "The Project Title you enetered already exists.\nPlease choose a different title.", "Duplication", JOptionPane.WARNING_MESSAGE); return; } } } if (!title.isEmpty()) { try { sDate = sdf.parse(startDate); eDate = sdf.parse(endDate); if (!sdf.format(sDate).equals(startDate) || !sdf.format(eDate).equals(endDate)) { JOptionPane.showMessageDialog(null, "Please enter a valid date.", "Invalid Date", JOptionPane.WARNING_MESSAGE); } else { //editing project details Project editProj = projectgui.getSelectProject(); TaskSystem.getProjectList().remove(editProj); editProj.setTitle(title); editProj.setEndDate(eDate); editProj.setStartDate(sDate); LinkedList<User> projMems = editProj.getMembers(); User userEmail; List<String> newemails = new ArrayList<>(); LinkedList<User> newMembers = new LinkedList<>(); //adding new members to list if (jList2.getModel().getSize() > 0) { for (int i = 0; i < jList2.getModel().getSize(); i++) { newemails.add((String) jList2.getModel().getElementAt(i)); } for (String s : newemails) { userEmail = TaskSystem.getUserByEmail(s); newMembers.add(userEmail); editProj.setMembers(newMembers); } } TaskSystem.setProjectList(editProj); this.dispose(); } } catch (ParseException ex) { JOptionPane.showMessageDialog(null, "Please enter date in mm/dd/yyyy format.", "Incorrect Date Value", JOptionPane.WARNING_MESSAGE); } if (projectgui != null) { projectgui.refreshProjectsList(); } } else { JOptionPane.showMessageDialog(null, "Please enter a valid Title", "Title missing", JOptionPane.WARNING_MESSAGE); return; } } TaskSystem.Finalize(); }//GEN-LAST:event_jButtonCreateProjectActionPerformed private void jXDatePicker1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jXDatePicker1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jXDatePicker1ActionPerformed private void jButtonAddMemberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddMemberActionPerformed // TODO add your handling code here: if (!weAreCreating) { clicked = true; List<String> usersToAdd = jList1.getSelectedValuesList(); for (String user : usersToAdd) { DefaultListModel model1 = (DefaultListModel) jList1.getModel(); DefaultListModel model2 = (DefaultListModel) jList2.getModel(); model2.addElement(user); int selectedIndex = jList1.getSelectedIndex(); if (selectedIndex != -1) { model1.remove(selectedIndex); } } } else if (jList1.isSelectionEmpty()) { JOptionPane.showMessageDialog(null, "Please select a member to add to a project."); } else { List<String> usersToAdd = jList1.getSelectedValuesList(); DefaultListModel model2 = null; if(jList2.getModel().getSize() == 0) { model2 = new DefaultListModel(); jList2.setModel(model2); } else { model2 = (DefaultListModel) jList2.getModel(); } for (String user : usersToAdd) { DefaultListModel model1 = (DefaultListModel) jList1.getModel(); model2.addElement(user); int selectedIndex = jList1.getSelectedIndex(); if (selectedIndex != -1) { model1.remove(selectedIndex); } } } }//GEN-LAST:event_jButtonAddMemberActionPerformed private void jXDatePicker2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jXDatePicker2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jXDatePicker2ActionPerformed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped // TODO add your handling code here: }//GEN-LAST:event_jTextField1KeyTyped private void jButtonRemoveMemberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveMemberActionPerformed if (jList2.isSelectionEmpty()) { JOptionPane.showMessageDialog(null, "Please select a member to remove from the project."); } else { List<String> usersToAdd = jList2.getSelectedValuesList(); DefaultListModel model1 = (DefaultListModel) jList1.getModel(); DefaultListModel model2 = (DefaultListModel) jList2.getModel(); boolean hasTask = false; for (String user : usersToAdd) { for (Task t : projectgui.getSelectProject().getTasks()){ if(t.getOwner().equalsIgnoreCase(user)){hasTask = true;} } if(!hasTask){ model2.removeElement(user); model1.add(0, user); jList1.setModel(model1); jList2.setModel(model2); } else{ JOptionPane.showMessageDialog(null, "Can't remove: User(s) selected are currently assigned to a task.");} //true } } }//GEN-LAST:event_jButtonRemoveMemberActionPerformed private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField2ActionPerformed private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField3ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: Project p = projectgui.getSelectProject(); TaskSystem.getProjectList().remove(p); if (projectgui != null) { projectgui.refreshProjectsList();} this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { //java.util.logging.Logger.getLogger(EditProjectGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "An error occured!", "Error", JOptionPane.ERROR_MESSAGE); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { EditProjectGUI dialog = new EditProjectGUI(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } } ); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButtonAddMember; private javax.swing.JButton jButtonCreateProject; private javax.swing.JButton jButtonRemoveMember; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JList jList1; private javax.swing.JList jList2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; // End of variables declaration//GEN-END:variables @Override public void actionPerformed(ActionEvent e) { clicked = true; } }
/* * 3D City Database - The Open Source CityGML Database * https://www.3dcitydb.org/ * * Copyright 2013 - 2021 * Chair of Geoinformatics * Technical University of Munich, Germany * https://www.lrg.tum.de/gis/ * * The 3D City Database is jointly developed with the following * cooperation partners: * * Virtual City Systems, Berlin <https://vc.systems/> * M.O.S.S. Computer Grafik Systeme GmbH, Taufkirchen <http://www.moss.de/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citydb.citygml.common.cache.model; import org.citydb.database.adapter.AbstractSQLAdapter; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class CacheTableGroupToCityObject extends AbstractCacheTableModel { public static CacheTableGroupToCityObject instance = null; public synchronized static CacheTableGroupToCityObject getInstance() { if (instance == null) instance = new CacheTableGroupToCityObject(); return instance; } @Override public void createIndexes(Connection conn, String tableName, String properties) throws SQLException { try (Statement stmt = conn.createStatement()) { stmt.executeUpdate("create index idx_" + tableName + " on " + tableName + " (GROUP_ID) " + properties); stmt.executeUpdate("create index idx2_" + tableName + " on " + tableName + " (IS_PARENT) " + properties); } } @Override public CacheTableModel getType() { return CacheTableModel.GROUP_TO_CITYOBJECT; } @Override protected String getColumns(AbstractSQLAdapter sqlAdapter) { return "(" + "GROUP_ID " + sqlAdapter.getInteger() + ", " + "GMLID " + sqlAdapter.getCharacterVarying(256) + ", " + "IS_PARENT " + sqlAdapter.getNumeric(1, 0) + ", " + "ROLE " + sqlAdapter.getCharacterVarying(256) + ")"; } }
/* * libjingle * Copyright 2015 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.webrtc; public class CallSessionFileRotatingLogSink { static { System.loadLibrary("jingle_peerconnection_so"); } private long nativeSink; public static byte[] getLogData(String dirPath) { return nativeGetLogData(dirPath); } public CallSessionFileRotatingLogSink( String dirPath, int maxFileSize, Logging.Severity severity) { nativeSink = nativeAddSink(dirPath, maxFileSize, severity.ordinal()); } public void dispose() { if (nativeSink != 0) { nativeDeleteSink(nativeSink); nativeSink = 0; } } private static native long nativeAddSink( String dirPath, int maxFileSize, int severity); private static native void nativeDeleteSink(long nativeSink); private static native byte[] nativeGetLogData(String dirPath); }
package com.TeamOne411.backend.service; import com.TeamOne411.backend.entity.Vehicle; import com.TeamOne411.backend.entity.users.CarOwner; import com.TeamOne411.backend.repository.VehicleRepository; import org.springframework.stereotype.Service; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; @Service public class VehicleService { private static final Logger LOGGER = Logger.getLogger(VehicleService.class.getName()); private VehicleRepository vehicleRepository; public VehicleService(VehicleRepository vehicleRepository) { this.vehicleRepository = vehicleRepository; } public List<Vehicle> findAll() { return vehicleRepository.findAll(); } public List<Vehicle> findByCarOwner(CarOwner carOwner) { return vehicleRepository.findByCarOwner(carOwner); } public long count() { return vehicleRepository.count(); } public void delete(Vehicle vehicle) { vehicleRepository.delete(vehicle); } public void save(Vehicle vehicle) { if (vehicle == null) { LOGGER.log(Level.SEVERE, "Vehicle is null. Are you sure you have connected your form to the application?"); return; } vehicleRepository.save(vehicle); } // public void registerNewVehicle(Vehicle vehicle) { // } // // public void updateVehicle(Vehicle vehicle) { // } }
package com.thoughtworks.dddworkshop.infrastructure.persistence.mapping; import com.thoughtworks.dddworkshop.domain.vo.PaymentEventType; import lombok.*; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.time.LocalDateTime; @NoArgsConstructor @Getter @Setter @EqualsAndHashCode(exclude = {"eventData", "timestamp"}) @ToString @Entity public class PaymentEventTable { @Id private String eventId; private PaymentEventType eventType; private String paymentId; private LocalDateTime timestamp; @Column(length = 1024) private String eventData; }
/* * 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.hadoop.hive.metastore; import org.apache.hadoop.hive.common.TableName; import org.apache.hadoop.hive.metastore.api.CreationMetadata; import org.apache.hadoop.hive.metastore.api.GetPartitionsFilterSpec; import org.apache.hadoop.hive.metastore.api.GetPartitionsProjectionSpec; import org.apache.hadoop.hive.metastore.api.ISchemaName; import org.apache.hadoop.hive.metastore.api.SchemaVersionDescriptor; import org.apache.hadoop.hive.metastore.api.Catalog; import org.apache.hadoop.hive.metastore.api.WMFullResourcePlan; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.metastore.api.AggrStats; import org.apache.hadoop.hive.metastore.api.AlreadyExistsException; import org.apache.hadoop.hive.metastore.api.ColumnStatistics; import org.apache.hadoop.hive.metastore.api.CurrentNotificationEventId; import org.apache.hadoop.hive.metastore.api.Database; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.FileMetadataExprType; import org.apache.hadoop.hive.metastore.api.Function; import org.apache.hadoop.hive.metastore.api.HiveObjectPrivilege; import org.apache.hadoop.hive.metastore.api.HiveObjectRef; import org.apache.hadoop.hive.metastore.api.ISchema; import org.apache.hadoop.hive.metastore.api.InvalidInputException; import org.apache.hadoop.hive.metastore.api.InvalidObjectException; import org.apache.hadoop.hive.metastore.api.InvalidOperationException; import org.apache.hadoop.hive.metastore.api.InvalidPartitionException; import org.apache.hadoop.hive.metastore.api.MetaException; import org.apache.hadoop.hive.metastore.api.NoSuchObjectException; import org.apache.hadoop.hive.metastore.api.NotificationEvent; import org.apache.hadoop.hive.metastore.api.NotificationEventRequest; import org.apache.hadoop.hive.metastore.api.NotificationEventResponse; import org.apache.hadoop.hive.metastore.api.NotificationEventsCountRequest; import org.apache.hadoop.hive.metastore.api.NotificationEventsCountResponse; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.PartitionEventType; import org.apache.hadoop.hive.metastore.api.PartitionValuesResponse; import org.apache.hadoop.hive.metastore.api.PrincipalPrivilegeSet; import org.apache.hadoop.hive.metastore.api.PrincipalType; import org.apache.hadoop.hive.metastore.api.PrivilegeBag; import org.apache.hadoop.hive.metastore.api.Role; import org.apache.hadoop.hive.metastore.api.RolePrincipalGrant; import org.apache.hadoop.hive.metastore.api.RuntimeStat; import org.apache.hadoop.hive.metastore.api.SQLCheckConstraint; import org.apache.hadoop.hive.metastore.api.SQLDefaultConstraint; import org.apache.hadoop.hive.metastore.api.SQLForeignKey; import org.apache.hadoop.hive.metastore.api.SQLNotNullConstraint; import org.apache.hadoop.hive.metastore.api.SQLPrimaryKey; import org.apache.hadoop.hive.metastore.api.SQLUniqueConstraint; import org.apache.hadoop.hive.metastore.api.ScheduledQuery; import org.apache.hadoop.hive.metastore.api.ScheduledQueryKey; import org.apache.hadoop.hive.metastore.api.ScheduledQueryMaintenanceRequest; import org.apache.hadoop.hive.metastore.api.ScheduledQueryPollRequest; import org.apache.hadoop.hive.metastore.api.ScheduledQueryPollResponse; import org.apache.hadoop.hive.metastore.api.ScheduledQueryProgressInfo; import org.apache.hadoop.hive.metastore.api.SchemaVersion; import org.apache.hadoop.hive.metastore.api.SerDeInfo; import org.apache.hadoop.hive.metastore.api.Table; import org.apache.hadoop.hive.metastore.api.TableMeta; import org.apache.hadoop.hive.metastore.api.Type; import org.apache.hadoop.hive.metastore.api.UnknownDBException; import org.apache.hadoop.hive.metastore.api.UnknownPartitionException; import org.apache.hadoop.hive.metastore.api.UnknownTableException; import org.apache.hadoop.hive.metastore.api.WMMapping; import org.apache.hadoop.hive.metastore.api.WMNullablePool; import org.apache.hadoop.hive.metastore.api.WMNullableResourcePlan; import org.apache.hadoop.hive.metastore.api.WMPool; import org.apache.hadoop.hive.metastore.api.WMResourcePlan; import org.apache.hadoop.hive.metastore.api.WMTrigger; import org.apache.hadoop.hive.metastore.api.WMValidateResourcePlanResponse; import org.apache.hadoop.hive.metastore.api.WriteEventInfo; import org.apache.hadoop.hive.metastore.partition.spec.PartitionSpecProxy; import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.ColStatsObjWithSourceInfo; import org.apache.thrift.TException; /** * A wrapper around {@link org.apache.hadoop.hive.metastore.ObjectStore} * with the ability to control the result of commitTransaction(). * All other functions simply delegate to an embedded ObjectStore object. * Ideally, we should have just extended ObjectStore instead of using * delegation. However, since HiveMetaStore uses a Proxy, this class must * not inherit from any other class. */ public class DummyRawStoreControlledCommit implements RawStore, Configurable { private final ObjectStore objectStore; public DummyRawStoreControlledCommit() { objectStore = new ObjectStore(); } /** * If true, shouldCommit() will simply call delegate commitTransaction() to the * underlying ObjectStore. * If false, shouldCommit() immediately returns false. */ private static boolean shouldCommitSucceed = true; public static void setCommitSucceed(boolean flag) { shouldCommitSucceed = flag; } @Override public boolean commitTransaction() { if (shouldCommitSucceed) { return objectStore.commitTransaction(); } else { return false; } } @Override public boolean isActiveTransaction() { return false; } // All remaining functions simply delegate to objectStore @Override public Configuration getConf() { return objectStore.getConf(); } @Override public void setConf(Configuration conf) { objectStore.setConf(conf); } @Override public void shutdown() { objectStore.shutdown(); } @Override public boolean openTransaction() { return objectStore.openTransaction(); } @Override public void rollbackTransaction() { objectStore.rollbackTransaction(); } @Override public void createCatalog(Catalog cat) throws MetaException { objectStore.createCatalog(cat); } @Override public void alterCatalog(String catName, Catalog cat) throws MetaException, InvalidOperationException { objectStore.alterCatalog(catName, cat); } @Override public Catalog getCatalog(String catalogName) throws NoSuchObjectException, MetaException { return objectStore.getCatalog(catalogName); } @Override public List<String> getCatalogs() throws MetaException { return objectStore.getCatalogs(); } @Override public void dropCatalog(String catalogName) throws NoSuchObjectException, MetaException { objectStore.dropCatalog(catalogName); } @Override public void createDatabase(Database db) throws InvalidObjectException, MetaException { objectStore.createDatabase(db); } @Override public Database getDatabase(String catName, String dbName) throws NoSuchObjectException { return objectStore.getDatabase(catName, dbName); } @Override public boolean dropDatabase(String catName, String dbName) throws NoSuchObjectException, MetaException { return objectStore.dropDatabase(catName, dbName); } @Override public boolean alterDatabase(String catName, String dbName, Database db) throws NoSuchObjectException, MetaException { return objectStore.alterDatabase(catName, dbName, db); } @Override public List<String> getDatabases(String catName, String pattern) throws MetaException { return objectStore.getDatabases(catName, pattern); } @Override public List<String> getAllDatabases(String catName) throws MetaException { return objectStore.getAllDatabases(catName); } @Override public boolean createType(Type type) { return objectStore.createType(type); } @Override public Type getType(String typeName) { return objectStore.getType(typeName); } @Override public boolean dropType(String typeName) { return objectStore.dropType(typeName); } @Override public void createTable(Table tbl) throws InvalidObjectException, MetaException { objectStore.createTable(tbl); } @Override public boolean dropTable(String catName, String dbName, String tableName) throws MetaException, NoSuchObjectException, InvalidObjectException, InvalidInputException { return objectStore.dropTable(catName, dbName, tableName); } @Override public Table getTable(String catName, String dbName, String tableName) throws MetaException { return objectStore.getTable(catName, dbName, tableName); } @Override public Table getTable(String catName, String dbName, String tableName, String writeIdList) throws MetaException { return objectStore.getTable(catName, dbName, tableName, writeIdList); } @Override public boolean addPartition(Partition part) throws InvalidObjectException, MetaException { return objectStore.addPartition(part); } @Override public Partition getPartition(String catName, String dbName, String tableName, List<String> partVals) throws MetaException, NoSuchObjectException { return objectStore.getPartition(catName, dbName, tableName, partVals); } @Override public Partition getPartition(String catName, String dbName, String tableName, List<String> partVals, String writeIdList) throws MetaException, NoSuchObjectException { return objectStore.getPartition(catName, dbName, tableName, partVals, writeIdList); } @Override public boolean dropPartition(String catName, String dbName, String tableName, List<String> partVals) throws MetaException, NoSuchObjectException, InvalidObjectException, InvalidInputException { return objectStore.dropPartition(catName, dbName, tableName, partVals); } @Override public List<Partition> getPartitions(String catName, String dbName, String tableName, int max) throws MetaException, NoSuchObjectException { return objectStore.getPartitions(catName, dbName, tableName, max); } @Override public Map<String, String> getPartitionLocations(String catName, String dbName, String tblName, String baseLocationToNotShow, int max) { return objectStore.getPartitionLocations(catName, dbName, tblName, baseLocationToNotShow, max); } @Override public Table alterTable(String catName, String dbName, String name, Table newTable, String queryValidWriteIds) throws InvalidObjectException, MetaException { return objectStore.alterTable(catName, dbName, name, newTable, queryValidWriteIds); } @Override public void updateCreationMetadata(String catName, String dbname, String tablename, CreationMetadata cm) throws MetaException { objectStore.updateCreationMetadata(catName, dbname, tablename, cm); } @Override public List<String> getTables(String catName, String dbName, String pattern) throws MetaException { return objectStore.getTables(catName, dbName, pattern); } @Override public List<String> getTables(String catName, String dbName, String pattern, TableType tableType, int limit) throws MetaException { return objectStore.getTables(catName, dbName, pattern, tableType, limit); } @Override public List<Table> getAllMaterializedViewObjectsForRewriting(String catName) throws MetaException { return objectStore.getAllMaterializedViewObjectsForRewriting(catName); } @Override public List<String> getMaterializedViewsForRewriting(String catName, String dbName) throws MetaException, NoSuchObjectException { return objectStore.getMaterializedViewsForRewriting(catName, dbName); } @Override public List<TableMeta> getTableMeta(String catName, String dbNames, String tableNames, List<String> tableTypes) throws MetaException { return objectStore.getTableMeta(catName, dbNames, tableNames, tableTypes); } @Override public List<Table> getTableObjectsByName(String catName, String dbName, List<String> tableNames) throws MetaException, UnknownDBException { return objectStore.getTableObjectsByName(catName, dbName, tableNames); } @Override public List<String> getAllTables(String catName, String dbName) throws MetaException { return objectStore.getAllTables(catName, dbName); } @Override public List<String> listTableNamesByFilter(String catName, String dbName, String filter, short maxTables) throws MetaException, UnknownDBException { return objectStore.listTableNamesByFilter(catName, dbName, filter, maxTables); } @Override public List<String> listPartitionNames(String catName, String dbName, String tblName, short maxParts) throws MetaException { return objectStore.listPartitionNames(catName, dbName, tblName, maxParts); } @Override public PartitionValuesResponse listPartitionValues(String catName, String db_name, String tbl_name, List<FieldSchema> cols, boolean applyDistinct, String filter, boolean ascending, List<FieldSchema> order, long maxParts) throws MetaException { return null; } @Override public Partition alterPartition(String catName, String dbName, String tblName, List<String> partVals, Partition newPart, String queryValidWriteIds) throws InvalidObjectException, MetaException { return objectStore.alterPartition(catName, dbName, tblName, partVals, newPart, queryValidWriteIds); } @Override public List<Partition> alterPartitions(String catName, String dbName, String tblName, List<List<String>> partValsList, List<Partition> newParts, long writeId, String queryValidWriteIds) throws InvalidObjectException, MetaException { return objectStore.alterPartitions( catName, dbName, tblName, partValsList, newParts, writeId, queryValidWriteIds); } @Override public List<Partition> getPartitionsByFilter(String catName, String dbName, String tblName, String filter, short maxParts) throws MetaException, NoSuchObjectException { return objectStore.getPartitionsByFilter(catName, dbName, tblName, filter, maxParts); } @Override public List<Partition> getPartitionSpecsByFilterAndProjection(Table table, GetPartitionsProjectionSpec projectionSpec, GetPartitionsFilterSpec filterSpec) throws MetaException, NoSuchObjectException { return objectStore.getPartitionSpecsByFilterAndProjection(table, projectionSpec, filterSpec); } @Override public int getNumPartitionsByFilter(String catName, String dbName, String tblName, String filter) throws MetaException, NoSuchObjectException { return objectStore.getNumPartitionsByFilter(catName, dbName, tblName, filter); } @Override public int getNumPartitionsByExpr(String catName, String dbName, String tblName, byte[] expr) throws MetaException, NoSuchObjectException { return objectStore.getNumPartitionsByExpr(catName, dbName, tblName, expr); } @Override public List<Partition> getPartitionsByNames(String catName, String dbName, String tblName, List<String> partNames) throws MetaException, NoSuchObjectException { return objectStore.getPartitionsByNames(catName, dbName, tblName, partNames); } @Override public boolean getPartitionsByExpr(String catName, String dbName, String tblName, byte[] expr, String defaultPartitionName, short maxParts, List<Partition> result) throws TException { return objectStore.getPartitionsByExpr(catName, dbName, tblName, expr, defaultPartitionName, maxParts, result); } @Override public Table markPartitionForEvent(String catName, String dbName, String tblName, Map<String, String> partVals, PartitionEventType evtType) throws MetaException, UnknownTableException, InvalidPartitionException, UnknownPartitionException { return objectStore.markPartitionForEvent(catName, dbName, tblName, partVals, evtType); } @Override public boolean isPartitionMarkedForEvent(String catName, String dbName, String tblName, Map<String, String> partName, PartitionEventType evtType) throws MetaException, UnknownTableException, InvalidPartitionException, UnknownPartitionException { return objectStore.isPartitionMarkedForEvent(catName, dbName, tblName, partName, evtType); } @Override public boolean addRole(String rowName, String ownerName) throws InvalidObjectException, MetaException, NoSuchObjectException { return objectStore.addRole(rowName, ownerName); } @Override public boolean removeRole(String roleName) throws MetaException, NoSuchObjectException { return objectStore.removeRole(roleName); } @Override public boolean grantRole(Role role, String userName, PrincipalType principalType, String grantor, PrincipalType grantorType, boolean grantOption) throws MetaException, NoSuchObjectException, InvalidObjectException { return objectStore.grantRole(role, userName, principalType, grantor, grantorType, grantOption); } @Override public boolean revokeRole(Role role, String userName, PrincipalType principalType, boolean grantOption) throws MetaException, NoSuchObjectException { return objectStore.revokeRole(role, userName, principalType, grantOption); } @Override public PrincipalPrivilegeSet getUserPrivilegeSet(String userName, List<String> groupNames) throws InvalidObjectException, MetaException { return objectStore.getUserPrivilegeSet(userName, groupNames); } @Override public PrincipalPrivilegeSet getDBPrivilegeSet(String catName, String dbName, String userName, List<String> groupNames) throws InvalidObjectException, MetaException { return objectStore.getDBPrivilegeSet(catName, dbName, userName, groupNames); } @Override public PrincipalPrivilegeSet getTablePrivilegeSet(String catName, String dbName, String tableName, String userName, List<String> groupNames) throws InvalidObjectException, MetaException { return objectStore.getTablePrivilegeSet(catName, dbName, tableName, userName, groupNames); } @Override public PrincipalPrivilegeSet getPartitionPrivilegeSet(String catName, String dbName, String tableName, String partition, String userName, List<String> groupNames) throws InvalidObjectException, MetaException { return objectStore.getPartitionPrivilegeSet(catName, dbName, tableName, partition, userName, groupNames); } @Override public PrincipalPrivilegeSet getColumnPrivilegeSet(String catName, String dbName, String tableName, String partitionName, String columnName, String userName, List<String> groupNames) throws InvalidObjectException, MetaException { return objectStore.getColumnPrivilegeSet(catName, dbName, tableName, partitionName, columnName, userName, groupNames); } @Override public List<HiveObjectPrivilege> listPrincipalGlobalGrants(String principalName, PrincipalType principalType) { return objectStore.listPrincipalGlobalGrants(principalName, principalType); } @Override public List<HiveObjectPrivilege> listPrincipalDBGrants(String principalName, PrincipalType principalType, String catName, String dbName) { return objectStore.listPrincipalDBGrants(principalName, principalType, catName, dbName); } @Override public List<HiveObjectPrivilege> listAllTableGrants(String principalName, PrincipalType principalType, String catName, String dbName, String tableName) { return objectStore.listAllTableGrants(principalName, principalType, catName, dbName, tableName); } @Override public List<HiveObjectPrivilege> listPrincipalPartitionGrants(String principalName, PrincipalType principalType, String catName, String dbName, String tableName, List<String> partValues, String partName) { return objectStore.listPrincipalPartitionGrants(principalName, principalType, catName, dbName, tableName, partValues, partName); } @Override public List<HiveObjectPrivilege> listPrincipalTableColumnGrants(String principalName, PrincipalType principalType, String catName, String dbName, String tableName, String columnName) { return objectStore.listPrincipalTableColumnGrants(principalName, principalType, catName, dbName, tableName, columnName); } @Override public List<HiveObjectPrivilege> listPrincipalPartitionColumnGrants( String principalName, PrincipalType principalType, String catName, String dbName, String tableName, List<String> partVals, String partName, String columnName) { return objectStore.listPrincipalPartitionColumnGrants(principalName, principalType, catName, dbName, tableName, partVals, partName, columnName); } @Override public boolean grantPrivileges(PrivilegeBag privileges) throws InvalidObjectException, MetaException, NoSuchObjectException { return objectStore.grantPrivileges(privileges); } @Override public boolean revokePrivileges(PrivilegeBag privileges, boolean grantOption) throws InvalidObjectException, MetaException, NoSuchObjectException { return objectStore.revokePrivileges(privileges, grantOption); } @Override public boolean refreshPrivileges(HiveObjectRef objToRefresh, String authorizer, PrivilegeBag grantPrivileges) throws InvalidObjectException, MetaException, NoSuchObjectException { return objectStore.refreshPrivileges(objToRefresh, authorizer, grantPrivileges); } @Override public Role getRole(String roleName) throws NoSuchObjectException { return objectStore.getRole(roleName); } @Override public List<String> listRoleNames() { return objectStore.listRoleNames(); } @Override public List<Role> listRoles(String principalName, PrincipalType principalType) { return objectStore.listRoles(principalName, principalType); } @Override public List<RolePrincipalGrant> listRolesWithGrants(String principalName, PrincipalType principalType) { return objectStore.listRolesWithGrants(principalName, principalType); } @Override public List<RolePrincipalGrant> listRoleMembers(String roleName) { return objectStore.listRoleMembers(roleName); } @Override public Partition getPartitionWithAuth(String catName, String dbName, String tblName, List<String> partVals, String userName, List<String> groupNames) throws MetaException, NoSuchObjectException, InvalidObjectException { return objectStore.getPartitionWithAuth(catName, dbName, tblName, partVals, userName, groupNames); } @Override public List<Partition> getPartitionsWithAuth(String catName, String dbName, String tblName, short maxParts, String userName, List<String> groupNames) throws MetaException, NoSuchObjectException, InvalidObjectException { return objectStore.getPartitionsWithAuth(catName, dbName, tblName, maxParts, userName, groupNames); } @Override public List<String> listPartitionNamesPs(String catName, String dbName, String tblName, List<String> partVals, short maxParts) throws MetaException, NoSuchObjectException { return objectStore.listPartitionNamesPs(catName, dbName, tblName, partVals, maxParts); } @Override public List<Partition> listPartitionsPsWithAuth(String catName, String dbName, String tblName, List<String> partVals, short maxParts, String userName, List<String> groupNames) throws MetaException, InvalidObjectException, NoSuchObjectException { return objectStore.listPartitionsPsWithAuth(catName, dbName, tblName, partVals, maxParts, userName, groupNames); } @Override public long cleanupEvents() { return objectStore.cleanupEvents(); } @Override public List<HiveObjectPrivilege> listPrincipalDBGrantsAll( String principalName, PrincipalType principalType) { return objectStore.listPrincipalDBGrantsAll(principalName, principalType); } @Override public List<HiveObjectPrivilege> listPrincipalTableGrantsAll( String principalName, PrincipalType principalType) { return objectStore.listPrincipalTableGrantsAll(principalName, principalType); } @Override public List<HiveObjectPrivilege> listPrincipalPartitionGrantsAll( String principalName, PrincipalType principalType) { return objectStore.listPrincipalPartitionGrantsAll(principalName, principalType); } @Override public List<HiveObjectPrivilege> listPrincipalTableColumnGrantsAll( String principalName, PrincipalType principalType) { return objectStore.listPrincipalTableColumnGrantsAll(principalName, principalType); } @Override public List<HiveObjectPrivilege> listPrincipalPartitionColumnGrantsAll( String principalName, PrincipalType principalType) { return objectStore.listPrincipalPartitionColumnGrantsAll(principalName, principalType); } @Override public List<HiveObjectPrivilege> listGlobalGrantsAll() { return objectStore.listGlobalGrantsAll(); } @Override public List<HiveObjectPrivilege> listDBGrantsAll(String catName, String dbName) { return objectStore.listDBGrantsAll(catName, dbName); } @Override public List<HiveObjectPrivilege> listPartitionColumnGrantsAll(String catName, String dbName, String tableName, String partitionName, String columnName) { return objectStore.listPartitionColumnGrantsAll(catName, dbName, tableName, partitionName, columnName); } @Override public List<HiveObjectPrivilege> listTableGrantsAll(String catName, String dbName, String tableName) { return objectStore.listTableGrantsAll(catName, dbName, tableName); } @Override public List<HiveObjectPrivilege> listPartitionGrantsAll(String catName, String dbName, String tableName, String partitionName) { return objectStore.listPartitionGrantsAll(catName, dbName, tableName, partitionName); } @Override public List<HiveObjectPrivilege> listTableColumnGrantsAll(String catName, String dbName, String tableName, String columnName) { return objectStore.listTableColumnGrantsAll(catName, dbName, tableName, columnName); } @Override public List<ColumnStatistics> getTableColumnStatistics(String catName, String dbName, String tableName, List<String> colNames) throws MetaException, NoSuchObjectException { return objectStore.getTableColumnStatistics(catName, dbName, tableName, colNames); } @Override public ColumnStatistics getTableColumnStatistics(String catName, String dbName, String tableName, List<String> colNames, String engine) throws MetaException, NoSuchObjectException { return objectStore.getTableColumnStatistics(catName, dbName, tableName, colNames, engine); } @Override public ColumnStatistics getTableColumnStatistics(String catName, String dbName, String tableName, List<String> colNames, String engine, String writeIdList) throws MetaException, NoSuchObjectException { return objectStore.getTableColumnStatistics( catName, dbName, tableName, colNames, engine, writeIdList); } @Override public boolean deleteTableColumnStatistics(String catName, String dbName, String tableName, String colName, String engine) throws NoSuchObjectException, MetaException, InvalidObjectException, InvalidInputException { return objectStore.deleteTableColumnStatistics(catName, dbName, tableName, colName, engine); } @Override public boolean deletePartitionColumnStatistics(String catName, String dbName, String tableName, String partName, List<String> partVals, String colName, String engine) throws NoSuchObjectException, MetaException, InvalidObjectException, InvalidInputException { return objectStore.deletePartitionColumnStatistics(catName, dbName, tableName, partName, partVals, colName, engine); } @Override public Map<String, String> updateTableColumnStatistics(ColumnStatistics statsObj, String validWriteIds, long writeId) throws NoSuchObjectException, MetaException, InvalidObjectException, InvalidInputException { return objectStore.updateTableColumnStatistics(statsObj, validWriteIds, writeId); } @Override public Map<String, String> updatePartitionColumnStatistics(ColumnStatistics statsObj, List<String> partVals, String validWriteIds, long writeId) throws NoSuchObjectException, MetaException, InvalidObjectException, InvalidInputException { return objectStore.updatePartitionColumnStatistics(statsObj, partVals, validWriteIds, writeId); } @Override public boolean addToken(String tokenIdentifier, String delegationToken) { return false; } @Override public boolean removeToken(String tokenIdentifier) { return false; } @Override public String getToken(String tokenIdentifier) { return ""; } @Override public List<String> getAllTokenIdentifiers() { return new ArrayList<>(); } @Override public int addMasterKey(String key) throws MetaException { return -1; } @Override public void updateMasterKey(Integer seqNo, String key) throws NoSuchObjectException, MetaException {} @Override public boolean removeMasterKey(Integer keySeq) { return false; } @Override public String[] getMasterKeys() { return new String[0]; } @Override public void verifySchema() throws MetaException { } @Override public String getMetaStoreSchemaVersion() throws MetaException { return objectStore.getMetaStoreSchemaVersion(); } @Override public void setMetaStoreSchemaVersion(String schemaVersion, String comment) throws MetaException { objectStore.setMetaStoreSchemaVersion(schemaVersion, comment); } @Override public List<List<ColumnStatistics>> getPartitionColumnStatistics(String catName, String dbName, String tblName, List<String> colNames, List<String> partNames) throws MetaException, NoSuchObjectException { return objectStore.getPartitionColumnStatistics(catName, dbName, tblName , colNames, partNames); } @Override public List<ColumnStatistics> getPartitionColumnStatistics(String catName, String dbName, String tblName, List<String> colNames, List<String> partNames, String engine) throws MetaException, NoSuchObjectException { return objectStore.getPartitionColumnStatistics(catName, dbName, tblName, colNames, partNames, engine); } @Override public List<ColumnStatistics> getPartitionColumnStatistics( String catName, String dbName, String tblName, List<String> partNames, List<String> colNames, String engine, String writeIdList) throws MetaException, NoSuchObjectException { return objectStore.getPartitionColumnStatistics( catName, dbName, tblName , colNames, partNames, engine, writeIdList); } @Override public boolean doesPartitionExist(String catName, String dbName, String tableName, List<FieldSchema> partKeys, List<String> partVals) throws MetaException, NoSuchObjectException { return objectStore.doesPartitionExist(catName, dbName, tableName, partKeys, partVals); } @Override public boolean addPartitions(String catName, String dbName, String tblName, List<Partition> parts) throws InvalidObjectException, MetaException { return objectStore.addPartitions(catName, dbName, tblName, parts); } @Override public boolean addPartitions(String catName, String dbName, String tblName, PartitionSpecProxy partitionSpec, boolean ifNotExists) throws InvalidObjectException, MetaException { return false; } @Override public void dropPartitions(String catName, String dbName, String tblName, List<String> partNames) throws MetaException, NoSuchObjectException { objectStore.dropPartitions(catName, dbName, tblName, partNames); } @Override public void createFunction(Function func) throws InvalidObjectException, MetaException { objectStore.createFunction(func); } @Override public void alterFunction(String catName, String dbName, String funcName, Function newFunction) throws InvalidObjectException, MetaException { objectStore.alterFunction(catName, dbName, funcName, newFunction); } @Override public void dropFunction(String catName, String dbName, String funcName) throws MetaException, NoSuchObjectException, InvalidObjectException, InvalidInputException { objectStore.dropFunction(catName, dbName, funcName); } @Override public Function getFunction(String catName, String dbName, String funcName) throws MetaException { return objectStore.getFunction(catName, dbName, funcName); } @Override public List<Function> getAllFunctions(String catName) throws MetaException { return Collections.emptyList(); } @Override public List<String> getFunctions(String catName, String dbName, String pattern) throws MetaException { return objectStore.getFunctions(catName, dbName, pattern); } @Override public AggrStats get_aggr_stats_for(String catName, String dbName, String tblName, List<String> partNames, List<String> colNames, String engine) throws MetaException { return null; } @Override public AggrStats get_aggr_stats_for(String catName, String dbName, String tblName, List<String> partNames, List<String> colNames, String engine, String writeIdList) throws MetaException, NoSuchObjectException { return null; } @Override public NotificationEventResponse getNextNotification(NotificationEventRequest rqst) { return objectStore.getNextNotification(rqst); } @Override public void addNotificationEvent(NotificationEvent event) throws MetaException { objectStore.addNotificationEvent(event); } @Override public void cleanNotificationEvents(int olderThan) { objectStore.cleanNotificationEvents(olderThan); } @Override public CurrentNotificationEventId getCurrentNotificationEventId() { return objectStore.getCurrentNotificationEventId(); } @Override public NotificationEventsCountResponse getNotificationEventsCount(NotificationEventsCountRequest rqst) { return objectStore.getNotificationEventsCount(rqst); } @Override public void flushCache() { objectStore.flushCache(); } @Override public ByteBuffer[] getFileMetadata(List<Long> fileIds) { return null; } @Override public void putFileMetadata( List<Long> fileIds, List<ByteBuffer> metadata, FileMetadataExprType type) { } @Override public boolean isFileMetadataSupported() { return false; } @Override public void getFileMetadataByExpr(List<Long> fileIds, FileMetadataExprType type, byte[] expr, ByteBuffer[] metadatas, ByteBuffer[] stripeBitsets, boolean[] eliminated) { } @Override public int getTableCount() throws MetaException { return objectStore.getTableCount(); } @Override public int getPartitionCount() throws MetaException { return objectStore.getPartitionCount(); } @Override public int getDatabaseCount() throws MetaException { return objectStore.getDatabaseCount(); } @Override public FileMetadataHandler getFileMetadataHandler(FileMetadataExprType type) { return null; } @Override public List<SQLPrimaryKey> getPrimaryKeys(String catName, String db_name, String tbl_name) throws MetaException { // TODO Auto-generated method stub return null; } @Override public List<SQLForeignKey> getForeignKeys(String catName, String parent_db_name, String parent_tbl_name, String foreign_db_name, String foreign_tbl_name) throws MetaException { // TODO Auto-generated method stub return null; } @Override public List<SQLUniqueConstraint> getUniqueConstraints(String catName, String db_name, String tbl_name) throws MetaException { // TODO Auto-generated method stub return null; } @Override public List<SQLNotNullConstraint> getNotNullConstraints(String catName, String db_name, String tbl_name) throws MetaException { // TODO Auto-generated method stub return null; } @Override public List<SQLDefaultConstraint> getDefaultConstraints(String catName, String db_name, String tbl_name) throws MetaException { // TODO Auto-generated method stub return null; } @Override public List<SQLCheckConstraint> getCheckConstraints(String catName, String db_name, String tbl_name) throws MetaException { // TODO Auto-generated method stub return null; } @Override public List<String> createTableWithConstraints(Table tbl, List<SQLPrimaryKey> primaryKeys, List<SQLForeignKey> foreignKeys, List<SQLUniqueConstraint> uniqueConstraints, List<SQLNotNullConstraint> notNullConstraints, List<SQLDefaultConstraint> defaultConstraints, List<SQLCheckConstraint> checkConstraints) throws InvalidObjectException, MetaException { // TODO Auto-generated method stub return null; } @Override public void dropConstraint(String catName, String dbName, String tableName, String constraintName, boolean missingOk) throws NoSuchObjectException { // TODO Auto-generated method stub } @Override public List<String> addPrimaryKeys(List<SQLPrimaryKey> pks) throws InvalidObjectException, MetaException { return null; } @Override public List<String> addForeignKeys(List<SQLForeignKey> fks) throws InvalidObjectException, MetaException { return null; } @Override public List<String> addUniqueConstraints(List<SQLUniqueConstraint> uks) throws InvalidObjectException, MetaException { // TODO Auto-generated method stub return null; } @Override public List<String> addNotNullConstraints(List<SQLNotNullConstraint> nns) throws InvalidObjectException, MetaException { // TODO Auto-generated method stub return null; } @Override public List<String> addDefaultConstraints(List<SQLDefaultConstraint> nns) throws InvalidObjectException, MetaException { // TODO Auto-generated method stub return null; } @Override public List<String> addCheckConstraints(List<SQLCheckConstraint> nns) throws InvalidObjectException, MetaException { // TODO Auto-generated method stub return null; } @Override public String getMetastoreDbUuid() throws MetaException { throw new MetaException("Get metastore uuid is not implemented"); } @Override public void createResourcePlan(WMResourcePlan resourcePlan, String copyFrom, int defaultPoolSize) throws AlreadyExistsException, InvalidObjectException, MetaException, NoSuchObjectException { objectStore.createResourcePlan(resourcePlan, copyFrom, defaultPoolSize); } @Override public WMFullResourcePlan getResourcePlan(String name, String ns) throws NoSuchObjectException, MetaException { return objectStore.getResourcePlan(name, ns); } @Override public List<WMResourcePlan> getAllResourcePlans(String ns) throws MetaException { return objectStore.getAllResourcePlans(ns); } @Override public WMFullResourcePlan alterResourcePlan(String name, String ns, WMNullableResourcePlan resourcePlan, boolean canActivateDisabled, boolean canDeactivate, boolean isReplace) throws AlreadyExistsException, NoSuchObjectException, InvalidOperationException, MetaException { return objectStore.alterResourcePlan( name, ns, resourcePlan, canActivateDisabled, canDeactivate, isReplace); } @Override public WMFullResourcePlan getActiveResourcePlan(String ns) throws MetaException { return objectStore.getActiveResourcePlan(ns); } @Override public WMValidateResourcePlanResponse validateResourcePlan(String name, String ns) throws NoSuchObjectException, InvalidObjectException, MetaException { return objectStore.validateResourcePlan(name, ns); } @Override public void dropResourcePlan(String name, String ns) throws NoSuchObjectException, MetaException { objectStore.dropResourcePlan(name, ns); } @Override public void createWMTrigger(WMTrigger trigger) throws AlreadyExistsException, MetaException, NoSuchObjectException, InvalidOperationException { objectStore.createWMTrigger(trigger); } @Override public void alterWMTrigger(WMTrigger trigger) throws NoSuchObjectException, InvalidOperationException, MetaException { objectStore.alterWMTrigger(trigger); } @Override public void dropWMTrigger(String resourcePlanName, String triggerName, String ns) throws NoSuchObjectException, InvalidOperationException, MetaException { objectStore.dropWMTrigger(resourcePlanName, triggerName, ns); } @Override public List<WMTrigger> getTriggersForResourcePlan(String resourcePlanName, String ns) throws NoSuchObjectException, MetaException { return objectStore.getTriggersForResourcePlan(resourcePlanName, ns); } @Override public void createPool(WMPool pool) throws AlreadyExistsException, NoSuchObjectException, InvalidOperationException, MetaException { objectStore.createPool(pool); } @Override public void alterPool(WMNullablePool pool, String poolPath) throws AlreadyExistsException, NoSuchObjectException, InvalidOperationException, MetaException { objectStore.alterPool(pool, poolPath); } @Override public void dropWMPool(String resourcePlanName, String poolPath, String ns) throws NoSuchObjectException, InvalidOperationException, MetaException { objectStore.dropWMPool(resourcePlanName, poolPath, ns); } @Override public void createOrUpdateWMMapping(WMMapping mapping, boolean update) throws AlreadyExistsException, NoSuchObjectException, InvalidOperationException, MetaException { objectStore.createOrUpdateWMMapping(mapping, update); } @Override public void dropWMMapping(WMMapping mapping) throws NoSuchObjectException, InvalidOperationException, MetaException { objectStore.dropWMMapping(mapping); } @Override public void createWMTriggerToPoolMapping(String resourcePlanName, String triggerName, String poolPath, String ns) throws AlreadyExistsException, NoSuchObjectException, InvalidOperationException, MetaException { objectStore.createWMTriggerToPoolMapping(resourcePlanName, triggerName, poolPath, ns); } @Override public void dropWMTriggerToPoolMapping(String resourcePlanName, String triggerName, String poolPath, String ns) throws NoSuchObjectException, InvalidOperationException, MetaException { objectStore.dropWMTriggerToPoolMapping(resourcePlanName, triggerName, poolPath, ns); } @Override public List<ColStatsObjWithSourceInfo> getPartitionColStatsForDatabase(String catName, String dbName) throws MetaException, NoSuchObjectException { // TODO Auto-generated method stub return null; } @Override public void createISchema(ISchema schema) throws AlreadyExistsException, MetaException, NoSuchObjectException { objectStore.createISchema(schema); } @Override public void alterISchema(ISchemaName schemaName, ISchema newSchema) throws NoSuchObjectException, MetaException { objectStore.alterISchema(schemaName, newSchema); } @Override public ISchema getISchema(ISchemaName schemaName) throws MetaException { return objectStore.getISchema(schemaName); } @Override public void dropISchema(ISchemaName schemaName) throws NoSuchObjectException, MetaException { objectStore.dropISchema(schemaName); } @Override public void addSchemaVersion(SchemaVersion schemaVersion) throws AlreadyExistsException, InvalidObjectException, NoSuchObjectException, MetaException { objectStore.addSchemaVersion(schemaVersion); } @Override public void alterSchemaVersion(SchemaVersionDescriptor version, SchemaVersion newVersion) throws NoSuchObjectException, MetaException { objectStore.alterSchemaVersion(version, newVersion); } @Override public SchemaVersion getSchemaVersion(SchemaVersionDescriptor version) throws MetaException { return objectStore.getSchemaVersion(version); } @Override public SchemaVersion getLatestSchemaVersion(ISchemaName schemaName) throws MetaException { return objectStore.getLatestSchemaVersion(schemaName); } @Override public List<SchemaVersion> getAllSchemaVersion(ISchemaName schemaName) throws MetaException { return objectStore.getAllSchemaVersion(schemaName); } @Override public List<SchemaVersion> getSchemaVersionsByColumns(String colName, String colNamespace, String type) throws MetaException { return objectStore.getSchemaVersionsByColumns(colName, colNamespace, type); } @Override public void dropSchemaVersion(SchemaVersionDescriptor version) throws NoSuchObjectException, MetaException { objectStore.dropSchemaVersion(version); } @Override public SerDeInfo getSerDeInfo(String serDeName) throws NoSuchObjectException, MetaException { return objectStore.getSerDeInfo(serDeName); } @Override public void addSerde(SerDeInfo serde) throws AlreadyExistsException, MetaException { objectStore.addSerde(serde); } @Override public void addRuntimeStat(RuntimeStat stat) throws MetaException { objectStore.addRuntimeStat(stat); } @Override public List<RuntimeStat> getRuntimeStats(int maxEntries, int maxCreateTime) throws MetaException { return objectStore.getRuntimeStats(maxEntries, maxCreateTime); } @Override public int deleteRuntimeStats(int maxRetainSecs) throws MetaException { return objectStore.deleteRuntimeStats(maxRetainSecs); } @Override public void cleanWriteNotificationEvents(int olderThan) { objectStore.cleanWriteNotificationEvents(olderThan); } @Override public List<WriteEventInfo> getAllWriteEventInfo(long txnId, String dbName, String tableName) throws MetaException { return objectStore.getAllWriteEventInfo(txnId, dbName, tableName); } @Override public List<TableName> getTableNamesWithStats() throws MetaException, NoSuchObjectException { return null; } @Override public List<TableName> getAllTableNamesForStats() throws MetaException, NoSuchObjectException { return null; } @Override public List<String> isPartOfMaterializedView(String catName, String dbName, String tblName) { return objectStore.isPartOfMaterializedView(catName, dbName, tblName); } @Override public Map<String, List<String>> getPartitionColsWithStats(String catName, String dbName, String tableName) throws MetaException, NoSuchObjectException { return null; } @Override public ScheduledQueryPollResponse scheduledQueryPoll(ScheduledQueryPollRequest request) throws MetaException { return objectStore.scheduledQueryPoll(request); } @Override public void scheduledQueryMaintenance(ScheduledQueryMaintenanceRequest request) throws MetaException, NoSuchObjectException, AlreadyExistsException, InvalidInputException { objectStore.scheduledQueryMaintenance(request); } @Override public void scheduledQueryProgress(ScheduledQueryProgressInfo info) throws InvalidOperationException, MetaException { objectStore.scheduledQueryProgress(info); } @Override public ScheduledQuery getScheduledQuery(ScheduledQueryKey scheduleKey) throws NoSuchObjectException { return objectStore.getScheduledQuery(scheduleKey); } @Override public int deleteScheduledExecutions(int maxRetainSecs) { return objectStore.deleteScheduledExecutions(maxRetainSecs); } @Override public int markScheduledExecutionsTimedOut(int timeoutSecs) throws InvalidOperationException, MetaException { return objectStore.markScheduledExecutionsTimedOut(timeoutSecs); } }
package com.web.erwins_fst.moneymoney; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.web.erwins_fst.moneymoney", appContext.getPackageName()); } }
package com.ql.util.express.instruction.detail; import java.util.List; import com.ql.util.express.InstructionSet; import com.ql.util.express.InstructionSetContext; import com.ql.util.express.InstructionSetRunner; import com.ql.util.express.OperateData; import com.ql.util.express.RunEnvironment; import com.ql.util.express.instruction.OperateDataCacheManager; public class InstructionCallMacro extends Instruction { private final String name; public InstructionCallMacro(String name) { this.name = name; } @Override public void execute(RunEnvironment environment, List<String> errorList) throws Exception { if (environment.isTrace() && log.isDebugEnabled()) { log.debug(this); } InstructionSetContext context = environment.getContext(); Object functionSet = context.getSymbol(this.name); Object result = InstructionSetRunner.execute(context.getExpressRunner(), (InstructionSet)functionSet, context.getExpressLoader(), context, errorList, environment.isTrace(), false, false, log, environment.getContext().isSupportDynamicFieldName()); if (result instanceof OperateData) { environment.push((OperateData)result); } else { environment.push(OperateDataCacheManager.fetchOperateData(result, null)); } environment.programPointAddOne(); } @Override public String toString() { return "call macro " + this.name; } }
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.integtests; import org.gradle.integtests.fixtures.AbstractIntegrationTest; import org.gradle.integtests.fixtures.executer.ExecutionFailure; import org.gradle.integtests.fixtures.executer.ExecutionResult; import org.gradle.test.fixtures.file.TestFile; import org.junit.Test; import java.io.File; import static org.hamcrest.Matchers.startsWith; public class ProjectLoadingIntegrationTest extends AbstractIntegrationTest { @Test public void handlesSimilarlyNamedBuildFilesInSameDirectory() { TestFile buildFile1 = testFile("similarly-named build.gradle").write("task build"); TestFile buildFile2 = testFile("similarly_named_build_gradle").write("task 'other-build'"); usingBuildFile(buildFile1).withTasks("build").run(); usingBuildFile(buildFile2).withTasks("other-build").run(); usingBuildFile(buildFile1).withTasks("build").run(); } @Test public void handlesWhitespaceOnlySettingsAndBuildFiles() { testFile("settings.gradle").write(" \n "); testFile("build.gradle").write(" "); inTestDirectory().withTaskList().run(); } @Test public void canDetermineRootProjectAndDefaultProjectBasedOnCurrentDirectory() { File rootDir = getTestDirectory(); File childDir = new File(rootDir, "child"); testFile("settings.gradle").write("include('child')"); testFile("build.gradle").write("task('do-stuff')"); testFile("child/build.gradle").write("task('do-stuff')"); inDirectory(rootDir).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":do-stuff", ":child:do-stuff"); inDirectory(rootDir).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); inDirectory(childDir).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":child:do-stuff"); inDirectory(childDir).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); } @Test public void canDetermineRootProjectAndDefaultProjectBasedOnProjectDirectory() { File rootDir = getTestDirectory(); File childDir = new File(rootDir, "child"); testFile("settings.gradle").write("include('child')"); testFile("build.gradle").write("task('do-stuff')"); testFile("child/build.gradle").write("task('do-stuff')"); usingProjectDir(rootDir).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":do-stuff", ":child:do-stuff"); usingProjectDir(rootDir).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); usingProjectDir(childDir).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":child:do-stuff"); usingProjectDir(childDir).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); } @Test public void canDetermineRootProjectAndDefaultProjectBasedOnBuildFile() { testFile("settings.gradle").write("include('child')"); TestFile rootBuildFile = testFile("build.gradle"); rootBuildFile.write("task('do-stuff')"); TestFile childBuildFile = testFile("child/build.gradle"); childBuildFile.write("task('do-stuff')"); usingBuildFile(rootBuildFile).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":do-stuff", ":child:do-stuff"); usingBuildFile(rootBuildFile).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); usingBuildFile(childBuildFile).withSearchUpwards().withTasks("do-stuff").run().assertTasksExecuted(":child:do-stuff"); usingBuildFile(childBuildFile).withSearchUpwards().withTasks(":do-stuff").run().assertTasksExecuted(":do-stuff"); } @Test public void buildFailsWhenMultipleProjectsMeetDefaultProjectCriteria() { testFile("settings.gradle").writelns( "include 'child'", "project(':child').projectDir = rootProject.projectDir"); testFile("build.gradle").write("// empty"); ExecutionFailure result = inTestDirectory().withTasks("test").runWithFailure(); result.assertThatDescription(startsWith("Multiple projects in this build have project directory")); result = usingProjectDir(getTestDirectory()).withTasks("test").runWithFailure(); result.assertThatDescription(startsWith("Multiple projects in this build have project directory")); result = usingBuildFile(testFile("build.gradle")).withTasks("test").runWithFailure(); result.assertThatDescription(startsWith("Multiple projects in this build have build file")); } @Test public void buildFailsWhenSpecifiedBuildFileIsNotAFile() { TestFile file = testFile("unknown"); ExecutionFailure result = usingBuildFile(file).runWithFailure(); result.assertHasDescription("The specified build file '" + file + "' does not exist."); file.createDir(); result = usingBuildFile(file).runWithFailure(); result.assertHasDescription("The specified build file '" + file + "' is not a file."); } @Test public void buildFailsWhenSpecifiedProjectDirectoryIsNotADirectory() { TestFile file = testFile("unknown"); ExecutionFailure result = usingProjectDir(file).runWithFailure(); result.assertHasDescription("The specified project directory '" + file + "' does not exist."); file.createFile(); result = usingProjectDir(file).runWithFailure(); result.assertHasDescription("The specified project directory '" + file + "' is not a directory."); } @Test public void buildFailsWhenSpecifiedSettingsFileIsNotAFile() { TestFile file = testFile("unknown"); ExecutionFailure result = inTestDirectory().usingSettingsFile(file).runWithFailure(); result.assertHasDescription("The specified settings file '" + file + "' does not exist."); file.createDir(); result = inTestDirectory().usingSettingsFile(file).runWithFailure(); result.assertHasDescription("The specified settings file '" + file + "' is not a file."); } @Test public void buildFailsWhenSpecifiedSettingsFileDoesNotContainMatchingProject() { TestFile settingsFile = testFile("settings.gradle"); settingsFile.write("// empty"); TestFile projectDir = testFile("project dir"); TestFile buildFile = projectDir.file("build.gradle").createFile(); ExecutionFailure result = usingProjectDir(projectDir).usingSettingsFile(settingsFile).runWithFailure(); result.assertHasDescription(String.format("No projects in this build have project directory '%s'.", projectDir)); result = usingBuildFile(buildFile).usingSettingsFile(settingsFile).runWithFailure(); result.assertHasDescription(String.format("No projects in this build have build file '%s'.", buildFile)); } @Test public void settingsFileTakesPrecedenceOverBuildFileInSameDirectory() { testFile("settings.gradle").write("rootProject.buildFileName = 'root.gradle'"); testFile("root.gradle").write("task('do-stuff')"); TestFile buildFile = testFile("build.gradle"); buildFile.write("throw new RuntimeException()"); inTestDirectory().withTasks("do-stuff").run(); usingProjectDir(getTestDirectory()).withTasks("do-stuff").run(); } @Test public void settingsFileInParentDirectoryTakesPrecedenceOverBuildFile() { testFile("settings.gradle").writelns( "include 'child'", "project(':child').buildFileName = 'child.gradle'" ); TestFile subDirectory = getTestDirectory().file("child"); subDirectory.file("build.gradle").write("throw new RuntimeException()"); subDirectory.file("child.gradle").write("task('do-stuff')"); inDirectory(subDirectory).withSearchUpwards().withTasks("do-stuff").run(); usingProjectDir(subDirectory).withSearchUpwards().withTasks("do-stuff").run(); } @Test public void explicitBuildFileTakesPrecedenceOverSettingsFileInSameDirectory() { testFile("settings.gradle").write("rootProject.buildFileName = 'root.gradle'"); testFile("root.gradle").write("throw new RuntimeException()"); TestFile buildFile = testFile("build.gradle"); buildFile.write("task('do-stuff')"); usingBuildFile(buildFile).withTasks("do-stuff").run(); } @Test public void ignoresMultiProjectBuildInParentDirectoryWhichDoesNotMeetDefaultProjectCriteria() { testFile("settings.gradle").write("include 'another'"); testFile("gradle.properties").writelns("prop=value2", "otherProp=value"); TestFile subDirectory = getTestDirectory().file("subdirectory"); TestFile buildFile = subDirectory.file("build.gradle"); buildFile.writelns("task('do-stuff') {", "doLast {", "assert prop == 'value'", "assert !project.hasProperty('otherProp')", "}", "}"); testFile("subdirectory/gradle.properties").write("prop=value"); inDirectory(subDirectory).withSearchUpwards().withTasks("do-stuff").expectDeprecationWarning().run(); usingProjectDir(subDirectory).withSearchUpwards().withTasks("do-stuff").expectDeprecationWarning().run(); usingBuildFile(buildFile).withSearchUpwards().withTasks("do-stuff").expectDeprecationWarning().run(); } @Test public void deprecationWarningAppearsWhenNestedBuildHasNoSettingsFile() { testFile("settings.gradle").write("include 'another'"); TestFile subDirectory = getTestDirectory().file("sub"); TestFile subBuildFile = subDirectory.file("sub.gradle").write(""); subDirectory.file("build.gradle").write(""); ExecutionResult result = inDirectory(subDirectory).withSearchUpwards().withTasks("help").expectDeprecationWarning().run(); result.assertOutputContains("Support for nested build without a settings file was deprecated and will be removed in Gradle 5.0. You should create a empty settings file in " + subDirectory.getAbsolutePath()); result = usingBuildFile(subBuildFile).inDirectory(subDirectory).withSearchUpwards().withTasks("help").expectDeprecationWarning().run(); result.assertOutputContains("Support for nested build without a settings file was deprecated and will be removed in Gradle 5.0. You should create a empty settings file in " + subDirectory.getAbsolutePath()); result = usingProjectDir(subDirectory).withSearchUpwards().withTasks("help").expectDeprecationWarning().run(); result.assertOutputContains("Support for nested build without a settings file was deprecated and will be removed in Gradle 5.0. You should create a empty settings file in " + subDirectory.getAbsolutePath()); } @Test public void noDeprecationWarningAppearsWhenUsingRootProject() { testFile("settings.gradle").write("include 'another'"); TestFile subDirectory = getTestDirectory().file("sub"); subDirectory.file("build.gradle").write(""); usingProjectDir(getTestDirectory()).inDirectory(subDirectory).withSearchUpwards().withTasks("help").run(); } @Test public void noDeprecationWarningAppearsWhenSettingsFileIsSpecified() { testFile("settings.gradle").write("include 'another'"); TestFile subDirectory = getTestDirectory().file("sub"); TestFile subSettingsFile = subDirectory.file("renamed_settings.gradle").write(""); subDirectory.file("build.gradle").write(""); inDirectory(subDirectory).usingSettingsFile(subSettingsFile).withSearchUpwards().withTasks("help").run(); } @Test public void noDeprecationWarningAppearsWhenEnclosingBuildUsesAnotherBuildFile() { testFile("settings.gradle").write("include 'another'"); TestFile renamedBuildGradle = getTestDirectory().file("renamed_build.gradle").createFile(); usingBuildFile(renamedBuildGradle).inDirectory(getTestDirectory()).withSearchUpwards().withTasks("help").run(); } @Test public void multiProjectBuildCanHaveMultipleProjectsWithSameProjectDir() { testFile("settings.gradle").writelns( "include 'child1', 'child2'", "project(':child1').projectDir = new File(settingsDir, 'shared')", "project(':child2').projectDir = new File(settingsDir, 'shared')" ); testFile("shared/build.gradle").write("task('do-stuff')"); inTestDirectory().withTasks("do-stuff").run().assertTasksExecuted(":child1:do-stuff", ":child2:do-stuff"); } @Test public void multiProjectBuildCanHaveSeveralProjectsWithSameBuildFile() { testFile("settings.gradle").writelns( "include 'child1', 'child2'", "project(':child1').buildFileName = '../child.gradle'", "project(':child2').buildFileName = '../child.gradle'" ); testFile("child.gradle").write("task('do-stuff')"); inTestDirectory().withTasks("do-stuff").run().assertTasksExecuted(":child1:do-stuff", ":child2:do-stuff"); } @Test public void multiProjectBuildCanHaveSettingsFileAndRootBuildFileInSubDir() { TestFile buildFilesDir = getTestDirectory().file("root"); TestFile settingsFile = buildFilesDir.file("settings.gradle"); settingsFile.writelns( "includeFlat 'child'", "rootProject.projectDir = new File(settingsDir, '..')", "rootProject.buildFileName = 'root/build.gradle'" ); TestFile rootBuildFile = buildFilesDir.file("build.gradle"); rootBuildFile.write("task('do-stuff', dependsOn: ':child:task')"); TestFile childBuildFile = testFile("child/build.gradle"); childBuildFile.writelns("task('do-stuff')", "task('task')"); usingProjectDir(getTestDirectory()).usingSettingsFile(settingsFile).withTasks("do-stuff").run().assertTasksExecuted(":child:task", ":do-stuff", ":child:do-stuff").assertTaskOrder(":child:task", ":do-stuff"); usingBuildFile(rootBuildFile).withTasks("do-stuff").run().assertTasksExecuted(":child:task", ":do-stuff", ":child:do-stuff").assertTaskOrder(":child:task", ":do-stuff"); usingBuildFile(childBuildFile).usingSettingsFile(settingsFile).withTasks("do-stuff").run().assertTasksExecutedInOrder(":child:do-stuff"); } @Test public void multiProjectBuildCanHaveAllProjectsAsChildrenOfSettingsDir() { TestFile settingsFile = testFile("settings.gradle"); settingsFile.writelns( "rootProject.projectDir = new File(settingsDir, 'root')", "include 'sub'", "project(':sub').projectDir = new File(settingsDir, 'root/sub')" ); getTestDirectory().createDir("root").file("build.gradle").writelns("allprojects { task thing }"); inTestDirectory().withTasks(":thing").run().assertTasksExecuted(":thing"); inTestDirectory().withTasks(":sub:thing").run().assertTasksExecuted(":sub:thing"); } @Test public void usesRootProjectAsDefaultProjectWhenInSettingsDir() { TestFile settingsDir = testFile("gradle"); TestFile settingsFile = settingsDir.file("settings.gradle"); settingsFile.writelns( "rootProject.projectDir = new File(settingsDir, '../root')", "include 'sub'", "project(':sub').projectDir = new File(settingsDir, '../root/sub')" ); getTestDirectory().createDir("root").file("build.gradle").writelns("allprojects { task thing }"); inDirectory(settingsDir).withTasks("thing").run().assertTasksExecuted(":thing", ":sub:thing"); } @Test public void rootProjectDirectoryAndBuildFileDoNotHaveToExistWhenInSettingsDir() { TestFile settingsDir = testFile("gradle"); TestFile settingsFile = settingsDir.file("settings.gradle"); settingsFile.writelns( "rootProject.projectDir = new File(settingsDir, '../root')", "include 'sub'", "project(':sub').projectDir = new File(settingsDir, '../sub')" ); getTestDirectory().createDir("sub").file("build.gradle").writelns("task thing"); inDirectory(settingsDir).withTasks("thing").run().assertTasksExecuted(":sub:thing"); } @Test public void settingsFileGetsIgnoredWhenUsingSettingsOnlyDirectoryAsProjectDirectory() { TestFile settingsDir = testFile("gradle"); TestFile settingsFile = settingsDir.file("settings.gradle"); settingsFile.writelns( "rootProject.projectDir = new File(settingsDir, '../root')" ); getTestDirectory().createDir("root").file("build.gradle").writelns("task thing"); inTestDirectory().withArguments("-p", settingsDir.getAbsolutePath()).withTasks("thing").runWithFailure() .assertHasDescription("Task 'thing' not found in root project 'gradle'."); } }
package net.boomerangplatform.mongo.service; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import net.boomerangplatform.mongo.entity.RevisionEntity; public interface RevisionService { void deleteWorkflow(RevisionEntity flowWorkflowVersionEntity); RevisionEntity getLatestWorkflowVersion(String workflowId); RevisionEntity getLatestWorkflowVersion(String workflowId, long version); long getWorkflowCount(String workFlowId); RevisionEntity getWorkflowlWithId(String id); RevisionEntity insertWorkflow(RevisionEntity flowWorkflowVersionEntity); RevisionEntity updateWorkflow(RevisionEntity flowWorkflowVersionEntity); Page<RevisionEntity> getAllWorkflowVersions(Optional<String> workFlowId, Pageable pageable); }
package com.atguigu.gmall.sms.controller; import java.util.Arrays; import java.util.Map; import com.atguigu.core.bean.PageVo; import com.atguigu.core.bean.QueryCondition; import com.atguigu.core.bean.Resp; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import com.atguigu.gmall.sms.entity.SeckillSessionEntity; import com.atguigu.gmall.sms.service.SeckillSessionService; /** * 秒杀活动场次 * * @author fengchen * @email ${email} * @date 2020-08-13 16:02:05 */ @Api(tags = "秒杀活动场次 管理") @RestController @RequestMapping("sms/seckillsession") public class SeckillSessionController { @Autowired private SeckillSessionService seckillSessionService; /** * 列表 */ @ApiOperation("分页查询(排序)") @GetMapping("/list") @PreAuthorize("hasAuthority('sms:seckillsession:list')") public Resp<PageVo> list(QueryCondition queryCondition) { PageVo page = seckillSessionService.queryPage(queryCondition); return Resp.ok(page); } /** * 信息 */ @ApiOperation("详情查询") @GetMapping("/info/{id}") @PreAuthorize("hasAuthority('sms:seckillsession:info')") public Resp<SeckillSessionEntity> info(@PathVariable("id") Long id){ SeckillSessionEntity seckillSession = seckillSessionService.getById(id); return Resp.ok(seckillSession); } /** * 保存 */ @ApiOperation("保存") @PostMapping("/save") @PreAuthorize("hasAuthority('sms:seckillsession:save')") public Resp<Object> save(@RequestBody SeckillSessionEntity seckillSession){ seckillSessionService.save(seckillSession); return Resp.ok(null); } /** * 修改 */ @ApiOperation("修改") @PostMapping("/update") @PreAuthorize("hasAuthority('sms:seckillsession:update')") public Resp<Object> update(@RequestBody SeckillSessionEntity seckillSession){ seckillSessionService.updateById(seckillSession); return Resp.ok(null); } /** * 删除 */ @ApiOperation("删除") @PostMapping("/delete") @PreAuthorize("hasAuthority('sms:seckillsession:delete')") public Resp<Object> delete(@RequestBody Long[] ids){ seckillSessionService.removeByIds(Arrays.asList(ids)); return Resp.ok(null); } }
/* * Copyright 2006-2018 Prowide * * 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.prowidesoftware.swift.model; import java.util.Calendar; import java.util.Objects; import com.prowidesoftware.swift.utils.SwiftFormatUtils; /** * This class models and parses the Message Input Reference (MIR), * String of 28 characters, always local to the sender of the message. * It includes the date the sender sent the message to SWIFT, * followed by the full LT address of the sender of the * message, and the sender's session and sequence to SWIFT. * YYMMDD BANKBEBBAXXX 2222 123456<br><br> * * <p>MIR and MOR are messages unique identifiers containing the date, * logical terminal (including branch code), session and sequence numbers. * Nevertheless this identifiers can be confusing sometimes because they must * be thought from SWIFT perspective. * * <p>A message created by the sender user/application is considered an * INPUT message, because it gets into the SWIFT network. When the message * is delivered and gets out of the network it is considered an OUTPUT message. * Therefore the headers of a sent message are not exactly the same as the * headers of the received message at the destination party. Analogous the * headers of a message that the receiving user/application gets from SWIFT * are not exactly the same as the headers when the message was created and * sent by the sending party. * * <p>The usage of MIR and MOR are clear when analyzing system messages. * A non delivery warning for example, includes the original MIR of the * sent message, but not the MOR because the message was not delivered yet. * But a delivery confirmation on the other hand, includes both, the sender’s MIR * and the receiver’s MOR.<br> * System messages provide MIR/MOR information using fields 106 and 107 respectively. * * @since 6.0 */ public class MIR { private static final transient java.util.logging.Logger log = java.util.logging.Logger.getLogger(MIR.class.getName()); /** * @param date * @param logicalTerminal * @param sessionNumber * @param sequenceNumber */ public MIR(String date, String logicalTerminal, String sessionNumber, String sequenceNumber) { super(); this.date = date; this.logicalTerminal = logicalTerminal; this.sessionNumber = sessionNumber; this.sequenceNumber = sequenceNumber; } /** * Creates a MIR object parsing the literal string value. * If the value is incorrect (cannot be parsed) the object will not be initialized. * @param value the MIR value, it is expected to 28 characters length */ public MIR(String value) { super(); if (value != null && value.length() == 28) { final StringBuilder sb = new StringBuilder(value); int offset = 0; int len; len = 6; this.date = String.valueOf(sb.subSequence(offset, offset + len)); offset += len; len = 12; this.logicalTerminal = String.valueOf(sb.subSequence(offset, offset + len)); offset += len; len = 4; this.sessionNumber = String.valueOf(sb.subSequence(offset, offset + len)); offset += len; len = 6; this.sequenceNumber = String.valueOf(sb.subSequence(offset, offset + len)); } else { log.severe("invalid MIR value "+value); } } /** * Default constructor */ public MIR() { super(); } /** * 6 characters string containing the date field of the MIR. */ private String date; /** * String of 12 characters containing the logical terminal field of the MIR * (address of the sender of the message). * @see "MIR on the WIFE Wiki" */ private String logicalTerminal; /** * String of 4 characters containing the session number field of the MIR. * @see "MIR on the WIFE Wiki" */ private String sessionNumber; /** * String of 6 characters containing the sequence number field of the MIR. * @see "MIR on the WIFE Wiki" */ private String sequenceNumber; /** * @return the date */ public String getDate() { return date; } /** * @param date */ public void setDate(String date) { this.date = date; } /** * @return the logical terminal */ public String getLogicalTerminal() { return logicalTerminal; } /** * @param logicalTerminal */ public void setLogicalTerminal(String logicalTerminal) { this.logicalTerminal = logicalTerminal; } /** * @return the session number */ public String getSessionNumber() { return sessionNumber; } /** * @param sessionNumber */ public void setSessionNumber(String sessionNumber) { this.sessionNumber = sessionNumber; } /** * @return the sequence number */ public String getSequenceNumber() { return sequenceNumber; } /** * @param sequenceNumber */ public void setSequenceNumber(String sequenceNumber) { this.sequenceNumber = sequenceNumber; } /** * Gets the full MIR (Message Input Reference) string of 28 * characters containing the sender's date, LT address, * session and sequence:<br> * for example YYMMDDBANKBEBBAXXX2222123456<br> * * @return a String with MIR, returns null if all MIR components are null */ public String getMIR() { if (date == null && logicalTerminal == null && sessionNumber == null && sequenceNumber == null) { return null; } final StringBuilder v = new StringBuilder(); if (date != null) { v.append(date); } if (logicalTerminal != null) { v.append(logicalTerminal); } if (sessionNumber != null) { v.append(sessionNumber); } if (sequenceNumber != null) { v.append(sequenceNumber); } return v.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MIR mir = (MIR) o; return Objects.equals(date, mir.date) && Objects.equals(logicalTerminal, mir.logicalTerminal) && Objects.equals(sessionNumber, mir.sessionNumber) && Objects.equals(sequenceNumber, mir.sequenceNumber); } @Override public int hashCode() { return Objects.hash(date, logicalTerminal, sessionNumber, sequenceNumber); } /** * Returns this MIR date as Calendar. * This implementation uses {@link SwiftFormatUtils#getDate2(String)} * @return the parsed date or null if MIR date is invalid or not set * @since 7.8.8 */ public final Calendar getDateAsCalendar() { return SwiftFormatUtils.getDate2(this.date); } }
package com.site.common; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * Spring Context 工具类 */ @Component public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtils.applicationContext = applicationContext; } public static Object getBean(String name){ return applicationContext.getBean(name); } public static <T>T getBean(Class<T> clazz){ return applicationContext.getBean(clazz); } public static <T>T getBean(String name,Class<T> requiredType){ return applicationContext.getBean(name,requiredType); } public static boolean containsBean(String name){ return applicationContext.containsBean(name); } public static boolean isSingleton(String name) { return applicationContext.isSingleton(name); } public static Class<? extends Object> getType(String name){ return applicationContext.getType(name); } }
package com.afrozaar.wordpress.wpapi.v2.api; import com.afrozaar.wordpress.wpapi.v2.exception.TermNotFoundException; import com.afrozaar.wordpress.wpapi.v2.exception.WpApiParsedException; import com.afrozaar.wordpress.wpapi.v2.model.Post; import com.afrozaar.wordpress.wpapi.v2.model.Term; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; public interface Tags { Term createTag(Term tagTerm) throws WpApiParsedException; List<Term> getTags(); Term getTag(Long id) throws TermNotFoundException; /** * Does not make the call to wordpress with {@code ?force=true}. If tag trashing is not supported, * an exception will be thrown. * @throws TermNotFoundException */ Term deleteTag(Term tagTerm) throws TermNotFoundException; Term deleteTag(Term tagTerm, boolean force) throws TermNotFoundException; Term updateTag(Term tag); Term createPostTag(Post post, Term tag) throws WpApiParsedException; List<Term> getPostTags(Post post); Term deletePostTag(Post post, Term tagTerm, boolean force) throws TermNotFoundException; Term getPostTag(Post post, Term tagTerm) throws TermNotFoundException; Function<List<Term>, List<Long>> termIds = terms -> terms.stream().map(Term::getId).collect(Collectors.toList()); }
/** * Copyright © 2018 The Lambico Datatest Team (lucio.benfante@gmail.com) * * This file is part of lambico-datatest-jpa. * * 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.lambico.datatest.example1; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import java.util.Collection; import org.junit.ClassRule; import org.junit.Test; import org.lambico.datatest.DataAggregator; import org.lambico.datatest.annotation.TestData; import org.lambico.datatest.example1.model.Entity1; import org.lambico.datatest.example1.model.Entity2; import org.lambico.datatest.junit.Dataset; @TestData(resources = "org/lambico/datatest/example1/dataset/dataset.json") public class InMemoryRuleTest { @ClassRule public static Dataset dataset = Dataset.builder().build(); @Test public void testEntity1() { DataAggregator dataAggregator = dataset.getDataAggregator(); Collection<?> entities1 = dataAggregator.getObjects().get("org.lambico.datatest.example1.model.Entity1"); Entity1 entity1 = ((Entity1)entities1.iterator().next()); assertEquals("test1", entity1.getStringField()); } @Test public void testEntity2() { DataAggregator dataAggregator = dataset.getDataAggregator(); Collection<?> entities2 = dataAggregator.getObjects().get("org.lambico.datatest.example1.model.Entity2"); Entity2 entity2 = ((Entity2)entities2.iterator().next()); assertEquals("test2", entity2.getStringField()); } @Test public void testCircularReferences() { DataAggregator dataAggregator = dataset.getDataAggregator(); Collection<?> entities1 = dataAggregator.getObjects().get("org.lambico.datatest.example1.model.Entity1"); Entity1 entity1 = ((Entity1)entities1.iterator().next()); Collection<?> entities2 = dataAggregator.getObjects().get("org.lambico.datatest.example1.model.Entity2"); Entity2 entity2 = ((Entity2)entities2.iterator().next()); assertSame(entity2, entity1.getEntity2()); assertSame(entity1, entity2.getEntity1()); } }
package org.monarchinitiative.phenol.cli.demo; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import org.monarchinitiative.phenol.io.OntologyLoader; import org.monarchinitiative.phenol.ontology.algo.OntologyAlgorithm; import org.monarchinitiative.phenol.ontology.data.Dbxref; import org.monarchinitiative.phenol.ontology.data.Ontology; import org.monarchinitiative.phenol.ontology.data.Term; import org.monarchinitiative.phenol.ontology.data.TermId; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; /** * A demonstration of how to access data in MONDO. We will extract a list of all OMIM diseases that are members of * a given phenoseries * * @author <a href="mailto:peter.robinson@jax.org">Peter Robinson</a> */ public class MondoDemo { private final String mondoPath; private final String outPath; private Ontology mondo; private List<Term> phenoseriesRoots; private Multimap<Term, TermId> phenoseries2omimMap; public MondoDemo(String mondoPath, String out) { this.mondoPath = mondoPath; this.outPath = out; phenoseriesRoots = new ArrayList<>(); phenoseries2omimMap = ArrayListMultimap.create(); } // todo -- also check if is exact match private boolean isOmimEntry(Term term) { for (Dbxref xref : term.getXrefs()) { if (xref.getName().startsWith("OMIM")) return true; } return false; } private Optional<TermId> getOMIMid(Term term) { for (Dbxref xref : term.getXrefs()) { if (xref.getName().startsWith("OMIM") && !xref.getName().startsWith("OMIMPS")) return Optional.of(TermId.of(xref.getName())); } return Optional.empty(); } public void run() { File file = new File(mondoPath); if (!file.exists()) { System.err.print("[ERROR] Could not find mondo.obo at " + mondoPath); return; } mondo = OntologyLoader.loadOntology(file); Set<TermId> obsolete = mondo.getObsoleteTermIds(); for (Map.Entry<TermId, Term> entry : mondo.getTermMap().entrySet()) { if (obsolete.contains(entry.getKey())) { continue; } Term term = entry.getValue(); for (Dbxref xref : term.getXrefs()) { if (xref.getName().startsWith("OMIMPS")) phenoseriesRoots.add(term); } } for (Term psterm : phenoseriesRoots) { Set<TermId> members = OntologyAlgorithm.getDescendents(mondo, psterm.getId()); for (TermId member : members) { Term candidate = mondo.getTermMap().get(member); if (isOmimEntry(candidate)) { phenoseries2omimMap.put(psterm, candidate.getId()); } } } try { BufferedWriter writer = new BufferedWriter(new FileWriter(this.outPath)); for (Term psterm : phenoseries2omimMap.keySet()) { Collection<TermId> coll = phenoseries2omimMap.get(psterm); for (TermId tid : coll) { Term omimentry = mondo.getTermMap().get(tid); Optional<TermId> omimIdopt = getOMIMid(omimentry); if (omimIdopt.isPresent()) { TermId omimId = omimIdopt.get(); String line = psterm.getId().getValue() + "\t" + psterm.getName() + "\t" + omimId.getValue() + "\t" + omimentry.getName(); System.out.println(line); writer.write(line + "\n"); } } } writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
package org.nuaa.tomax.harcs.common; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @Author: ToMax * @Description: * @Date: Created in 2019/7/14 15:21 */ public class ConfigUtil { /** * 加载配置文件 * @param fileName 文件名称 * @return */ public static Properties loadProperties(String fileName){ Properties props = null; InputStream is = null; try { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (is == null){ throw new FileNotFoundException(fileName+" file is not found"); } props = new Properties(); props.load(is); } catch (IOException e) { System.out.println(e+" 配置文件"+fileName+"加载失败"); } finally { if (is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return props; } /** * 根据key获取字符串类型的配置项 * @param props * @param key * @return */ public static String getString(Properties props, String key){ return getString(props, key, ""); } /** * 获取字符串型的配置值 * @param props 加载好的配置文件 * @param key * @param defaultValue key值为空时的默认值 * @return */ public static String getString(Properties props, String key, String defaultValue){ String value = defaultValue; if (props.containsKey(key)){ value = props.getProperty(key); } return value; } /** * 获取key值对应的int型配置值,含默认值 * @param props * @param key * @param defaultValue * @return */ public static int getInt(Properties props, String key, int defaultValue){ int value = defaultValue; if (props.containsKey(key)){ value = CastUtil.o2Int(props.getProperty(key),defaultValue); } return value; } /** * 获取key值对应int型的配置值,含默认值 * @param props * @param key * @return */ public static int getInt(Properties props, String key){ return getInt(props,key,0); } /** * 获取key值对应的double型配置值,含默认值 * @param props * @param key * @param defaultValue * @return */ public static double getDouble(Properties props, String key, double defaultValue){ double value = defaultValue; if (props.containsKey(key)){ value = CastUtil.o2Double(props.getProperty(key)); } return value; } /** * 获取key值对应的double型配置值 * @param props * @param key * @return */ public static double getDouble(Properties props, String key){ return getDouble(props,key,0); } /** * 获取key值对应的long型配置值,含默认值 * @param props * @param key * @param defaultValue * @return */ public static long getLong(Properties props, String key, long defaultValue){ long value = defaultValue; if (props.containsKey(key)){ value = CastUtil.o2Long(props.getProperty(key)); } return value; } /** * 获取key值对应的long型配置值 * @param props * @param key * @return */ public static long getLong(Properties props, String key){ return getLong(props,key,0); } }
/* * 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: XMLStreamException.java 670245 2008-06-21 18:03:15Z mrglavas $ package javax.xml.stream; public class XMLStreamException extends Exception { private static final long serialVersionUID = 2018819321811497362L; protected Throwable nested; protected Location location; public XMLStreamException() { super(); } public XMLStreamException(String msg) { super(msg); } public XMLStreamException(Throwable th) { this.nested = th; } public XMLStreamException(String msg, Throwable th) { super(msg); this.nested = th; } public XMLStreamException(String msg, Location location, Throwable th) { super(msg); this.location = location; this.nested = th; } public XMLStreamException(String msg, Location location) { super(msg); this.location = location; } public Throwable getNestedException() { return nested; } public Location getLocation() { return location; } }
package frc.robot.commands.HopperCommands; import frc.robot.subsystems.hopper; //import frc.robot.commands.*; import edu.wpi.first.wpilibj2.command.CommandBase; public class HopperBSetPos extends CommandBase{ private hopper hopper; private double value; public HopperBSetPos(hopper subsystem, double value){ hopper = subsystem; //value = speed; addRequirements(hopper); } public void initialize(){ hopper.hopperBSetPos(value); } public void execute(){ } public boolean isFinished(){ return false; } public void end() { } public void interrupted(){ end(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.cosmos.implementation.directconnectivity; import com.azure.cosmos.BadRequestException; import com.azure.cosmos.BridgeInternal; import com.azure.cosmos.ConflictException; import com.azure.cosmos.CosmosClientException; import com.azure.cosmos.ForbiddenException; import com.azure.cosmos.GoneException; import com.azure.cosmos.InternalServerErrorException; import com.azure.cosmos.InvalidPartitionException; import com.azure.cosmos.LockedException; import com.azure.cosmos.MethodNotAllowedException; import com.azure.cosmos.NotFoundException; import com.azure.cosmos.PartitionIsMigratingException; import com.azure.cosmos.PartitionKeyRangeGoneException; import com.azure.cosmos.PartitionKeyRangeIsSplittingException; import com.azure.cosmos.PreconditionFailedException; import com.azure.cosmos.RequestEntityTooLargeException; import com.azure.cosmos.RequestRateTooLargeException; import com.azure.cosmos.RequestTimeoutException; import com.azure.cosmos.RetryWithException; import com.azure.cosmos.ServiceUnavailableException; import com.azure.cosmos.UnauthorizedException; import com.azure.cosmos.implementation.Configs; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.Integers; import com.azure.cosmos.implementation.Lists; import com.azure.cosmos.implementation.Longs; import com.azure.cosmos.implementation.MutableVolatile; import com.azure.cosmos.implementation.OperationType; import com.azure.cosmos.implementation.PathsHelper; import com.azure.cosmos.implementation.RMResources; import com.azure.cosmos.implementation.ResourceType; import com.azure.cosmos.implementation.RuntimeConstants; import com.azure.cosmos.implementation.RxDocumentServiceRequest; import com.azure.cosmos.implementation.Strings; import com.azure.cosmos.implementation.UserAgentContainer; import com.azure.cosmos.implementation.Utils; import com.azure.cosmos.implementation.http.HttpClient; import com.azure.cosmos.implementation.http.HttpClientConfig; import com.azure.cosmos.implementation.http.HttpHeaders; import com.azure.cosmos.implementation.http.HttpRequest; import com.azure.cosmos.implementation.http.HttpResponse; import io.netty.handler.codec.http.HttpMethod; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import java.net.URI; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import static com.azure.cosmos.implementation.Utils.trimBeginningAndEndingSlashes; /* * The following code only support Document Write without any error handling support. */ public class HttpTransportClient extends TransportClient { private final Logger logger = LoggerFactory.getLogger(HttpTransportClient.class); private final HttpClient httpClient; private final Map<String, String> defaultHeaders; private final Configs configs; HttpClient createHttpClient(int requestTimeout) { // TODO: use one instance of SSL context everywhere HttpClientConfig httpClientConfig = new HttpClientConfig(this.configs); httpClientConfig.withRequestTimeoutInMillis(requestTimeout * 1000); httpClientConfig.withPoolSize(configs.getDirectHttpsMaxConnectionLimit()); return HttpClient.createFixed(httpClientConfig); } public HttpTransportClient(Configs configs, int requestTimeout, UserAgentContainer userAgent) { this.configs = configs; this.httpClient = createHttpClient(requestTimeout); this.defaultHeaders = new HashMap<>(); // Set requested API version header for version enforcement. this.defaultHeaders.put(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); this.defaultHeaders.put(HttpConstants.HttpHeaders.CACHE_CONTROL, HttpConstants.HeaderValues.NoCache); if (userAgent == null) { userAgent = new UserAgentContainer(); } this.defaultHeaders.put(HttpConstants.HttpHeaders.USER_AGENT, userAgent.getUserAgent()); this.defaultHeaders.put(HttpConstants.HttpHeaders.ACCEPT, RuntimeConstants.MediaTypes.JSON); } @Override public void close() { httpClient.shutdown(); } public Mono<StoreResponse> invokeStoreAsync( Uri physicalAddressUri, RxDocumentServiceRequest request) { try { URI physicalAddress = physicalAddressUri.getURI(); ResourceOperation resourceOperation = new ResourceOperation(request.getOperationType(), request.getResourceType()); // uuid correlation manager String activityId = request.getActivityId().toString(); if (resourceOperation.operationType == OperationType.Recreate) { Map<String, String> errorResponseHeaders = new HashMap<>(); errorResponseHeaders.put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); logger.error("Received Recreate request on Http client"); throw new InternalServerErrorException(RMResources.InternalServerError, null, errorResponseHeaders, null); } HttpRequest httpRequest = prepareHttpMessage(activityId, physicalAddressUri, resourceOperation, request); MutableVolatile<Instant> sendTimeUtc = new MutableVolatile<>(); Mono<HttpResponse> httpResponseMono = this.httpClient .send(httpRequest) .doOnSubscribe(subscription -> { sendTimeUtc.v = Instant.now(); this.beforeRequest( activityId, httpRequest.uri(), request.getResourceType(), httpRequest.headers()); }) .onErrorResume(t -> { Exception exception = Utils.as(t, Exception.class); if (exception == null) { logger.error("critical failure", t); t.printStackTrace(); assert false : "critical failure"; return Mono.error(t); } //Trace.CorrelationManager.ActivityId = activityId; if (WebExceptionUtility.isWebExceptionRetriable(exception)) { logger.debug("Received retriable exception {} " + "sending the request to {}, will re-resolve the address " + "send time UTC: {}", exception, physicalAddress, sendTimeUtc); GoneException goneException = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), exception, null, physicalAddress); return Mono.error(goneException); } else if (request.isReadOnlyRequest()) { logger.trace("Received exception {} on readonly request" + "sending the request to {}, will reresolve the address " + "send time UTC: {}", exception, physicalAddress, sendTimeUtc); GoneException goneException = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), exception, null, physicalAddress); return Mono.error(goneException); } else { // We can't throw a GoneException here because it will cause retry and we don't // know if the request failed before or after the message got sent to the server. // So in order to avoid duplicating the request we will not retry. // TODO: a possible solution for this is to add the ability to send a request to the server // to check if the previous request was received or not and act accordingly. ServiceUnavailableException serviceUnavailableException = new ServiceUnavailableException( String.format( RMResources.ExceptionMessage, RMResources.ServiceUnavailable), exception, null, physicalAddress.toString()); serviceUnavailableException.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); serviceUnavailableException.getResponseHeaders().put(HttpConstants.HttpHeaders.WRITE_REQUEST_TRIGGER_ADDRESS_REFRESH, "1"); return Mono.error(serviceUnavailableException); }}) .doOnSuccess(httpClientResponse -> { Instant receivedTimeUtc = Instant.now(); double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); this.afterRequest( activityId, httpClientResponse.statusCode(), durationInMilliSeconds, httpClientResponse.headers()); }) .doOnError(e -> { Instant receivedTimeUtc = Instant.now(); double durationInMilliSeconds = (receivedTimeUtc.toEpochMilli() - sendTimeUtc.v.toEpochMilli()); this.afterRequest( activityId, 0, durationInMilliSeconds, null); }); return httpResponseMono.flatMap(rsp -> processHttpResponse(request.getResourceAddress(), httpRequest, activityId.toString(), rsp, physicalAddress)); } catch (Exception e) { return Mono.error(e); } } private void beforeRequest(String activityId, URI uri, ResourceType resourceType, HttpHeaders requestHeaders) { // TODO: perf counters // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 } private void afterRequest(String activityId, int statusCode, double durationInMilliSeconds, HttpHeaders responseHeaders) { // TODO: perf counters // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 } private static void addHeader(HttpHeaders requestHeaders, String headerName, RxDocumentServiceRequest request) { String headerValue = request.getHeaders().get(headerName); if (!Strings.isNullOrEmpty(headerValue)) { requestHeaders.set(headerName, headerValue); } } private static void addHeader(HttpHeaders requestHeaders, String headerName, String headerValue) { if (!Strings.isNullOrEmpty(headerValue)) { requestHeaders.set(headerName, headerValue); } } private String getMatch(RxDocumentServiceRequest request, ResourceOperation resourceOperation) { switch (resourceOperation.operationType) { case Delete: case ExecuteJavaScript: case Replace: case Update: case Upsert: return request.getHeaders().get(HttpConstants.HttpHeaders.IF_MATCH); case Read: case ReadFeed: return request.getHeaders().get(HttpConstants.HttpHeaders.IF_NONE_MATCH); default: return null; } } private HttpRequest prepareHttpMessage( String activityId, Uri physicalAddress, ResourceOperation resourceOperation, RxDocumentServiceRequest request) throws Exception { HttpRequest httpRequestMessage; String requestUri; HttpMethod method; // The StreamContent created below will own and dispose its underlying stream, but we may need to reuse the stream on the // RxDocumentServiceRequest for future requests. Hence we need to clone without incurring copy cost, so that when // HttpRequestMessage -> StreamContent -> MemoryStream all get disposed, the original stream will be left open. switch (resourceOperation.operationType) { case Create: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContent() != null; httpRequestMessage = new HttpRequest(method, requestUri, physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContent()); break; case ExecuteJavaScript: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContent() != null; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContent()); break; case Delete: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.DELETE; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); break; case Read: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.GET; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); break; case ReadFeed: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.GET; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); break; case Replace: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.PUT; assert request.getContent() != null; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContent()); break; case Update: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = new HttpMethod("PATCH"); assert request.getContent() != null; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContent()); break; case Query: case SqlQuery: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContent() != null; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContent()); HttpTransportClient.addHeader(httpRequestMessage.headers(), HttpConstants.HttpHeaders.CONTENT_TYPE, request); break; case Upsert: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.POST; assert request.getContent() != null; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); httpRequestMessage.withBody(request.getContent()); break; case Head: requestUri = getResourceEntryUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.HEAD; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); break; case HeadFeed: requestUri = getResourceFeedUri(resourceOperation.resourceType, physicalAddress.getURIAsString(), request); method = HttpMethod.HEAD; httpRequestMessage = new HttpRequest(method, requestUri.toString(), physicalAddress.getURI().getPort()); break; default: assert false : "Unsupported operation type"; throw new IllegalStateException(); } Map<String, String> documentServiceRequestHeaders = request.getHeaders(); HttpHeaders httpRequestHeaders = httpRequestMessage.headers(); // add default headers for(Map.Entry<String, String> entry: defaultHeaders.entrySet()) { HttpTransportClient.addHeader(httpRequestHeaders, entry.getKey(), entry.getValue()); } HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.VERSION, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.USER_AGENT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PAGE_SIZE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PRE_TRIGGER_INCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PRE_TRIGGER_EXCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POST_TRIGGER_INCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POST_TRIGGER_EXCLUDE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.AUTHORIZATION, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.INDEXING_DIRECTIVE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.MIGRATE_COLLECTION_DIRECTIVE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONSISTENCY_LEVEL, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.SESSION_TOKEN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PREFER, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.RESOURCE_TOKEN_EXPIRY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_SCAN_IN_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.EMIT_VERBOSE_TRACES_IN_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_CHARGE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_THROTTLE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_LOW_PRECISION_ORDER_BY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ENABLE_LOGGING, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_READ_ONLY_SCRIPT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONTENT_SERIALIZATION_FORMAT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CONTINUATION, request.getContinuation()); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.ACTIVITY_ID, activityId.toString()); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PARTITION_KEY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.PARTITION_KEY_RANGE_ID, request); String dateHeader = HttpUtils.getDateHeader(documentServiceRequestHeaders); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.X_DATE, dateHeader); HttpTransportClient.addHeader(httpRequestHeaders, "Match", this.getMatch(request, resourceOperation)); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IF_MODIFIED_SINCE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.A_IM, request); if (!request.getIsNameBased()) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.RESOURCE_ID, request.getResourceId()); } HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.ENTITY_ID, request.entityId); String fanoutRequestHeader = request.getHeaders().get(WFConstants.BackendHeaders.IS_FANOUT_REQUEST); HttpTransportClient.addHeader(httpRequestMessage.headers(), WFConstants.BackendHeaders.IS_FANOUT_REQUEST, fanoutRequestHeader); if (request.getResourceType() == ResourceType.DocumentCollection) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_PARTITION_INDEX, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.COLLECTION_PARTITION_INDEX)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_SERVICE_INDEX, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.COLLECTION_SERVICE_INDEX)); } if (documentServiceRequestHeaders.get(WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE) != null) { HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.BIND_REPLICA_DIRECTIVE)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PRIMARY_MASTER_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.PRIMARY_MASTER_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SECONDARY_MASTER_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.SECONDARY_MASTER_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PRIMARY_READONLY_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.PRIMARY_READONLY_KEY)); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SECONDARY_READONLY_KEY, documentServiceRequestHeaders.get(WFConstants.BackendHeaders.SECONDARY_READONLY_KEY)); } if (documentServiceRequestHeaders.get(HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE) != null) { HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE, documentServiceRequestHeaders.get(HttpConstants.HttpHeaders.CAN_OFFER_REPLACE_COMPLETE)); } //Query HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_QUERY, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.QUERY, request); // Upsert HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.IS_UPSERT, request); // SupportSpatialLegacyCoordinates HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.SUPPORT_SPATIAL_LEGACY_COORDINATES, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.PARTITION_COUNT, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.COLLECTION_RID, request); // Filter by schema HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.FILTER_BY_SCHEMA_RESOURCE_ID, request); // UsePolygonsSmallerThanAHemisphere HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.USE_POLYGONS_SMALLER_THAN_AHEMISPHERE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.GATEWAY_SIGNATURE, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_QUOTA_INFO, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_QUERY_METRICS, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.FORCE_QUERY_SCAN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.RESPONSE_CONTINUATION_TOKEN_LIMIT_IN_KB, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.REMOTE_STORAGE_TYPE, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.SHARE_THROUGHPUT, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_PARTITION_STATISTICS, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.POPULATE_COLLECTION_THROUGHPUT_INFO, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.REMAINING_TIME_IN_MS_ON_CLIENT_REQUEST, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.CLIENT_RETRY_ATTEMPT_COUNT, request); // target lsn for head requests. HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.TARGET_LSN, request); HttpTransportClient.addHeader(httpRequestHeaders, HttpConstants.HttpHeaders.TARGET_GLOBAL_COMMITTED_LSN, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.FEDERATION_ID_FOR_AUTH, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.FANOUT_OPERATION_STATE, request); HttpTransportClient.addHeader(httpRequestHeaders, WFConstants.BackendHeaders.ALLOW_TENTATIVE_WRITES, request); HttpTransportClient.addHeader(httpRequestHeaders, CustomHeaders.HttpHeaders.EXCLUDE_SYSTEM_PROPERTIES, request); return httpRequestMessage; } static String getResourceFeedUri(ResourceType resourceType, String physicalAddress, RxDocumentServiceRequest request) throws Exception { switch (resourceType) { case Attachment: return getAttachmentFeedUri(physicalAddress, request); case DocumentCollection: return getCollectionFeedUri(physicalAddress, request); case Conflict: return getConflictFeedUri(physicalAddress, request); case Database: return getDatabaseFeedUri(physicalAddress); case Document: return getDocumentFeedUri(physicalAddress, request); case Permission: return getPermissionFeedUri(physicalAddress, request); case StoredProcedure: return getStoredProcedureFeedUri(physicalAddress, request); case Trigger: return getTriggerFeedUri(physicalAddress, request); case User: return getUserFeedUri(physicalAddress, request); case UserDefinedFunction: return getUserDefinedFunctionFeedUri(physicalAddress, request); case Schema: return getSchemaFeedUri(physicalAddress, request); case Offer: return getOfferFeedUri(physicalAddress, request); // Other types: Replica, Module, ModuleCommand, Record, UserDefinedType not applicable to SDK. default: assert false : "Unexpected resource type: " + resourceType; throw new NotFoundException(); } } private static String getResourceEntryUri(ResourceType resourceType, String physicalAddress, RxDocumentServiceRequest request) throws Exception { switch (resourceType) { case Attachment: return getAttachmentEntryUri(physicalAddress, request); case DocumentCollection: return getCollectionEntryUri(physicalAddress, request); case Conflict: return getConflictEntryUri(physicalAddress, request); case Database: return getDatabaseEntryUri(physicalAddress, request); case Document: return getDocumentEntryUri(physicalAddress, request); case Permission: return getPermissionEntryUri(physicalAddress, request); case StoredProcedure: return getStoredProcedureEntryUri(physicalAddress, request); case Trigger: return getTriggerEntryUri(physicalAddress, request); case User: return getUserEntryUri(physicalAddress, request); case UserDefinedFunction: return getUserDefinedFunctionEntryUri(physicalAddress, request); case Schema: return getSchemaEntryUri(physicalAddress, request); case Offer: return getOfferEntryUri(physicalAddress, request); // Other types: Replica, Module, ModuleCommand, Record, UserDefinedType not applicable to SDK. default: assert false: "Unexpected resource type: " + resourceType; throw new IllegalStateException(); } } static String createURI(String baseAddress, String resourcePath) { if (baseAddress.charAt(baseAddress.length() - 1) == '/') { return baseAddress + HttpUtils.urlEncode(trimBeginningAndEndingSlashes(resourcePath)); } else { return baseAddress + '/' + HttpUtils.urlEncode(trimBeginningAndEndingSlashes(resourcePath)); } } static String getRootFeedUri(String baseAddress) { return baseAddress; } private static String getDatabaseFeedUri(String baseAddress) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Database, StringUtils.EMPTY, true)); } private static String getDatabaseEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Database, request, false)); } private static String getCollectionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.DocumentCollection, request, true)); } private static String getStoredProcedureFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.StoredProcedure, request, true)); } private static String getTriggerFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Trigger, request, true)); } private static String getUserDefinedFunctionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.UserDefinedFunction, request, true)); } private static String getCollectionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.DocumentCollection, request, false)); } private static String getStoredProcedureEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.StoredProcedure, request, false)); } private static String getTriggerEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Trigger, request, false)); } private static String getUserDefinedFunctionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.UserDefinedFunction, request, false)); } private static String getDocumentFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Document, request, true)); } private static String getDocumentEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Document, request, false)); } private static String getConflictFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Conflict, request, true)); } private static String getConflictEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Conflict, request, false)); } private static String getAttachmentFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Attachment, request, true)); } private static String getAttachmentEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Attachment, request, false)); } private static String getUserFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.User, request, true)); } private static String getUserEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.User, request, false)); } private static String getPermissionFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Permission, request, true)); } private static String getPermissionEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Permission, request, false)); } private static String getOfferFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Offer, request, true)); } private static String getSchemaFeedUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Schema, request, true)); } private static String getSchemaEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Schema, request, false)); } private static String getOfferEntryUri(String baseAddress, RxDocumentServiceRequest request) { return createURI(baseAddress, PathsHelper.generatePath(ResourceType.Offer, request, false)); } static String getHeader(String[] names, String[] values, String name) { for (int idx = 0; idx < names.length; idx++) { if (Strings.areEqual(names[idx], name)) { return values[idx]; } } return null; } private Mono<StoreResponse> processHttpResponse(String resourceAddress, HttpRequest httpRequest, String activityId, HttpResponse response, URI physicalAddress) { if (response == null) { InternalServerErrorException exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), null, physicalAddress); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.REQUEST_VALIDATION_FAILURE, "1"); return Mono.error(exception); } // If the status code is < 300 or 304 NotModified (we treat not modified as success) then it means that it's a success code and shouldn't throw. if (response.statusCode() < HttpConstants.StatusCodes.MINIMUM_STATUSCODE_AS_ERROR_GATEWAY || response.statusCode() == HttpConstants.StatusCodes.NOT_MODIFIED) { return ResponseUtils.toStoreResponse(response, httpRequest); } else { return this.createErrorResponseFromHttpResponse(resourceAddress, activityId, httpRequest, response); } } private Mono<StoreResponse> createErrorResponseFromHttpResponse(String resourceAddress, String activityId, HttpRequest request, HttpResponse response) { int statusCode = response.statusCode(); Mono<String> errorMessageObs = ErrorUtils.getErrorResponseAsync(response, request); return errorMessageObs.flatMap( errorMessage -> { long responseLSN = -1; List<String> lsnValues = null; String[] headerValues = response.headers().values(WFConstants.BackendHeaders.LSN); if (headerValues != null) { lsnValues = com.google.common.collect.Lists.newArrayList(headerValues); } if (lsnValues != null) { String temp = lsnValues.isEmpty() ? null : lsnValues.get(0); responseLSN = Longs.tryParse(temp, responseLSN); } String responsePartitionKeyRangeId = null; List<String> partitionKeyRangeIdValues = null; headerValues = response.headers().values(WFConstants.BackendHeaders.PARTITION_KEY_RANGE_ID); if (headerValues != null) { partitionKeyRangeIdValues = com.google.common.collect.Lists.newArrayList(headerValues); } if (partitionKeyRangeIdValues != null) { responsePartitionKeyRangeId = Lists.firstOrDefault(partitionKeyRangeIdValues, null); } CosmosClientException exception; switch (statusCode) { case HttpConstants.StatusCodes.UNAUTHORIZED: exception = new UnauthorizedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Unauthorized : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.FORBIDDEN: exception = new ForbiddenException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Forbidden : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.NOTFOUND: // HTTP.SYS returns NotFound (404) if the URI // is not registered. This is really an indication that // the replica which registered the URI is not // available at the server. We detect this case by // the presence of Content-Type header in the response // and map it to HTTP Gone (410), which is the more // appropriate response for this case. if (response.body() != null && response.headers() != null && response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE) != null && !Strings.isNullOrEmpty(response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE)) && Strings.containsIgnoreCase(response.headers().value(HttpConstants.HttpHeaders.CONTENT_TYPE), RuntimeConstants.MediaTypes.TEXT_HTML)) { // Have the request URL in the exception message for debugging purposes. exception = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), request.uri().toString()); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); break; } else { exception = new NotFoundException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.NotFound : errorMessage), response.headers(), request.uri()); break; } case HttpConstants.StatusCodes.BADREQUEST: exception = new BadRequestException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.BadRequest : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.METHOD_NOT_ALLOWED: exception = new MethodNotAllowedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.MethodNotAllowed : errorMessage), null, response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.GONE: { // TODO: update perf counter // https://msdata.visualstudio.com/CosmosDB/_workitems/edit/258624 ErrorUtils.logGoneException(request.uri(), activityId); Integer nSubStatus = 0; String valueSubStatus = response.headers().value(WFConstants.BackendHeaders.SUB_STATUS); if (!Strings.isNullOrEmpty(valueSubStatus)) { if ((nSubStatus = Integers.tryParse(valueSubStatus)) == null) { exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), response.headers(), request.uri()); break; } } if (nSubStatus == HttpConstants.SubStatusCodes.NAME_CACHE_IS_STALE) { exception = new InvalidPartitionException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.PARTITION_KEY_RANGE_GONE) { exception = new PartitionKeyRangeGoneException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.COMPLETING_SPLIT) { exception = new PartitionKeyRangeIsSplittingException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else if (nSubStatus == HttpConstants.SubStatusCodes.COMPLETING_PARTITION_MIGRATION) { exception = new PartitionIsMigratingException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Gone : errorMessage), response.headers(), request.uri().toString()); break; } else { // Have the request URL in the exception message for debugging purposes. exception = new GoneException( String.format( RMResources.ExceptionMessage, RMResources.Gone), response.headers(), request.uri()); exception.getResponseHeaders().put(HttpConstants.HttpHeaders.ACTIVITY_ID, activityId); break; } } case HttpConstants.StatusCodes.CONFLICT: exception = new ConflictException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.EntityAlreadyExists : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.PRECONDITION_FAILED: exception = new PreconditionFailedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.PreconditionFailed : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.REQUEST_ENTITY_TOO_LARGE: exception = new RequestEntityTooLargeException( String.format( RMResources.ExceptionMessage, String.format( RMResources.RequestEntityTooLarge, HttpConstants.HttpHeaders.PAGE_SIZE)), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.LOCKED: exception = new LockedException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.Locked : errorMessage), response.headers(), request.uri().toString()); break; case HttpConstants.StatusCodes.SERVICE_UNAVAILABLE: exception = new ServiceUnavailableException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.ServiceUnavailable : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.REQUEST_TIMEOUT: exception = new RequestTimeoutException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.RequestTimeout : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.RETRY_WITH: exception = new RetryWithException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.RetryWith : errorMessage), response.headers(), request.uri()); break; case HttpConstants.StatusCodes.TOO_MANY_REQUESTS: exception = new RequestRateTooLargeException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.TooManyRequests : errorMessage), response.headers(), request.uri()); List<String> values = null; headerValues = response.headers().values(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS); if (headerValues != null) { values = com.google.common.collect.Lists.newArrayList(headerValues); } if (values == null || values.isEmpty()) { logger.warn("RequestRateTooLargeException being thrown without RetryAfter."); } else { exception.getResponseHeaders().put(HttpConstants.HttpHeaders.RETRY_AFTER_IN_MILLISECONDS, values.get(0)); } break; case HttpConstants.StatusCodes.INTERNAL_SERVER_ERROR: exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, Strings.isNullOrEmpty(errorMessage) ? RMResources.InternalServerError : errorMessage), response.headers(), request.uri()); break; default: logger.error("Unrecognized status code {} returned by backend. ActivityId {}", statusCode, activityId); ErrorUtils.logException(request.uri(), activityId); exception = new InternalServerErrorException( String.format( RMResources.ExceptionMessage, RMResources.InvalidBackendResponse), response.headers(), request.uri()); break; } BridgeInternal.setLSN(exception, responseLSN); BridgeInternal.setPartitionKeyRangeId(exception, responsePartitionKeyRangeId); BridgeInternal.setResourceAddress(exception, resourceAddress); BridgeInternal.setRequestHeaders(exception, HttpUtils.asMap(request.headers())); return Mono.error(exception); } ); } }
/* Copyright (c) 2015 LinkedIn Corp. 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.linkedin.multipart; import com.linkedin.data.ByteString; import com.linkedin.r2.message.stream.entitystream.WriteHandle; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.mockito.stubbing.OngoingStubbing; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; /** * Tests for {@link com.linkedin.multipart.MultiPartMIMEInputStream} * * @author Karim Vidhani */ public class TestMIMEInputStream extends AbstractMIMEUnitTest { private static final int TEST_CHUNK_SIZE = 4; /////////////////////////////////////////////////////////////////////////////////////// //Classes for tests below //We need a convenient input stream for testing so we use ByteArrayInputStream. //This input stream should also be a bit more rigid in behavior. Therefore it should complain about being closed more //then once so that we don't over-close our data sources. This input stream should also complain when reads are made //after closing. ByteArrayInputStream is convenient, but out of the box its too flexible. private static class StrictByteArrayInputStream extends ByteArrayInputStream { private boolean _isClosed = false; private StrictByteArrayInputStream(final byte[] bytes) { super(bytes); } @Override public void close() throws IOException { if (_isClosed) { throw new IOException("Can only close once"); } _isClosed = true; super.close(); } @Override public int read(byte[] b) throws IOException { if (_isClosed) { throw new IOException("Already closed!"); } return super.read(b); } //Doesn't exist in ByteArrayInputStream so we introduce our own check. boolean isClosed() { return _isClosed; } } //Simulates an input stream that responds slower and slower. We also need the strict behavior //here as well. private static class SlowByteArrayInputStream extends StrictByteArrayInputStream { private int _readDelay = 0; private final int _delayIncrement; private SlowByteArrayInputStream(final byte[] bytes, final int initialDelay, final int delayIncrement) { super(bytes); _readDelay = initialDelay; _delayIncrement = delayIncrement; } @Override public int read(byte[] b) throws IOException { try { Thread.sleep(_readDelay); _readDelay = _readDelay + _delayIncrement; } catch (InterruptedException interruptException) { Assert.fail(); } return super.read(b); } } //Simulates an input stream that times out after a specified number of reads. private static class TimeoutByteArrayInputStream extends StrictByteArrayInputStream { private int _numberOfReadsBeforeTimeout; private final CountDownLatch _latch; private TimeoutByteArrayInputStream(final byte[] bytes, final int numberOfReadsBeforeTimeout, final CountDownLatch latchToWaitOnTimeout) { super(bytes); _numberOfReadsBeforeTimeout = numberOfReadsBeforeTimeout; _latch = latchToWaitOnTimeout; } @Override public int read(byte[] b) throws IOException { try { if (_numberOfReadsBeforeTimeout == 0) { _latch.await(); } } catch (InterruptedException interruptException) { Assert.fail(); } _numberOfReadsBeforeTimeout--; return super.read(b); } } //Simulates an input stream that throws IOException after a configurable number of reads. private static class ExceptionThrowingByteArrayInputStream extends StrictByteArrayInputStream { private final int _permissibleReads; private int _readCount = 0; private final IOException _throwable; private ExceptionThrowingByteArrayInputStream(final byte[] bytes, final int permissibleReads, final IOException throwable) { super(bytes); _permissibleReads = permissibleReads; _throwable = throwable; } @Override public int read(byte[] b) throws IOException { if (_readCount == _permissibleReads) { throw _throwable; } _readCount++; return super.read(b); } } /////////////////////////////////////////////////////////////////////////////////////// //This test will use a small and large data source to verify behavior with a single //invocation of onWritePossible(). @DataProvider(name = "singleOnWritePossibleDataSources") public Object[][] singleOnWritePossibleDataSources() throws Exception { final byte[] smallInputData = "b".getBytes(); //Ensure three writes for the bigger data final StringBuilder builder = new StringBuilder(); for (int i = 0; i < (TEST_CHUNK_SIZE * 2) + 2; i++) { builder.append('a'); } final byte[] largeInputData = builder.toString().getBytes(); return new Object[][] { //One onWritePossible() providing one write on the writeHandle which results in 1 expected write {smallInputData, new StrictByteArrayInputStream(smallInputData), 1, 1}, //One OnWritePossible() providing three writes on the writeHandle, which results in 3 expected writes {largeInputData, new StrictByteArrayInputStream(largeInputData), 3, 3}, //Also verify that extra writes handles available do no harm: {smallInputData, new StrictByteArrayInputStream(smallInputData), 3, 1}, {largeInputData, new StrictByteArrayInputStream(largeInputData), 5, 3}, }; } @Test(dataProvider = "singleOnWritePossibleDataSources") public void testSingleOnWritePossibleDataSources(final byte[] inputData, final StrictByteArrayInputStream inputStream, final int writesRemainingPerOnWritePossibles, final int expectedTotalWrites) { //Setup: final WriteHandle writeHandle = Mockito.mock(WriteHandle.class); final MultiPartMIMEInputStream multiPartMIMEInputStream = new MultiPartMIMEInputStream.Builder(inputStream, _scheduledExecutorService, Collections.<String, String>emptyMap()).withWriteChunkSize(TEST_CHUNK_SIZE).build(); //Simulate a write handle that offers decreasing writeHandle.remaining() final Integer[] remainingWriteHandleCount = simulateDecreasingWriteHandleCount(writesRemainingPerOnWritePossibles); when(writeHandle.remaining()).thenReturn(writesRemainingPerOnWritePossibles, remainingWriteHandleCount); final ByteArrayOutputStream byteArrayOutputStream = setupMockWriteHandleToOutputStream(writeHandle); //Setup for done() final CountDownLatch doneLatch = new CountDownLatch(1); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { doneLatch.countDown(); return null; } }).when(writeHandle).done(); /////////////////////////////////// //Start things off //Init the data source multiPartMIMEInputStream.onInit(writeHandle); multiPartMIMEInputStream.onWritePossible(); //Wait to finish try { boolean successful = doneLatch.await(_testTimeout, TimeUnit.MILLISECONDS); if (!successful) { Assert.fail("Timeout when waiting for input stream to completely transfer"); } } catch (Exception exception) { Assert.fail("Unexpected exception when waiting for input stream to completely transfer"); } /////////////////////////////////// //Assert Assert.assertEquals(byteArrayOutputStream.toByteArray(), inputData, "All data from the input stream should have successfully been transferred"); Assert.assertEquals(inputStream.isClosed(), true); //Mock verifies: verify(writeHandle, times(expectedTotalWrites)).write(isA(ByteString.class)); verify(writeHandle, times(expectedTotalWrites)).remaining(); verify(writeHandle, never()).error(isA(Throwable.class)); verify(writeHandle, times(1)).done(); verifyNoMoreInteractions(writeHandle); } /////////////////////////////////////////////////////////////////////////////////////// //This test will use a small and large data source to verify behavior with a multiple //invocations of onWritePossible(). @DataProvider(name = "multipleOnWritePossibleDataSources") public Object[][] multipleOnWritePossibleDataSources() throws Exception { //Ensure three writes for the bigger data final StringBuilder builder = new StringBuilder(); for (int i = 0; i < (TEST_CHUNK_SIZE * 2) + 2; i++) { builder.append('a'); } final byte[] largeInputData = builder.toString().getBytes(); return new Object[][] { //Represents 3 invocations of onWritePossible(), each providing 1 write on the write handle. //We expect a total of 3 writes based on our chunk size. //We also expect 5 invocations of writeHandle.remaining(). This is because the first two //onWritePossibles() will lead to writeHandle.remaining() being called twice (returning 1,0) //and the last onWritePossible() will lead to writeHandle.remaining() being called once (returning 1) //at which point the data is finished. {largeInputData, new StrictByteArrayInputStream(largeInputData), 3, 1, 3, 5}, //Represents 2 invocation of onWritePossible, each providing 2 writes on the write handle. //We expect a total of 3 writes based on our chunk size. //We also expect 4 invocation of writeHandle.remaining(). This is because the first onWritePossible() //will lead to writeHandle.remaining() being called thrice (returning 2,1,0) and the second //onWritePossible() will lead to writeHandle.remaining() being called once (returning 2) //at which point the data is finished. {largeInputData, new StrictByteArrayInputStream(largeInputData), 2, 2, 3, 4}, }; } @Test(dataProvider = "multipleOnWritePossibleDataSources") public void testMultipleOnWritePossibleDataSources(final byte[] inputData, final StrictByteArrayInputStream inputStream, final int onWritePossibles, final int writesRemainingPerOnWritePossible, final int expectedTotalWrites, final int expectedWriteHandleRemainingCalls) { //Setup: final WriteHandle writeHandle = Mockito.mock(WriteHandle.class); final MultiPartMIMEInputStream multiPartMIMEInputStream = new MultiPartMIMEInputStream.Builder(inputStream, _scheduledExecutorService, Collections.<String, String>emptyMap()).withWriteChunkSize(TEST_CHUNK_SIZE).build(); //We want to simulate a decreasing return from writeHandle.remaining(). //Note that the 0 is added on later so we stop at 1: final Integer[] remainingWriteHandleCount; if (writesRemainingPerOnWritePossible > 1) { //This represents writeHandle.remaining() -> n, n -1, n - 2, .... 1, 0 remainingWriteHandleCount = new Integer[writesRemainingPerOnWritePossible - 1]; int writeHandleCountTemp = writesRemainingPerOnWritePossible; for (int i = 0; i < writesRemainingPerOnWritePossible - 1; i++) { remainingWriteHandleCount[i] = --writeHandleCountTemp; } } else { //This represents writeHandle.remaining() -> 1, 0 remainingWriteHandleCount = new Integer[]{}; } OngoingStubbing<Integer> writeHandleOngoingStubbing = when(writeHandle.remaining()); for (int i = 0; i < onWritePossibles; i++) { //Each onWritePossible() will provide the corresponding number of writes remaining on the write handle. //When the writeHandle.remaining() reaches zero, onWritePossible() will be invoked again. //Mockito does not mention that chaining requires keeping the references and only allows one append at a time. //A painful lesson that I had to learn so I will leave a comment here for future people. writeHandleOngoingStubbing = writeHandleOngoingStubbing.thenReturn(writesRemainingPerOnWritePossible, remainingWriteHandleCount); writeHandleOngoingStubbing = writeHandleOngoingStubbing.thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { //There is no better way to do this with mockito. R2 observes that 0 has been returned and THEN //invokes onWritePossible(). We need to make sure that the value of 0 is returned //and then onWritePossible() is invoked afterwards. _scheduledExecutorService.schedule(new Runnable() { @Override public void run() { multiPartMIMEInputStream.onWritePossible(); } }, 1000, TimeUnit.MILLISECONDS); return 0; } }); } final ByteArrayOutputStream byteArrayOutputStream = setupMockWriteHandleToOutputStream(writeHandle); //Setup for done() final CountDownLatch doneLatch = new CountDownLatch(1); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { doneLatch.countDown(); return null; } }).when(writeHandle).done(); /////////////////////////////////// //Start things off //Init the data source multiPartMIMEInputStream.onInit(writeHandle); multiPartMIMEInputStream.onWritePossible(); //Wait to finish try { boolean successful = doneLatch.await(_testTimeout, TimeUnit.MILLISECONDS); if (!successful) { Assert.fail("Timeout when waiting for input stream to completely transfer"); } } catch (Exception exception) { Assert.fail("Unexpected exception when waiting for input stream to completely transfer"); } /////////////////////////////////// //Assert Assert.assertEquals(byteArrayOutputStream.toByteArray(), inputData, "All data from the input stream should have successfully been transferred"); Assert.assertEquals(inputStream.isClosed(), true); //Mock verifies: //The amount of times we write and the amount of times we call remaining() is the same. verify(writeHandle, times(expectedTotalWrites)).write(isA(ByteString.class)); verify(writeHandle, times(expectedWriteHandleRemainingCalls)).remaining(); verify(writeHandle, never()).error(isA(Throwable.class)); verify(writeHandle, times(1)).done(); verifyNoMoreInteractions(writeHandle); } /////////////////////////////////////////////////////////////////////////////////////// //This test will verify that timeouts on reads are handled properly. @DataProvider(name = "timeoutDataSources") public Object[][] timeoutDataSources() throws Exception { final StringBuilder builder = new StringBuilder(); final Random rand = new Random(); //Create some large data for (int i = 0; i < (TEST_CHUNK_SIZE * 120); i++) { //Randomly populate char c = (char) (rand.nextInt(26) + 'a'); builder.append(c); } final byte[] largeInputData = builder.toString().getBytes(); final CountDownLatch timeoutFirstLatch = new CountDownLatch(1); final CountDownLatch timeoutSubsequentlyLatch = new CountDownLatch(1); final TimeoutByteArrayInputStream timeoutFirst = new TimeoutByteArrayInputStream(largeInputData, 0, timeoutFirstLatch); final TimeoutByteArrayInputStream timeoutSubsequently = new TimeoutByteArrayInputStream(largeInputData, 5, timeoutSubsequentlyLatch); //TEST_CHUNK_SIZE * 5 writes should be how much data was copied over final byte[] largeInputDataPartial = Arrays.copyOf(largeInputData, TEST_CHUNK_SIZE * 5); return new Object[][] { //Timeout on first read. Nothing should have been read. One call on writeHandle.remaining() should have been seen. {timeoutFirst, 0, 1, new byte[0], timeoutFirstLatch}, //Timeout on the 6th read. We should expect 5 writes. Six calls on writeHandle.remaining() should have been seen. {timeoutSubsequently, 5, 6, largeInputDataPartial, timeoutSubsequentlyLatch} }; } @Test(dataProvider = "timeoutDataSources") public void testTimeoutDataSources(final TimeoutByteArrayInputStream timeoutByteArrayInputStream, final int expectedTotalWrites, final int expectedWriteHandleRemainingCalls, final byte[] expectedDataWritten, final CountDownLatch latch) { //Setup final WriteHandle writeHandle = Mockito.mock(WriteHandle.class); //For the maximum blocking time, we choose some value that isn't too short for a read to occur from the in memory //InputStream, but also not too long to prevent the test from taking a while to finish (due to waiting for the timeout //to occur). final MultiPartMIMEInputStream multiPartMIMEInputStream = new MultiPartMIMEInputStream.Builder(timeoutByteArrayInputStream, _scheduledExecutorService, Collections.<String, String>emptyMap()).withWriteChunkSize(TEST_CHUNK_SIZE) .withMaximumBlockingTime(100) .build(); //Doesn't matter what we return here as long as its constant and above 0. when(writeHandle.remaining()).thenReturn(1); final ByteArrayOutputStream byteArrayOutputStream = setupMockWriteHandleToOutputStream(writeHandle); //Setup for error() final CountDownLatch errorLatch = new CountDownLatch(1); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { errorLatch.countDown(); return null; } }).when(writeHandle).error(isA(Throwable.class)); /////////////////////////////////// //Start things off //Init the data source multiPartMIMEInputStream.onInit(writeHandle); multiPartMIMEInputStream.onWritePossible(); //Wait to finish try { boolean successful = errorLatch.await(_testTimeout, TimeUnit.MILLISECONDS); //Unblock the thread in the thread pool. latch.countDown(); if (!successful) { Assert.fail("Timeout when waiting for input stream to completely transfer"); } } catch (Exception exception) { Assert.fail("Unexpected exception when waiting for input stream to transfer"); } /////////////////////////////////// //Assert Assert.assertEquals(byteArrayOutputStream.toByteArray(), expectedDataWritten, "Partial data should have been transferred in the case of a timeout"); Assert.assertEquals(timeoutByteArrayInputStream.isClosed(), true); //Mock verifies: verify(writeHandle, times(expectedTotalWrites)).write(isA(ByteString.class)); verify(writeHandle, times(expectedWriteHandleRemainingCalls)).remaining(); verify(writeHandle, times(1)).error(isA(TimeoutException.class)); //Since we can't override equals verify(writeHandle, never()).done(); verifyNoMoreInteractions(writeHandle); } /////////////////////////////////////////////////////////////////////////////////////// //This test will make sure that exceptions thrown by the read are handled properly @DataProvider(name = "exceptionDataSources") public Object[][] exceptionDataSources() throws Exception { final StringBuilder builder = new StringBuilder(); final Random rand = new Random(); //Create some large data for (int i = 0; i < (TEST_CHUNK_SIZE * 120); i++) { //Randomly populate char c = (char) (rand.nextInt(26) + 'a'); builder.append(c); } final byte[] largeInputData = builder.toString().getBytes(); final ExceptionThrowingByteArrayInputStream exceptionFirst = new ExceptionThrowingByteArrayInputStream(largeInputData, 0, new IOException()); final ExceptionThrowingByteArrayInputStream exceptionSubsequently = new ExceptionThrowingByteArrayInputStream(largeInputData, 5, new IOException()); //TEST_CHUNK_SIZE * 5 writes should be how much data was copied over final byte[] largeInputDataPartial = Arrays.copyOf(largeInputData, TEST_CHUNK_SIZE * 5); return new Object[][] { //Timeout on first read. Nothing should have been read. One call on writeHandle.remaining() should have been seen. {exceptionFirst, 0, 1, new byte[0]}, //Timeout on the 6th read. We should expect 5 writes. Six calls on writeHandle.remaining() should have been seen. {exceptionSubsequently, 5, 6, largeInputDataPartial} }; } @Test(dataProvider = "exceptionDataSources") public void testExceptionDataSources( final ExceptionThrowingByteArrayInputStream exceptionThrowingByteArrayInputStream, final int expectedTotalWrites, final int expectedWriteHandleRemainingCalls, final byte[] expectedDataWritten) { //Setup: final WriteHandle writeHandle = Mockito.mock(WriteHandle.class); final MultiPartMIMEInputStream multiPartMIMEInputStream = new MultiPartMIMEInputStream.Builder(exceptionThrowingByteArrayInputStream, _scheduledExecutorService, Collections.<String, String>emptyMap()).withWriteChunkSize(TEST_CHUNK_SIZE).build(); //Doesn't matter what we return here as long as its constant and above 0. when(writeHandle.remaining()).thenReturn(500); final ByteArrayOutputStream byteArrayOutputStream = setupMockWriteHandleToOutputStream(writeHandle); //Setup for error() final CountDownLatch errorLatch = new CountDownLatch(1); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { errorLatch.countDown(); return null; } }).when(writeHandle).error(isA(Throwable.class)); /////////////////////////////////// //Start things off //Init the data source multiPartMIMEInputStream.onInit(writeHandle); multiPartMIMEInputStream.onWritePossible(); //Wait to finish try { boolean successful = errorLatch.await(_testTimeout, TimeUnit.MILLISECONDS); if (!successful) { Assert.fail("Timeout when waiting for input stream to completely transfer"); } } catch (Exception exception) { Assert.fail("Unexpected exception when waiting for input stream to transfer"); } /////////////////////////////////// //Assert Assert.assertEquals(byteArrayOutputStream.toByteArray(), expectedDataWritten, "Partial data should have been transferred in the case of an exception"); Assert.assertEquals(exceptionThrowingByteArrayInputStream.isClosed(), true); //Mock verifies: verify(writeHandle, times(expectedTotalWrites)).write(isA(ByteString.class)); verify(writeHandle, times(expectedWriteHandleRemainingCalls)).remaining(); verify(writeHandle, times(1)).error(isA(IOException.class)); //Since we can't override equals verify(writeHandle, never()).done(); verifyNoMoreInteractions(writeHandle); } /////////////////////////////////////////////////////////////////////////////////////// //These tests will verify that MultiPartMIMEInputStream behaves correctly in the face of //different bytesRead values inside of the input stream reader task. Essentially we are testing: // //if (bytesRead == -1) { // 1. N==-1. This signifies the stream is complete in the case that we coincidentally read to completion on the // last read from the InputStream. //} else if (bytesRead == _writeChunkSize) { // 2. N==Capacity. This signifies the most common case which is that we read as many bytes as we originally desired. //} else { // 3. Capacity > N >= 0. This signifies that the input stream is wrapping up and we just got the last few bytes. // @DataProvider(name = "differentDataSourceSizes") public Object[][] differentDataSourceSizes() throws Exception { //The data source is evenly divisible by the number of chunks. This should handle case 1 and it should //also handle case 2. final StringBuilder multipleEvenlyDivisibleChunksBuilder = new StringBuilder(); for (int i = 0; i < TEST_CHUNK_SIZE * 3; i++) { multipleEvenlyDivisibleChunksBuilder.append('a'); } final byte[] multipleEvenlyDivisibleChunks = multipleEvenlyDivisibleChunksBuilder.toString().getBytes(); //Less then one chunk of data. This should handle case 3. final StringBuilder lessThenOneChunkBuilder = new StringBuilder(); for (int i = 0; i < TEST_CHUNK_SIZE - 2; i++) { lessThenOneChunkBuilder.append('a'); } final byte[] lessThenOneChunk = lessThenOneChunkBuilder.toString().getBytes(); return new Object[][] { //One onWritePossible() providing 4 writes on the writeHandle which results in 3 expected writes. //We need the 4th write on the writeHandle since we coincidentally have modulo 0 chunk sizes. //The first three writes on the write handles write each chunk and the 4th is needed to realize //we just reached the end (-1 returned). {multipleEvenlyDivisibleChunks, new StrictByteArrayInputStream(multipleEvenlyDivisibleChunks), 4, 4, 3}, //One OnWritePossible() providing 1 write on the writeHandle, which results in 1 expected write. {lessThenOneChunk, new StrictByteArrayInputStream(lessThenOneChunk), 1, 1, 1}, //Also verify that extra writes handles available do no harm: {multipleEvenlyDivisibleChunks, new StrictByteArrayInputStream(multipleEvenlyDivisibleChunks), 10, 4, 3}, {lessThenOneChunk, new StrictByteArrayInputStream(lessThenOneChunk), 10, 1, 1} }; } @Test(dataProvider = "differentDataSourceSizes") public void testDifferentDataSourceSizes(final byte[] inputData, final StrictByteArrayInputStream inputStream, final int writesRemainingPerOnWritePossibles, final int expectedWriteHandleRemaining, final int expectedTotalWrites) { //Setup: final WriteHandle writeHandle = Mockito.mock(WriteHandle.class); final MultiPartMIMEInputStream multiPartMIMEInputStream = new MultiPartMIMEInputStream.Builder(inputStream, _scheduledExecutorService, Collections.<String, String>emptyMap()).withWriteChunkSize(TEST_CHUNK_SIZE).build(); //Simulate a write handle that offers decreasing writeHandle.remaining() final Integer[] remainingWriteHandleCount = simulateDecreasingWriteHandleCount(writesRemainingPerOnWritePossibles); when(writeHandle.remaining()).thenReturn(writesRemainingPerOnWritePossibles, remainingWriteHandleCount); final ByteArrayOutputStream byteArrayOutputStream = setupMockWriteHandleToOutputStream(writeHandle); //Setup for done() final CountDownLatch doneLatch = new CountDownLatch(1); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { doneLatch.countDown(); return null; } }).when(writeHandle).done(); /////////////////////////////////// //Start things off //Init the data source multiPartMIMEInputStream.onInit(writeHandle); multiPartMIMEInputStream.onWritePossible(); //Wait to finish try { boolean successful = doneLatch.await(_testTimeout, TimeUnit.MILLISECONDS); if (!successful) { Assert.fail("Timeout when waiting for input stream to completely transfer"); } } catch (Exception exception) { Assert.fail("Unexpected exception when waiting for input stream to completely transfer"); } /////////////////////////////////// //Assert Assert.assertEquals(byteArrayOutputStream.toByteArray(), inputData, "All data from the input stream should have successfully been transferred"); Assert.assertEquals(inputStream.isClosed(), true); //Mock verifies: verify(writeHandle, times(expectedTotalWrites)).write(isA(ByteString.class)); verify(writeHandle, times(expectedWriteHandleRemaining)).remaining(); verify(writeHandle, never()).error(isA(Throwable.class)); verify(writeHandle, times(1)).done(); verifyNoMoreInteractions(writeHandle); } /////////////////////////////////////////////////////////////////////////////////////// // //These tests will verify that aborts work properly and close the input stream regardless of the //current state. //This test will simulate an abort before any writes requested. @Test public void testAbortBeforeWrite() throws Exception { final byte[] smallInputData = "b".getBytes(); final StrictByteArrayInputStream inputStream = new StrictByteArrayInputStream(smallInputData); final StrictByteArrayInputStream spyInputStream = spy(inputStream); //Setup: final WriteHandle writeHandle = Mockito.mock(WriteHandle.class); final MultiPartMIMEInputStream multiPartMIMEInputStream = new MultiPartMIMEInputStream.Builder(spyInputStream, _scheduledExecutorService, Collections.<String, String>emptyMap()).withWriteChunkSize(TEST_CHUNK_SIZE).build(); //Setup for the close on the input stream. //The close must happen for the test to finish. final CountDownLatch closeInputStreamLatch = new CountDownLatch(1); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { closeInputStreamLatch.countDown(); return null; } }).when(spyInputStream).close(); /////////////////////////////////// //Start things off //Init the data source multiPartMIMEInputStream.onInit(writeHandle); multiPartMIMEInputStream.onAbort(new IOException()); //Wait to finish try { boolean successful = closeInputStreamLatch.await(_testTimeout, TimeUnit.MILLISECONDS); if (!successful) { Assert.fail("Timeout when waiting for abort to happen!"); } } catch (Exception exception) { Assert.fail("Unexpected exception when waiting for input stream to be closed!"); } /////////////////////////////////// //Mock verifies: verify(spyInputStream, times(1)).close(); verify(spyInputStream, never()).read(isA(byte[].class)); verify(writeHandle, never()).write(isA(ByteString.class)); verify(writeHandle, never()).remaining(); verify(writeHandle, never()).error(isA(Throwable.class)); verify(writeHandle, never()).done(); verifyNoMoreInteractions(writeHandle); } //Abort in the middle of a write task. @Test public void abortWhenNoOutstandingReadTask() throws Exception { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < (TEST_CHUNK_SIZE * 10) + 2; i++) { builder.append('a'); } //The slow byte array input stream will verify that we call an abort before the first read task is finished. final byte[] largeInputData = builder.toString().getBytes(); final SlowByteArrayInputStream inputStream = new SlowByteArrayInputStream(largeInputData, 300, 10); final SlowByteArrayInputStream spyInputStream = spy(inputStream); //Setup: final WriteHandle writeHandle = Mockito.mock(WriteHandle.class); final MultiPartMIMEInputStream multiPartMIMEInputStream = new MultiPartMIMEInputStream.Builder(spyInputStream, _scheduledExecutorService, Collections.<String, String>emptyMap()).withWriteChunkSize(TEST_CHUNK_SIZE).build(); //By the time the first onWritePossible() completes, half the data should be transferred //Then the abort task will run. when(writeHandle.remaining()).thenReturn(5, new Integer[]{4, 3, 2, 1, 0}); final ByteArrayOutputStream byteArrayOutputStream = setupMockWriteHandleToOutputStream(writeHandle); //Setup for the close on the input stream. //The close must happen for the test to finish. final CountDownLatch closeInputStreamLatch = new CountDownLatch(1); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { closeInputStreamLatch.countDown(); return null; } }).when(spyInputStream).close(); /////////////////////////////////// //Start things off //Init the data source multiPartMIMEInputStream.onInit(writeHandle); multiPartMIMEInputStream.onWritePossible(); multiPartMIMEInputStream.onAbort(new IOException()); //Wait to finish try { boolean successful = closeInputStreamLatch.await(_testTimeout, TimeUnit.MILLISECONDS); if (!successful) { Assert.fail("Timeout when waiting for abort to happen!"); } } catch (Exception exception) { Assert.fail("Unexpected exception when waiting for input stream to be closed!"); } /////////////////////////////////// //Assert final byte[] expectedBytes = Arrays.copyOf(largeInputData, TEST_CHUNK_SIZE * 5); Assert.assertEquals(byteArrayOutputStream.toByteArray(), expectedBytes, "Partial data from the input stream should have successfully been transferred"); //Mock verifies: verify(spyInputStream, times(1)).close(); verify(spyInputStream, times(5)).read(isA(byte[].class)); verify(writeHandle, times(5)).write(isA(ByteString.class)); verify(writeHandle, times(6)).remaining(); verify(writeHandle, never()).error(isA(Throwable.class)); verify(writeHandle, never()).done(); verifyNoMoreInteractions(writeHandle); } //We want to simulate a decreasing return from writeHandle.remaining(). //I.e 3, 2, 1, 0.... private static Integer[] simulateDecreasingWriteHandleCount(final int writesRemainingPerOnWritePossibles) { final Integer[] remainingWriteHandleCount; if (writesRemainingPerOnWritePossibles > 1) { //This represents writeHandle.remaining() -> n, n -1, n - 2, .... 1, 0 remainingWriteHandleCount = new Integer[writesRemainingPerOnWritePossibles]; int writeHandleCountTemp = writesRemainingPerOnWritePossibles; for (int i = 0; i < writesRemainingPerOnWritePossibles; i++) { remainingWriteHandleCount[i] = --writeHandleCountTemp; } } else { //This represents writeHandle.remaining() -> 1, 0 remainingWriteHandleCount = new Integer[]{0}; } return remainingWriteHandleCount; } //Adjust the write handle so that when its written to it writes to the ByteArrayOutputStream so we can aggregate the bytes. private static ByteArrayOutputStream setupMockWriteHandleToOutputStream(final WriteHandle writeHandle) { //When data is written to the write handle, we append to the buffer final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final ByteString argument = (ByteString) invocation.getArguments()[0]; appendByteStringToBuffer(byteArrayOutputStream, argument); return null; } }).when(writeHandle).write(isA(ByteString.class)); return byteArrayOutputStream; } private static void appendByteStringToBuffer(final ByteArrayOutputStream outputStream, final ByteString byteString) { try { outputStream.write(byteString.copyBytes()); } catch (Exception e) { Assert.fail(); } } }
package top.gabin.tools.request.ecommerce.profitsharing; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.EqualsAndHashCode; /** * <pre> * 不需要进行分账的订单,可直接调用本接口将订单的金额全部解冻给二级商户。 * 文档地址:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/profitsharing/chapter3_5.shtml * </pre> */ @Data @EqualsAndHashCode @JsonIgnoreProperties() public class ProfitSharingFinishRequest { /** * <pre> * 字段名:二级商户号 * 变量名:sub_mchid * 是否必填:是 * 类型:string[1,32] * 描述: * body 分账出资的电商平台二级商户,填写微信支付分配的商户号。 * 示例值:1900000109 * </pre> */ @JsonProperty(value = "sub_mchid") private String subMchid; /** * <pre> * 字段名:微信订单号 * 变量名:transaction_id * 是否必填:是 * 类型:string[1,32] * 描述: * body 微信支付订单号。 * 示例值: 4208450740201411110007820472 * </pre> */ @JsonProperty(value = "transaction_id") private String transactionId; /** * <pre> * 字段名:商户分帐单号 * 变量名:out_order_no * 是否必填:是 * 类型:string[1,64] * 描述: * body 商户系统内部的分账单号,在商户系统内部唯一(单次分账、多次分账、完结分账应使用不同的商户分账单号),同一分账单号多次请求等同一次。 * 示例值:P20150806125346 * </pre> */ @JsonProperty(value = "out_order_no") private String outOrderNo; /** * <pre> * 字段名:分账描述 * 变量名:description * 是否必填:是 * 类型:string[1,80] * 描述: * body 分账的原因描述,分账账单中需要体现。 * 示例值:分账完结 * </pre> */ @JsonProperty(value = "description") private String description; }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved. * */ package com.sleepycat.persist.impl; import com.sleepycat.bind.EntryBinding; import com.sleepycat.bind.tuple.TupleBase; import com.sleepycat.compat.DbCompat; import com.sleepycat.je.DatabaseEntry; /** * A persistence key binding for a given key class. * * @author Mark Hayes */ public class PersistKeyBinding implements EntryBinding { /* See Store.refresh for an explanation of the use of volatile fields. */ volatile Catalog catalog; volatile Format keyFormat; final boolean rawAccess; /** * Creates a key binding for a given key class. */ public PersistKeyBinding(Catalog catalogParam, String clsName, boolean rawAccess) { catalog = catalogParam; try { keyFormat = PersistEntityBinding.getOrCreateFormat (catalog, clsName, rawAccess); } catch (RefreshException e) { /* Must assign catalog field in constructor. */ catalog = e.refresh(); try { keyFormat = PersistEntityBinding.getOrCreateFormat (catalog, clsName, rawAccess); } catch (RefreshException e2) { throw DbCompat.unexpectedException(e2); } } if (!keyFormat.isSimple() && !keyFormat.isEnum() && !(keyFormat.getClassMetadata() != null && keyFormat.getClassMetadata().getCompositeKeyFields() != null)) { throw new IllegalArgumentException ("Key class is not a simple type, an enum, or a composite " + "key class (composite keys must include @KeyField " + "annotations): " + clsName); } this.rawAccess = rawAccess; } /** * Creates a key binding dynamically for use by PersistComparator. Formats * are created from scratch rather than using a shared catalog. */ PersistKeyBinding(final Catalog catalog, final Class cls, final String[] compositeFieldOrder) { this.catalog = catalog; keyFormat = new CompositeKeyFormat(catalog, cls, compositeFieldOrder); keyFormat.initializeIfNeeded(catalog, null /*model*/); rawAccess = false; } /** * Binds bytes to an object for use by PersistComparator as well as * entryToObject. */ Object bytesToObject(byte[] bytes, int offset, int length) throws RefreshException { return readKey(keyFormat, catalog, bytes, offset, length, rawAccess); } /** * Binds bytes to an object for use by PersistComparator as well as * entryToObject. */ static Object readKey(Format keyFormat, Catalog catalog, byte[] bytes, int offset, int length, boolean rawAccess) throws RefreshException { EntityInput input = new RecordInput (catalog, rawAccess, null, 0, bytes, offset, length); return input.readKeyObject(keyFormat); } public Object entryToObject(DatabaseEntry entry) { try { return entryToObjectInternal(entry); } catch (RefreshException e) { e.refresh(); try { return entryToObjectInternal(entry); } catch (RefreshException e2) { throw DbCompat.unexpectedException(e2); } } } private Object entryToObjectInternal(DatabaseEntry entry) throws RefreshException { return bytesToObject (entry.getData(), entry.getOffset(), entry.getSize()); } public void objectToEntry(Object object, DatabaseEntry entry) { try { objectToEntryInternal(object, entry); } catch (RefreshException e) { e.refresh(); try { objectToEntryInternal(object, entry); } catch (RefreshException e2) { throw DbCompat.unexpectedException(e2); } } } private void objectToEntryInternal(Object object, DatabaseEntry entry) throws RefreshException { RecordOutput output = new RecordOutput(catalog, rawAccess); output.writeKeyObject(object, keyFormat); TupleBase.outputToEntry(output, entry); } /** * See Store.refresh. */ void refresh(final PersistCatalog newCatalog) { catalog = newCatalog; keyFormat = catalog.getFormat(keyFormat.getClassName()); } }
package org.anarres.ircd; import javax.annotation.OverridingMethodsMustInvokeSuper; /** Abstract superclass of Client and Server. */ public abstract class Target { private Server server; private Link link; private String name; protected Target(Link link, String name) { this.server = null; this.link = link; this.name = name; } protected Target(Server server, String name) { this.server = server; this.link = server.getLink(); this.name = name; } /** * Returns the core daemon object. */ public Daemon getDaemon() { Link l = getLink(); if (l == null) return null; return l.getDaemon(); } /** * Returns the server via which this target is connected. * * This will be null if the target is directly connected. */ protected Server getServer() { return server; } /** * Returns the link by which this target is directly connected. */ protected Link getLink() { return link; } /** * Returns the name of this target. * * This is the {@link Server} name or {@link Client} nick. */ public String getName() { return name; } /** * Sets the name of this target. * * This is called in response to the client NICK command. */ protected void setName(String name) { this.name = name; } protected void send(Message m) { getLink().send(m); } protected void send(Response r, Object... args) { getLink().send(r, args); } protected void forward(Iterable<Link> links, Message m) { // Link _l = getLink(); for (Link l : links) // if (l != _l) l.send(m); } public abstract void helo(); /** Interprets the given message as a command from a locally * connected target. */ public abstract void cmd(Message m); /** Breaks all pointers to this object. */ @OverridingMethodsMustInvokeSuper public void destroy() { server = null; link = null; } }
/* * This Java source file was generated by the Gradle 'init' task. */ package local.mc; public class Library { public boolean someLibraryMethod() { return true; } }
package org.wikipedia.dataclient; /** * The API reported an error in the payload. */ public interface ServiceError { String getTitle(); String getDetails(); }
package org.icepear.echarts.origin.coord; /** * https://github.com/apache/echarts/blob/790687df55a5dbe286e52cf182c0983938efd367/src/coord/axisCommonTypes.ts#L137 */ public interface ValueAxisBaseOption extends NumericAxisBaseOptionCommon { ValueAxisBaseOption setType(String type); ValueAxisBaseOption setAxisLabel(Object axisLabel); ValueAxisBaseOption setScale(Boolean scale); }
// This code is based on: // // com.thoughtworks.selenium.webdriven.commands.WaitForPageToLoad // // in Selenium WebDriver. // // The following copyright is copied from original. // --- // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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 jp.vmi.selenium.selenese.command; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Strings; import jp.vmi.selenium.selenese.Context; import jp.vmi.selenium.selenese.SeleneseCommandErrorException; import jp.vmi.selenium.selenese.result.Error; import jp.vmi.selenium.selenese.result.Result; import jp.vmi.selenium.selenese.utils.Wait; import jp.vmi.selenium.selenese.utils.Wait.StopCondition; import static jp.vmi.selenium.selenese.command.ArgumentType.*; import static jp.vmi.selenium.selenese.result.Success.*; /** * Re-implementation of "waitForPageToLoad". */ public class WaitForPageToLoad extends AbstractCommand { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(WaitForPageToLoad.class); private static final int ARG_TIMEOUT = 0; WaitForPageToLoad(int index, String name, String... args) { super(index, name, args, VALUE); } @Override public boolean mayUpdateScreen() { return false; } @Override protected Result executeImpl(Context context, String... curArgs) { long timeout = 0; // no wait if (curArgs.length > 0) { String arg = curArgs[ARG_TIMEOUT]; if (!Strings.isNullOrEmpty(arg)) { try { timeout = Long.parseLong(arg); } catch (NumberFormatException e) { return new Error(e); } } } return execute(context, timeout); } /** * Wait for page to load. * * @param context context object. * @param timeout timeout (ms). * @return page is loaded within timeout if result value is Success. */ public static Result execute(Context context, long timeout) { if (timeout < 0) return new Error("Illegal timeout parameter: " + timeout); else if (timeout == 0) return SUCCESS; long startTime = System.currentTimeMillis(); WebDriver driver = context.getWrappedDriver(); if (!(driver instanceof JavascriptExecutor)) return new Error("WebDriver is not support JavaScript."); StopCondition condition = isReadyStateSupported(driver) ? checkByReadyState(driver) : checkByBodyLength(driver); if (!Wait.defaultInterval.wait(startTime, timeout, condition)) return new Error("Failed to load page within " + timeout + " ms"); return SUCCESS; } private static boolean isReadyStateSupported(WebDriver driver) { try { return isReadyStateSupportedInternal(driver); } catch (WebDriverException e) { // no operation. } Wait.sleep(250); try { return isReadyStateSupportedInternal(driver); } catch (WebDriverException e) { // no operation. } Wait.sleep(500); try { return isReadyStateSupportedInternal(driver); } catch (WebDriverException e) { throw new SeleneseCommandErrorException("Cannot determine whether page supports ready state."); } } private static boolean isReadyStateSupportedInternal(WebDriver driver) { Boolean result = (Boolean) ((JavascriptExecutor) driver).executeScript("return !!document['readyState'];"); return result != null ? result : false; } private static StopCondition checkByReadyState(final WebDriver driver) { return new StopCondition() { @Override public boolean isSatisfied() { try { Boolean result = (Boolean) ((JavascriptExecutor) driver).executeScript("return document.readyState === 'complete';"); if (result != null && result) return true; } catch (Exception e) { // no operation. } return false; } }; } private static StopCondition checkByBodyLength(final WebDriver driver) { return new StopCondition() { private int prevLen = -1; private long prevTime = 0; @Override public boolean isSatisfied() { WebElement body; try { body = driver.findElement(By.tagName("body")); } catch (NoSuchElementException e) { return false; } String text = body.getText(); if (text == null) return false; int len = text.length(); long now = System.currentTimeMillis(); if (prevLen == len) return now - prevTime > 1000; prevLen = len; prevTime = now; return false; } }; } }
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://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.costandusagereport.model; import java.io.Serializable; import javax.annotation.Generated; /** * Response of DeleteReportDefinition * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cur-2017-01-06/DeleteReportDefinition" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteReportDefinitionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { private String responseMessage; /** * @param responseMessage */ public void setResponseMessage(String responseMessage) { this.responseMessage = responseMessage; } /** * @return */ public String getResponseMessage() { return this.responseMessage; } /** * @param responseMessage * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteReportDefinitionResult withResponseMessage(String responseMessage) { setResponseMessage(responseMessage); 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 (getResponseMessage() != null) sb.append("ResponseMessage: ").append(getResponseMessage()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteReportDefinitionResult == false) return false; DeleteReportDefinitionResult other = (DeleteReportDefinitionResult) obj; if (other.getResponseMessage() == null ^ this.getResponseMessage() == null) return false; if (other.getResponseMessage() != null && other.getResponseMessage().equals(this.getResponseMessage()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getResponseMessage() == null) ? 0 : getResponseMessage().hashCode()); return hashCode; } @Override public DeleteReportDefinitionResult clone() { try { return (DeleteReportDefinitionResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package org.decomposer.math; import org.decomposer.math.vector.MapVector; public interface EigenUpdater { void update(MapVector pseudoEigen, MapVector trainingVector, TrainingState currentState); }
/** * Copyright 2011-2015 John Ericksen * * 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.androidtransfuse.gen.variableBuilder; import org.androidtransfuse.adapter.ASTBase; import org.androidtransfuse.adapter.ASTType; import org.androidtransfuse.analysis.AnalysisContext; import org.androidtransfuse.analysis.Analyzer; import org.androidtransfuse.model.InjectionNode; import org.androidtransfuse.model.InjectionSignature; import javax.inject.Inject; import javax.inject.Provider; /** * @author John Ericksen */ public class VariableASTImplementationInjectionNodeBuilder implements InjectionNodeBuilder { private final Analyzer analyzer; private final ASTType implType; private final Provider<VariableInjectionBuilder> variableInjectionBuilderProvider; @Inject public VariableASTImplementationInjectionNodeBuilder(/*@Assisted*/ ASTType implType, Analyzer analyzer, Provider<VariableInjectionBuilder> variableInjectionBuilderProvider) { this.analyzer = analyzer; this.implType = implType; this.variableInjectionBuilderProvider = variableInjectionBuilderProvider; } @Override public InjectionNode buildInjectionNode(ASTBase target, InjectionSignature signature, AnalysisContext context) { //InjectionNode injectionNode = analyzer.analyze(signature, implType, context); InjectionSignature implSignature = new InjectionSignature(implType); InjectionNode injectionNode = analyzer.analyze(signature, implSignature, context); //default variable builder injectionNode.addAspect(VariableBuilder.class, variableInjectionBuilderProvider.get()); return injectionNode; } }
package threading; /** * Deadlock describes a situation where two or more threads are blocked * forever, waiting for each other. Deadlock occurs when multiple threads * need the same locks but obtain them in different order. A Java * multithreaded program may suffer from the deadlock condition because * the synchronized keyword causes the executing thread to block while * waiting for the lock, or monitor, associated with the specified object. * */ public class Deadlock { public static void main(String[] args) { AppDeadlock app = new AppDeadlock(); app.deadlock(); //app.noDeadlock(); } } class AppDeadlock { Object lock1 = new Object(); Object lock2 = new Object(); public void deadlock() { Thread t1 = new Thread(new Runnable() { public void run() { synchronized(lock1) { System.out.println("Thread1 holds lock1"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread1 waiting for lock2"); synchronized(lock2) { System.out.println("Thread1 holds lock1 and lock2"); } } } }); Thread t2 = new Thread(new Runnable() { public void run() { synchronized(lock2) { System.out.println("Thread2 holds lock2"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread2 waiting for lock1"); synchronized(lock1) { System.out.println("Thread2 holds lock2 and lock1"); } } } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void noDeadlock() { Thread t1 = new Thread(new Runnable() { public void run() { synchronized(lock1) { System.out.println("Thread1 holds lock1"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread1 waiting for lock2"); synchronized(lock2) { System.out.println("Thread1 holds lock1 and lock2"); } } } }); Thread t2 = new Thread(new Runnable() { public void run() { synchronized(lock1) { System.out.println("Thread2 holds lock1"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread2 waiting for lock2"); synchronized(lock2) { System.out.println("Thread2 holds lock2 and lock1"); } } } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
/* * 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.solr.cloud.hdfs; import java.io.IOException; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.lucene.util.LuceneTestCase.Slow; import org.apache.lucene.util.QuickPatchThreadsFilter; import org.apache.solr.SolrIgnoredThreadsFilter; import org.apache.solr.cloud.BasicDistributedZkTest; import org.apache.solr.util.BadHdfsThreadsFilter; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; @Slow @ThreadLeakFilters(defaultFilters = true, filters = { SolrIgnoredThreadsFilter.class, QuickPatchThreadsFilter.class, BadHdfsThreadsFilter.class // hdfs currently leaks thread(s) }) public class HdfsNNFailoverTest extends BasicDistributedZkTest { private static final String COLLECTION = "collection"; private static MiniDFSCluster dfsCluster; @BeforeClass public static void setupClass() throws Exception { dfsCluster = HdfsTestUtil.setupClass(createTempDir().toFile().getAbsolutePath(), false, true); } @AfterClass public static void teardownClass() throws Exception { try { HdfsTestUtil.teardownClass(dfsCluster); } finally { dfsCluster = null; } } @Override protected String getDataDir(String dataDir) throws IOException { return HdfsTestUtil.getDataDir(dfsCluster, dataDir); } public HdfsNNFailoverTest() { super(); sliceCount = 1; fixShardCount(TEST_NIGHTLY ? 7 : random().nextInt(2) + 1); } protected String getSolrXml() { return "solr.xml"; } @Test public void test() throws Exception { createCollection(COLLECTION, "conf1", 1, 1); waitForRecoveriesToFinish(COLLECTION, false); // TODO: SOLR-7360 Enable HDFS NameNode failover testing. // dfsCluster.transitionToStandby(0); // dfsCluster.transitionToActive(1); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Aula01_Aquecimento; import java.util.Scanner; /** * * @author Marcos */ public class _1158_Soma_De_Impares_Consecutivos { public static void main(String[] args) { Scanner in = new Scanner(System.in); int casos = in.nextInt(); int x, y; for (int i = 0; i < casos; i++) { x = in.nextInt(); y = in.nextInt(); if (x % 2 == 0) { x++; } System.out.println((x * y) + (y*(y-1))); } in.close(); } }
package org.ojalgo.matrix.jama; /** Eigenvalues and eigenvectors of a real matrix. <P> If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is diagonal and the eigenvector matrix V is orthogonal. I.e. A = V.times(D.times(V.transpose())) and V.times(V.transpose()) equals the identity matrix. <P> If A is not symmetric, then the eigenvalue matrix D is block diagonal with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The columns of V represent the eigenvectors in the sense that A*V = V*D, i.e. A.times(V) equals V.times(D). The matrix V may be badly conditioned, or even singular, so the validity of the equation A = V*D*inverse(V) depends upon V.cond(). **/ class EigenvalueDecomposition implements java.io.Serializable { /* ------------------------ Class variables * ------------------------ */ /** Row and column dimension (square matrix). @serial matrix dimension. */ private final int n; /** Symmetry flag. @serial internal symmetry flag. */ private boolean issymmetric; /** Arrays for internal storage of eigenvalues. @serial internal storage of eigenvalues. */ private final double[] d, e; /** Array for internal storage of eigenvectors. @serial internal storage of eigenvectors. */ private final double[][] V; /** Array for internal storage of nonsymmetric Hessenberg form. @serial internal storage of nonsymmetric Hessenberg form. */ private double[][] H; /** Working storage for nonsymmetric algorithm. @serial working storage for nonsymmetric algorithm. */ private double[] ort; /* ------------------------ Private Methods * ------------------------ */ // Symmetric Householder reduction to tridiagonal form. private transient double cdivr, cdivi; // Symmetric tridiagonal QL algorithm. private static final long serialVersionUID = 1; // Nonsymmetric reduction to Hessenberg form. /** Check for symmetry, then construct the eigenvalue decomposition Structure to access D and V. @param Arg Square matrix */ public EigenvalueDecomposition(final Matrix Arg) { final double[][] A = Arg.getArray(); n = Arg.getColumnDimension(); V = new double[n][n]; d = new double[n]; e = new double[n]; issymmetric = true; for (int j = 0; (j < n) & issymmetric; j++) { for (int i = 0; (i < n) & issymmetric; i++) { issymmetric = (A[i][j] == A[j][i]); } } if (issymmetric) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i][j] = A[i][j]; } } // Tridiagonalize. this.tred2(); // Diagonalize. this.tql2(); } else { H = new double[n][n]; ort = new double[n]; for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { H[i][j] = A[i][j]; } } // Reduce to Hessenberg form. this.orthes(); // Reduce Hessenberg to real Schur form. this.hqr2(); } } public EigenvalueDecomposition(final Matrix Arg, final boolean issymmetric) { final double[][] A = Arg.getArray(); n = Arg.getColumnDimension(); V = new double[n][n]; d = new double[n]; e = new double[n]; if (issymmetric) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i][j] = A[i][j]; } } // Tridiagonalize. this.tred2(); // Diagonalize. this.tql2(); } else { H = new double[n][n]; ort = new double[n]; for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { H[i][j] = A[i][j]; } } // Reduce to Hessenberg form. this.orthes(); // Reduce Hessenberg to real Schur form. this.hqr2(); } } // Complex scalar division. /** Return the block diagonal eigenvalue matrix @return D */ public Matrix getD() { final Matrix X = new Matrix(n, n); final double[][] D = X.getArray(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { D[i][j] = 0.0; } D[i][i] = d[i]; if (e[i] > 0) { D[i][i + 1] = e[i]; } else if (e[i] < 0) { D[i][i - 1] = e[i]; } } return X; } /** Return the imaginary parts of the eigenvalues @return imag(diag(D)) */ public double[] getImagEigenvalues() { return e; } // Nonsymmetric reduction from Hessenberg to real Schur form. /** Return the real parts of the eigenvalues @return real(diag(D)) */ public double[] getRealEigenvalues() { return d; } /* ------------------------ Constructor * ------------------------ */ /** Return the eigenvector matrix @return V */ public Matrix getV() { return new Matrix(V, n, n); } /* ------------------------ Public Methods * ------------------------ */ private void cdiv(final double xr, final double xi, final double yr, final double yi) { double r, d; if (Math.abs(yr) > Math.abs(yi)) { r = yi / yr; d = yr + (r * yi); cdivr = (xr + (r * xi)) / d; cdivi = (xi - (r * xr)) / d; } else { r = yr / yi; d = yi + (r * yr); cdivr = ((r * xr) + xi) / d; cdivi = ((r * xi) - xr) / d; } } private void hqr2() { // This is derived from the Algol procedure hqr2, // by Martin and Wilkinson, Handbook for Auto. Comp., // Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. // Initialize final int nn = n; int n = nn - 1; final int low = 0; final int high = nn - 1; final double eps = Math.pow(2.0, -52.0); double exshift = 0.0; double p = 0, q = 0, r = 0, s = 0, z = 0, t, w, x, y; // Store roots isolated by balanc and compute matrix norm double norm = 0.0; for (int i = 0; i < nn; i++) { if ((i < low) | (i > high)) { d[i] = H[i][i]; e[i] = 0.0; } for (int j = Math.max(i - 1, 0); j < nn; j++) { norm = norm + Math.abs(H[i][j]); } } // Outer loop over eigenvalue index int iter = 0; while (n >= low) { // Look for single small sub-diagonal element int l = n; while (l > low) { s = Math.abs(H[l - 1][l - 1]) + Math.abs(H[l][l]); if (s == 0.0) { s = norm; } if (Math.abs(H[l][l - 1]) < (eps * s)) { break; } l--; } // Check for convergence // One root found if (l == n) { H[n][n] = H[n][n] + exshift; d[n] = H[n][n]; e[n] = 0.0; n--; iter = 0; // Two roots found } else if (l == (n - 1)) { w = H[n][n - 1] * H[n - 1][n]; p = (H[n - 1][n - 1] - H[n][n]) / 2.0; q = (p * p) + w; z = Math.sqrt(Math.abs(q)); H[n][n] = H[n][n] + exshift; H[n - 1][n - 1] = H[n - 1][n - 1] + exshift; x = H[n][n]; // Real pair if (q >= 0) { if (p >= 0) { z = p + z; } else { z = p - z; } d[n - 1] = x + z; d[n] = d[n - 1]; if (z != 0.0) { d[n] = x - (w / z); } e[n - 1] = 0.0; e[n] = 0.0; x = H[n][n - 1]; s = Math.abs(x) + Math.abs(z); p = x / s; q = z / s; r = Math.sqrt((p * p) + (q * q)); p = p / r; q = q / r; // Row modification for (int j = n - 1; j < nn; j++) { z = H[n - 1][j]; H[n - 1][j] = (q * z) + (p * H[n][j]); H[n][j] = (q * H[n][j]) - (p * z); } // Column modification for (int i = 0; i <= n; i++) { z = H[i][n - 1]; H[i][n - 1] = (q * z) + (p * H[i][n]); H[i][n] = (q * H[i][n]) - (p * z); } // Accumulate transformations for (int i = low; i <= high; i++) { z = V[i][n - 1]; V[i][n - 1] = (q * z) + (p * V[i][n]); V[i][n] = (q * V[i][n]) - (p * z); } // Complex pair } else { d[n - 1] = x + p; d[n] = x + p; e[n - 1] = z; e[n] = -z; } n = n - 2; iter = 0; // No convergence yet } else { // Form shift x = H[n][n]; y = 0.0; w = 0.0; if (l < n) { y = H[n - 1][n - 1]; w = H[n][n - 1] * H[n - 1][n]; } // Wilkinson's original ad hoc shift if (iter == 10) { exshift += x; for (int i = low; i <= n; i++) { H[i][i] -= x; } s = Math.abs(H[n][n - 1]) + Math.abs(H[n - 1][n - 2]); x = y = 0.75 * s; w = -0.4375 * s * s; } // MATLAB's new ad hoc shift if (iter == 30) { s = (y - x) / 2.0; s = (s * s) + w; if (s > 0) { s = Math.sqrt(s); if (y < x) { s = -s; } s = x - (w / (((y - x) / 2.0) + s)); for (int i = low; i <= n; i++) { H[i][i] -= s; } exshift += s; x = y = w = 0.964; } } iter = iter + 1; // (Could check iteration count here.) // Look for two consecutive small sub-diagonal elements int m = n - 2; while (m >= l) { z = H[m][m]; r = x - z; s = y - z; p = (((r * s) - w) / H[m + 1][m]) + H[m][m + 1]; q = H[m + 1][m + 1] - z - r - s; r = H[m + 2][m + 1]; s = Math.abs(p) + Math.abs(q) + Math.abs(r); p = p / s; q = q / s; r = r / s; if (m == l) { break; } if ((Math.abs(H[m][m - 1]) * (Math.abs(q) + Math.abs(r))) < (eps * (Math.abs(p) * (Math.abs(H[m - 1][m - 1]) + Math.abs(z) + Math .abs(H[m + 1][m + 1]))))) { break; } m--; } for (int i = m + 2; i <= n; i++) { H[i][i - 2] = 0.0; if (i > (m + 2)) { H[i][i - 3] = 0.0; } } // Double QR step involving rows l:n and columns m:n for (int k = m; k <= (n - 1); k++) { final boolean notlast = (k != (n - 1)); if (k != m) { p = H[k][k - 1]; q = H[k + 1][k - 1]; r = (notlast ? H[k + 2][k - 1] : 0.0); x = Math.abs(p) + Math.abs(q) + Math.abs(r); if (x == 0.0) { continue; } p = p / x; q = q / x; r = r / x; } s = Math.sqrt((p * p) + (q * q) + (r * r)); if (p < 0) { s = -s; } if (s != 0) { if (k != m) { H[k][k - 1] = -s * x; } else if (l != m) { H[k][k - 1] = -H[k][k - 1]; } p = p + s; x = p / s; y = q / s; z = r / s; q = q / p; r = r / p; // Row modification for (int j = k; j < nn; j++) { p = H[k][j] + (q * H[k + 1][j]); if (notlast) { p = p + (r * H[k + 2][j]); H[k + 2][j] = H[k + 2][j] - (p * z); } H[k][j] = H[k][j] - (p * x); H[k + 1][j] = H[k + 1][j] - (p * y); } // Column modification for (int i = 0; i <= Math.min(n, k + 3); i++) { p = (x * H[i][k]) + (y * H[i][k + 1]); if (notlast) { p = p + (z * H[i][k + 2]); H[i][k + 2] = H[i][k + 2] - (p * r); } H[i][k] = H[i][k] - p; H[i][k + 1] = H[i][k + 1] - (p * q); } // Accumulate transformations for (int i = low; i <= high; i++) { p = (x * V[i][k]) + (y * V[i][k + 1]); if (notlast) { p = p + (z * V[i][k + 2]); V[i][k + 2] = V[i][k + 2] - (p * r); } V[i][k] = V[i][k] - p; V[i][k + 1] = V[i][k + 1] - (p * q); } } // (s != 0) } // k loop } // check convergence } // while (n >= low) // Backsubstitute to find vectors of upper triangular form if (norm == 0.0) { return; } for (n = nn - 1; n >= 0; n--) { p = d[n]; q = e[n]; // Real vector if (q == 0) { int l = n; H[n][n] = 1.0; for (int i = n - 1; i >= 0; i--) { w = H[i][i] - p; r = 0.0; for (int j = l; j <= n; j++) { r = r + (H[i][j] * H[j][n]); } if (e[i] < 0.0) { z = w; s = r; } else { l = i; if (e[i] == 0.0) { if (w != 0.0) { H[i][n] = -r / w; } else { H[i][n] = -r / (eps * norm); } // Solve real equations } else { x = H[i][i + 1]; y = H[i + 1][i]; q = ((d[i] - p) * (d[i] - p)) + (e[i] * e[i]); t = ((x * s) - (z * r)) / q; H[i][n] = t; if (Math.abs(x) > Math.abs(z)) { H[i + 1][n] = (-r - (w * t)) / x; } else { H[i + 1][n] = (-s - (y * t)) / z; } } // Overflow control t = Math.abs(H[i][n]); if (((eps * t) * t) > 1) { for (int j = i; j <= n; j++) { H[j][n] = H[j][n] / t; } } } } // Complex vector } else if (q < 0) { int l = n - 1; // Last vector component imaginary so matrix is triangular if (Math.abs(H[n][n - 1]) > Math.abs(H[n - 1][n])) { H[n - 1][n - 1] = q / H[n][n - 1]; H[n - 1][n] = -(H[n][n] - p) / H[n][n - 1]; } else { this.cdiv(0.0, -H[n - 1][n], H[n - 1][n - 1] - p, q); H[n - 1][n - 1] = cdivr; H[n - 1][n] = cdivi; } H[n][n - 1] = 0.0; H[n][n] = 1.0; for (int i = n - 2; i >= 0; i--) { double ra, sa, vr, vi; ra = 0.0; sa = 0.0; for (int j = l; j <= n; j++) { ra = ra + (H[i][j] * H[j][n - 1]); sa = sa + (H[i][j] * H[j][n]); } w = H[i][i] - p; if (e[i] < 0.0) { z = w; r = ra; s = sa; } else { l = i; if (e[i] == 0) { this.cdiv(-ra, -sa, w, q); H[i][n - 1] = cdivr; H[i][n] = cdivi; } else { // Solve complex equations x = H[i][i + 1]; y = H[i + 1][i]; vr = (((d[i] - p) * (d[i] - p)) + (e[i] * e[i])) - (q * q); vi = (d[i] - p) * 2.0 * q; if ((vr == 0.0) & (vi == 0.0)) { vr = eps * norm * (Math.abs(w) + Math.abs(q) + Math.abs(x) + Math.abs(y) + Math.abs(z)); } this.cdiv(((x * r) - (z * ra)) + (q * sa), (x * s) - (z * sa) - (q * ra), vr, vi); H[i][n - 1] = cdivr; H[i][n] = cdivi; if (Math.abs(x) > (Math.abs(z) + Math.abs(q))) { H[i + 1][n - 1] = ((-ra - (w * H[i][n - 1])) + (q * H[i][n])) / x; H[i + 1][n] = (-sa - (w * H[i][n]) - (q * H[i][n - 1])) / x; } else { this.cdiv(-r - (y * H[i][n - 1]), -s - (y * H[i][n]), z, q); H[i + 1][n - 1] = cdivr; H[i + 1][n] = cdivi; } } // Overflow control t = Math.max(Math.abs(H[i][n - 1]), Math.abs(H[i][n])); if (((eps * t) * t) > 1) { for (int j = i; j <= n; j++) { H[j][n - 1] = H[j][n - 1] / t; H[j][n] = H[j][n] / t; } } } } } } // Vectors of isolated roots for (int i = 0; i < nn; i++) { if ((i < low) | (i > high)) { for (int j = i; j < nn; j++) { V[i][j] = H[i][j]; } } } // Back transformation to get eigenvectors of original matrix for (int j = nn - 1; j >= low; j--) { for (int i = low; i <= high; i++) { z = 0.0; for (int k = low; k <= Math.min(j, high); k++) { z = z + (V[i][k] * H[k][j]); } V[i][j] = z; } } } private void orthes() { // This is derived from the Algol procedures orthes and ortran, // by Martin and Wilkinson, Handbook for Auto. Comp., // Vol.ii-Linear Algebra, and the corresponding // Fortran subroutines in EISPACK. final int low = 0; final int high = n - 1; for (int m = low + 1; m <= (high - 1); m++) { // Scale column. double scale = 0.0; for (int i = m; i <= high; i++) { scale = scale + Math.abs(H[i][m - 1]); } if (scale != 0.0) { // Compute Householder transformation. double h = 0.0; for (int i = high; i >= m; i--) { ort[i] = H[i][m - 1] / scale; h += ort[i] * ort[i]; } double g = Math.sqrt(h); if (ort[m] > 0) { g = -g; } h = h - (ort[m] * g); ort[m] = ort[m] - g; // Apply Householder similarity transformation // H = (I-u*u'/h)*H*(I-u*u')/h) for (int j = m; j < n; j++) { double f = 0.0; for (int i = high; i >= m; i--) { f += ort[i] * H[i][j]; } f = f / h; for (int i = m; i <= high; i++) { H[i][j] -= f * ort[i]; } } for (int i = 0; i <= high; i++) { double f = 0.0; for (int j = high; j >= m; j--) { f += ort[j] * H[i][j]; } f = f / h; for (int j = m; j <= high; j++) { H[i][j] -= f * ort[j]; } } ort[m] = scale * ort[m]; H[m][m - 1] = scale * g; } } // Accumulate transformations (Algol's ortran). for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i][j] = (i == j ? 1.0 : 0.0); } } for (int m = high - 1; m >= (low + 1); m--) { if (H[m][m - 1] != 0.0) { for (int i = m + 1; i <= high; i++) { ort[i] = H[i][m - 1]; } for (int j = m; j <= high; j++) { double g = 0.0; for (int i = m; i <= high; i++) { g += ort[i] * V[i][j]; } // Double division avoids possible underflow g = (g / ort[m]) / H[m][m - 1]; for (int i = m; i <= high; i++) { V[i][j] += g * ort[i]; } } } } } private void tql2() { // This is derived from the Algol procedures tql2, by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. for (int i = 1; i < n; i++) { e[i - 1] = e[i]; } e[n - 1] = 0.0; double f = 0.0; double tst1 = 0.0; final double eps = Math.pow(2.0, -52.0); for (int l = 0; l < n; l++) { // Find small subdiagonal element tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l])); int m = l; while (m < n) { if (Math.abs(e[m]) <= (eps * tst1)) { break; } m++; } // If m == l, d[l] is an eigenvalue, // otherwise, iterate. if (m > l) { int iter = 0; do { iter = iter + 1; // (Could check iteration count here.) // Compute implicit shift double g = d[l]; double p = (d[l + 1] - g) / (2.0 * e[l]); double r = Maths.hypot(p, 1.0); if (p < 0) { r = -r; } d[l] = e[l] / (p + r); d[l + 1] = e[l] * (p + r); final double dl1 = d[l + 1]; double h = g - d[l]; for (int i = l + 2; i < n; i++) { d[i] -= h; } f = f + h; // Implicit QL transformation. p = d[m]; double c = 1.0; double c2 = c; double c3 = c; final double el1 = e[l + 1]; double s = 0.0; double s2 = 0.0; for (int i = m - 1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; r = Maths.hypot(p, e[i]); e[i + 1] = s * r; s = e[i] / r; c = p / r; p = (c * d[i]) - (s * g); d[i + 1] = h + (s * ((c * g) + (s * d[i]))); // Accumulate transformation. for (int k = 0; k < n; k++) { h = V[k][i + 1]; V[k][i + 1] = (s * V[k][i]) + (c * h); V[k][i] = (c * V[k][i]) - (s * h); } } p = (-s * s2 * c3 * el1 * e[l]) / dl1; e[l] = s * p; d[l] = c * p; // Check for convergence. } while (Math.abs(e[l]) > (eps * tst1)); } d[l] = d[l] + f; e[l] = 0.0; } // Sort eigenvalues and corresponding vectors. for (int i = 0; i < (n - 1); i++) { int k = i; double p = d[i]; for (int j = i + 1; j < n; j++) { if (d[j] < p) { k = j; p = d[j]; } } if (k != i) { d[k] = d[i]; d[i] = p; for (int j = 0; j < n; j++) { p = V[j][i]; V[j][i] = V[j][k]; V[j][k] = p; } } } } private void tred2() { // This is derived from the Algol procedures tred2 by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding // Fortran subroutine in EISPACK. for (int j = 0; j < n; j++) { d[j] = V[n - 1][j]; } // Householder reduction to tridiagonal form. for (int i = n - 1; i > 0; i--) { // Scale to avoid under/overflow. double scale = 0.0; double h = 0.0; for (int k = 0; k < i; k++) { scale = scale + Math.abs(d[k]); } if (scale == 0.0) { e[i] = d[i - 1]; for (int j = 0; j < i; j++) { d[j] = V[i - 1][j]; V[i][j] = 0.0; V[j][i] = 0.0; } } else { // Generate Householder vector. for (int k = 0; k < i; k++) { d[k] /= scale; h += d[k] * d[k]; } double f = d[i - 1]; double g = Math.sqrt(h); if (f > 0) { g = -g; } e[i] = scale * g; h = h - (f * g); d[i - 1] = f - g; for (int j = 0; j < i; j++) { e[j] = 0.0; } // Apply similarity transformation to remaining columns. for (int j = 0; j < i; j++) { f = d[j]; V[j][i] = f; g = e[j] + (V[j][j] * f); for (int k = j + 1; k <= (i - 1); k++) { g += V[k][j] * d[k]; e[k] += V[k][j] * f; } e[j] = g; } f = 0.0; for (int j = 0; j < i; j++) { e[j] /= h; f += e[j] * d[j]; } final double hh = f / (h + h); for (int j = 0; j < i; j++) { e[j] -= hh * d[j]; } for (int j = 0; j < i; j++) { f = d[j]; g = e[j]; for (int k = j; k <= (i - 1); k++) { V[k][j] -= ((f * e[k]) + (g * d[k])); } d[j] = V[i - 1][j]; V[i][j] = 0.0; } } d[i] = h; } // Accumulate transformations. for (int i = 0; i < (n - 1); i++) { V[n - 1][i] = V[i][i]; V[i][i] = 1.0; final double h = d[i + 1]; if (h != 0.0) { for (int k = 0; k <= i; k++) { d[k] = V[k][i + 1] / h; } for (int j = 0; j <= i; j++) { double g = 0.0; for (int k = 0; k <= i; k++) { g += V[k][i + 1] * V[k][j]; } for (int k = 0; k <= i; k++) { V[k][j] -= g * d[k]; } } } for (int k = 0; k <= i; k++) { V[k][i + 1] = 0.0; } } for (int j = 0; j < n; j++) { d[j] = V[n - 1][j]; V[n - 1][j] = 0.0; } V[n - 1][n - 1] = 1.0; e[0] = 0.0; } boolean isSymmetric() { return issymmetric; } }
package yaes; import java.io.FileOutputStream; import java.util.Properties; public class Version { public static final String PROJECTNAME = "YAES: Yet Another Extensible Simulator"; /** * Description of the Field */ public static String VERSION_DATE = "April 12, 2016"; /** * Description of the Field */ public static int VERSION_MAJOR = 0; /** * Description of the Field */ public static int VERSION_MICRO = 80; /** * Description of the Field */ public static int VERSION_MINOR = 9; // Use: Development, Alpha, Beta, Release /** * Description of the Field */ public static String VERSION_STATUS = "Development"; /** * Creates a property file for the use of the ant generator * * @param args * The command line arguments */ public static void main(String[] args) { try { System.out.println("Created the version property:" + Version.versionNumberString()); final Properties property = new Properties(); property.setProperty("version", Version.versionNumberString()); final FileOutputStream fos = new FileOutputStream( "version.properties"); property.store(fos, "Yaes"); fos.close(); } catch (final Exception ex) { ex.printStackTrace(); } } /** * Description of the Method * * @return Description of the Return Value */ public static int versionNumber() { return 10000 * Version.VERSION_MAJOR + 100 * Version.VERSION_MINOR + Version.VERSION_MICRO; } /** * Description of the Method * * @return Description of the Return Value */ public static String versionNumberString() { return "" + Version.VERSION_MAJOR + "." + Version.VERSION_MINOR + "." + Version.VERSION_MICRO; } /** * Description of the Method * * @return Description of the Return Value */ public static String versionString() { return Version.PROJECTNAME + " " + Version.VERSION_MAJOR + "." + Version.VERSION_MINOR + "." + Version.VERSION_MICRO + " (" + Version.VERSION_DATE + ")"; } public static String versionStringNoDate() { return Version.PROJECTNAME + " " + Version.VERSION_MAJOR + "." + Version.VERSION_MINOR + "." + Version.VERSION_MICRO; } }
package io.github.powerinside.syncplay; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteConstraintException; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import de.cketti.library.changelog.ChangeLog; import io.github.powerinside.syncplay.database.ServerListContract; import io.github.powerinside.syncplay.database.ServerListHelper; public class MainActivity extends AppCompatActivity { private static final String TAG = "SyncPlay"; private static final boolean DEVELOPER_MODE = false; private static final int REQUEST_INVITE = 1; private static final int READ_EXTERNAL_STORAGE_FOR_MEDIA = 2; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ ChangeLog cl; private int REQUEST_TAKE_GALLERY_VIDEO = 1; private Intent tovideoplayer; private Intent pickerprovider; @Override protected void onResume() { super.onResume(); } @Override protected void onCreate(Bundle savedInstanceState) { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cl = new ChangeLog(this); if (cl.isFirstRun()) { cl.getFullLogDialog().show(); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final ServerListHelper serverListHelper = new ServerListHelper(this); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); ListView listView = (ListView) findViewById(R.id.listView); final SQLiteDatabase db_read = serverListHelper.getReadableDatabase(); final String[] projection = { ServerListContract.ServerEntry._ID, ServerListContract.ServerEntry.COLUMN_NAME_NAME }; final Cursor cursor; cursor = db_read.query(ServerListContract.ServerEntry.TABLE_NAME, projection, null, null, null, null, null ); String[] from = { ServerListContract.ServerEntry.COLUMN_NAME_NAME }; int[] to = { R.id.textView }; final SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.simple_list, cursor, from, to, 0); assert listView != null; listView.setAdapter(mAdapter); listView.setEmptyView(findViewById(R.id.emptyTextView)); listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { TextView tv = (TextView) view.findViewById(R.id.textView); final String[] label = {tv.getText().toString()}; final SQLiteDatabase db_w = serverListHelper.getWritableDatabase(); final Cursor cursor_mod = db_w.query(ServerListContract.ServerEntry.TABLE_NAME, null, ServerListContract.ServerEntry.COLUMN_NAME_NAME + " = ?", label, null, null, null); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); final String[] oldname = {null}; final AlertDialog alertDialog = builder.setTitle(R.string.modify_entry_title).setPositiveButton(R.string.save_button, null).setNegativeButton(R.string.delete_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // delete SQLiteDatabase db = serverListHelper.getWritableDatabase(); String[] whereargs = {oldname[0]}; try { db.delete(ServerListContract.ServerEntry.TABLE_NAME, ServerListContract.ServerEntry.COLUMN_NAME_NAME + " = ?" , whereargs); Cursor cursor; cursor = db_read.query(ServerListContract.ServerEntry.TABLE_NAME, projection, null, null, null, null, null ); mAdapter.changeCursor(cursor); mAdapter.notifyDataSetChanged(); } catch (SQLException e) { e.printStackTrace(); } } }).setView(R.layout.fabdialog_add).create(); alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { final EditText namefield = (EditText) alertDialog.findViewById(R.id.name); final EditText serverfield = (EditText) alertDialog.findViewById(R.id.server); final EditText roomfield = (EditText) alertDialog.findViewById(R.id.defaultRoom); final EditText passwdfield = (EditText) alertDialog.findViewById(R.id.password); final EditText userfield = (EditText) alertDialog.findViewById(R.id.username); if (cursor_mod.moveToNext()) { oldname[0] = cursor_mod.getString(1); namefield.setText(cursor_mod.getString(1)); serverfield.setText(cursor_mod.getString(2)); passwdfield.setText(cursor_mod.getString(3)); roomfield.setText(cursor_mod.getString(4)); userfield.setText(cursor_mod.getString(5)); } Button b = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE); final String finalOldname = oldname[0]; b.setOnClickListener(new View.OnClickListener() { //target api kitkat? @Override public void onClick(View v) { if (namefield.getText().length() > 0 && serverfield.getText().length() > 0 && roomfield.getText().length() > 0 && userfield.getText().length() > 0) { ContentValues cv = new ContentValues(); cv.put(ServerListContract.ServerEntry.COLUMN_NAME_NAME, namefield.getText().toString()); cv.put(ServerListContract.ServerEntry.COLUMN_NAME_ADDRESS, serverfield.getText().toString()); cv.put(ServerListContract.ServerEntry.COLUMN_NAME_DEFAULT_ROOM, roomfield.getText().toString()); cv.put(ServerListContract.ServerEntry.COLUMN_NAME_PASSWORD, passwdfield.getText().toString()); cv.put(ServerListContract.ServerEntry.COLUMN_NAME_USERNAME, userfield.getText().toString()); try { db_w.update(ServerListContract.ServerEntry.TABLE_NAME, cv, ServerListContract.ServerEntry.COLUMN_NAME_NAME + " = ?", new String[]{finalOldname}); Cursor cursorold; cursorold = db_read.query(ServerListContract.ServerEntry.TABLE_NAME, projection, null, null, null, null, null ); mAdapter.changeCursor(cursorold); mAdapter.notifyDataSetChanged(); alertDialog.dismiss(); } catch (SQLiteConstraintException e) { // Not unique! Toast.makeText(getApplicationContext(), "Error! Label " + namefield.getText() + " already exists! Use a different name there.", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), R.string.fields_error, Toast.LENGTH_SHORT).show(); } } }); } }); alertDialog.show(); return true; } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tv = (TextView) view.findViewById(R.id.textView); String label = tv.getText().toString(); Cursor itemdetails = db_read.query(ServerListContract.ServerEntry.TABLE_NAME, null, ServerListContract.ServerEntry.COLUMN_NAME_NAME + " = ?", new String[]{label}, null, null, null); if (itemdetails.moveToNext()) { String server = itemdetails.getString(2); String passwd = itemdetails.getString(3); String room = itemdetails.getString(4); String username = itemdetails.getString(5); pickerprovider = new Intent() .setType("video/*, audio/*") .setAction(Intent.ACTION_GET_CONTENT); tovideoplayer = new Intent() .putExtra("server", server) .putExtra("passwd", passwd) .putExtra("room", room) .putExtra("username", username); startActivity(new Intent(getApplicationContext(), videoPlayer.class) .putExtras(tovideoplayer)); } } }); assert fab != null; // TODO: Suggest and autofill username fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this).setView(R.layout.fabdialog_add); final AlertDialog mdialog = builder.setTitle(R.string.add_server_dialog) .setPositiveButton(R.string.save_button, null).setNegativeButton(R.string.cancel_button, null).create(); mdialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button b = mdialog.getButton(AlertDialog.BUTTON_POSITIVE); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ContentValues values = new ContentValues(); SQLiteDatabase db = serverListHelper.getWritableDatabase(); EditText namefield = (EditText) mdialog.findViewById(R.id.name); EditText serverfield = (EditText) mdialog.findViewById(R.id.server); EditText roomfield = (EditText) mdialog.findViewById(R.id.defaultRoom); EditText passwdfield = (EditText) mdialog.findViewById(R.id.password); EditText userfield = (EditText) mdialog.findViewById(R.id.username); values.put(ServerListContract.ServerEntry.COLUMN_NAME_ADDRESS, serverfield.getText().toString()); values.put(ServerListContract.ServerEntry.COLUMN_NAME_NAME, namefield.getText().toString()); values.put(ServerListContract.ServerEntry.COLUMN_NAME_DEFAULT_ROOM, roomfield.getText().toString()); values.put(ServerListContract.ServerEntry.COLUMN_NAME_PASSWORD, passwdfield.getText().toString()); values.put(ServerListContract.ServerEntry.COLUMN_NAME_USERNAME, userfield.getText().toString()); if (namefield.getText().length() > 0 && serverfield.getText().length() > 0 && roomfield.getText().length() > 0 && userfield.getText().length() > 0) { try { // TODO: Validate mandatory fields properly db.insertOrThrow(ServerListContract.ServerEntry.TABLE_NAME, null, values); Cursor cursor; cursor = db_read.query(ServerListContract.ServerEntry.TABLE_NAME, projection, null, null, null, null, null ); mAdapter.changeCursor(cursor); mAdapter.notifyDataSetChanged(); mdialog.dismiss(); } catch (SQLException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), R.string.insertOrThrow, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getApplicationContext(), getString(R.string.fields_error), Toast.LENGTH_SHORT).show(); } } }); } }); if (!mdialog.isShowing()) mdialog.show(); Snackbar.make(view, "", Snackbar.LENGTH_LONG) .setAction(R.string.add_server_dialog, new View.OnClickListener() { @Override public void onClick(View v) { } }); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode) { case READ_EXTERNAL_STORAGE_FOR_MEDIA: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startActivityForResult(Intent.createChooser(pickerprovider, "Pick a video"), REQUEST_TAKE_GALLERY_VIDEO); } } } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.changelog) { if (!cl.getFullLogDialog().isShowing()) cl.getFullLogDialog().show(); } if (id == R.id.about) { startActivity(new Intent(this, AboutActivity.class)); } if (id == R.id.privacyPolicy) { startActivity(new Intent(this, privacyPolicy.class)); } return super.onOptionsItemSelected(item); } @Override public void onStart() { super.onStart(); } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onPause() { super.onPause(); } @Override public void onStop() { super.onStop(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == 1) { // Make sure the request was successful if (resultCode == RESULT_OK) { Uri selectedFile = data.getData(); if (selectedFile != null) { startActivity(new Intent(this, videoPlayer.class) .setData(selectedFile) .putExtras(tovideoplayer)); } else if (resultCode != REQUEST_INVITE) { Toast.makeText(this, "Error loading the file.", Toast.LENGTH_SHORT) .show(); } } } } }
package com.fguarino.scoreboard.framework; import java.io.File; import java.io.IOException; import java.util.Timer; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.StageStyle; public class MatchSettings { @FXML BorderPane root; @FXML TextField matchNameTextField, matchTimeTextField, shortPauseTextField, longPauseTextField, homeNameTextField, guestNameTextField; @FXML VBox homeBox, guestBox; @FXML Button startButton, quitButton; @FXML CheckBox showNameCheckBox; boolean isNameActive = false; @FXML Button homeLogoButton, guestLogoButton; Stage stage = new Stage(); Scene scene; MatchSettings() { try { FXMLLoader fxmlLoaderS = new FXMLLoader(getClass().getResource("/com/fguarino/settings.fxml")); fxmlLoaderS.setController(this); root = fxmlLoaderS.load(); } catch (IOException e) { } FileChooser homeFileChooser = new FileChooser(); homeFileChooser.setTitle("Open Resource File"); homeLogoButton.setOnAction(e -> { File file = homeFileChooser.showOpenDialog(stage); if (file != null) { Globals.homeTeam.setLogo(file.getAbsolutePath()); } }); FileChooser guestFileChooser = new FileChooser(); guestFileChooser.setTitle("Open Resource File"); guestLogoButton.setOnAction(e -> { File file = guestFileChooser.showOpenDialog(stage); if (file != null) { Globals.guestTeam.setLogo(file.getAbsolutePath()); } }); // homeNameTextField.setOnAction(e -> // Globals.homeTeam.setTeamName(homeNameTextField.getText().toUpperCase())); homeNameTextField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) { homeNameTextField.setText(checkInput(homeNameTextField, 3)); } }); homeNameTextField.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getCode().equals(KeyCode.ENTER) || event.getCode().equals(KeyCode.TAB)) { Globals.homeTeam.setTeamName(checkInput(homeNameTextField, 3).toUpperCase()); homeNameTextField.clear(); if (event.getCode().equals(KeyCode.ENTER)) { root.requestFocus(); } homeNameTextField.setText(Globals.homeTeam.getTeamName()); } if (event.getCode().equals(KeyCode.ESCAPE)) { root.requestFocus(); homeNameTextField.clear(); homeNameTextField.setText(Globals.homeTeam.getTeamName()); } } }); for (PlayerAbs p : Globals.homePlayers) { SettingsPlayer s = new SettingsPlayer(p); homeBox.getChildren().add(s.getRoot()); } homeNameTextField.setPromptText("TEAMKÜRZEL"); guestNameTextField.setPromptText("TEAMKÜRZEL"); // guestNameTextField.setOnAction(e -> // Globals.guestTeam.setTeamName(guestNameTextField.getText().toUpperCase())); guestNameTextField.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getCode().equals(KeyCode.ENTER) || event.getCode().equals(KeyCode.TAB)) { Globals.guestTeam.setTeamName(checkInput(guestNameTextField, 3).toUpperCase()); guestNameTextField.clear(); if (event.getCode().equals(KeyCode.ENTER)) { root.requestFocus(); } guestNameTextField.setText(Globals.guestTeam.getTeamName()); } if (event.getCode().equals(KeyCode.ESCAPE)) { root.requestFocus(); guestNameTextField.clear(); guestNameTextField.setText(Globals.guestTeam.getTeamName()); } } }); guestNameTextField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) { guestNameTextField.setText(checkInput(guestNameTextField, 3)); } }); for (PlayerAbs p : Globals.guestPlayers) { SettingsPlayer s = new SettingsPlayer(p); guestBox.getChildren().add(s.getRoot()); } removeNameLabel(); startButton.setOnAction(e -> startMatch()); quitButton.setOnAction(e -> quitMatch()); matchNameTextField.setOnAction(e -> Globals.scoreboardRef.setMatchName(matchNameTextField.getText())); matchTimeTextField .setOnAction(e -> Globals.matchTime.setPeriodTime(Long.valueOf(matchTimeTextField.getText()) * 60000)); // periodTextField.setOnAction(e -> // Globals.matchTime.setPeriod(Integer.valueOf(periodTextField.getText()))); shortPauseTextField.setOnAction( e -> Globals.matchTime.setShortPauseTime(Long.valueOf(shortPauseTextField.getText()) * 60000)); longPauseTextField.setOnAction( e -> Globals.matchTime.setLongPauseTime(Long.valueOf(longPauseTextField.getText()) * 60000)); showNameCheckBox.setOnAction(e -> { isNameActive = !isNameActive; Globals.isLive = true; checkNameLabel(); }); scene = new Scene(getRoot()); stage.initStyle(StageStyle.TRANSPARENT); stage.setScene(scene); root.requestFocus(); stage.show(); } public void startMatch() { startButton.setDisable(true); removeNameLabel(); checkNameLabel(); Globals.scoreboardRef.scoreboardStage.show(); Globals.scoreboardRef.controlStage.show(); stage.close(); } public void checkNameLabel() { if (isNameActive) { addNameLabel(); } else { removeNameLabel(); } } public void checkLive() { if (Globals.isLive) { Selenium selenium = new Selenium(); Globals.selenium = selenium; selenium.start(); } else { removeNameLabel(); } } public void addNameLabel() { for (PlayerAbs p : Globals.homePlayers) { p.centerHBoxS.getChildren().add(1, p.nameLabelS); } for (PlayerAbs p : Globals.guestPlayers) { if (p.centerHBoxS.getChildren().size() == 1) { p.centerHBoxS.getChildren().add(0, p.nameLabelS); } else { p.centerHBoxS.getChildren().add(1, p.nameLabelS); } } } public void removeNameLabel() { for (PlayerAbs p : Globals.homePlayers) { p.centerHBoxS.getChildren().remove(p.nameLabelS); } for (PlayerAbs p : Globals.guestPlayers) { p.centerHBoxS.getChildren().remove(p.nameLabelS); } } public void quitMatch() { if (Globals.scoreboardRef.scoreboardStage.isShowing()) { stage.hide(); } else { Platform.exit(); } } public BorderPane getRoot() { return root; } public void open() { stage.hide(); stage.show(); } class SettingsPlayer { HBox pRoot; @FXML TextField nameTextField; @FXML Label numberLabel; public SettingsPlayer(PlayerAbs p) { try { FXMLLoader fxmlLoaderS = new FXMLLoader(getClass().getResource("/com/fguarino/settingsPlayer.fxml")); fxmlLoaderS.setController(this); pRoot = fxmlLoaderS.load(); } catch (Exception e) { // TODO: handle exception } numberLabel.setText(String.valueOf(p.number)); nameTextField.setPromptText(p.getName()); nameTextField.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getCode().equals(KeyCode.ENTER) || event.getCode().equals(KeyCode.TAB)) { p.setName(checkInput(nameTextField, 14)); nameTextField.clear(); if (event.getCode().equals(KeyCode.ENTER)) { pRoot.requestFocus(); } nameTextField.setText(p.getName()); } if (event.getCode().equals(KeyCode.ESCAPE)) { pRoot.requestFocus(); nameTextField.clear(); nameTextField.setText(p.getName()); } } }); nameTextField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) { nameTextField.setText(checkInput(nameTextField, 14)); } }); } public HBox getRoot() { return pRoot; } } public String checkInput(TextField t, int limit) { String s = t.getText(); if (s.length() > limit) { s = s.substring(0, limit); } return s; } }
/* * Copyright 2017-present Open Networking 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.onosproject.provider.general.device.impl; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.annotations.Beta; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.util.concurrent.Striped; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Modified; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.onlab.packet.ChassisId; import org.onlab.util.ItemNotFoundException; import org.onlab.util.Tools; import org.onosproject.cfg.ComponentConfigService; import org.onosproject.cluster.ClusterService; import org.onosproject.cluster.LeadershipService; import org.onosproject.core.CoreService; import org.onosproject.mastership.MastershipService; import org.onosproject.net.AnnotationKeys; import org.onosproject.net.DefaultAnnotations; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.MastershipRole; import org.onosproject.net.PortNumber; import org.onosproject.net.behaviour.PiPipelineProgrammable; import org.onosproject.net.behaviour.PortAdmin; import org.onosproject.net.config.ConfigFactory; import org.onosproject.net.config.NetworkConfigEvent; import org.onosproject.net.config.NetworkConfigListener; import org.onosproject.net.config.NetworkConfigRegistry; import org.onosproject.net.config.basics.BasicDeviceConfig; import org.onosproject.net.config.basics.SubjectFactories; import org.onosproject.net.device.DefaultDeviceDescription; import org.onosproject.net.device.DeviceAgentEvent; import org.onosproject.net.device.DeviceAgentListener; import org.onosproject.net.device.DeviceDescription; import org.onosproject.net.device.DeviceDescriptionDiscovery; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceHandshaker; import org.onosproject.net.device.DeviceListener; import org.onosproject.net.device.DeviceProvider; import org.onosproject.net.device.DeviceProviderRegistry; import org.onosproject.net.device.DeviceProviderService; import org.onosproject.net.device.DeviceService; import org.onosproject.net.device.PortDescription; import org.onosproject.net.device.PortStatistics; import org.onosproject.net.device.PortStatisticsDiscovery; import org.onosproject.net.driver.Behaviour; import org.onosproject.net.driver.DefaultDriverData; import org.onosproject.net.driver.DefaultDriverHandler; import org.onosproject.net.driver.Driver; import org.onosproject.net.driver.DriverData; import org.onosproject.net.driver.DriverService; import org.onosproject.net.pi.model.PiPipeconf; import org.onosproject.net.pi.model.PiPipeconfId; import org.onosproject.net.pi.service.PiPipeconfConfig; import org.onosproject.net.pi.service.PiPipeconfService; import org.onosproject.net.provider.AbstractProvider; import org.onosproject.net.provider.ProviderId; import org.onosproject.provider.general.device.api.GeneralProviderDeviceConfig; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Dictionary; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Lock; import java.util.function.Supplier; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; import static org.onlab.util.Tools.groupedThreads; import static org.onosproject.net.device.DeviceEvent.Type; import static org.slf4j.LoggerFactory.getLogger; /** * Provider which uses drivers to detect device and do initial handshake and * channel establishment with devices. Any other provider specific operation is * also delegated to the DeviceHandshaker driver. */ @Beta @Component(immediate = true) public class GeneralDeviceProvider extends AbstractProvider implements DeviceProvider { private static final String DRIVER = "driver"; private final Logger log = getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private DeviceProviderRegistry providerRegistry; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private ComponentConfigService componentConfigService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private NetworkConfigRegistry cfgService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private DeviceService deviceService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private DriverService driverService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private MastershipService mastershipService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private PiPipeconfService piPipeconfService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private ClusterService clusterService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) private LeadershipService leadershipService; private static final String STATS_POLL_FREQUENCY = "deviceStatsPollFrequency"; private static final int DEFAULT_STATS_POLL_FREQUENCY = 10; @Property(name = STATS_POLL_FREQUENCY, intValue = DEFAULT_STATS_POLL_FREQUENCY, label = "Configure poll frequency for port status and statistics; " + "default is 10 sec") private int statsPollFrequency = DEFAULT_STATS_POLL_FREQUENCY; private static final String PROBE_FREQUENCY = "deviceProbeFrequency"; private static final int DEFAULT_PROBE_FREQUENCY = 10; @Property(name = PROBE_FREQUENCY, intValue = DEFAULT_PROBE_FREQUENCY, label = "Configure probe frequency for checking device availability; " + "default is 10 sec") private int probeFrequency = DEFAULT_PROBE_FREQUENCY; private static final String OP_TIMEOUT_SHORT = "deviceOperationTimeoutShort"; private static final int DEFAULT_OP_TIMEOUT_SHORT = 10; @Property(name = OP_TIMEOUT_SHORT, intValue = DEFAULT_OP_TIMEOUT_SHORT, label = "Configure timeout in seconds for device operations " + "that are supposed to take a short time " + "(e.g. checking device reachability); default is 10 seconds") private int opTimeoutShort = DEFAULT_OP_TIMEOUT_SHORT; private static final String OP_TIMEOUT_LONG = "deviceOperationTimeoutLong"; private static final int DEFAULT_OP_TIMEOUT_LONG = 60; @Property(name = OP_TIMEOUT_LONG, intValue = DEFAULT_OP_TIMEOUT_LONG, label = "Configure timeout in seconds for device operations " + "that are supposed to take a relatively long time " + "(e.g. pushing a large pipeline configuration with slow " + "network); default is 60 seconds") private int opTimeoutLong = DEFAULT_OP_TIMEOUT_LONG; private static final String APP_NAME = "org.onosproject.generaldeviceprovider"; private static final String URI_SCHEME = "device"; private static final String CFG_SCHEME = "generalprovider"; private static final String DEVICE_PROVIDER_PACKAGE = "org.onosproject.general.provider.device"; private static final int CORE_POOL_SIZE = 10; private static final String UNKNOWN = "unknown"; //FIXME this will be removed when the configuration is synced at the source. private static final Set<String> PIPELINE_CONFIGURABLE_PROTOCOLS = ImmutableSet.of("p4runtime"); //FIXME to be removed when netcfg will issue device events in a bundle or //ensures all configuration needed is present private Set<DeviceId> deviceConfigured = new CopyOnWriteArraySet<>(); private Set<DeviceId> driverConfigured = new CopyOnWriteArraySet<>(); private Set<DeviceId> pipelineConfigured = new CopyOnWriteArraySet<>(); private final Map<DeviceId, DeviceHandshaker> handshakers = Maps.newConcurrentMap(); private final Map<DeviceId, MastershipRole> requestedRoles = Maps.newConcurrentMap(); private final Striped<Lock> deviceLocks = Striped.lock(30); private ExecutorService connectionExecutor = newFixedThreadPool(CORE_POOL_SIZE, groupedThreads( "onos/generaldeviceprovider-device-connect", "%d", log)); private ScheduledExecutorService statsExecutor = newScheduledThreadPool(CORE_POOL_SIZE, groupedThreads( "onos/generaldeviceprovider-stats-poll", "%d", log)); private ConcurrentMap<DeviceId, ScheduledFuture<?>> statsPollingTasks = new ConcurrentHashMap<>(); private ScheduledExecutorService probeExecutor = newSingleThreadScheduledExecutor(groupedThreads( "onos/generaldeviceprovider-probe-", "%d", log)); private ScheduledFuture<?> probeTask = null; private DeviceProviderService providerService; private InternalDeviceListener deviceListener = new InternalDeviceListener(); private final ConfigFactory factory = new ConfigFactory<DeviceId, GeneralProviderDeviceConfig>( SubjectFactories.DEVICE_SUBJECT_FACTORY, GeneralProviderDeviceConfig.class, CFG_SCHEME) { @Override public GeneralProviderDeviceConfig createConfig() { return new GeneralProviderDeviceConfig(); } }; private final NetworkConfigListener cfgListener = new InternalNetworkConfigListener(); private final DeviceAgentListener deviceAgentListener = new InternalDeviceAgentListener(); @Activate public void activate(ComponentContext context) { providerService = providerRegistry.register(this); componentConfigService.registerProperties(getClass()); coreService.registerApplication(APP_NAME); cfgService.registerConfigFactory(factory); cfgService.addListener(cfgListener); deviceService.addListener(deviceListener); handshakers.clear(); //This will fail if ONOS has CFG and drivers which depend on this provider // are activated, failing due to not finding the driver. cfgService.getSubjects(DeviceId.class, GeneralProviderDeviceConfig.class) .forEach(this::triggerConnect); //Initiating a periodic check to see if any device is available again and reconnect it. rescheduleProbeTask(); modified(context); log.info("Started"); } @Modified public void modified(ComponentContext context) { if (context == null) { return; } Dictionary<?, ?> properties = context.getProperties(); final int oldStatsPollFrequency = statsPollFrequency; statsPollFrequency = Tools.getIntegerProperty( properties, STATS_POLL_FREQUENCY, DEFAULT_STATS_POLL_FREQUENCY); log.info("Configured. {} is configured to {} seconds", STATS_POLL_FREQUENCY, statsPollFrequency); final int oldProbeFrequency = probeFrequency; probeFrequency = Tools.getIntegerProperty( properties, PROBE_FREQUENCY, DEFAULT_PROBE_FREQUENCY); log.info("Configured. {} is configured to {} seconds", PROBE_FREQUENCY, probeFrequency); opTimeoutShort = Tools.getIntegerProperty( properties, OP_TIMEOUT_SHORT, DEFAULT_OP_TIMEOUT_SHORT); log.info("Configured. {} is configured to {} seconds", OP_TIMEOUT_SHORT, opTimeoutShort); opTimeoutLong = Tools.getIntegerProperty( properties, OP_TIMEOUT_LONG, DEFAULT_OP_TIMEOUT_LONG); log.info("Configured. {} is configured to {} seconds", OP_TIMEOUT_LONG, opTimeoutLong); if (oldStatsPollFrequency != statsPollFrequency) { rescheduleStatsPollingTasks(); } if (oldProbeFrequency != probeFrequency) { rescheduleProbeTask(); } } private synchronized void rescheduleProbeTask() { if (probeTask != null) { probeTask.cancel(false); } probeTask = probeExecutor.scheduleAtFixedRate( this::triggerProbeAllDevices, probeFrequency, probeFrequency, TimeUnit.SECONDS); } @Deactivate public void deactivate() { statsExecutor.shutdown(); probeExecutor.shutdown(); componentConfigService.unregisterProperties(getClass(), false); cfgService.removeListener(cfgListener); //Not Removing the device so they can still be used from other driver providers //cfgService.getSubjects(DeviceId.class, GeneralProviderDeviceConfig.class) // .forEach(did -> connectionExecutor.execute(() -> disconnectDevice(did))); connectionExecutor.shutdown(); deviceService.removeListener(deviceListener); providerRegistry.unregister(this); handshakers.clear(); providerService = null; cfgService.unregisterConfigFactory(factory); log.info("Stopped"); } public GeneralDeviceProvider() { super(new ProviderId(URI_SCHEME, DEVICE_PROVIDER_PACKAGE)); } @Override public void triggerProbe(DeviceId deviceId) { connectionExecutor.execute(withDeviceLock( () -> doDeviceProbe(deviceId), deviceId)); } @Override public void roleChanged(DeviceId deviceId, MastershipRole newRole) { log.info("Received role {} for device {}", newRole, deviceId); requestedRoles.put(deviceId, newRole); connectionExecutor.execute(() -> doRoleChanged(deviceId, newRole)); } private void doRoleChanged(DeviceId deviceId, MastershipRole newRole) { final DeviceHandshaker handshaker = getHandshaker(deviceId); if (handshaker == null) { log.error("Null handshaker. Unable to notify new role {} to {}", newRole, deviceId); return; } handshaker.roleChanged(newRole); } @Override public boolean isReachable(DeviceId deviceId) { log.debug("Testing reachability for device {}", deviceId); final DeviceHandshaker handshaker = getHandshaker(deviceId); if (handshaker == null) { return false; } return getFutureWithDeadline( handshaker.isReachable(), "checking reachability", deviceId, false, opTimeoutShort); } @Override public void changePortState(DeviceId deviceId, PortNumber portNumber, boolean enable) { connectionExecutor.execute( () -> doChangePortState(deviceId, portNumber, enable)); } private void doChangePortState(DeviceId deviceId, PortNumber portNumber, boolean enable) { if (!deviceService.getDevice(deviceId).is(PortAdmin.class)) { log.warn("Missing PortAdmin behaviour on {}, aborting port state change", deviceId); return; } final PortAdmin portAdmin = deviceService.getDevice(deviceId) .as(PortAdmin.class); final CompletableFuture<Boolean> modifyTask = enable ? portAdmin.enable(portNumber) : portAdmin.disable(portNumber); final String descr = (enable ? "enabling" : "disabling") + " port " + portNumber; getFutureWithDeadline( modifyTask, descr, deviceId, null, opTimeoutShort); } @Override public void triggerDisconnect(DeviceId deviceId) { log.debug("Triggering disconnection of device {}", deviceId); connectionExecutor.execute(withDeviceLock( () -> doDisconnectDevice(deviceId), deviceId)); } private DeviceHandshaker getHandshaker(DeviceId deviceId) { return handshakers.computeIfAbsent(deviceId, id -> { Driver driver = getDriver(deviceId); return driver == null ? null : getBehaviour( driver, DeviceHandshaker.class, new DefaultDriverData(driver, deviceId)); }); } private Driver getDriver(DeviceId deviceId) { try { // DriverManager checks first using basic device config. return driverService.getDriver(deviceId); } catch (ItemNotFoundException e) { log.error("Driver not found for {}", deviceId); return null; } } private <T extends Behaviour> T getBehaviour(Driver driver, Class<T> type, DriverData data) { // Allows obtaining behavior implementations before the device is pushed // to the core. if (driver != null && driver.hasBehaviour(type)) { DefaultDriverHandler handler = new DefaultDriverHandler(data); return driver.createBehaviour(handler, type); } else { return null; } } private void doConnectDevice(DeviceId deviceId) { // Some operations can be performed by one node only. final boolean isLocalLeader = leadershipService.runForLeadership( GeneralProviderDeviceConfig.class.getName() + deviceId) .leader().nodeId().equals(clusterService.getLocalNode().id()); if (deviceService.getDevice(deviceId) != null && deviceService.isAvailable(deviceId)) { log.info("Device {} is already connected to ONOS and is available", deviceId); return; } // Retrieve config final GeneralProviderDeviceConfig providerConfig = cfgService.getConfig( deviceId, GeneralProviderDeviceConfig.class); final BasicDeviceConfig basicDeviceConfig = cfgService.getConfig( deviceId, BasicDeviceConfig.class); if (providerConfig == null || basicDeviceConfig == null) { log.error("Configuration missing, cannot connect to {}. " + "basicDeviceConfig={}, generalProvider={}", deviceId, basicDeviceConfig, providerConfig); return; } log.info("Initiating connection to device {} with driver {} ... asMaster={}", deviceId, basicDeviceConfig.driver(), isLocalLeader); // Get handshaker, driver and driver data. final DeviceHandshaker handshaker = getHandshaker(deviceId); if (handshaker == null) { log.error("Missing DeviceHandshaker behavior for {}, aborting connection", deviceId); return; } final Driver driver = handshaker.handler().driver(); // Enhance driver data with info in GDP config. augmentConfigData(providerConfig, handshaker.data()); final DriverData driverData = handshaker.data(); // Start connection via handshaker. final Boolean connectSuccess = getFutureWithDeadline( handshaker.connect(), "initiating connection", deviceId, null, opTimeoutShort); if (connectSuccess == null) { // Error logged by getFutureWithDeadline(). return; } else if (!connectSuccess) { log.warn("Unable to connect to {}", deviceId); return; } // Handle pipeconf (if device is capable) if (!handlePipeconf(deviceId, driver, driverData, isLocalLeader)) { // We already logged the error. getFutureWithDeadline( handshaker.disconnect(), "performing disconnection", deviceId, null, opTimeoutShort); return; } // Add device agent listener. handshaker.addDeviceAgentListener(deviceAgentListener); // All good. Notify core (if master). if (isLocalLeader) { advertiseDevice(deviceId, driver, providerConfig, driverData); } } private void advertiseDevice(DeviceId deviceId, Driver driver, GeneralProviderDeviceConfig providerConfig, DriverData driverData) { // Obtain device and port description and advertise device to core. DeviceDescription description = null; final List<PortDescription> ports; final DeviceDescriptionDiscovery deviceDiscovery = getBehaviour( driver, DeviceDescriptionDiscovery.class, driverData); if (deviceDiscovery != null) { description = deviceDiscovery.discoverDeviceDetails(); ports = deviceDiscovery.discoverPortDetails(); } else { log.warn("Missing DeviceDescriptionDiscovery behavior for {}, " + "no update for description or ports.", deviceId); ports = new ArrayList<>(); } if (description == null) { // Generate one here. // FIXME: a behavior impl should not return a null description // (e.g. as GnmiDeviceDescriptionDiscovery). This case should apply // only if a the behavior is not available. description = new DefaultDeviceDescription( deviceId.uri(), Device.Type.SWITCH, driver.manufacturer(), driver.hwVersion(), driver.swVersion(), UNKNOWN, new ChassisId(), true, DefaultAnnotations.builder() .set(AnnotationKeys.PROTOCOL, providerConfig.protocolsInfo().keySet().toString()) .build()); } providerService.deviceConnected(deviceId, description); providerService.updatePorts(deviceId, ports); } /** * Handles the case of a device that is pipeline programmable. Returns true * if the operation wa successful and the device can be registered to the * core, false otherwise. */ private boolean handlePipeconf(DeviceId deviceId, Driver driver, DriverData driverData, boolean asMaster) { final PiPipelineProgrammable pipelineProg = getBehaviour( driver, PiPipelineProgrammable.class, driverData); if (pipelineProg == null) { // Device is not pipeline programmable. return true; } final PiPipeconf pipeconf = getPipeconf(deviceId, pipelineProg); if (pipeconf == null) { return false; } final PiPipeconfId pipeconfId = pipeconf.id(); final String mergedDriverName = piPipeconfService.mergeDriver( deviceId, pipeconfId); if (mergedDriverName == null) { log.error("Unable to get merged driver for {} and {}, aborting device discovery", deviceId, pipeconfId); return false; } if (!asMaster) { // From now one only the master. return true; } if (!setDriverViaCfg(deviceId, mergedDriverName)) { return false; } // FIXME: we just introduced a race condition as it might happen that a // node does not receive the new cfg (with the merged driver) before the // device is advertised to the core. Perhaps we should be waiting for a // NetworkConfig event signaling that the driver has been updated on all // nodes? The effect is mitigated by deploying the pipeconf (slow // operation), after calling setDriverViaCfg(). piPipeconfService.bindToDevice(pipeconfId, deviceId); final Boolean deploySuccess = getFutureWithDeadline( pipelineProg.deployPipeconf(pipeconf), "deploying pipeconf", deviceId, null, opTimeoutLong); if (deploySuccess == null) { // Error logged by getFutureWithDeadline(). return false; } else if (!deploySuccess) { log.error("Unable to deploy pipeconf {} to {}, aborting device discovery", pipeconfId, deviceId); return false; } return true; } private boolean setDriverViaCfg(DeviceId deviceId, String driverName) { BasicDeviceConfig cfg = cfgService.getConfig(deviceId, BasicDeviceConfig.class); if (cfg == null) { log.error("Unable to get basic device config for {}, aborting device discovery", deviceId); return false; } ObjectNode newCfg = (ObjectNode) cfg.node(); newCfg = newCfg.put(DRIVER, driverName); ObjectMapper mapper = new ObjectMapper(); JsonNode newCfgNode = mapper.convertValue(newCfg, JsonNode.class); cfgService.applyConfig(deviceId, BasicDeviceConfig.class, newCfgNode); return true; } private PiPipeconf getPipeconf(DeviceId deviceId, PiPipelineProgrammable pipelineProg) { PiPipeconfId pipeconfId = getPipeconfFromCfg(deviceId); if (pipeconfId == null || pipeconfId.id().isEmpty()) { // No pipeconf has been provided in the cfg. // Check if device driver provides a default one. if (pipelineProg.getDefaultPipeconf().isPresent()) { final PiPipeconf defaultPipeconf = pipelineProg.getDefaultPipeconf().get(); log.info("Using default pipeconf {} for {}", defaultPipeconf.id(), deviceId); pipeconfId = defaultPipeconf.id(); } else { log.warn("Device {} is pipeline programmable but no pipeconf can be associated to it", deviceId); return null; } } // Check if registered if (!piPipeconfService.getPipeconf(pipeconfId).isPresent()) { log.warn("Pipeconf {} is not registered", pipeconfId); return null; } return piPipeconfService.getPipeconf(pipeconfId).get(); } private void doDisconnectDevice(DeviceId deviceId) { log.debug("Initiating disconnection from {}...", deviceId); final DeviceHandshaker handshaker = handshakers.remove(deviceId); final boolean isAvailable = deviceService.isAvailable(deviceId); // Signal disconnection to core (if master). if (isAvailable && mastershipService.isLocalMaster(deviceId)) { providerService.deviceDisconnected(deviceId); } // Cancel tasks. cancelStatsPolling(deviceId); // Disconnect device. if (handshaker == null) { if (isAvailable) { // If not available don't bother logging. We are probably // invoking this method multiple times for the same device. log.warn("Missing DeviceHandshaker behavior for {}, " + "no guarantees of complete disconnection", deviceId); } return; } handshaker.removeDeviceAgentListener(deviceAgentListener); final boolean disconnectSuccess = getFutureWithDeadline( handshaker.disconnect(), "performing disconnection", deviceId, false, opTimeoutShort); if (!disconnectSuccess) { log.warn("Unable to disconnect from {}", deviceId); } } // Needed to catch the exception in the executors since are not rethrown otherwise. private Runnable exceptionSafe(Runnable runnable) { return () -> { try { runnable.run(); } catch (Exception e) { log.error("Unhandled Exception", e); } }; } private <U> U withDeviceLock(Supplier<U> task, DeviceId deviceId) { final Lock lock = deviceLocks.get(deviceId); lock.lock(); try { return task.get(); } finally { lock.unlock(); } } private Runnable withDeviceLock(Runnable task, DeviceId deviceId) { // Wrapper of withDeviceLock(Supplier, ...) for void tasks. return () -> withDeviceLock(() -> { task.run(); return null; }, deviceId); } private void updatePortStatistics(DeviceId deviceId) { Device device = deviceService.getDevice(deviceId); if (device != null && deviceService.isAvailable(deviceId) && device.is(PortStatisticsDiscovery.class)) { Collection<PortStatistics> statistics = device.as(PortStatisticsDiscovery.class) .discoverPortStatistics(); //updating statistcs only if not empty if (!statistics.isEmpty()) { providerService.updatePortStatistics(deviceId, statistics); } } else { log.debug("Can't update port statistics for device {}", deviceId); } } private boolean notMyScheme(DeviceId deviceId) { return !deviceId.uri().getScheme().equals(URI_SCHEME); } private void triggerConnect(DeviceId deviceId) { connectionExecutor.execute(withDeviceLock( () -> doConnectDevice(deviceId), deviceId)); } /** * Listener for configuration events. */ private class InternalNetworkConfigListener implements NetworkConfigListener { @Override public void event(NetworkConfigEvent event) { connectionExecutor.execute(() -> consumeConfigEvent(event)); } @Override public boolean isRelevant(NetworkConfigEvent event) { return (event.configClass().equals(GeneralProviderDeviceConfig.class) || event.configClass().equals(BasicDeviceConfig.class) || event.configClass().equals(PiPipeconfConfig.class)) && (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED); } private void consumeConfigEvent(NetworkConfigEvent event) { DeviceId deviceId = (DeviceId) event.subject(); //Assuming that the deviceId comes with uri 'device:' if (notMyScheme(deviceId)) { // not under my scheme, skipping log.debug("{} is not my scheme, skipping", deviceId); return; } final boolean configComplete = withDeviceLock( () -> isDeviceConfigComplete(event, deviceId), deviceId); if (!configComplete) { // Still waiting for some configuration. return; } // Good to go. triggerConnect(deviceId); cleanUpConfigInfo(deviceId); } private boolean isDeviceConfigComplete(NetworkConfigEvent event, DeviceId deviceId) { // FIXME to be removed when netcfg will issue device events in a bundle or // ensure all configuration needed is present if (event.configClass().equals(GeneralProviderDeviceConfig.class)) { //FIXME we currently assume that p4runtime devices are pipeline configurable. //If we want to connect a p4runtime device with no pipeline if (event.config().isPresent()) { deviceConfigured.add(deviceId); final boolean isNotPipelineConfigurable = Collections.disjoint( ImmutableSet.copyOf(event.config().get().node().fieldNames()), PIPELINE_CONFIGURABLE_PROTOCOLS); if (isNotPipelineConfigurable) { // Skip waiting for a pipeline if we can't support it. pipelineConfigured.add(deviceId); } } } else if (event.configClass().equals(BasicDeviceConfig.class)) { if (event.config().isPresent() && event.config().get().node().has(DRIVER)) { driverConfigured.add(deviceId); } } else if (event.configClass().equals(PiPipeconfConfig.class)) { if (event.config().isPresent() && event.config().get().node().has(PiPipeconfConfig.PIPIPECONFID)) { pipelineConfigured.add(deviceId); } } if (deviceConfigured.contains(deviceId) && driverConfigured.contains(deviceId) && pipelineConfigured.contains(deviceId)) { return true; } else { if (deviceConfigured.contains(deviceId) && driverConfigured.contains(deviceId)) { log.debug("Waiting for pipeline configuration for device {}", deviceId); } else if (pipelineConfigured.contains(deviceId) && driverConfigured.contains(deviceId)) { log.debug("Waiting for device configuration for device {}", deviceId); } else if (pipelineConfigured.contains(deviceId) && deviceConfigured.contains(deviceId)) { log.debug("Waiting for driver configuration for device {}", deviceId); } else if (driverConfigured.contains(deviceId)) { log.debug("Only driver configuration for device {}", deviceId); } else if (deviceConfigured.contains(deviceId)) { log.debug("Only device configuration for device {}", deviceId); } } return false; } } private void augmentConfigData(GeneralProviderDeviceConfig providerConfig, DriverData driverData) { //Storing deviceKeyId and all other config values // as data in the driver with protocol_<info> // name as the key. e.g protocol_ip providerConfig.protocolsInfo() .forEach((protocol, deviceInfoConfig) -> { deviceInfoConfig.configValues() .forEach((k, v) -> driverData.set(protocol + "_" + k, v)); driverData.set(protocol + "_key", deviceInfoConfig.deviceKeyId()); }); } private void cleanUpConfigInfo(DeviceId deviceId) { deviceConfigured.remove(deviceId); driverConfigured.remove(deviceId); pipelineConfigured.remove(deviceId); } private void startStatsPolling(DeviceId deviceId, boolean withRandomDelay) { statsPollingTasks.compute(deviceId, (did, oldTask) -> { if (oldTask != null) { oldTask.cancel(false); } final int delay = withRandomDelay ? new SecureRandom().nextInt(10) : 0; return statsExecutor.scheduleAtFixedRate( exceptionSafe(() -> updatePortStatistics(deviceId)), delay, statsPollFrequency, TimeUnit.SECONDS); }); } private void cancelStatsPolling(DeviceId deviceId) { statsPollingTasks.computeIfPresent(deviceId, (did, task) -> { task.cancel(false); return null; }); } private void rescheduleStatsPollingTasks() { statsPollingTasks.keySet().forEach(deviceId -> { // startStatsPolling cancels old one if present. startStatsPolling(deviceId, true); }); } private void triggerProbeAllDevices() { // Async trigger a task for all devices in the cfg. cfgService.getSubjects(DeviceId.class, GeneralProviderDeviceConfig.class) .forEach(deviceId -> connectionExecutor.execute(withDeviceLock( () -> doDeviceProbe(deviceId), deviceId))); } private PiPipeconfId getPipeconfFromCfg(DeviceId deviceId) { PiPipeconfConfig config = cfgService.getConfig( deviceId, PiPipeconfConfig.class); if (config == null) { return null; } return config.piPipeconfId(); } private void doDeviceProbe(DeviceId deviceId) { if (!configIsPresent(deviceId)) { return; } final boolean isAvailable = deviceService.getDevice(deviceId) != null && deviceService.isAvailable(deviceId); final boolean isLocalMaster = mastershipService.isLocalMaster(deviceId); if (isAvailable) { if (!isLocalMaster) { return; } if (!isReachable(deviceId)) { log.info("Disconnecting available but unreachable device {}...", deviceId); triggerDisconnect(deviceId); } } else { // We do not check for reachability using isReachable() // since the behaviour of this method can vary depending on protocol // nuances. We leave this check to the device handshaker at later // stages of the connection process. triggerConnect(deviceId); } } private boolean configIsPresent(DeviceId deviceId) { final boolean present = cfgService.getConfig(deviceId, GeneralProviderDeviceConfig.class) != null && cfgService.getConfig(deviceId, BasicDeviceConfig.class) != null; if (!present) { log.warn("Configuration for device {} is not complete", deviceId); } return present; } private void handleChannelClosed(DeviceId deviceId) { log.info("Disconnecting device {}, due to channel closed event", deviceId); triggerDisconnect(deviceId); } private void handleMastershipResponse(DeviceId deviceId, MastershipRole response) { //Notify core about response. if (!requestedRoles.containsKey(deviceId)) { return; } providerService.receivedRoleReply(deviceId, requestedRoles.get(deviceId), response); if (response.equals(MastershipRole.MASTER)) { startStatsPolling(deviceId, false); } else { cancelStatsPolling(deviceId); } } private <U> U getFutureWithDeadline(CompletableFuture<U> future, String opDescription, DeviceId deviceId, U defaultValue, int timeout) { try { return future.get(timeout, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error("Thread interrupted while {} on {}", opDescription, deviceId); Thread.currentThread().interrupt(); } catch (ExecutionException e) { log.error("Exception while {} on {}", opDescription, deviceId, e.getCause()); } catch (TimeoutException e) { log.error("Operation TIMEOUT while {} on {}", opDescription, deviceId); } return defaultValue; } /** * Listener for core device events. */ private class InternalDeviceListener implements DeviceListener { @Override public void event(DeviceEvent event) { DeviceId deviceId = event.subject().id(); // For now this is scheduled periodically, when streaming API will // be available we check and base it on the streaming API (e.g. gNMI) if (mastershipService.isLocalMaster(deviceId)) { startStatsPolling(deviceId, true); } } @Override public boolean isRelevant(DeviceEvent event) { return event.type() == Type.DEVICE_ADDED && event.subject().id().toString().startsWith(URI_SCHEME.toLowerCase()); } } /** * Listener for device agent events. */ private class InternalDeviceAgentListener implements DeviceAgentListener { @Override public void event(DeviceAgentEvent event) { DeviceId deviceId = event.subject(); switch (event.type()) { case CHANNEL_OPEN: // Ignore. break; case CHANNEL_CLOSED: handleChannelClosed(deviceId); break; case CHANNEL_ERROR: // TODO evaluate other reaction to channel error. log.warn("Received CHANNEL_ERROR from {}. Is the channel still open?", deviceId); handleChannelClosed(deviceId); break; case ROLE_MASTER: handleMastershipResponse(deviceId, MastershipRole.MASTER); break; case ROLE_STANDBY: handleMastershipResponse(deviceId, MastershipRole.STANDBY); break; case ROLE_NONE: handleMastershipResponse(deviceId, MastershipRole.NONE); break; default: log.warn("Unrecognized device agent event {}", event.type()); } } } }
package com.liushaoming.jseckill.backend.mq; import com.liushaoming.jseckill.backend.constant.MQConstant; import com.rabbitmq.client.Channel; import com.rabbitmq.client.ConfirmListener; import com.rabbitmq.client.MessageProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.concurrent.TimeoutException; @Component public class MQProducer { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private MQChannelManager mqChannelManager; public void send(String msg) { //获取当前线程使用的Rabbitmq通道 Channel channel = mqChannelManager.getSendChannel(); try { logger.info(" [mqSend] '" + msg + "'"); channel.confirmSelect(); channel.basicPublish("", MQConstant.QUEUE_NAME_SECKILL, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes()); } catch (IOException e) { e.printStackTrace(); } boolean sendAcked = false; try { sendAcked = channel.waitForConfirms(100); } catch (InterruptedException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } logger.info("sendAcked={}", sendAcked); if (!sendAcked) { logger.info("!!!mqSend_NACKED,NOW_RETRY>>>"); try { channel.basicPublish("", MQConstant.QUEUE_NAME_SECKILL, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes()); } catch (IOException e) { e.printStackTrace(); } } } }
package org.jpacman.framework.model; /** * Directions in which sprites can move. * * @author Arie van Deursen, TU Delft, Jan 23, 2012 */ public enum Direction { UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0); private int dx, dy; /** * Create a new direction. * @param dx horizontal move * @param dy vertical move */ Direction(int dx, int dy) { this.dx = dx; this.dy = dy; } /** * @return Number of cells to move in horizontal direction */ public int getDx() { return dx; } /** * @return Number of cells to move in vertical direction. */ public int getDy() { return dy; } }
package controllers; import akka.dispatch.MessageDispatcher; import com.fasterxml.jackson.databind.JsonNode; import dispatchers.AkkaDispatcher; import models.PropuestaMusical; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import static play.libs.Json.toJson; /** * Created by Lady Pinzon on 11/02/2017. */ public class PropuestaMusicalController extends Controller{ public CompletionStage<Result> getPropuestaMusicals() { MessageDispatcher jdbcDispatcher = AkkaDispatcher.jdbcDispatcher; return CompletableFuture. supplyAsync(() -> { return PropuestaMusical.FINDER.all(); } ,jdbcDispatcher) .thenApply(PropuestaMusicalEntities -> {return ok(toJson(PropuestaMusicalEntities));} ); } public CompletionStage<Result> getPropuestaMusical(Long idM) { MessageDispatcher jdbcDispatcher = AkkaDispatcher.jdbcDispatcher; return CompletableFuture. supplyAsync(() -> { return PropuestaMusical.FINDER.byId(idM); } ,jdbcDispatcher) .thenApply(PropuestaMusicals -> {return ok(toJson(PropuestaMusicals));} ); } public CompletionStage<Result> createPropuestaMusical() { JsonNode n = request().body().asJson(); PropuestaMusical PropuestaMusical = Json.fromJson( n , models.PropuestaMusical.class ) ; return CompletableFuture.supplyAsync( ()->{ PropuestaMusical.save(); return PropuestaMusical; } ).thenApply( PropuestaMusicals -> { return ok(Json.toJson(PropuestaMusicals)); } ); } public CompletionStage<Result> deletePropuestaMusical(Long idE) { return CompletableFuture.supplyAsync( ()->{ PropuestaMusical propuestaMusical = PropuestaMusical.FINDER.byId(idE); propuestaMusical.delete(); return propuestaMusical; } ).thenApply( PropuestaMusicals -> { return ok(Json.toJson(PropuestaMusicals)); } ); } public CompletionStage<Result> updatePropuestaMusical( Long idE) { JsonNode n = request().body().asJson(); PropuestaMusical m = Json.fromJson( n , PropuestaMusical.class ) ; PropuestaMusical antiguo = PropuestaMusical.FINDER.byId(idE); return CompletableFuture.supplyAsync( ()->{ antiguo.setId(m.getId()); antiguo.setCanciones(m.getCanciones()); antiguo.setVideos(m.getVideos()); antiguo.update(); return antiguo; } ).thenApply( PropuestaMusicals -> { return ok(Json.toJson(PropuestaMusicals)); } ); } }
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.testfixtures.internal; import org.gradle.api.logging.LogLevel; import org.gradle.api.logging.StandardOutputListener; import org.gradle.logging.LoggingManagerInternal; import org.gradle.logging.internal.OutputEventListener; public class NoOpLoggingManager implements LoggingManagerInternal { private LogLevel level = LogLevel.LIFECYCLE; private LogLevel stdoutLevel = LogLevel.LIFECYCLE; public LoggingManagerInternal captureStandardOutput(LogLevel level) { stdoutLevel = level; return this; } public LogLevel getStandardOutputCaptureLevel() { return stdoutLevel; } public LoggingManagerInternal captureStandardError(LogLevel level) { return this; } public LogLevel getLevel() { return level; } public LoggingManagerInternal setLevel(LogLevel level) { this.level = level; return this; } public LogLevel getStandardErrorCaptureLevel() { return LogLevel.ERROR; } public LoggingManagerInternal start() { return this; } public LoggingManagerInternal stop() { return this; } public void addStandardErrorListener(StandardOutputListener listener) { } public void addStandardOutputListener(StandardOutputListener listener) { } public void removeStandardOutputListener(StandardOutputListener listener) { } public void removeStandardErrorListener(StandardOutputListener listener) { } public void addOutputEventListener(OutputEventListener listener) { } public void removeOutputEventListener(OutputEventListener listener) { } public void attachConsole(boolean colorOutput) { } public void addStandardOutputAndError() { } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.07.17 at 08:51:15 AM BRT // package org.jabref.logic.importer.fileformat.medline; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}Keyword" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;attGroup ref="{}attlist.KeywordList"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "keyword" }) @XmlRootElement(name = "KeywordList") public class KeywordList { @XmlElement(name = "Keyword", required = true) protected List<Keyword> keyword; @XmlAttribute(name = "Owner") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String owner; /** * Gets the value of the keyword 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 keyword property. * * <p> * For example, to add a new item, do as follows: * <pre> * getKeyword().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Keyword } * * */ public List<Keyword> getKeyword() { if (keyword == null) { keyword = new ArrayList<Keyword>(); } return this.keyword; } /** * Gets the value of the owner property. * * @return * possible object is * {@link String } * */ public String getOwner() { if (owner == null) { return "NLM"; } else { return owner; } } /** * Sets the value of the owner property. * * @param value * allowed object is * {@link String } * */ public void setOwner(String value) { this.owner = value; } }
/* * This file is part of AudioCue, * Copyright 2017 Philip Freihofner. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of * its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package src.main.java.com.adonax.audiocue; /** * The {@code AudioCueInstanceEvent} class represents an event * in the life cycle of an {@code AudioCue} <em>instance</em>. * An {@code AudioCueInstanceEvent} is passed as * an argument to every class that implements the * {@code AudioCueListener} interface and is registered to * receive notifications about <em>instance</em> events. * <p> * An {@code AudioCue} supports concurrent plays of its media, where * the maximum number of concurrent plays is equal to the value * held in the final variable {@code AudioCue.polyphony}. * Each concurrent play is referred to as an <em>instance</em>. * Instance <em>events</em> mark the life cycle of * a single playing or playable instance as follows: * <ul> * <li>OBTAIN_INSTANCE: an instance is obtained from the pool * of available instances if the limit of allocated concurrent * instances is not exceeded</li> * <li>START_INSTANCE: an instance starts to play</li> * <li>LOOP: a instance that finishes playing restarts from the * beginning</li> * <li>STOP_INSTANCE: a playing instance is stopped (but can * still be restarted)</li> * <li>RELEASE_INSTANCE: an instance is released back into the * pool of available instances. </li> * </ul> * <p> * The information packaged in the {@code AudioCueInstanceEvent} * is contained in the following immutable fields: * <ul> * <li><strong>type</strong> - an {@code enum} designating the * nature of the event</li> * <li><strong>time</strong> - a {@code long} containing the time * of occurrence of the event, to the nearest millisecond</li> * <li><strong>source</strong> - the originating * {@code AudioCue}</li> * <li><strong>frame</strong> - a {@code double} containing the * sample frame (may be fractional) current at the time of the * event</li> * <li><strong>instanceID</strong> - an {@code int} used to * identify the {@code AudioCue} instance.</li></ul> * * @author Philip Freihofner * @version AudioCue 1.1 * @see http://adonax.com/AudioCue */ public class AudioCueInstanceEvent { /** * The {@code enum Type} represents events that occur during * the lifetime of an {@code AudioCue} <em>instance</em>. */ static public enum Type { /** * Indicates that an instance has been obtained from * the pool of available instances. */ OBTAIN_INSTANCE, /** * Indicates that an instance has been released and * returned to the pool of available instances. */ RELEASE_INSTANCE, /** * Indicates that an instance has started playing. */ START_INSTANCE, /** * Indicates that an instance has stopped playing. */ STOP_INSTANCE, /** * Indicates that an instance has finished playing * and is starting to play again from the beginning * of the media. */ LOOP}; /** * the triggering event */ public final Type type; /** * the time in milliseconds when the event occurred */ public final long time; /** * the {@code AudioCue} from which the event originated */ public final AudioCue source; /** * the hook used to identify the instance */ public final int instanceID; /** * the sample frame number (may be fractional) current * at the time of the event */ public final double frame; /** * Constructor for an {@code AudioCueInstanceEvent}, a * class that is passed as a parameter for * {@code AudioCuelistener}. * * @param type an {@code enum} that designates the * category of {@code AudioCue} instance event * @param source the {@code AudioCue} that is the origin * of the event * @param instanceID an {@code int} hook used to identify the * {@code AudioCue} instance * @param frame a {@code double} that holds the sample * frame current at the time of the event */ public AudioCueInstanceEvent(Type type, AudioCue source, int instanceID, double frame) { this.type = type; time = System.currentTimeMillis(); this.source = source; this.instanceID = instanceID; this.frame = frame; } }
package Presentacion; import Dominio.*; import java.io.*; import java.util.*; public class Main { public static Scanner in = new Scanner(System.in); public static String codigoLogin; public static void main(String[] args) throws IOException { //Añadimos objetos a la programa List<Empleado> empleados = new ArrayList<>(); //y escribimos objetos en fichero Empleado empleado = new Empleado("1", "Oleh", "123"); Empleado empleado1 = new Empleado("2", "Alex", "1234"); Empleado empleado2 = new Empleado("3", "Daniel", "12345"); empleados.add(empleado); empleados.add(empleado1); empleados.add(empleado2); empleado.escribirEmpleados(empleados); Empleado loggedIn = new Empleado(); List<Producto> productos = new ArrayList<>(); Producto producto = new Producto(1, "soap", 2.43); Producto producto1 = new Producto(2, "banana", 5); Producto producto2 = new Producto(3, "book", 25.5); Producto producto3 = new Producto(4, "phone", 225.5); Producto producto4 = new Producto(5, "laptop", 2199.0); productos.add(producto); productos.add(producto1); productos.add(producto2); productos.add(producto3); productos.add(producto4); producto.escribirProductos(productos); RandomAccessFile file = new RandomAccessFile("empleados.txt", "rw"); RandomAccessFile file1 = new RandomAccessFile("productos.txt", "rw"); boolean logOut; boolean existe = false; do { //inicializamos el bloque general de programa System.out.print("Introduzca su nombre de usuario: "); //con login y su menu principal codigoLogin = in.next(); System.out.print("Intrduzca su contraseña: "); String password = in.next(); if (userValidation(password, empleados, loggedIn)) { logOut = false; boolean returnMenu; System.out.println("\nBienvenido a la sesion"); do { //menu principal con switch-case returnMenu = false; System.out.println("\n[1] Make order"); System.out.println("[2] Modificar producto"); System.out.println("[3] Cambiar contraseña empleado"); System.out.println("[4] Log out"); System.out.print("\nInsert selection: "); int function = in.nextInt(); switch (function) { case 1: // CASE 1 HACER PEDIDO List<Producto> basket = new ArrayList<>(); //Creamos la cesta boolean modmenu = true; while (modmenu) { modmenu = false; System.out.println("\n[1] Add product"); System.out.println("[2] Visualise precio total"); System.out.println("[3] Imprimir factura"); System.out.println("[4] Terminar pedido"); System.out.print("\nInsert selection: "); int subMenuRedactor = in.nextInt(); in.nextLine(); switch (subMenuRedactor) { case 1: // Añadir producto for (int i = 0; i < productos.size(); i++) { //visualizamos todos los productos System.out.println("Producto numero " + (i + 1) + " " + productos.get(i)); } basketAdd(basket, productos); System.out.println("\nProductos en cesta: "); // visualizamos productos en cesta for (int j = 0; j < basket.size(); j++) { System.out.println(basket.get(j)); } modmenu = true; break; case 2: // Visualizar precio total totalPrice(basket); System.out.printf("Precio de pedido es %.2f: ", totalPrice(basket)); modmenu = true; break; case 3: // Imprimir factura double finalPrice = totalPrice(basket); checkVisual(basket, loggedIn, finalPrice); modmenu = true; break; case 4: // Terminar pedido returnMenu = true; basket.clear(); break; default: System.out.println("\nThe selection was invalid!"); modmenu = true; } } break; case 2: // CASE 2 MOD PRODUCT boolean submenu = true; for (int i = 0; i < productos.size(); i++) { // Mostramos todos los productos y comprobamos que ese producto es existente System.out.println("Producto numero " + (i + 1) + " " + productos.get(i)); } System.out.print("\nIntroduzca el codigo de producto que quieres modificar: "); // elegimos producto para modificar int productoMod = in.nextInt(); Producto toModProduct = elegirProducto(productos, productoMod); while (toModProduct.getCodigo() == 0) { System.out.println("\nEste producto no existe, introduzca codigo de nuevo: "); productoMod = in.nextInt(); toModProduct = elegirProducto(productos, productoMod); } while (submenu) { submenu = false; System.out.println("\n[1] Modificar nombre"); System.out.println("[2] Modificar precio"); System.out.println("[3] Modificar código"); System.out.println("[4] Return to the main menu"); System.out.print("\nInsert selection: "); int subMenuRedactor = in.nextInt(); in.nextLine(); switch (subMenuRedactor) { case 1: //case 1 Modificar nombre productNameChanger(productos, toModProduct); producto.escribirProductos(productos); submenu = true; break; case 2: //case 2 Modificar precio productPriceChanger(productos, toModProduct); producto.escribirProductos(productos); submenu = true; break; case 3: // case 3 Modificar código productCodigoChanger(productos, toModProduct); producto.escribirProductos(productos); submenu = true; break; case 4: // case 4 Return to the main menu returnMenu = true; break; default: System.out.println("\nThe selection was invalid!"); submenu = true; } } break; case 3: //CAMBIAR CONTRASEÑA passChange(empleados, loggedIn); empleado.escribirEmpleados(empleados); System.out.println("\nHas cambiado contraseña"); returnMenu = true; break; case 4: // LOGOUT System.out.println("\nGracias por usar nuestra programa - " + loggedIn.getNombreUsuario()); System.out.println("--------------SESSION WAS TERMINATED SUCCESSFULLY--------------"); logOut = true; break; default: System.out.println("\nThe selection was invalid!"); returnMenu = true; } } while (returnMenu); } else { System.out.println("\nHas introducido mal el codigo de acceso o la contraseña. "); logOut = true; } } while (logOut); } private static void checkVisual(List<Producto> basket, Empleado loggedIn, double finalPrice) { // Metodo de factura if (basket.size() == 0) { System.out.println("\nNo tienes productos en la cesta para obtener factura"); } else { System.out.println("-------------Factura-------------"); System.out.println("\nDatos de la persona que hace el pedido: " + loggedIn.getNombreUsuario() + "\n"); for (int i = 0; i < basket.size(); i++) { System.out.println("Producto en la cesta con numero " + (i + 1) + " y con nombre " + basket.get(i).getNombre() + " tiene precio " + basket.get(i).getPrecio()); } System.out.printf("\nPrecio de pedido es - %.2f", finalPrice); } } private static double totalPrice(List<Producto> basket) { // Calculo de precio total de pedido double totalPrice = 0; for (int i = 0; i < basket.size(); i++) { totalPrice += basket.get(i).getPrecio(); } return totalPrice; } private static void basketAdd(List<Producto> basket, List<Producto> productos) { // Metodo para añadir producto a la cesta if (productos.size() == basket.size()) { System.out.println("Ya tienes todos productos existentes en la cesta."); } Producto savedProduct = new Producto(); String prodName = null; boolean exist = false; while (exist == false) { // Comprobamos que productos existe System.out.print("\nIntroduzca nombre del producto que quires comprar: "); prodName = in.nextLine(); while (prodName == null || prodName.trim().length() == 0) { // comprobamos que no sea nombre nulo o vacio System.out.println("No puedes tener nombre vacio,\n" + "Intoduzca nombre del producto que quires comprar: "); prodName = in.nextLine(); } for (int i = 0; i < productos.size(); i++) { if (productos.get(i).getNombre().equalsIgnoreCase(prodName)) { savedProduct = productos.get(i); exist = true; break; } exist = false; } if (exist == false) { System.out.print("\nNo hay producto en stock."); } if (exist == true) { boolean prodExist = false; if (basket.size() < 1) { basket.add(savedProduct); } else { // Verificamos que no haya 2 iguales productos en la cesta while (prodExist == false) { for (int i = 0; i < basket.size(); i++) { if (basket.get(i).getNombre().equalsIgnoreCase(prodName)) { prodExist = true; System.out.println("\nEste producto ya esta en la cesta."); break; } else { prodExist = false; } } if (prodExist == false) { basket.add(savedProduct); } prodExist = true; } } } } } private static void productNameChanger(List<Producto> productos, Producto toModProduct) throws IOException { // Metodo para cambiar nombre de producto String newName = null; boolean exist = true; while (exist == true) { // comprobamos que no haya 2 nombres iguales System.out.print("\nIntoduzca nuevo nombre del producto: "); newName = in.nextLine(); while (newName == null || newName.trim().length() == 0) { // comprobamos que no sea nombre nulo o vacio System.out.println("No puedes tener nombre vacio,\n" + "Intoduzca nuevo nombre del producto: "); newName = in.nextLine(); } for (int i = 0; i < productos.size(); i++) { if (productos.get(i).getNombre().equalsIgnoreCase(newName)) { exist = true; System.out.print("\nEse nombre ya existe."); break; } exist = false; } } for (int i = 0; i < productos.size(); i++) { if (toModProduct.getCodigo() == productos.get(i).getCodigo()) { productos.get(i).setNombre(newName); } } } private static void productPriceChanger(List<Producto> productos, Producto toModProduct) throws IOException { // Metodo para cambiar precio de producto System.out.print("Introduzca nuevo precio para el producto: "); double newPrice = in.nextDouble(); while (newPrice <= 0) { System.out.println("No puedes tener precio negativo o nulo,\n" + "Introduzca nuevo precio para el producto: "); newPrice = in.nextDouble(); } for (int i = 0; i < productos.size(); i++) { if (toModProduct.getCodigo() == productos.get(i).getCodigo()) { productos.get(i).setPrecio(newPrice); } } } private static void productCodigoChanger(List<Producto> productos, Producto toModProduct) throws IOException { // Metodo para cambiar codigo de producto int newCode = 0; boolean exist = true; while (exist == true) { // Comprobamos que no sean 2 codigos iguales o codigos negativos System.out.print("\nIntoduzca nuevo codigo del producto: "); newCode = in.nextInt(); while (newCode < 0) { System.out.println("No puedes tener codigo negativo,\n" + "Introduzca nuevo codigo para el producto: "); newCode = in.nextInt(); } for (int i = 0; i < productos.size(); i++) { if (productos.get(i).getCodigo() == newCode) { exist = true; System.out.print("\nEse codigo ya existe."); break; } exist = false; } } for (int i = 0; i < productos.size(); i++) { if (toModProduct.getCodigo() == productos.get(i).getCodigo()) { productos.get(i).setCodigo(newCode); } } } private static Producto elegirProducto(List<Producto> productos, int productoMod) { //metodo para elegir producto que quremos modificar Producto object0 = new Producto(); for (int j = 0; j < productos.size(); j++) { if (productos.get(j).getCodigo() == productoMod) { return productos.get(j); } } return object0; } public static boolean userValidation(String passwrod, List<Empleado> empleados, Empleado loggedIn) { // metodo para comprobar datos de usuario boolean verdadero = false; for (int i = 0; i < empleados.size(); i++) { if ((codigoLogin.equals(empleados.get(i).getCodigo_acceso())) && (passwrod.equals(empleados.get(i).getPassword()))) { verdadero = true; loggedIn.setCodigo_acceso(empleados.get(i).getCodigo_acceso()); //guardamos datos de usuario que esta en sistema loggedIn.setNombreUsuario(empleados.get(i).getNombreUsuario()); loggedIn.setPassword(empleados.get(i).getPassword()); } } return verdadero; } public static void passChange(List<Empleado> empleados, Empleado loggedIn) { // Metodo para cambiar contraseña System.out.print("Introduzca nueva contraseña de usuario: "); String newPass = in.next(); for (int i = 0; i < empleados.size(); i++) { if (loggedIn.getPassword().equals(empleados.get(i).getPassword()) && (loggedIn.getCodigo_acceso() == empleados.get(i).getCodigo_acceso())) { empleados.get(i).setPassword(newPass); } } } }
package com.example.shinelon.ocrcamera.dataModel; /** * Created by Shinelon on 2017/7/7. */ public class UserInfoLab { private String phone; private String name; private String email; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } private static UserInfoLab mUserInfoLab; private UserInfoLab(){} public static UserInfoLab getUserInfo(){ if(mUserInfoLab == null){ mUserInfoLab = new UserInfoLab(); } return mUserInfoLab; } public void setPhone(String phone) { this.phone = phone; } public void setName(String name) { this.name = name; } public void setUserId(String userId) { this.userId = userId; } public String getPhone() { return phone; } public String getName() { return name; } public String getUserId() { return userId; } private String userId; }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.util; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.jetbrains.annotations.Nullable; /** * This is an utility class for 'splitting' locking of some * {@code int}- or {@code long}-keyed resources. * * Map {@code int} and {@code long} values to some number of locks, * and supply convenience methods to obtain and release these locks using key values. */ public class GridStripedLock { /** Array of underlying locks. */ private final Lock[] locks; /** * Creates new instance with the given concurrency level (number of locks). * * @param concurrencyLevel Concurrency level. */ public GridStripedLock(int concurrencyLevel) { locks = new Lock[concurrencyLevel]; for (int i = 0; i < concurrencyLevel; i++) locks[i] = new ReentrantLock(); } /** * Gets concurrency level. * * @return Concurrency level. */ public int concurrencyLevel() { return locks.length; } /** * Returns {@link Lock} object for the given key. * @param key Key. * @return Lock. */ public Lock getLock(int key) { return locks[U.safeAbs(key) % locks.length]; } /** * Returns {@link Lock} object for the given key. * @param key Key. * @return Lock. */ public Lock getLock(long key) { return locks[U.safeAbs((int)(key % locks.length))]; } /** * Returns lock for object. * * @param o Object. * @return Lock. */ public Lock getLock(@Nullable Object o) { return o == null ? locks[0] : getLock(o.hashCode()); } /** * Locks given key. * * @param key Key. */ public void lock(int key) { getLock(key).lock(); } /** * Unlocks given key. * * @param key Key. */ public void unlock(int key) { getLock(key).unlock(); } /** * Locks given key. * * @param key Key. */ public void lock(long key) { getLock(key).lock(); } /** * Unlocks given key. * * @param key Key. */ public void unlock(long key) { getLock(key).unlock(); } /** * Locks an object. * * @param o Object. */ public void lock(@Nullable Object o) { getLock(o).lock(); } /** * Unlocks an object. * * @param o Object. */ public void unlock(@Nullable Object o) { getLock(o).unlock(); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(GridStripedLock.class, this, "concurrency", locks.length); } }
/* * Copyright (C) 2010 ZXing 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.zxing.oned; import com.google.zxing.BarcodeFormat; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitArray; import java.util.EnumMap; import java.util.Map; /** * @see UPCEANExtension2Support */ final class UPCEANExtension5Support { private static final int[] CHECK_DIGIT_ENCODINGS = { 0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05 }; private final int[] decodeMiddleCounters = new int[4]; private final StringBuilder decodeRowStringBuffer = new StringBuilder(); Result decodeRow(int rowNumber, BitArray row, int[] extensionStartRange) throws NotFoundException { StringBuilder result = decodeRowStringBuffer; result.setLength(0); int end = decodeMiddle(row, extensionStartRange, result); String resultString = result.toString(); Map<ResultMetadataType, Object> extensionData = parseExtensionString(resultString); Result extensionResult = new Result(resultString, null, new ResultPoint[]{ new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, rowNumber), new ResultPoint(end, rowNumber), }, BarcodeFormat.UPC_EAN_EXTENSION); if (extensionData != null) { extensionResult.putAllMetadata(extensionData); } return extensionResult; } private int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int lgPatternFound = 0; for (int x = 0; x < 5 && rowOffset < end; x++) { int bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS); resultString.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { lgPatternFound |= 1 << (4 - x); } if (x != 4) { // Read off separator if not last rowOffset = row.getNextSet(rowOffset); rowOffset = row.getNextUnset(rowOffset); } } if (resultString.length() != 5) { throw NotFoundException.getNotFoundInstance(); } int checkDigit = determineCheckDigit(lgPatternFound); if (extensionChecksum(resultString.toString()) != checkDigit) { throw NotFoundException.getNotFoundInstance(); } return rowOffset; } private static int extensionChecksum(CharSequence s) { int length = s.length(); int sum = 0; for (int i = length - 2; i >= 0; i -= 2) { sum += s.charAt(i) - '0'; } sum *= 3; for (int i = length - 1; i >= 0; i -= 2) { sum += s.charAt(i) - '0'; } sum *= 3; return sum % 10; } private static int determineCheckDigit(int lgPatternFound) throws NotFoundException { for (int d = 0; d < 10; d++) { if (lgPatternFound == CHECK_DIGIT_ENCODINGS[d]) { return d; } } throw NotFoundException.getNotFoundInstance(); } /** * @param raw raw content of extension * @return formatted interpretation of raw content as a {@link Map} mapping * one {@link ResultMetadataType} to appropriate value, or {@code null} if not known */ private static Map<ResultMetadataType, Object> parseExtensionString(String raw) { if (raw.length() != 5) { return null; } Object value = parseExtension5String(raw); if (value == null) { return null; } Map<ResultMetadataType, Object> result = new EnumMap<>(ResultMetadataType.class); result.put(ResultMetadataType.SUGGESTED_PRICE, value); return result; } private static String parseExtension5String(String raw) { String currency; switch (raw.charAt(0)) { case '0': currency = "£"; break; case '5': currency = "$"; break; case '9': // Reference: http://www.jollytech.com switch (raw) { case "90000": // No suggested retail price return null; case "99991": // Complementary return "0.00"; case "99990": return "Used"; } // Otherwise... unknown currency? currency = ""; break; default: currency = ""; break; } int rawAmount = Integer.parseInt(raw.substring(1)); String unitsString = String.valueOf(rawAmount / 100); int hundredths = rawAmount % 100; String hundredthsString = hundredths < 10 ? "0" + hundredths : String.valueOf(hundredths); return currency + unitsString + '.' + hundredthsString; } }
package de.develman.mmi.export; import de.develman.mmi.model.Graph; /** * @author Georg Henkel <georg@develman.de> */ public class GraphExporter { private final Graph graph; public GraphExporter(Graph graph) { this.graph = graph; } public String export() { StringBuilder builder = new StringBuilder(); builder.append("{\"vertices\":["); graph.getVertices().forEach(v -> { builder.append("{\"id\":\""); builder.append(v); builder.append("\",\"label\":\""); builder.append(v); if (!v.getBalance().isNaN()) { builder.append(",("); builder.append(v.getBalance()); builder.append(")"); } builder.append("\"},"); }); builder.deleteCharAt(builder.length() - 1); builder.append("],\"edges\":["); graph.getEdges().forEach(e -> { builder.append("{\"from\":\""); builder.append(e.getSource()); builder.append("\",\"to\":\""); builder.append(e.getSink()); if (!Double.isNaN(e.getCapacity())) { if (!Double.isNaN(e.getCost())) { builder.append("\",\"label\":\""); builder.append("("); builder.append(e.getCapacity()); builder.append("),"); builder.append(e.getCost()); } else { builder.append("\",\"label\":\""); builder.append(e.getCapacity()); } } if (graph.isDirected()) { builder.append("\",\"style\":\"arrow"); } builder.append("\"},"); }); builder.deleteCharAt(builder.length() - 1); builder.append("]}"); return builder.toString(); } }
package primal.bukkit.world; import org.bukkit.Material; /** * Blast resistance * * @author cyberpwn */ public enum BlastResistance { BARRIER(18000003), BEDROCK(18000000), COMMAND(18000000), ENDER_PORTAL(18000000), ENDER_PORTAL_FRAME(18000000), ANVIL(6000), ENCHANTMENT_TABLE(6000), OBSIDIAN(6000), ENDER_CHEST(3000), WATER(500), LAVA(500), STATIONARY_WATER(500), DRAGON_EGG(45), ENDER_STONE(45), COAL_BLOCK(30), DIAMOND_BLOCK(30), EMERALD_BLOCK(30), GOLD_BLOCK(30), IRON_BLOCK(30), REDSTONE_BLOCK(30), BRICK(30), BRICK_STAIRS(30), HARD_CLAY(30), STONE(30), SMOOTH_BRICK(30), SMOOTH_STAIRS(30), DOUBLE_STONE_SLAB2(30), STONE_SLAB2(30), IRON_DOOR(30), IRON_DOOR_BLOCK(25), IRON_TRAPDOOR(25), MOB_SPAWNER(25), WEB(20), DISPENSER(17), DROPPER(17), FURNACE(17), BURNING_FURNACE(17), BEACON(15), COAL_ORE(15), COCOA(15), DIAMOND_ORE(15), EMERALD_ORE(15), FENCE(15), FENCE_GATE(15), ACACIA_FENCE_GATE(15), BIRCH_FENCE_GATE(15), DARK_OAK_FENCE_GATE(15), SPRUCE_FENCE_GATE(15), JUNGLE_FENCE_GATE(15), ACACIA_FENCE(15), BIRCH_FENCE(15), DARK_OAK_FENCE(15), SPRUCE_FENCE(15), JUNGLE_FENCE(15), ACACIA_WOOD_STAIRS(15), BIRCH_WOOD_STAIRS(15), DARK_OAK_WOOD_STAIRS(15), SPRUCE_WOOD_STAIRS(15), JUNGLE_WOOD_STAIRS(15), QUARTZ_STAIRS(15), COBBLESTONE_STAIRS(15), SANDSTONE_STAIRS(15), NETHER_BRICK_STAIRS(15), WOOD_STAIRS(15), RED_SANDSTONE_STAIRS(15), ACACIA_DOOR(15), BIRCH_DOOR(15), DARK_OAK_DOOR(15), SPRUCE_DOOR(15), JUNGLE_DOOR(15), GOLD_ORE(15), HOPPER(15), IRON_ORE(15), LAPIS_BLOCK(15), LAPIS_ORE(15), QUARTZ_ORE(15), REDSTONE_ORE(15), TRAP_DOOR(15), WOOD(15), CHEST(12), TRAPPED_CHEST(12), WORKBENCH(12), CAULDRON(12), LOG(10), LOG_2(10), BOOKSHELF(7), BANNER(5), STANDING_BANNER(5), WALL_BANNER(5), JACK_O_LANTERN(5), MELON_BLOCK(5), SKULL(5), PUMPKIN(5), SIGN(5), SIGN_POST(5), WALL_SIGN(5), QUARTZ_BLOCK(4), NOTE_BLOCK(4), RED_SANDSTONE(4), SANDSTONE(4), WOOL(4), MONSTER_EGG(4), RAILS(3), ACTIVATOR_RAIL(3), DETECTOR_RAIL(3), POWERED_RAIL(3), CLAY(3), DIRT(3), GRASS(3), GRAVEL(3), SPONGE(3), BREWING_STAND(3), STONE_BUTTON(3), WOOD_BUTTON(3), CAKE_BLOCK(3), ICE(3), PACKED_ICE(3), LEVER(3), MYCEL(3), PISTON_BASE(3), PISTON_EXTENSION(3), PISTON_MOVING_PIECE(3), PISTON_STICKY_BASE(3), GOLD_PLATE(3), IRON_PLATE(3), STONE_PLATE(3), WOOD_PLATE(3), SAND(3), SOUL_SAND(3), CACTUS(2), LADDER(2), NETHERRACK(2), GLASS(1), THIN_GLASS(1), STAINED_GLASS(1), STAINED_GLASS_PANE(1), GLOWSTONE(1), REDSTONE_LAMP_OFF(1), REDSTONE_LAMP_ON(1), SEA_LANTERN(1), BED_BLOCK(1), DAYLIGHT_DETECTOR(1), DAYLIGHT_DETECTOR_INVERTED(1), HUGE_MUSHROOM_1(1), HUGE_MUSHROOM_2(1), LEAVES(1), LEAVES_2(1), SNOW(1); private int br; private BlastResistance(int br) { this.br = br; } public int getBlastResistance() { return br; } public static int get(Material m) { if(!m.isBlock()) { return 0; } try { return valueOf(m.name()).getBlastResistance(); } catch(Exception e) { } return 0; } }
package com.ruoyi.system.service; import com.ruoyi.system.domain.Summary; import java.util.List; /** * 总结上报 服务层 * * @author lyb * @date 2019-08-15 */ public interface ISummaryService { /** * 查询总结上报信息 * * @param sId 总结上报ID * @return 总结上报信息 */ public Summary selectSummaryById(Integer sId); /** * 查询总结上报列表 * * @param summary 总结上报信息 * @return 总结上报集合 */ public List<Summary> selectSummaryList(Summary summary); /** * 新增总结上报 * * @param summary 总结上报信息 * @return 结果 */ public int insertSummary(Summary summary); /** * 修改总结上报 * * @param summary 总结上报信息 * @return 结果 */ public int updateSummary(Summary summary); /** * 删除总结上报信息 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteSummaryByIds(String ids); }